Get rid of VEC(probe_p)
[external/binutils.git] / gdb / breakpoint.c
1 /* Everything about breakpoints, for GDB.
2
3    Copyright (C) 1986-2017 Free Software Foundation, Inc.
4
5    This file is part of GDB.
6
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
19
20 #include "defs.h"
21 #include "arch-utils.h"
22 #include <ctype.h>
23 #include "hashtab.h"
24 #include "symtab.h"
25 #include "frame.h"
26 #include "breakpoint.h"
27 #include "tracepoint.h"
28 #include "gdbtypes.h"
29 #include "expression.h"
30 #include "gdbcore.h"
31 #include "gdbcmd.h"
32 #include "value.h"
33 #include "command.h"
34 #include "inferior.h"
35 #include "infrun.h"
36 #include "gdbthread.h"
37 #include "target.h"
38 #include "language.h"
39 #include "gdb-demangle.h"
40 #include "filenames.h"
41 #include "annotate.h"
42 #include "symfile.h"
43 #include "objfiles.h"
44 #include "source.h"
45 #include "linespec.h"
46 #include "completer.h"
47 #include "ui-out.h"
48 #include "cli/cli-script.h"
49 #include "block.h"
50 #include "solib.h"
51 #include "solist.h"
52 #include "observer.h"
53 #include "memattr.h"
54 #include "ada-lang.h"
55 #include "top.h"
56 #include "valprint.h"
57 #include "jit.h"
58 #include "parser-defs.h"
59 #include "gdb_regex.h"
60 #include "probe.h"
61 #include "cli/cli-utils.h"
62 #include "continuations.h"
63 #include "stack.h"
64 #include "skip.h"
65 #include "ax-gdb.h"
66 #include "dummy-frame.h"
67 #include "interps.h"
68 #include "format.h"
69 #include "thread-fsm.h"
70 #include "tid-parse.h"
71
72 /* readline include files */
73 #include "readline/readline.h"
74 #include "readline/history.h"
75
76 /* readline defines this.  */
77 #undef savestring
78
79 #include "mi/mi-common.h"
80 #include "extension.h"
81 #include <algorithm>
82 #include "progspace-and-thread.h"
83 #include "common/array-view.h"
84 #include "common/gdb_optional.h"
85
86 /* Enums for exception-handling support.  */
87 enum exception_event_kind
88 {
89   EX_EVENT_THROW,
90   EX_EVENT_RETHROW,
91   EX_EVENT_CATCH
92 };
93
94 /* Prototypes for local functions.  */
95
96 static void map_breakpoint_numbers (const char *,
97                                     gdb::function_view<void (breakpoint *)>);
98
99 static void ignore_command (char *, int);
100
101 static void breakpoint_re_set_default (struct breakpoint *);
102
103 static void
104   create_sals_from_location_default (const struct event_location *location,
105                                      struct linespec_result *canonical,
106                                      enum bptype type_wanted);
107
108 static void create_breakpoints_sal_default (struct gdbarch *,
109                                             struct linespec_result *,
110                                             gdb::unique_xmalloc_ptr<char>,
111                                             gdb::unique_xmalloc_ptr<char>,
112                                             enum bptype,
113                                             enum bpdisp, int, int,
114                                             int,
115                                             const struct breakpoint_ops *,
116                                             int, int, int, unsigned);
117
118 static std::vector<symtab_and_line> decode_location_default
119   (struct breakpoint *b, const struct event_location *location,
120    struct program_space *search_pspace);
121
122 static void clear_command (char *, int);
123
124 static int can_use_hardware_watchpoint (struct value *);
125
126 static void mention (struct breakpoint *);
127
128 static struct breakpoint *set_raw_breakpoint_without_location (struct gdbarch *,
129                                                                enum bptype,
130                                                                const struct breakpoint_ops *);
131 static struct bp_location *add_location_to_breakpoint (struct breakpoint *,
132                                                        const struct symtab_and_line *);
133
134 /* This function is used in gdbtk sources and thus can not be made
135    static.  */
136 struct breakpoint *set_raw_breakpoint (struct gdbarch *gdbarch,
137                                        struct symtab_and_line,
138                                        enum bptype,
139                                        const struct breakpoint_ops *);
140
141 static struct breakpoint *
142   momentary_breakpoint_from_master (struct breakpoint *orig,
143                                     enum bptype type,
144                                     const struct breakpoint_ops *ops,
145                                     int loc_enabled);
146
147 static void breakpoint_adjustment_warning (CORE_ADDR, CORE_ADDR, int, int);
148
149 static CORE_ADDR adjust_breakpoint_address (struct gdbarch *gdbarch,
150                                             CORE_ADDR bpaddr,
151                                             enum bptype bptype);
152
153 static void describe_other_breakpoints (struct gdbarch *,
154                                         struct program_space *, CORE_ADDR,
155                                         struct obj_section *, int);
156
157 static int watchpoint_locations_match (struct bp_location *loc1,
158                                        struct bp_location *loc2);
159
160 static int breakpoint_location_address_match (struct bp_location *bl,
161                                               const struct address_space *aspace,
162                                               CORE_ADDR addr);
163
164 static int breakpoint_location_address_range_overlap (struct bp_location *,
165                                                       const address_space *,
166                                                       CORE_ADDR, int);
167
168 static void info_breakpoints_command (char *, int);
169
170 static void info_watchpoints_command (char *, int);
171
172 static void commands_command (char *, int);
173
174 static void condition_command (char *, int);
175
176 static int remove_breakpoint (struct bp_location *);
177 static int remove_breakpoint_1 (struct bp_location *, enum remove_bp_reason);
178
179 static enum print_stop_action print_bp_stop_message (bpstat bs);
180
181 static int hw_breakpoint_used_count (void);
182
183 static int hw_watchpoint_use_count (struct breakpoint *);
184
185 static int hw_watchpoint_used_count_others (struct breakpoint *except,
186                                             enum bptype type,
187                                             int *other_type_used);
188
189 static void hbreak_command (char *, int);
190
191 static void thbreak_command (char *, int);
192
193 static void enable_breakpoint_disp (struct breakpoint *, enum bpdisp,
194                                     int count);
195
196 static void stop_command (char *arg, int from_tty);
197
198 static void free_bp_location (struct bp_location *loc);
199 static void incref_bp_location (struct bp_location *loc);
200 static void decref_bp_location (struct bp_location **loc);
201
202 static struct bp_location *allocate_bp_location (struct breakpoint *bpt);
203
204 /* update_global_location_list's modes of operation wrt to whether to
205    insert locations now.  */
206 enum ugll_insert_mode
207 {
208   /* Don't insert any breakpoint locations into the inferior, only
209      remove already-inserted locations that no longer should be
210      inserted.  Functions that delete a breakpoint or breakpoints
211      should specify this mode, so that deleting a breakpoint doesn't
212      have the side effect of inserting the locations of other
213      breakpoints that are marked not-inserted, but should_be_inserted
214      returns true on them.
215
216      This behavior is useful is situations close to tear-down -- e.g.,
217      after an exec, while the target still has execution, but
218      breakpoint shadows of the previous executable image should *NOT*
219      be restored to the new image; or before detaching, where the
220      target still has execution and wants to delete breakpoints from
221      GDB's lists, and all breakpoints had already been removed from
222      the inferior.  */
223   UGLL_DONT_INSERT,
224
225   /* May insert breakpoints iff breakpoints_should_be_inserted_now
226      claims breakpoints should be inserted now.  */
227   UGLL_MAY_INSERT,
228
229   /* Insert locations now, irrespective of
230      breakpoints_should_be_inserted_now.  E.g., say all threads are
231      stopped right now, and the user did "continue".  We need to
232      insert breakpoints _before_ resuming the target, but
233      UGLL_MAY_INSERT wouldn't insert them, because
234      breakpoints_should_be_inserted_now returns false at that point,
235      as no thread is running yet.  */
236   UGLL_INSERT
237 };
238
239 static void update_global_location_list (enum ugll_insert_mode);
240
241 static void update_global_location_list_nothrow (enum ugll_insert_mode);
242
243 static int is_hardware_watchpoint (const struct breakpoint *bpt);
244
245 static void insert_breakpoint_locations (void);
246
247 static void info_tracepoints_command (char *, int);
248
249 static void enable_trace_command (char *, int);
250
251 static void disable_trace_command (char *, int);
252
253 static void trace_pass_command (char *, int);
254
255 static void set_tracepoint_count (int num);
256
257 static int is_masked_watchpoint (const struct breakpoint *b);
258
259 static struct bp_location **get_first_locp_gte_addr (CORE_ADDR address);
260
261 /* Return 1 if B refers to a static tracepoint set by marker ("-m"), zero
262    otherwise.  */
263
264 static int strace_marker_p (struct breakpoint *b);
265
266 /* The breakpoint_ops structure to be inherited by all breakpoint_ops
267    that are implemented on top of software or hardware breakpoints
268    (user breakpoints, internal and momentary breakpoints, etc.).  */
269 static struct breakpoint_ops bkpt_base_breakpoint_ops;
270
271 /* Internal breakpoints class type.  */
272 static struct breakpoint_ops internal_breakpoint_ops;
273
274 /* Momentary breakpoints class type.  */
275 static struct breakpoint_ops momentary_breakpoint_ops;
276
277 /* The breakpoint_ops structure to be used in regular user created
278    breakpoints.  */
279 struct breakpoint_ops bkpt_breakpoint_ops;
280
281 /* Breakpoints set on probes.  */
282 static struct breakpoint_ops bkpt_probe_breakpoint_ops;
283
284 /* Dynamic printf class type.  */
285 struct breakpoint_ops dprintf_breakpoint_ops;
286
287 /* The style in which to perform a dynamic printf.  This is a user
288    option because different output options have different tradeoffs;
289    if GDB does the printing, there is better error handling if there
290    is a problem with any of the arguments, but using an inferior
291    function lets you have special-purpose printers and sending of
292    output to the same place as compiled-in print functions.  */
293
294 static const char dprintf_style_gdb[] = "gdb";
295 static const char dprintf_style_call[] = "call";
296 static const char dprintf_style_agent[] = "agent";
297 static const char *const dprintf_style_enums[] = {
298   dprintf_style_gdb,
299   dprintf_style_call,
300   dprintf_style_agent,
301   NULL
302 };
303 static const char *dprintf_style = dprintf_style_gdb;
304
305 /* The function to use for dynamic printf if the preferred style is to
306    call into the inferior.  The value is simply a string that is
307    copied into the command, so it can be anything that GDB can
308    evaluate to a callable address, not necessarily a function name.  */
309
310 static char *dprintf_function;
311
312 /* The channel to use for dynamic printf if the preferred style is to
313    call into the inferior; if a nonempty string, it will be passed to
314    the call as the first argument, with the format string as the
315    second.  As with the dprintf function, this can be anything that
316    GDB knows how to evaluate, so in addition to common choices like
317    "stderr", this could be an app-specific expression like
318    "mystreams[curlogger]".  */
319
320 static char *dprintf_channel;
321
322 /* True if dprintf commands should continue to operate even if GDB
323    has disconnected.  */
324 static int disconnected_dprintf = 1;
325
326 struct command_line *
327 breakpoint_commands (struct breakpoint *b)
328 {
329   return b->commands ? b->commands.get () : NULL;
330 }
331
332 /* Flag indicating that a command has proceeded the inferior past the
333    current breakpoint.  */
334
335 static int breakpoint_proceeded;
336
337 const char *
338 bpdisp_text (enum bpdisp disp)
339 {
340   /* NOTE: the following values are a part of MI protocol and
341      represent values of 'disp' field returned when inferior stops at
342      a breakpoint.  */
343   static const char * const bpdisps[] = {"del", "dstp", "dis", "keep"};
344
345   return bpdisps[(int) disp];
346 }
347
348 /* Prototypes for exported functions.  */
349 /* If FALSE, gdb will not use hardware support for watchpoints, even
350    if such is available.  */
351 static int can_use_hw_watchpoints;
352
353 static void
354 show_can_use_hw_watchpoints (struct ui_file *file, int from_tty,
355                              struct cmd_list_element *c,
356                              const char *value)
357 {
358   fprintf_filtered (file,
359                     _("Debugger's willingness to use "
360                       "watchpoint hardware is %s.\n"),
361                     value);
362 }
363
364 /* If AUTO_BOOLEAN_FALSE, gdb will not attempt to create pending breakpoints.
365    If AUTO_BOOLEAN_TRUE, gdb will automatically create pending breakpoints
366    for unrecognized breakpoint locations.
367    If AUTO_BOOLEAN_AUTO, gdb will query when breakpoints are unrecognized.  */
368 static enum auto_boolean pending_break_support;
369 static void
370 show_pending_break_support (struct ui_file *file, int from_tty,
371                             struct cmd_list_element *c,
372                             const char *value)
373 {
374   fprintf_filtered (file,
375                     _("Debugger's behavior regarding "
376                       "pending breakpoints is %s.\n"),
377                     value);
378 }
379
380 /* If 1, gdb will automatically use hardware breakpoints for breakpoints
381    set with "break" but falling in read-only memory.
382    If 0, gdb will warn about such breakpoints, but won't automatically
383    use hardware breakpoints.  */
384 static int automatic_hardware_breakpoints;
385 static void
386 show_automatic_hardware_breakpoints (struct ui_file *file, int from_tty,
387                                      struct cmd_list_element *c,
388                                      const char *value)
389 {
390   fprintf_filtered (file,
391                     _("Automatic usage of hardware breakpoints is %s.\n"),
392                     value);
393 }
394
395 /* If on, GDB keeps breakpoints inserted even if the inferior is
396    stopped, and immediately inserts any new breakpoints as soon as
397    they're created.  If off (default), GDB keeps breakpoints off of
398    the target as long as possible.  That is, it delays inserting
399    breakpoints until the next resume, and removes them again when the
400    target fully stops.  This is a bit safer in case GDB crashes while
401    processing user input.  */
402 static int always_inserted_mode = 0;
403
404 static void
405 show_always_inserted_mode (struct ui_file *file, int from_tty,
406                      struct cmd_list_element *c, const char *value)
407 {
408   fprintf_filtered (file, _("Always inserted breakpoint mode is %s.\n"),
409                     value);
410 }
411
412 /* See breakpoint.h.  */
413
414 int
415 breakpoints_should_be_inserted_now (void)
416 {
417   if (gdbarch_has_global_breakpoints (target_gdbarch ()))
418     {
419       /* If breakpoints are global, they should be inserted even if no
420          thread under gdb's control is running, or even if there are
421          no threads under GDB's control yet.  */
422       return 1;
423     }
424   else if (target_has_execution)
425     {
426       struct thread_info *tp;
427
428       if (always_inserted_mode)
429         {
430           /* The user wants breakpoints inserted even if all threads
431              are stopped.  */
432           return 1;
433         }
434
435       if (threads_are_executing ())
436         return 1;
437
438       /* Don't remove breakpoints yet if, even though all threads are
439          stopped, we still have events to process.  */
440       ALL_NON_EXITED_THREADS (tp)
441         if (tp->resumed
442             && tp->suspend.waitstatus_pending_p)
443           return 1;
444     }
445   return 0;
446 }
447
448 static const char condition_evaluation_both[] = "host or target";
449
450 /* Modes for breakpoint condition evaluation.  */
451 static const char condition_evaluation_auto[] = "auto";
452 static const char condition_evaluation_host[] = "host";
453 static const char condition_evaluation_target[] = "target";
454 static const char *const condition_evaluation_enums[] = {
455   condition_evaluation_auto,
456   condition_evaluation_host,
457   condition_evaluation_target,
458   NULL
459 };
460
461 /* Global that holds the current mode for breakpoint condition evaluation.  */
462 static const char *condition_evaluation_mode_1 = condition_evaluation_auto;
463
464 /* Global that we use to display information to the user (gets its value from
465    condition_evaluation_mode_1.  */
466 static const char *condition_evaluation_mode = condition_evaluation_auto;
467
468 /* Translate a condition evaluation mode MODE into either "host"
469    or "target".  This is used mostly to translate from "auto" to the
470    real setting that is being used.  It returns the translated
471    evaluation mode.  */
472
473 static const char *
474 translate_condition_evaluation_mode (const char *mode)
475 {
476   if (mode == condition_evaluation_auto)
477     {
478       if (target_supports_evaluation_of_breakpoint_conditions ())
479         return condition_evaluation_target;
480       else
481         return condition_evaluation_host;
482     }
483   else
484     return mode;
485 }
486
487 /* Discovers what condition_evaluation_auto translates to.  */
488
489 static const char *
490 breakpoint_condition_evaluation_mode (void)
491 {
492   return translate_condition_evaluation_mode (condition_evaluation_mode);
493 }
494
495 /* Return true if GDB should evaluate breakpoint conditions or false
496    otherwise.  */
497
498 static int
499 gdb_evaluates_breakpoint_condition_p (void)
500 {
501   const char *mode = breakpoint_condition_evaluation_mode ();
502
503   return (mode == condition_evaluation_host);
504 }
505
506 /* Are we executing breakpoint commands?  */
507 static int executing_breakpoint_commands;
508
509 /* Are overlay event breakpoints enabled? */
510 static int overlay_events_enabled;
511
512 /* See description in breakpoint.h. */
513 int target_exact_watchpoints = 0;
514
515 /* Walk the following statement or block through all breakpoints.
516    ALL_BREAKPOINTS_SAFE does so even if the statement deletes the
517    current breakpoint.  */
518
519 #define ALL_BREAKPOINTS(B)  for (B = breakpoint_chain; B; B = B->next)
520
521 #define ALL_BREAKPOINTS_SAFE(B,TMP)     \
522         for (B = breakpoint_chain;      \
523              B ? (TMP=B->next, 1): 0;   \
524              B = TMP)
525
526 /* Similar iterator for the low-level breakpoints.  SAFE variant is
527    not provided so update_global_location_list must not be called
528    while executing the block of ALL_BP_LOCATIONS.  */
529
530 #define ALL_BP_LOCATIONS(B,BP_TMP)                                      \
531         for (BP_TMP = bp_locations;                                     \
532              BP_TMP < bp_locations + bp_locations_count && (B = *BP_TMP);\
533              BP_TMP++)
534
535 /* Iterates through locations with address ADDRESS for the currently selected
536    program space.  BP_LOCP_TMP points to each object.  BP_LOCP_START points
537    to where the loop should start from.
538    If BP_LOCP_START is a NULL pointer, the macro automatically seeks the
539    appropriate location to start with.  */
540
541 #define ALL_BP_LOCATIONS_AT_ADDR(BP_LOCP_TMP, BP_LOCP_START, ADDRESS)   \
542         for (BP_LOCP_START = BP_LOCP_START == NULL ? get_first_locp_gte_addr (ADDRESS) : BP_LOCP_START, \
543              BP_LOCP_TMP = BP_LOCP_START;                               \
544              BP_LOCP_START                                              \
545              && (BP_LOCP_TMP < bp_locations + bp_locations_count        \
546              && (*BP_LOCP_TMP)->address == ADDRESS);                    \
547              BP_LOCP_TMP++)
548
549 /* Iterator for tracepoints only.  */
550
551 #define ALL_TRACEPOINTS(B)  \
552   for (B = breakpoint_chain; B; B = B->next)  \
553     if (is_tracepoint (B))
554
555 /* Chains of all breakpoints defined.  */
556
557 struct breakpoint *breakpoint_chain;
558
559 /* Array is sorted by bp_locations_compare - primarily by the ADDRESS.  */
560
561 static struct bp_location **bp_locations;
562
563 /* Number of elements of BP_LOCATIONS.  */
564
565 static unsigned bp_locations_count;
566
567 /* Maximum alignment offset between bp_target_info.PLACED_ADDRESS and
568    ADDRESS for the current elements of BP_LOCATIONS which get a valid
569    result from bp_location_has_shadow.  You can use it for roughly
570    limiting the subrange of BP_LOCATIONS to scan for shadow bytes for
571    an address you need to read.  */
572
573 static CORE_ADDR bp_locations_placed_address_before_address_max;
574
575 /* Maximum offset plus alignment between bp_target_info.PLACED_ADDRESS
576    + bp_target_info.SHADOW_LEN and ADDRESS for the current elements of
577    BP_LOCATIONS which get a valid result from bp_location_has_shadow.
578    You can use it for roughly limiting the subrange of BP_LOCATIONS to
579    scan for shadow bytes for an address you need to read.  */
580
581 static CORE_ADDR bp_locations_shadow_len_after_address_max;
582
583 /* The locations that no longer correspond to any breakpoint, unlinked
584    from the bp_locations array, but for which a hit may still be
585    reported by a target.  */
586 VEC(bp_location_p) *moribund_locations = NULL;
587
588 /* Number of last breakpoint made.  */
589
590 static int breakpoint_count;
591
592 /* The value of `breakpoint_count' before the last command that
593    created breakpoints.  If the last (break-like) command created more
594    than one breakpoint, then the difference between BREAKPOINT_COUNT
595    and PREV_BREAKPOINT_COUNT is more than one.  */
596 static int prev_breakpoint_count;
597
598 /* Number of last tracepoint made.  */
599
600 static int tracepoint_count;
601
602 static struct cmd_list_element *breakpoint_set_cmdlist;
603 static struct cmd_list_element *breakpoint_show_cmdlist;
604 struct cmd_list_element *save_cmdlist;
605
606 /* See declaration at breakpoint.h.  */
607
608 struct breakpoint *
609 breakpoint_find_if (int (*func) (struct breakpoint *b, void *d),
610                     void *user_data)
611 {
612   struct breakpoint *b = NULL;
613
614   ALL_BREAKPOINTS (b)
615     {
616       if (func (b, user_data) != 0)
617         break;
618     }
619
620   return b;
621 }
622
623 /* Return whether a breakpoint is an active enabled breakpoint.  */
624 static int
625 breakpoint_enabled (struct breakpoint *b)
626 {
627   return (b->enable_state == bp_enabled);
628 }
629
630 /* Set breakpoint count to NUM.  */
631
632 static void
633 set_breakpoint_count (int num)
634 {
635   prev_breakpoint_count = breakpoint_count;
636   breakpoint_count = num;
637   set_internalvar_integer (lookup_internalvar ("bpnum"), num);
638 }
639
640 /* Used by `start_rbreak_breakpoints' below, to record the current
641    breakpoint count before "rbreak" creates any breakpoint.  */
642 static int rbreak_start_breakpoint_count;
643
644 /* Called at the start an "rbreak" command to record the first
645    breakpoint made.  */
646
647 void
648 start_rbreak_breakpoints (void)
649 {
650   rbreak_start_breakpoint_count = breakpoint_count;
651 }
652
653 /* Called at the end of an "rbreak" command to record the last
654    breakpoint made.  */
655
656 void
657 end_rbreak_breakpoints (void)
658 {
659   prev_breakpoint_count = rbreak_start_breakpoint_count;
660 }
661
662 /* Used in run_command to zero the hit count when a new run starts.  */
663
664 void
665 clear_breakpoint_hit_counts (void)
666 {
667   struct breakpoint *b;
668
669   ALL_BREAKPOINTS (b)
670     b->hit_count = 0;
671 }
672
673 \f
674 /* Return the breakpoint with the specified number, or NULL
675    if the number does not refer to an existing breakpoint.  */
676
677 struct breakpoint *
678 get_breakpoint (int num)
679 {
680   struct breakpoint *b;
681
682   ALL_BREAKPOINTS (b)
683     if (b->number == num)
684       return b;
685   
686   return NULL;
687 }
688
689 \f
690
691 /* Mark locations as "conditions have changed" in case the target supports
692    evaluating conditions on its side.  */
693
694 static void
695 mark_breakpoint_modified (struct breakpoint *b)
696 {
697   struct bp_location *loc;
698
699   /* This is only meaningful if the target is
700      evaluating conditions and if the user has
701      opted for condition evaluation on the target's
702      side.  */
703   if (gdb_evaluates_breakpoint_condition_p ()
704       || !target_supports_evaluation_of_breakpoint_conditions ())
705     return;
706
707   if (!is_breakpoint (b))
708     return;
709
710   for (loc = b->loc; loc; loc = loc->next)
711     loc->condition_changed = condition_modified;
712 }
713
714 /* Mark location as "conditions have changed" in case the target supports
715    evaluating conditions on its side.  */
716
717 static void
718 mark_breakpoint_location_modified (struct bp_location *loc)
719 {
720   /* This is only meaningful if the target is
721      evaluating conditions and if the user has
722      opted for condition evaluation on the target's
723      side.  */
724   if (gdb_evaluates_breakpoint_condition_p ()
725       || !target_supports_evaluation_of_breakpoint_conditions ())
726
727     return;
728
729   if (!is_breakpoint (loc->owner))
730     return;
731
732   loc->condition_changed = condition_modified;
733 }
734
735 /* Sets the condition-evaluation mode using the static global
736    condition_evaluation_mode.  */
737
738 static void
739 set_condition_evaluation_mode (char *args, int from_tty,
740                                struct cmd_list_element *c)
741 {
742   const char *old_mode, *new_mode;
743
744   if ((condition_evaluation_mode_1 == condition_evaluation_target)
745       && !target_supports_evaluation_of_breakpoint_conditions ())
746     {
747       condition_evaluation_mode_1 = condition_evaluation_mode;
748       warning (_("Target does not support breakpoint condition evaluation.\n"
749                  "Using host evaluation mode instead."));
750       return;
751     }
752
753   new_mode = translate_condition_evaluation_mode (condition_evaluation_mode_1);
754   old_mode = translate_condition_evaluation_mode (condition_evaluation_mode);
755
756   /* Flip the switch.  Flip it even if OLD_MODE == NEW_MODE as one of the
757      settings was "auto".  */
758   condition_evaluation_mode = condition_evaluation_mode_1;
759
760   /* Only update the mode if the user picked a different one.  */
761   if (new_mode != old_mode)
762     {
763       struct bp_location *loc, **loc_tmp;
764       /* If the user switched to a different evaluation mode, we
765          need to synch the changes with the target as follows:
766
767          "host" -> "target": Send all (valid) conditions to the target.
768          "target" -> "host": Remove all the conditions from the target.
769       */
770
771       if (new_mode == condition_evaluation_target)
772         {
773           /* Mark everything modified and synch conditions with the
774              target.  */
775           ALL_BP_LOCATIONS (loc, loc_tmp)
776             mark_breakpoint_location_modified (loc);
777         }
778       else
779         {
780           /* Manually mark non-duplicate locations to synch conditions
781              with the target.  We do this to remove all the conditions the
782              target knows about.  */
783           ALL_BP_LOCATIONS (loc, loc_tmp)
784             if (is_breakpoint (loc->owner) && loc->inserted)
785               loc->needs_update = 1;
786         }
787
788       /* Do the update.  */
789       update_global_location_list (UGLL_MAY_INSERT);
790     }
791
792   return;
793 }
794
795 /* Shows the current mode of breakpoint condition evaluation.  Explicitly shows
796    what "auto" is translating to.  */
797
798 static void
799 show_condition_evaluation_mode (struct ui_file *file, int from_tty,
800                                 struct cmd_list_element *c, const char *value)
801 {
802   if (condition_evaluation_mode == condition_evaluation_auto)
803     fprintf_filtered (file,
804                       _("Breakpoint condition evaluation "
805                         "mode is %s (currently %s).\n"),
806                       value,
807                       breakpoint_condition_evaluation_mode ());
808   else
809     fprintf_filtered (file, _("Breakpoint condition evaluation mode is %s.\n"),
810                       value);
811 }
812
813 /* A comparison function for bp_location AP and BP that is used by
814    bsearch.  This comparison function only cares about addresses, unlike
815    the more general bp_locations_compare function.  */
816
817 static int
818 bp_locations_compare_addrs (const void *ap, const void *bp)
819 {
820   const struct bp_location *a = *(const struct bp_location **) ap;
821   const struct bp_location *b = *(const struct bp_location **) bp;
822
823   if (a->address == b->address)
824     return 0;
825   else
826     return ((a->address > b->address) - (a->address < b->address));
827 }
828
829 /* Helper function to skip all bp_locations with addresses
830    less than ADDRESS.  It returns the first bp_location that
831    is greater than or equal to ADDRESS.  If none is found, just
832    return NULL.  */
833
834 static struct bp_location **
835 get_first_locp_gte_addr (CORE_ADDR address)
836 {
837   struct bp_location dummy_loc;
838   struct bp_location *dummy_locp = &dummy_loc;
839   struct bp_location **locp_found = NULL;
840
841   /* Initialize the dummy location's address field.  */
842   dummy_loc.address = address;
843
844   /* Find a close match to the first location at ADDRESS.  */
845   locp_found = ((struct bp_location **)
846                 bsearch (&dummy_locp, bp_locations, bp_locations_count,
847                          sizeof (struct bp_location **),
848                          bp_locations_compare_addrs));
849
850   /* Nothing was found, nothing left to do.  */
851   if (locp_found == NULL)
852     return NULL;
853
854   /* We may have found a location that is at ADDRESS but is not the first in the
855      location's list.  Go backwards (if possible) and locate the first one.  */
856   while ((locp_found - 1) >= bp_locations
857          && (*(locp_found - 1))->address == address)
858     locp_found--;
859
860   return locp_found;
861 }
862
863 void
864 set_breakpoint_condition (struct breakpoint *b, const char *exp,
865                           int from_tty)
866 {
867   xfree (b->cond_string);
868   b->cond_string = NULL;
869
870   if (is_watchpoint (b))
871     {
872       struct watchpoint *w = (struct watchpoint *) b;
873
874       w->cond_exp.reset ();
875     }
876   else
877     {
878       struct bp_location *loc;
879
880       for (loc = b->loc; loc; loc = loc->next)
881         {
882           loc->cond.reset ();
883
884           /* No need to free the condition agent expression
885              bytecode (if we have one).  We will handle this
886              when we go through update_global_location_list.  */
887         }
888     }
889
890   if (*exp == 0)
891     {
892       if (from_tty)
893         printf_filtered (_("Breakpoint %d now unconditional.\n"), b->number);
894     }
895   else
896     {
897       const char *arg = exp;
898
899       /* I don't know if it matters whether this is the string the user
900          typed in or the decompiled expression.  */
901       b->cond_string = xstrdup (arg);
902       b->condition_not_parsed = 0;
903
904       if (is_watchpoint (b))
905         {
906           struct watchpoint *w = (struct watchpoint *) b;
907
908           innermost_block = NULL;
909           arg = exp;
910           w->cond_exp = parse_exp_1 (&arg, 0, 0, 0);
911           if (*arg)
912             error (_("Junk at end of expression"));
913           w->cond_exp_valid_block = innermost_block;
914         }
915       else
916         {
917           struct bp_location *loc;
918
919           for (loc = b->loc; loc; loc = loc->next)
920             {
921               arg = exp;
922               loc->cond =
923                 parse_exp_1 (&arg, loc->address,
924                              block_for_pc (loc->address), 0);
925               if (*arg)
926                 error (_("Junk at end of expression"));
927             }
928         }
929     }
930   mark_breakpoint_modified (b);
931
932   observer_notify_breakpoint_modified (b);
933 }
934
935 /* Completion for the "condition" command.  */
936
937 static void
938 condition_completer (struct cmd_list_element *cmd,
939                      completion_tracker &tracker,
940                      const char *text, const char *word)
941 {
942   const char *space;
943
944   text = skip_spaces (text);
945   space = skip_to_space (text);
946   if (*space == '\0')
947     {
948       int len;
949       struct breakpoint *b;
950       VEC (char_ptr) *result = NULL;
951
952       if (text[0] == '$')
953         {
954           /* We don't support completion of history indices.  */
955           if (!isdigit (text[1]))
956             complete_internalvar (tracker, &text[1]);
957           return;
958         }
959
960       /* We're completing the breakpoint number.  */
961       len = strlen (text);
962
963       ALL_BREAKPOINTS (b)
964         {
965           char number[50];
966
967           xsnprintf (number, sizeof (number), "%d", b->number);
968
969           if (strncmp (number, text, len) == 0)
970             {
971               gdb::unique_xmalloc_ptr<char> copy (xstrdup (number));
972               tracker.add_completion (std::move (copy));
973             }
974         }
975
976       return;
977     }
978
979   /* We're completing the expression part.  */
980   text = skip_spaces (space);
981   expression_completer (cmd, tracker, text, word);
982 }
983
984 /* condition N EXP -- set break condition of breakpoint N to EXP.  */
985
986 static void
987 condition_command (char *arg, int from_tty)
988 {
989   struct breakpoint *b;
990   char *p;
991   int bnum;
992
993   if (arg == 0)
994     error_no_arg (_("breakpoint number"));
995
996   p = arg;
997   bnum = get_number (&p);
998   if (bnum == 0)
999     error (_("Bad breakpoint argument: '%s'"), arg);
1000
1001   ALL_BREAKPOINTS (b)
1002     if (b->number == bnum)
1003       {
1004         /* Check if this breakpoint has a "stop" method implemented in an
1005            extension language.  This method and conditions entered into GDB
1006            from the CLI are mutually exclusive.  */
1007         const struct extension_language_defn *extlang
1008           = get_breakpoint_cond_ext_lang (b, EXT_LANG_NONE);
1009
1010         if (extlang != NULL)
1011           {
1012             error (_("Only one stop condition allowed.  There is currently"
1013                      " a %s stop condition defined for this breakpoint."),
1014                    ext_lang_capitalized_name (extlang));
1015           }
1016         set_breakpoint_condition (b, p, from_tty);
1017
1018         if (is_breakpoint (b))
1019           update_global_location_list (UGLL_MAY_INSERT);
1020
1021         return;
1022       }
1023
1024   error (_("No breakpoint number %d."), bnum);
1025 }
1026
1027 /* Check that COMMAND do not contain commands that are suitable
1028    only for tracepoints and not suitable for ordinary breakpoints.
1029    Throw if any such commands is found.  */
1030
1031 static void
1032 check_no_tracepoint_commands (struct command_line *commands)
1033 {
1034   struct command_line *c;
1035
1036   for (c = commands; c; c = c->next)
1037     {
1038       int i;
1039
1040       if (c->control_type == while_stepping_control)
1041         error (_("The 'while-stepping' command can "
1042                  "only be used for tracepoints"));
1043
1044       for (i = 0; i < c->body_count; ++i)
1045         check_no_tracepoint_commands ((c->body_list)[i]);
1046
1047       /* Not that command parsing removes leading whitespace and comment
1048          lines and also empty lines.  So, we only need to check for
1049          command directly.  */
1050       if (strstr (c->line, "collect ") == c->line)
1051         error (_("The 'collect' command can only be used for tracepoints"));
1052
1053       if (strstr (c->line, "teval ") == c->line)
1054         error (_("The 'teval' command can only be used for tracepoints"));
1055     }
1056 }
1057
1058 struct longjmp_breakpoint : public breakpoint
1059 {
1060   ~longjmp_breakpoint () override;
1061 };
1062
1063 /* Encapsulate tests for different types of tracepoints.  */
1064
1065 static bool
1066 is_tracepoint_type (bptype type)
1067 {
1068   return (type == bp_tracepoint
1069           || type == bp_fast_tracepoint
1070           || type == bp_static_tracepoint);
1071 }
1072
1073 static bool
1074 is_longjmp_type (bptype type)
1075 {
1076   return type == bp_longjmp || type == bp_exception;
1077 }
1078
1079 int
1080 is_tracepoint (const struct breakpoint *b)
1081 {
1082   return is_tracepoint_type (b->type);
1083 }
1084
1085 /* Factory function to create an appropriate instance of breakpoint given
1086    TYPE.  */
1087
1088 static std::unique_ptr<breakpoint>
1089 new_breakpoint_from_type (bptype type)
1090 {
1091   breakpoint *b;
1092
1093   if (is_tracepoint_type (type))
1094     b = new tracepoint ();
1095   else if (is_longjmp_type (type))
1096     b = new longjmp_breakpoint ();
1097   else
1098     b = new breakpoint ();
1099
1100   return std::unique_ptr<breakpoint> (b);
1101 }
1102
1103 /* A helper function that validates that COMMANDS are valid for a
1104    breakpoint.  This function will throw an exception if a problem is
1105    found.  */
1106
1107 static void
1108 validate_commands_for_breakpoint (struct breakpoint *b,
1109                                   struct command_line *commands)
1110 {
1111   if (is_tracepoint (b))
1112     {
1113       struct tracepoint *t = (struct tracepoint *) b;
1114       struct command_line *c;
1115       struct command_line *while_stepping = 0;
1116
1117       /* Reset the while-stepping step count.  The previous commands
1118          might have included a while-stepping action, while the new
1119          ones might not.  */
1120       t->step_count = 0;
1121
1122       /* We need to verify that each top-level element of commands is
1123          valid for tracepoints, that there's at most one
1124          while-stepping element, and that the while-stepping's body
1125          has valid tracing commands excluding nested while-stepping.
1126          We also need to validate the tracepoint action line in the
1127          context of the tracepoint --- validate_actionline actually
1128          has side effects, like setting the tracepoint's
1129          while-stepping STEP_COUNT, in addition to checking if the
1130          collect/teval actions parse and make sense in the
1131          tracepoint's context.  */
1132       for (c = commands; c; c = c->next)
1133         {
1134           if (c->control_type == while_stepping_control)
1135             {
1136               if (b->type == bp_fast_tracepoint)
1137                 error (_("The 'while-stepping' command "
1138                          "cannot be used for fast tracepoint"));
1139               else if (b->type == bp_static_tracepoint)
1140                 error (_("The 'while-stepping' command "
1141                          "cannot be used for static tracepoint"));
1142
1143               if (while_stepping)
1144                 error (_("The 'while-stepping' command "
1145                          "can be used only once"));
1146               else
1147                 while_stepping = c;
1148             }
1149
1150           validate_actionline (c->line, b);
1151         }
1152       if (while_stepping)
1153         {
1154           struct command_line *c2;
1155
1156           gdb_assert (while_stepping->body_count == 1);
1157           c2 = while_stepping->body_list[0];
1158           for (; c2; c2 = c2->next)
1159             {
1160               if (c2->control_type == while_stepping_control)
1161                 error (_("The 'while-stepping' command cannot be nested"));
1162             }
1163         }
1164     }
1165   else
1166     {
1167       check_no_tracepoint_commands (commands);
1168     }
1169 }
1170
1171 /* Return a vector of all the static tracepoints set at ADDR.  The
1172    caller is responsible for releasing the vector.  */
1173
1174 VEC(breakpoint_p) *
1175 static_tracepoints_here (CORE_ADDR addr)
1176 {
1177   struct breakpoint *b;
1178   VEC(breakpoint_p) *found = 0;
1179   struct bp_location *loc;
1180
1181   ALL_BREAKPOINTS (b)
1182     if (b->type == bp_static_tracepoint)
1183       {
1184         for (loc = b->loc; loc; loc = loc->next)
1185           if (loc->address == addr)
1186             VEC_safe_push(breakpoint_p, found, b);
1187       }
1188
1189   return found;
1190 }
1191
1192 /* Set the command list of B to COMMANDS.  If breakpoint is tracepoint,
1193    validate that only allowed commands are included.  */
1194
1195 void
1196 breakpoint_set_commands (struct breakpoint *b, 
1197                          command_line_up &&commands)
1198 {
1199   validate_commands_for_breakpoint (b, commands.get ());
1200
1201   b->commands = std::move (commands);
1202   observer_notify_breakpoint_modified (b);
1203 }
1204
1205 /* Set the internal `silent' flag on the breakpoint.  Note that this
1206    is not the same as the "silent" that may appear in the breakpoint's
1207    commands.  */
1208
1209 void
1210 breakpoint_set_silent (struct breakpoint *b, int silent)
1211 {
1212   int old_silent = b->silent;
1213
1214   b->silent = silent;
1215   if (old_silent != silent)
1216     observer_notify_breakpoint_modified (b);
1217 }
1218
1219 /* Set the thread for this breakpoint.  If THREAD is -1, make the
1220    breakpoint work for any thread.  */
1221
1222 void
1223 breakpoint_set_thread (struct breakpoint *b, int thread)
1224 {
1225   int old_thread = b->thread;
1226
1227   b->thread = thread;
1228   if (old_thread != thread)
1229     observer_notify_breakpoint_modified (b);
1230 }
1231
1232 /* Set the task for this breakpoint.  If TASK is 0, make the
1233    breakpoint work for any task.  */
1234
1235 void
1236 breakpoint_set_task (struct breakpoint *b, int task)
1237 {
1238   int old_task = b->task;
1239
1240   b->task = task;
1241   if (old_task != task)
1242     observer_notify_breakpoint_modified (b);
1243 }
1244
1245 void
1246 check_tracepoint_command (char *line, void *closure)
1247 {
1248   struct breakpoint *b = (struct breakpoint *) closure;
1249
1250   validate_actionline (line, b);
1251 }
1252
1253 static void
1254 commands_command_1 (const char *arg, int from_tty,
1255                     struct command_line *control)
1256 {
1257   counted_command_line cmd;
1258
1259   std::string new_arg;
1260
1261   if (arg == NULL || !*arg)
1262     {
1263       if (breakpoint_count - prev_breakpoint_count > 1)
1264         new_arg = string_printf ("%d-%d", prev_breakpoint_count + 1,
1265                                  breakpoint_count);
1266       else if (breakpoint_count > 0)
1267         new_arg = string_printf ("%d", breakpoint_count);
1268       arg = new_arg.c_str ();
1269     }
1270
1271   map_breakpoint_numbers
1272     (arg, [&] (breakpoint *b)
1273      {
1274        if (cmd == NULL)
1275          {
1276            if (control != NULL)
1277              cmd = copy_command_lines (control->body_list[0]);
1278            else
1279              {
1280                std::string str
1281                  = string_printf (_("Type commands for breakpoint(s) "
1282                                     "%s, one per line."),
1283                                   arg);
1284
1285                cmd = read_command_lines (&str[0],
1286                                          from_tty, 1,
1287                                          (is_tracepoint (b)
1288                                           ? check_tracepoint_command : 0),
1289                                          b);
1290              }
1291          }
1292
1293        /* If a breakpoint was on the list more than once, we don't need to
1294           do anything.  */
1295        if (b->commands != cmd)
1296          {
1297            validate_commands_for_breakpoint (b, cmd.get ());
1298            b->commands = cmd;
1299            observer_notify_breakpoint_modified (b);
1300          }
1301      });
1302
1303   if (cmd == NULL)
1304     error (_("No breakpoints specified."));
1305 }
1306
1307 static void
1308 commands_command (char *arg, int from_tty)
1309 {
1310   commands_command_1 (arg, from_tty, NULL);
1311 }
1312
1313 /* Like commands_command, but instead of reading the commands from
1314    input stream, takes them from an already parsed command structure.
1315
1316    This is used by cli-script.c to DTRT with breakpoint commands
1317    that are part of if and while bodies.  */
1318 enum command_control_type
1319 commands_from_control_command (const char *arg, struct command_line *cmd)
1320 {
1321   commands_command_1 (arg, 0, cmd);
1322   return simple_control;
1323 }
1324
1325 /* Return non-zero if BL->TARGET_INFO contains valid information.  */
1326
1327 static int
1328 bp_location_has_shadow (struct bp_location *bl)
1329 {
1330   if (bl->loc_type != bp_loc_software_breakpoint)
1331     return 0;
1332   if (!bl->inserted)
1333     return 0;
1334   if (bl->target_info.shadow_len == 0)
1335     /* BL isn't valid, or doesn't shadow memory.  */
1336     return 0;
1337   return 1;
1338 }
1339
1340 /* Update BUF, which is LEN bytes read from the target address
1341    MEMADDR, by replacing a memory breakpoint with its shadowed
1342    contents.
1343
1344    If READBUF is not NULL, this buffer must not overlap with the of
1345    the breakpoint location's shadow_contents buffer.  Otherwise, a
1346    failed assertion internal error will be raised.  */
1347
1348 static void
1349 one_breakpoint_xfer_memory (gdb_byte *readbuf, gdb_byte *writebuf,
1350                             const gdb_byte *writebuf_org,
1351                             ULONGEST memaddr, LONGEST len,
1352                             struct bp_target_info *target_info,
1353                             struct gdbarch *gdbarch)
1354 {
1355   /* Now do full processing of the found relevant range of elements.  */
1356   CORE_ADDR bp_addr = 0;
1357   int bp_size = 0;
1358   int bptoffset = 0;
1359
1360   if (!breakpoint_address_match (target_info->placed_address_space, 0,
1361                                  current_program_space->aspace, 0))
1362     {
1363       /* The breakpoint is inserted in a different address space.  */
1364       return;
1365     }
1366
1367   /* Addresses and length of the part of the breakpoint that
1368      we need to copy.  */
1369   bp_addr = target_info->placed_address;
1370   bp_size = target_info->shadow_len;
1371
1372   if (bp_addr + bp_size <= memaddr)
1373     {
1374       /* The breakpoint is entirely before the chunk of memory we are
1375          reading.  */
1376       return;
1377     }
1378
1379   if (bp_addr >= memaddr + len)
1380     {
1381       /* The breakpoint is entirely after the chunk of memory we are
1382          reading.  */
1383       return;
1384     }
1385
1386   /* Offset within shadow_contents.  */
1387   if (bp_addr < memaddr)
1388     {
1389       /* Only copy the second part of the breakpoint.  */
1390       bp_size -= memaddr - bp_addr;
1391       bptoffset = memaddr - bp_addr;
1392       bp_addr = memaddr;
1393     }
1394
1395   if (bp_addr + bp_size > memaddr + len)
1396     {
1397       /* Only copy the first part of the breakpoint.  */
1398       bp_size -= (bp_addr + bp_size) - (memaddr + len);
1399     }
1400
1401   if (readbuf != NULL)
1402     {
1403       /* Verify that the readbuf buffer does not overlap with the
1404          shadow_contents buffer.  */
1405       gdb_assert (target_info->shadow_contents >= readbuf + len
1406                   || readbuf >= (target_info->shadow_contents
1407                                  + target_info->shadow_len));
1408
1409       /* Update the read buffer with this inserted breakpoint's
1410          shadow.  */
1411       memcpy (readbuf + bp_addr - memaddr,
1412               target_info->shadow_contents + bptoffset, bp_size);
1413     }
1414   else
1415     {
1416       const unsigned char *bp;
1417       CORE_ADDR addr = target_info->reqstd_address;
1418       int placed_size;
1419
1420       /* Update the shadow with what we want to write to memory.  */
1421       memcpy (target_info->shadow_contents + bptoffset,
1422               writebuf_org + bp_addr - memaddr, bp_size);
1423
1424       /* Determine appropriate breakpoint contents and size for this
1425          address.  */
1426       bp = gdbarch_breakpoint_from_pc (gdbarch, &addr, &placed_size);
1427
1428       /* Update the final write buffer with this inserted
1429          breakpoint's INSN.  */
1430       memcpy (writebuf + bp_addr - memaddr, bp + bptoffset, bp_size);
1431     }
1432 }
1433
1434 /* Update BUF, which is LEN bytes read from the target address MEMADDR,
1435    by replacing any memory breakpoints with their shadowed contents.
1436
1437    If READBUF is not NULL, this buffer must not overlap with any of
1438    the breakpoint location's shadow_contents buffers.  Otherwise,
1439    a failed assertion internal error will be raised.
1440
1441    The range of shadowed area by each bp_location is:
1442      bl->address - bp_locations_placed_address_before_address_max
1443      up to bl->address + bp_locations_shadow_len_after_address_max
1444    The range we were requested to resolve shadows for is:
1445      memaddr ... memaddr + len
1446    Thus the safe cutoff boundaries for performance optimization are
1447      memaddr + len <= (bl->address
1448                        - bp_locations_placed_address_before_address_max)
1449    and:
1450      bl->address + bp_locations_shadow_len_after_address_max <= memaddr  */
1451
1452 void
1453 breakpoint_xfer_memory (gdb_byte *readbuf, gdb_byte *writebuf,
1454                         const gdb_byte *writebuf_org,
1455                         ULONGEST memaddr, LONGEST len)
1456 {
1457   /* Left boundary, right boundary and median element of our binary
1458      search.  */
1459   unsigned bc_l, bc_r, bc;
1460
1461   /* Find BC_L which is a leftmost element which may affect BUF
1462      content.  It is safe to report lower value but a failure to
1463      report higher one.  */
1464
1465   bc_l = 0;
1466   bc_r = bp_locations_count;
1467   while (bc_l + 1 < bc_r)
1468     {
1469       struct bp_location *bl;
1470
1471       bc = (bc_l + bc_r) / 2;
1472       bl = bp_locations[bc];
1473
1474       /* Check first BL->ADDRESS will not overflow due to the added
1475          constant.  Then advance the left boundary only if we are sure
1476          the BC element can in no way affect the BUF content (MEMADDR
1477          to MEMADDR + LEN range).
1478
1479          Use the BP_LOCATIONS_SHADOW_LEN_AFTER_ADDRESS_MAX safety
1480          offset so that we cannot miss a breakpoint with its shadow
1481          range tail still reaching MEMADDR.  */
1482
1483       if ((bl->address + bp_locations_shadow_len_after_address_max
1484            >= bl->address)
1485           && (bl->address + bp_locations_shadow_len_after_address_max
1486               <= memaddr))
1487         bc_l = bc;
1488       else
1489         bc_r = bc;
1490     }
1491
1492   /* Due to the binary search above, we need to make sure we pick the
1493      first location that's at BC_L's address.  E.g., if there are
1494      multiple locations at the same address, BC_L may end up pointing
1495      at a duplicate location, and miss the "master"/"inserted"
1496      location.  Say, given locations L1, L2 and L3 at addresses A and
1497      B:
1498
1499       L1@A, L2@A, L3@B, ...
1500
1501      BC_L could end up pointing at location L2, while the "master"
1502      location could be L1.  Since the `loc->inserted' flag is only set
1503      on "master" locations, we'd forget to restore the shadow of L1
1504      and L2.  */
1505   while (bc_l > 0
1506          && bp_locations[bc_l]->address == bp_locations[bc_l - 1]->address)
1507     bc_l--;
1508
1509   /* Now do full processing of the found relevant range of elements.  */
1510
1511   for (bc = bc_l; bc < bp_locations_count; bc++)
1512   {
1513     struct bp_location *bl = bp_locations[bc];
1514
1515     /* bp_location array has BL->OWNER always non-NULL.  */
1516     if (bl->owner->type == bp_none)
1517       warning (_("reading through apparently deleted breakpoint #%d?"),
1518                bl->owner->number);
1519
1520     /* Performance optimization: any further element can no longer affect BUF
1521        content.  */
1522
1523     if (bl->address >= bp_locations_placed_address_before_address_max
1524         && memaddr + len <= (bl->address
1525                              - bp_locations_placed_address_before_address_max))
1526       break;
1527
1528     if (!bp_location_has_shadow (bl))
1529       continue;
1530
1531     one_breakpoint_xfer_memory (readbuf, writebuf, writebuf_org,
1532                                 memaddr, len, &bl->target_info, bl->gdbarch);
1533   }
1534 }
1535
1536 \f
1537
1538 /* Return true if BPT is either a software breakpoint or a hardware
1539    breakpoint.  */
1540
1541 int
1542 is_breakpoint (const struct breakpoint *bpt)
1543 {
1544   return (bpt->type == bp_breakpoint
1545           || bpt->type == bp_hardware_breakpoint
1546           || bpt->type == bp_dprintf);
1547 }
1548
1549 /* Return true if BPT is of any hardware watchpoint kind.  */
1550
1551 static int
1552 is_hardware_watchpoint (const struct breakpoint *bpt)
1553 {
1554   return (bpt->type == bp_hardware_watchpoint
1555           || bpt->type == bp_read_watchpoint
1556           || bpt->type == bp_access_watchpoint);
1557 }
1558
1559 /* Return true if BPT is of any watchpoint kind, hardware or
1560    software.  */
1561
1562 int
1563 is_watchpoint (const struct breakpoint *bpt)
1564 {
1565   return (is_hardware_watchpoint (bpt)
1566           || bpt->type == bp_watchpoint);
1567 }
1568
1569 /* Returns true if the current thread and its running state are safe
1570    to evaluate or update watchpoint B.  Watchpoints on local
1571    expressions need to be evaluated in the context of the thread that
1572    was current when the watchpoint was created, and, that thread needs
1573    to be stopped to be able to select the correct frame context.
1574    Watchpoints on global expressions can be evaluated on any thread,
1575    and in any state.  It is presently left to the target allowing
1576    memory accesses when threads are running.  */
1577
1578 static int
1579 watchpoint_in_thread_scope (struct watchpoint *b)
1580 {
1581   return (b->pspace == current_program_space
1582           && (ptid_equal (b->watchpoint_thread, null_ptid)
1583               || (ptid_equal (inferior_ptid, b->watchpoint_thread)
1584                   && !is_executing (inferior_ptid))));
1585 }
1586
1587 /* Set watchpoint B to disp_del_at_next_stop, even including its possible
1588    associated bp_watchpoint_scope breakpoint.  */
1589
1590 static void
1591 watchpoint_del_at_next_stop (struct watchpoint *w)
1592 {
1593   if (w->related_breakpoint != w)
1594     {
1595       gdb_assert (w->related_breakpoint->type == bp_watchpoint_scope);
1596       gdb_assert (w->related_breakpoint->related_breakpoint == w);
1597       w->related_breakpoint->disposition = disp_del_at_next_stop;
1598       w->related_breakpoint->related_breakpoint = w->related_breakpoint;
1599       w->related_breakpoint = w;
1600     }
1601   w->disposition = disp_del_at_next_stop;
1602 }
1603
1604 /* Extract a bitfield value from value VAL using the bit parameters contained in
1605    watchpoint W.  */
1606
1607 static struct value *
1608 extract_bitfield_from_watchpoint_value (struct watchpoint *w, struct value *val)
1609 {
1610   struct value *bit_val;
1611
1612   if (val == NULL)
1613     return NULL;
1614
1615   bit_val = allocate_value (value_type (val));
1616
1617   unpack_value_bitfield (bit_val,
1618                          w->val_bitpos,
1619                          w->val_bitsize,
1620                          value_contents_for_printing (val),
1621                          value_offset (val),
1622                          val);
1623
1624   return bit_val;
1625 }
1626
1627 /* Allocate a dummy location and add it to B, which must be a software
1628    watchpoint.  This is required because even if a software watchpoint
1629    is not watching any memory, bpstat_stop_status requires a location
1630    to be able to report stops.  */
1631
1632 static void
1633 software_watchpoint_add_no_memory_location (struct breakpoint *b,
1634                                             struct program_space *pspace)
1635 {
1636   gdb_assert (b->type == bp_watchpoint && b->loc == NULL);
1637
1638   b->loc = allocate_bp_location (b);
1639   b->loc->pspace = pspace;
1640   b->loc->address = -1;
1641   b->loc->length = -1;
1642 }
1643
1644 /* Returns true if B is a software watchpoint that is not watching any
1645    memory (e.g., "watch $pc").  */
1646
1647 static int
1648 is_no_memory_software_watchpoint (struct breakpoint *b)
1649 {
1650   return (b->type == bp_watchpoint
1651           && b->loc != NULL
1652           && b->loc->next == NULL
1653           && b->loc->address == -1
1654           && b->loc->length == -1);
1655 }
1656
1657 /* Assuming that B is a watchpoint:
1658    - Reparse watchpoint expression, if REPARSE is non-zero
1659    - Evaluate expression and store the result in B->val
1660    - Evaluate the condition if there is one, and store the result
1661      in b->loc->cond.
1662    - Update the list of values that must be watched in B->loc.
1663
1664    If the watchpoint disposition is disp_del_at_next_stop, then do
1665    nothing.  If this is local watchpoint that is out of scope, delete
1666    it.
1667
1668    Even with `set breakpoint always-inserted on' the watchpoints are
1669    removed + inserted on each stop here.  Normal breakpoints must
1670    never be removed because they might be missed by a running thread
1671    when debugging in non-stop mode.  On the other hand, hardware
1672    watchpoints (is_hardware_watchpoint; processed here) are specific
1673    to each LWP since they are stored in each LWP's hardware debug
1674    registers.  Therefore, such LWP must be stopped first in order to
1675    be able to modify its hardware watchpoints.
1676
1677    Hardware watchpoints must be reset exactly once after being
1678    presented to the user.  It cannot be done sooner, because it would
1679    reset the data used to present the watchpoint hit to the user.  And
1680    it must not be done later because it could display the same single
1681    watchpoint hit during multiple GDB stops.  Note that the latter is
1682    relevant only to the hardware watchpoint types bp_read_watchpoint
1683    and bp_access_watchpoint.  False hit by bp_hardware_watchpoint is
1684    not user-visible - its hit is suppressed if the memory content has
1685    not changed.
1686
1687    The following constraints influence the location where we can reset
1688    hardware watchpoints:
1689
1690    * target_stopped_by_watchpoint and target_stopped_data_address are
1691      called several times when GDB stops.
1692
1693    [linux] 
1694    * Multiple hardware watchpoints can be hit at the same time,
1695      causing GDB to stop.  GDB only presents one hardware watchpoint
1696      hit at a time as the reason for stopping, and all the other hits
1697      are presented later, one after the other, each time the user
1698      requests the execution to be resumed.  Execution is not resumed
1699      for the threads still having pending hit event stored in
1700      LWP_INFO->STATUS.  While the watchpoint is already removed from
1701      the inferior on the first stop the thread hit event is kept being
1702      reported from its cached value by linux_nat_stopped_data_address
1703      until the real thread resume happens after the watchpoint gets
1704      presented and thus its LWP_INFO->STATUS gets reset.
1705
1706    Therefore the hardware watchpoint hit can get safely reset on the
1707    watchpoint removal from inferior.  */
1708
1709 static void
1710 update_watchpoint (struct watchpoint *b, int reparse)
1711 {
1712   int within_current_scope;
1713   struct frame_id saved_frame_id;
1714   int frame_saved;
1715
1716   /* If this is a local watchpoint, we only want to check if the
1717      watchpoint frame is in scope if the current thread is the thread
1718      that was used to create the watchpoint.  */
1719   if (!watchpoint_in_thread_scope (b))
1720     return;
1721
1722   if (b->disposition == disp_del_at_next_stop)
1723     return;
1724  
1725   frame_saved = 0;
1726
1727   /* Determine if the watchpoint is within scope.  */
1728   if (b->exp_valid_block == NULL)
1729     within_current_scope = 1;
1730   else
1731     {
1732       struct frame_info *fi = get_current_frame ();
1733       struct gdbarch *frame_arch = get_frame_arch (fi);
1734       CORE_ADDR frame_pc = get_frame_pc (fi);
1735
1736       /* If we're at a point where the stack has been destroyed
1737          (e.g. in a function epilogue), unwinding may not work
1738          properly. Do not attempt to recreate locations at this
1739          point.  See similar comments in watchpoint_check.  */
1740       if (gdbarch_stack_frame_destroyed_p (frame_arch, frame_pc))
1741         return;
1742
1743       /* Save the current frame's ID so we can restore it after
1744          evaluating the watchpoint expression on its own frame.  */
1745       /* FIXME drow/2003-09-09: It would be nice if evaluate_expression
1746          took a frame parameter, so that we didn't have to change the
1747          selected frame.  */
1748       frame_saved = 1;
1749       saved_frame_id = get_frame_id (get_selected_frame (NULL));
1750
1751       fi = frame_find_by_id (b->watchpoint_frame);
1752       within_current_scope = (fi != NULL);
1753       if (within_current_scope)
1754         select_frame (fi);
1755     }
1756
1757   /* We don't free locations.  They are stored in the bp_location array
1758      and update_global_location_list will eventually delete them and
1759      remove breakpoints if needed.  */
1760   b->loc = NULL;
1761
1762   if (within_current_scope && reparse)
1763     {
1764       const char *s;
1765
1766       b->exp.reset ();
1767       s = b->exp_string_reparse ? b->exp_string_reparse : b->exp_string;
1768       b->exp = parse_exp_1 (&s, 0, b->exp_valid_block, 0);
1769       /* If the meaning of expression itself changed, the old value is
1770          no longer relevant.  We don't want to report a watchpoint hit
1771          to the user when the old value and the new value may actually
1772          be completely different objects.  */
1773       value_free (b->val);
1774       b->val = NULL;
1775       b->val_valid = 0;
1776
1777       /* Note that unlike with breakpoints, the watchpoint's condition
1778          expression is stored in the breakpoint object, not in the
1779          locations (re)created below.  */
1780       if (b->cond_string != NULL)
1781         {
1782           b->cond_exp.reset ();
1783
1784           s = b->cond_string;
1785           b->cond_exp = parse_exp_1 (&s, 0, b->cond_exp_valid_block, 0);
1786         }
1787     }
1788
1789   /* If we failed to parse the expression, for example because
1790      it refers to a global variable in a not-yet-loaded shared library,
1791      don't try to insert watchpoint.  We don't automatically delete
1792      such watchpoint, though, since failure to parse expression
1793      is different from out-of-scope watchpoint.  */
1794   if (!target_has_execution)
1795     {
1796       /* Without execution, memory can't change.  No use to try and
1797          set watchpoint locations.  The watchpoint will be reset when
1798          the target gains execution, through breakpoint_re_set.  */
1799       if (!can_use_hw_watchpoints)
1800         {
1801           if (b->ops->works_in_software_mode (b))
1802             b->type = bp_watchpoint;
1803           else
1804             error (_("Can't set read/access watchpoint when "
1805                      "hardware watchpoints are disabled."));
1806         }
1807     }
1808   else if (within_current_scope && b->exp)
1809     {
1810       int pc = 0;
1811       struct value *val_chain, *v, *result, *next;
1812       struct program_space *frame_pspace;
1813
1814       fetch_subexp_value (b->exp.get (), &pc, &v, &result, &val_chain, 0);
1815
1816       /* Avoid setting b->val if it's already set.  The meaning of
1817          b->val is 'the last value' user saw, and we should update
1818          it only if we reported that last value to user.  As it
1819          happens, the code that reports it updates b->val directly.
1820          We don't keep track of the memory value for masked
1821          watchpoints.  */
1822       if (!b->val_valid && !is_masked_watchpoint (b))
1823         {
1824           if (b->val_bitsize != 0)
1825             {
1826               v = extract_bitfield_from_watchpoint_value (b, v);
1827               if (v != NULL)
1828                 release_value (v);
1829             }
1830           b->val = v;
1831           b->val_valid = 1;
1832         }
1833
1834       frame_pspace = get_frame_program_space (get_selected_frame (NULL));
1835
1836       /* Look at each value on the value chain.  */
1837       for (v = val_chain; v; v = value_next (v))
1838         {
1839           /* If it's a memory location, and GDB actually needed
1840              its contents to evaluate the expression, then we
1841              must watch it.  If the first value returned is
1842              still lazy, that means an error occurred reading it;
1843              watch it anyway in case it becomes readable.  */
1844           if (VALUE_LVAL (v) == lval_memory
1845               && (v == val_chain || ! value_lazy (v)))
1846             {
1847               struct type *vtype = check_typedef (value_type (v));
1848
1849               /* We only watch structs and arrays if user asked
1850                  for it explicitly, never if they just happen to
1851                  appear in the middle of some value chain.  */
1852               if (v == result
1853                   || (TYPE_CODE (vtype) != TYPE_CODE_STRUCT
1854                       && TYPE_CODE (vtype) != TYPE_CODE_ARRAY))
1855                 {
1856                   CORE_ADDR addr;
1857                   enum target_hw_bp_type type;
1858                   struct bp_location *loc, **tmp;
1859                   int bitpos = 0, bitsize = 0;
1860
1861                   if (value_bitsize (v) != 0)
1862                     {
1863                       /* Extract the bit parameters out from the bitfield
1864                          sub-expression.  */
1865                       bitpos = value_bitpos (v);
1866                       bitsize = value_bitsize (v);
1867                     }
1868                   else if (v == result && b->val_bitsize != 0)
1869                     {
1870                      /* If VAL_BITSIZE != 0 then RESULT is actually a bitfield
1871                         lvalue whose bit parameters are saved in the fields
1872                         VAL_BITPOS and VAL_BITSIZE.  */
1873                       bitpos = b->val_bitpos;
1874                       bitsize = b->val_bitsize;
1875                     }
1876
1877                   addr = value_address (v);
1878                   if (bitsize != 0)
1879                     {
1880                       /* Skip the bytes that don't contain the bitfield.  */
1881                       addr += bitpos / 8;
1882                     }
1883
1884                   type = hw_write;
1885                   if (b->type == bp_read_watchpoint)
1886                     type = hw_read;
1887                   else if (b->type == bp_access_watchpoint)
1888                     type = hw_access;
1889
1890                   loc = allocate_bp_location (b);
1891                   for (tmp = &(b->loc); *tmp != NULL; tmp = &((*tmp)->next))
1892                     ;
1893                   *tmp = loc;
1894                   loc->gdbarch = get_type_arch (value_type (v));
1895
1896                   loc->pspace = frame_pspace;
1897                   loc->address = addr;
1898
1899                   if (bitsize != 0)
1900                     {
1901                       /* Just cover the bytes that make up the bitfield.  */
1902                       loc->length = ((bitpos % 8) + bitsize + 7) / 8;
1903                     }
1904                   else
1905                     loc->length = TYPE_LENGTH (value_type (v));
1906
1907                   loc->watchpoint_type = type;
1908                 }
1909             }
1910         }
1911
1912       /* Change the type of breakpoint between hardware assisted or
1913          an ordinary watchpoint depending on the hardware support
1914          and free hardware slots.  REPARSE is set when the inferior
1915          is started.  */
1916       if (reparse)
1917         {
1918           int reg_cnt;
1919           enum bp_loc_type loc_type;
1920           struct bp_location *bl;
1921
1922           reg_cnt = can_use_hardware_watchpoint (val_chain);
1923
1924           if (reg_cnt)
1925             {
1926               int i, target_resources_ok, other_type_used;
1927               enum bptype type;
1928
1929               /* Use an exact watchpoint when there's only one memory region to be
1930                  watched, and only one debug register is needed to watch it.  */
1931               b->exact = target_exact_watchpoints && reg_cnt == 1;
1932
1933               /* We need to determine how many resources are already
1934                  used for all other hardware watchpoints plus this one
1935                  to see if we still have enough resources to also fit
1936                  this watchpoint in as well.  */
1937
1938               /* If this is a software watchpoint, we try to turn it
1939                  to a hardware one -- count resources as if B was of
1940                  hardware watchpoint type.  */
1941               type = b->type;
1942               if (type == bp_watchpoint)
1943                 type = bp_hardware_watchpoint;
1944
1945               /* This watchpoint may or may not have been placed on
1946                  the list yet at this point (it won't be in the list
1947                  if we're trying to create it for the first time,
1948                  through watch_command), so always account for it
1949                  manually.  */
1950
1951               /* Count resources used by all watchpoints except B.  */
1952               i = hw_watchpoint_used_count_others (b, type, &other_type_used);
1953
1954               /* Add in the resources needed for B.  */
1955               i += hw_watchpoint_use_count (b);
1956
1957               target_resources_ok
1958                 = target_can_use_hardware_watchpoint (type, i, other_type_used);
1959               if (target_resources_ok <= 0)
1960                 {
1961                   int sw_mode = b->ops->works_in_software_mode (b);
1962
1963                   if (target_resources_ok == 0 && !sw_mode)
1964                     error (_("Target does not support this type of "
1965                              "hardware watchpoint."));
1966                   else if (target_resources_ok < 0 && !sw_mode)
1967                     error (_("There are not enough available hardware "
1968                              "resources for this watchpoint."));
1969
1970                   /* Downgrade to software watchpoint.  */
1971                   b->type = bp_watchpoint;
1972                 }
1973               else
1974                 {
1975                   /* If this was a software watchpoint, we've just
1976                      found we have enough resources to turn it to a
1977                      hardware watchpoint.  Otherwise, this is a
1978                      nop.  */
1979                   b->type = type;
1980                 }
1981             }
1982           else if (!b->ops->works_in_software_mode (b))
1983             {
1984               if (!can_use_hw_watchpoints)
1985                 error (_("Can't set read/access watchpoint when "
1986                          "hardware watchpoints are disabled."));
1987               else
1988                 error (_("Expression cannot be implemented with "
1989                          "read/access watchpoint."));
1990             }
1991           else
1992             b->type = bp_watchpoint;
1993
1994           loc_type = (b->type == bp_watchpoint? bp_loc_other
1995                       : bp_loc_hardware_watchpoint);
1996           for (bl = b->loc; bl; bl = bl->next)
1997             bl->loc_type = loc_type;
1998         }
1999
2000       for (v = val_chain; v; v = next)
2001         {
2002           next = value_next (v);
2003           if (v != b->val)
2004             value_free (v);
2005         }
2006
2007       /* If a software watchpoint is not watching any memory, then the
2008          above left it without any location set up.  But,
2009          bpstat_stop_status requires a location to be able to report
2010          stops, so make sure there's at least a dummy one.  */
2011       if (b->type == bp_watchpoint && b->loc == NULL)
2012         software_watchpoint_add_no_memory_location (b, frame_pspace);
2013     }
2014   else if (!within_current_scope)
2015     {
2016       printf_filtered (_("\
2017 Watchpoint %d deleted because the program has left the block\n\
2018 in which its expression is valid.\n"),
2019                        b->number);
2020       watchpoint_del_at_next_stop (b);
2021     }
2022
2023   /* Restore the selected frame.  */
2024   if (frame_saved)
2025     select_frame (frame_find_by_id (saved_frame_id));
2026 }
2027
2028
2029 /* Returns 1 iff breakpoint location should be
2030    inserted in the inferior.  We don't differentiate the type of BL's owner
2031    (breakpoint vs. tracepoint), although insert_location in tracepoint's
2032    breakpoint_ops is not defined, because in insert_bp_location,
2033    tracepoint's insert_location will not be called.  */
2034 static int
2035 should_be_inserted (struct bp_location *bl)
2036 {
2037   if (bl->owner == NULL || !breakpoint_enabled (bl->owner))
2038     return 0;
2039
2040   if (bl->owner->disposition == disp_del_at_next_stop)
2041     return 0;
2042
2043   if (!bl->enabled || bl->shlib_disabled || bl->duplicate)
2044     return 0;
2045
2046   if (user_breakpoint_p (bl->owner) && bl->pspace->executing_startup)
2047     return 0;
2048
2049   /* This is set for example, when we're attached to the parent of a
2050      vfork, and have detached from the child.  The child is running
2051      free, and we expect it to do an exec or exit, at which point the
2052      OS makes the parent schedulable again (and the target reports
2053      that the vfork is done).  Until the child is done with the shared
2054      memory region, do not insert breakpoints in the parent, otherwise
2055      the child could still trip on the parent's breakpoints.  Since
2056      the parent is blocked anyway, it won't miss any breakpoint.  */
2057   if (bl->pspace->breakpoints_not_allowed)
2058     return 0;
2059
2060   /* Don't insert a breakpoint if we're trying to step past its
2061      location, except if the breakpoint is a single-step breakpoint,
2062      and the breakpoint's thread is the thread which is stepping past
2063      a breakpoint.  */
2064   if ((bl->loc_type == bp_loc_software_breakpoint
2065        || bl->loc_type == bp_loc_hardware_breakpoint)
2066       && stepping_past_instruction_at (bl->pspace->aspace,
2067                                        bl->address)
2068       /* The single-step breakpoint may be inserted at the location
2069          we're trying to step if the instruction branches to itself.
2070          However, the instruction won't be executed at all and it may
2071          break the semantics of the instruction, for example, the
2072          instruction is a conditional branch or updates some flags.
2073          We can't fix it unless GDB is able to emulate the instruction
2074          or switch to displaced stepping.  */
2075       && !(bl->owner->type == bp_single_step
2076            && thread_is_stepping_over_breakpoint (bl->owner->thread)))
2077     {
2078       if (debug_infrun)
2079         {
2080           fprintf_unfiltered (gdb_stdlog,
2081                               "infrun: skipping breakpoint: "
2082                               "stepping past insn at: %s\n",
2083                               paddress (bl->gdbarch, bl->address));
2084         }
2085       return 0;
2086     }
2087
2088   /* Don't insert watchpoints if we're trying to step past the
2089      instruction that triggered one.  */
2090   if ((bl->loc_type == bp_loc_hardware_watchpoint)
2091       && stepping_past_nonsteppable_watchpoint ())
2092     {
2093       if (debug_infrun)
2094         {
2095           fprintf_unfiltered (gdb_stdlog,
2096                               "infrun: stepping past non-steppable watchpoint. "
2097                               "skipping watchpoint at %s:%d\n",
2098                               paddress (bl->gdbarch, bl->address),
2099                               bl->length);
2100         }
2101       return 0;
2102     }
2103
2104   return 1;
2105 }
2106
2107 /* Same as should_be_inserted but does the check assuming
2108    that the location is not duplicated.  */
2109
2110 static int
2111 unduplicated_should_be_inserted (struct bp_location *bl)
2112 {
2113   int result;
2114   const int save_duplicate = bl->duplicate;
2115
2116   bl->duplicate = 0;
2117   result = should_be_inserted (bl);
2118   bl->duplicate = save_duplicate;
2119   return result;
2120 }
2121
2122 /* Parses a conditional described by an expression COND into an
2123    agent expression bytecode suitable for evaluation
2124    by the bytecode interpreter.  Return NULL if there was
2125    any error during parsing.  */
2126
2127 static agent_expr_up
2128 parse_cond_to_aexpr (CORE_ADDR scope, struct expression *cond)
2129 {
2130   if (cond == NULL)
2131     return NULL;
2132
2133   agent_expr_up aexpr;
2134
2135   /* We don't want to stop processing, so catch any errors
2136      that may show up.  */
2137   TRY
2138     {
2139       aexpr = gen_eval_for_expr (scope, cond);
2140     }
2141
2142   CATCH (ex, RETURN_MASK_ERROR)
2143     {
2144       /* If we got here, it means the condition could not be parsed to a valid
2145          bytecode expression and thus can't be evaluated on the target's side.
2146          It's no use iterating through the conditions.  */
2147     }
2148   END_CATCH
2149
2150   /* We have a valid agent expression.  */
2151   return aexpr;
2152 }
2153
2154 /* Based on location BL, create a list of breakpoint conditions to be
2155    passed on to the target.  If we have duplicated locations with different
2156    conditions, we will add such conditions to the list.  The idea is that the
2157    target will evaluate the list of conditions and will only notify GDB when
2158    one of them is true.  */
2159
2160 static void
2161 build_target_condition_list (struct bp_location *bl)
2162 {
2163   struct bp_location **locp = NULL, **loc2p;
2164   int null_condition_or_parse_error = 0;
2165   int modified = bl->needs_update;
2166   struct bp_location *loc;
2167
2168   /* Release conditions left over from a previous insert.  */
2169   bl->target_info.conditions.clear ();
2170
2171   /* This is only meaningful if the target is
2172      evaluating conditions and if the user has
2173      opted for condition evaluation on the target's
2174      side.  */
2175   if (gdb_evaluates_breakpoint_condition_p ()
2176       || !target_supports_evaluation_of_breakpoint_conditions ())
2177     return;
2178
2179   /* Do a first pass to check for locations with no assigned
2180      conditions or conditions that fail to parse to a valid agent expression
2181      bytecode.  If any of these happen, then it's no use to send conditions
2182      to the target since this location will always trigger and generate a
2183      response back to GDB.  */
2184   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2185     {
2186       loc = (*loc2p);
2187       if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2188         {
2189           if (modified)
2190             {
2191               /* Re-parse the conditions since something changed.  In that
2192                  case we already freed the condition bytecodes (see
2193                  force_breakpoint_reinsertion).  We just
2194                  need to parse the condition to bytecodes again.  */
2195               loc->cond_bytecode = parse_cond_to_aexpr (bl->address,
2196                                                         loc->cond.get ());
2197             }
2198
2199           /* If we have a NULL bytecode expression, it means something
2200              went wrong or we have a null condition expression.  */
2201           if (!loc->cond_bytecode)
2202             {
2203               null_condition_or_parse_error = 1;
2204               break;
2205             }
2206         }
2207     }
2208
2209   /* If any of these happened, it means we will have to evaluate the conditions
2210      for the location's address on gdb's side.  It is no use keeping bytecodes
2211      for all the other duplicate locations, thus we free all of them here.
2212
2213      This is so we have a finer control over which locations' conditions are
2214      being evaluated by GDB or the remote stub.  */
2215   if (null_condition_or_parse_error)
2216     {
2217       ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2218         {
2219           loc = (*loc2p);
2220           if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2221             {
2222               /* Only go as far as the first NULL bytecode is
2223                  located.  */
2224               if (!loc->cond_bytecode)
2225                 return;
2226
2227               loc->cond_bytecode.reset ();
2228             }
2229         }
2230     }
2231
2232   /* No NULL conditions or failed bytecode generation.  Build a condition list
2233      for this location's address.  */
2234   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2235     {
2236       loc = (*loc2p);
2237       if (loc->cond
2238           && is_breakpoint (loc->owner)
2239           && loc->pspace->num == bl->pspace->num
2240           && loc->owner->enable_state == bp_enabled
2241           && loc->enabled)
2242         {
2243           /* Add the condition to the vector.  This will be used later
2244              to send the conditions to the target.  */
2245           bl->target_info.conditions.push_back (loc->cond_bytecode.get ());
2246         }
2247     }
2248
2249   return;
2250 }
2251
2252 /* Parses a command described by string CMD into an agent expression
2253    bytecode suitable for evaluation by the bytecode interpreter.
2254    Return NULL if there was any error during parsing.  */
2255
2256 static agent_expr_up
2257 parse_cmd_to_aexpr (CORE_ADDR scope, char *cmd)
2258 {
2259   struct cleanup *old_cleanups = 0;
2260   struct expression **argvec;
2261   const char *cmdrest;
2262   const char *format_start, *format_end;
2263   struct format_piece *fpieces;
2264   int nargs;
2265   struct gdbarch *gdbarch = get_current_arch ();
2266
2267   if (cmd == NULL)
2268     return NULL;
2269
2270   cmdrest = cmd;
2271
2272   if (*cmdrest == ',')
2273     ++cmdrest;
2274   cmdrest = skip_spaces (cmdrest);
2275
2276   if (*cmdrest++ != '"')
2277     error (_("No format string following the location"));
2278
2279   format_start = cmdrest;
2280
2281   fpieces = parse_format_string (&cmdrest);
2282
2283   old_cleanups = make_cleanup (free_format_pieces_cleanup, &fpieces);
2284
2285   format_end = cmdrest;
2286
2287   if (*cmdrest++ != '"')
2288     error (_("Bad format string, non-terminated '\"'."));
2289   
2290   cmdrest = skip_spaces (cmdrest);
2291
2292   if (!(*cmdrest == ',' || *cmdrest == '\0'))
2293     error (_("Invalid argument syntax"));
2294
2295   if (*cmdrest == ',')
2296     cmdrest++;
2297   cmdrest = skip_spaces (cmdrest);
2298
2299   /* For each argument, make an expression.  */
2300
2301   argvec = (struct expression **) alloca (strlen (cmd)
2302                                          * sizeof (struct expression *));
2303
2304   nargs = 0;
2305   while (*cmdrest != '\0')
2306     {
2307       const char *cmd1;
2308
2309       cmd1 = cmdrest;
2310       expression_up expr = parse_exp_1 (&cmd1, scope, block_for_pc (scope), 1);
2311       argvec[nargs++] = expr.release ();
2312       cmdrest = cmd1;
2313       if (*cmdrest == ',')
2314         ++cmdrest;
2315     }
2316
2317   agent_expr_up aexpr;
2318
2319   /* We don't want to stop processing, so catch any errors
2320      that may show up.  */
2321   TRY
2322     {
2323       aexpr = gen_printf (scope, gdbarch, 0, 0,
2324                           format_start, format_end - format_start,
2325                           fpieces, nargs, argvec);
2326     }
2327   CATCH (ex, RETURN_MASK_ERROR)
2328     {
2329       /* If we got here, it means the command could not be parsed to a valid
2330          bytecode expression and thus can't be evaluated on the target's side.
2331          It's no use iterating through the other commands.  */
2332     }
2333   END_CATCH
2334
2335   do_cleanups (old_cleanups);
2336
2337   /* We have a valid agent expression, return it.  */
2338   return aexpr;
2339 }
2340
2341 /* Based on location BL, create a list of breakpoint commands to be
2342    passed on to the target.  If we have duplicated locations with
2343    different commands, we will add any such to the list.  */
2344
2345 static void
2346 build_target_command_list (struct bp_location *bl)
2347 {
2348   struct bp_location **locp = NULL, **loc2p;
2349   int null_command_or_parse_error = 0;
2350   int modified = bl->needs_update;
2351   struct bp_location *loc;
2352
2353   /* Clear commands left over from a previous insert.  */
2354   bl->target_info.tcommands.clear ();
2355
2356   if (!target_can_run_breakpoint_commands ())
2357     return;
2358
2359   /* For now, limit to agent-style dprintf breakpoints.  */
2360   if (dprintf_style != dprintf_style_agent)
2361     return;
2362
2363   /* For now, if we have any duplicate location that isn't a dprintf,
2364      don't install the target-side commands, as that would make the
2365      breakpoint not be reported to the core, and we'd lose
2366      control.  */
2367   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2368     {
2369       loc = (*loc2p);
2370       if (is_breakpoint (loc->owner)
2371           && loc->pspace->num == bl->pspace->num
2372           && loc->owner->type != bp_dprintf)
2373         return;
2374     }
2375
2376   /* Do a first pass to check for locations with no assigned
2377      conditions or conditions that fail to parse to a valid agent expression
2378      bytecode.  If any of these happen, then it's no use to send conditions
2379      to the target since this location will always trigger and generate a
2380      response back to GDB.  */
2381   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2382     {
2383       loc = (*loc2p);
2384       if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2385         {
2386           if (modified)
2387             {
2388               /* Re-parse the commands since something changed.  In that
2389                  case we already freed the command bytecodes (see
2390                  force_breakpoint_reinsertion).  We just
2391                  need to parse the command to bytecodes again.  */
2392               loc->cmd_bytecode
2393                 = parse_cmd_to_aexpr (bl->address,
2394                                       loc->owner->extra_string);
2395             }
2396
2397           /* If we have a NULL bytecode expression, it means something
2398              went wrong or we have a null command expression.  */
2399           if (!loc->cmd_bytecode)
2400             {
2401               null_command_or_parse_error = 1;
2402               break;
2403             }
2404         }
2405     }
2406
2407   /* If anything failed, then we're not doing target-side commands,
2408      and so clean up.  */
2409   if (null_command_or_parse_error)
2410     {
2411       ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2412         {
2413           loc = (*loc2p);
2414           if (is_breakpoint (loc->owner)
2415               && loc->pspace->num == bl->pspace->num)
2416             {
2417               /* Only go as far as the first NULL bytecode is
2418                  located.  */
2419               if (loc->cmd_bytecode == NULL)
2420                 return;
2421
2422               loc->cmd_bytecode.reset ();
2423             }
2424         }
2425     }
2426
2427   /* No NULL commands or failed bytecode generation.  Build a command list
2428      for this location's address.  */
2429   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2430     {
2431       loc = (*loc2p);
2432       if (loc->owner->extra_string
2433           && is_breakpoint (loc->owner)
2434           && loc->pspace->num == bl->pspace->num
2435           && loc->owner->enable_state == bp_enabled
2436           && loc->enabled)
2437         {
2438           /* Add the command to the vector.  This will be used later
2439              to send the commands to the target.  */
2440           bl->target_info.tcommands.push_back (loc->cmd_bytecode.get ());
2441         }
2442     }
2443
2444   bl->target_info.persist = 0;
2445   /* Maybe flag this location as persistent.  */
2446   if (bl->owner->type == bp_dprintf && disconnected_dprintf)
2447     bl->target_info.persist = 1;
2448 }
2449
2450 /* Return the kind of breakpoint on address *ADDR.  Get the kind
2451    of breakpoint according to ADDR except single-step breakpoint.
2452    Get the kind of single-step breakpoint according to the current
2453    registers state.  */
2454
2455 static int
2456 breakpoint_kind (struct bp_location *bl, CORE_ADDR *addr)
2457 {
2458   if (bl->owner->type == bp_single_step)
2459     {
2460       struct thread_info *thr = find_thread_global_id (bl->owner->thread);
2461       struct regcache *regcache;
2462
2463       regcache = get_thread_regcache (thr->ptid);
2464
2465       return gdbarch_breakpoint_kind_from_current_state (bl->gdbarch,
2466                                                          regcache, addr);
2467     }
2468   else
2469     return gdbarch_breakpoint_kind_from_pc (bl->gdbarch, addr);
2470 }
2471
2472 /* Insert a low-level "breakpoint" of some type.  BL is the breakpoint
2473    location.  Any error messages are printed to TMP_ERROR_STREAM; and
2474    DISABLED_BREAKS, and HW_BREAKPOINT_ERROR are used to report problems.
2475    Returns 0 for success, 1 if the bp_location type is not supported or
2476    -1 for failure.
2477
2478    NOTE drow/2003-09-09: This routine could be broken down to an
2479    object-style method for each breakpoint or catchpoint type.  */
2480 static int
2481 insert_bp_location (struct bp_location *bl,
2482                     struct ui_file *tmp_error_stream,
2483                     int *disabled_breaks,
2484                     int *hw_breakpoint_error,
2485                     int *hw_bp_error_explained_already)
2486 {
2487   enum errors bp_err = GDB_NO_ERROR;
2488   const char *bp_err_message = NULL;
2489
2490   if (!should_be_inserted (bl) || (bl->inserted && !bl->needs_update))
2491     return 0;
2492
2493   /* Note we don't initialize bl->target_info, as that wipes out
2494      the breakpoint location's shadow_contents if the breakpoint
2495      is still inserted at that location.  This in turn breaks
2496      target_read_memory which depends on these buffers when
2497      a memory read is requested at the breakpoint location:
2498      Once the target_info has been wiped, we fail to see that
2499      we have a breakpoint inserted at that address and thus
2500      read the breakpoint instead of returning the data saved in
2501      the breakpoint location's shadow contents.  */
2502   bl->target_info.reqstd_address = bl->address;
2503   bl->target_info.placed_address_space = bl->pspace->aspace;
2504   bl->target_info.length = bl->length;
2505
2506   /* When working with target-side conditions, we must pass all the conditions
2507      for the same breakpoint address down to the target since GDB will not
2508      insert those locations.  With a list of breakpoint conditions, the target
2509      can decide when to stop and notify GDB.  */
2510
2511   if (is_breakpoint (bl->owner))
2512     {
2513       build_target_condition_list (bl);
2514       build_target_command_list (bl);
2515       /* Reset the modification marker.  */
2516       bl->needs_update = 0;
2517     }
2518
2519   if (bl->loc_type == bp_loc_software_breakpoint
2520       || bl->loc_type == bp_loc_hardware_breakpoint)
2521     {
2522       if (bl->owner->type != bp_hardware_breakpoint)
2523         {
2524           /* If the explicitly specified breakpoint type
2525              is not hardware breakpoint, check the memory map to see
2526              if the breakpoint address is in read only memory or not.
2527
2528              Two important cases are:
2529              - location type is not hardware breakpoint, memory
2530              is readonly.  We change the type of the location to
2531              hardware breakpoint.
2532              - location type is hardware breakpoint, memory is
2533              read-write.  This means we've previously made the
2534              location hardware one, but then the memory map changed,
2535              so we undo.
2536              
2537              When breakpoints are removed, remove_breakpoints will use
2538              location types we've just set here, the only possible
2539              problem is that memory map has changed during running
2540              program, but it's not going to work anyway with current
2541              gdb.  */
2542           struct mem_region *mr 
2543             = lookup_mem_region (bl->target_info.reqstd_address);
2544           
2545           if (mr)
2546             {
2547               if (automatic_hardware_breakpoints)
2548                 {
2549                   enum bp_loc_type new_type;
2550                   
2551                   if (mr->attrib.mode != MEM_RW)
2552                     new_type = bp_loc_hardware_breakpoint;
2553                   else 
2554                     new_type = bp_loc_software_breakpoint;
2555                   
2556                   if (new_type != bl->loc_type)
2557                     {
2558                       static int said = 0;
2559
2560                       bl->loc_type = new_type;
2561                       if (!said)
2562                         {
2563                           fprintf_filtered (gdb_stdout,
2564                                             _("Note: automatically using "
2565                                               "hardware breakpoints for "
2566                                               "read-only addresses.\n"));
2567                           said = 1;
2568                         }
2569                     }
2570                 }
2571               else if (bl->loc_type == bp_loc_software_breakpoint
2572                        && mr->attrib.mode != MEM_RW)
2573                 {
2574                   fprintf_unfiltered (tmp_error_stream,
2575                                       _("Cannot insert breakpoint %d.\n"
2576                                         "Cannot set software breakpoint "
2577                                         "at read-only address %s\n"),
2578                                       bl->owner->number,
2579                                       paddress (bl->gdbarch, bl->address));
2580                   return 1;
2581                 }
2582             }
2583         }
2584         
2585       /* First check to see if we have to handle an overlay.  */
2586       if (overlay_debugging == ovly_off
2587           || bl->section == NULL
2588           || !(section_is_overlay (bl->section)))
2589         {
2590           /* No overlay handling: just set the breakpoint.  */
2591           TRY
2592             {
2593               int val;
2594
2595               val = bl->owner->ops->insert_location (bl);
2596               if (val)
2597                 bp_err = GENERIC_ERROR;
2598             }
2599           CATCH (e, RETURN_MASK_ALL)
2600             {
2601               bp_err = e.error;
2602               bp_err_message = e.message;
2603             }
2604           END_CATCH
2605         }
2606       else
2607         {
2608           /* This breakpoint is in an overlay section.
2609              Shall we set a breakpoint at the LMA?  */
2610           if (!overlay_events_enabled)
2611             {
2612               /* Yes -- overlay event support is not active, 
2613                  so we must try to set a breakpoint at the LMA.
2614                  This will not work for a hardware breakpoint.  */
2615               if (bl->loc_type == bp_loc_hardware_breakpoint)
2616                 warning (_("hardware breakpoint %d not supported in overlay!"),
2617                          bl->owner->number);
2618               else
2619                 {
2620                   CORE_ADDR addr = overlay_unmapped_address (bl->address,
2621                                                              bl->section);
2622                   /* Set a software (trap) breakpoint at the LMA.  */
2623                   bl->overlay_target_info = bl->target_info;
2624                   bl->overlay_target_info.reqstd_address = addr;
2625
2626                   /* No overlay handling: just set the breakpoint.  */
2627                   TRY
2628                     {
2629                       int val;
2630
2631                       bl->overlay_target_info.kind
2632                         = breakpoint_kind (bl, &addr);
2633                       bl->overlay_target_info.placed_address = addr;
2634                       val = target_insert_breakpoint (bl->gdbarch,
2635                                                       &bl->overlay_target_info);
2636                       if (val)
2637                         bp_err = GENERIC_ERROR;
2638                     }
2639                   CATCH (e, RETURN_MASK_ALL)
2640                     {
2641                       bp_err = e.error;
2642                       bp_err_message = e.message;
2643                     }
2644                   END_CATCH
2645
2646                   if (bp_err != GDB_NO_ERROR)
2647                     fprintf_unfiltered (tmp_error_stream,
2648                                         "Overlay breakpoint %d "
2649                                         "failed: in ROM?\n",
2650                                         bl->owner->number);
2651                 }
2652             }
2653           /* Shall we set a breakpoint at the VMA? */
2654           if (section_is_mapped (bl->section))
2655             {
2656               /* Yes.  This overlay section is mapped into memory.  */
2657               TRY
2658                 {
2659                   int val;
2660
2661                   val = bl->owner->ops->insert_location (bl);
2662                   if (val)
2663                     bp_err = GENERIC_ERROR;
2664                 }
2665               CATCH (e, RETURN_MASK_ALL)
2666                 {
2667                   bp_err = e.error;
2668                   bp_err_message = e.message;
2669                 }
2670               END_CATCH
2671             }
2672           else
2673             {
2674               /* No.  This breakpoint will not be inserted.  
2675                  No error, but do not mark the bp as 'inserted'.  */
2676               return 0;
2677             }
2678         }
2679
2680       if (bp_err != GDB_NO_ERROR)
2681         {
2682           /* Can't set the breakpoint.  */
2683
2684           /* In some cases, we might not be able to insert a
2685              breakpoint in a shared library that has already been
2686              removed, but we have not yet processed the shlib unload
2687              event.  Unfortunately, some targets that implement
2688              breakpoint insertion themselves can't tell why the
2689              breakpoint insertion failed (e.g., the remote target
2690              doesn't define error codes), so we must treat generic
2691              errors as memory errors.  */
2692           if ((bp_err == GENERIC_ERROR || bp_err == MEMORY_ERROR)
2693               && bl->loc_type == bp_loc_software_breakpoint
2694               && (solib_name_from_address (bl->pspace, bl->address)
2695                   || shared_objfile_contains_address_p (bl->pspace,
2696                                                         bl->address)))
2697             {
2698               /* See also: disable_breakpoints_in_shlibs.  */
2699               bl->shlib_disabled = 1;
2700               observer_notify_breakpoint_modified (bl->owner);
2701               if (!*disabled_breaks)
2702                 {
2703                   fprintf_unfiltered (tmp_error_stream, 
2704                                       "Cannot insert breakpoint %d.\n", 
2705                                       bl->owner->number);
2706                   fprintf_unfiltered (tmp_error_stream, 
2707                                       "Temporarily disabling shared "
2708                                       "library breakpoints:\n");
2709                 }
2710               *disabled_breaks = 1;
2711               fprintf_unfiltered (tmp_error_stream,
2712                                   "breakpoint #%d\n", bl->owner->number);
2713               return 0;
2714             }
2715           else
2716             {
2717               if (bl->loc_type == bp_loc_hardware_breakpoint)
2718                 {
2719                   *hw_breakpoint_error = 1;
2720                   *hw_bp_error_explained_already = bp_err_message != NULL;
2721                   fprintf_unfiltered (tmp_error_stream,
2722                                       "Cannot insert hardware breakpoint %d%s",
2723                                       bl->owner->number, bp_err_message ? ":" : ".\n");
2724                   if (bp_err_message != NULL)
2725                     fprintf_unfiltered (tmp_error_stream, "%s.\n", bp_err_message);
2726                 }
2727               else
2728                 {
2729                   if (bp_err_message == NULL)
2730                     {
2731                       std::string message
2732                         = memory_error_message (TARGET_XFER_E_IO,
2733                                                 bl->gdbarch, bl->address);
2734
2735                       fprintf_unfiltered (tmp_error_stream,
2736                                           "Cannot insert breakpoint %d.\n"
2737                                           "%s\n",
2738                                           bl->owner->number, message.c_str ());
2739                     }
2740                   else
2741                     {
2742                       fprintf_unfiltered (tmp_error_stream,
2743                                           "Cannot insert breakpoint %d: %s\n",
2744                                           bl->owner->number,
2745                                           bp_err_message);
2746                     }
2747                 }
2748               return 1;
2749
2750             }
2751         }
2752       else
2753         bl->inserted = 1;
2754
2755       return 0;
2756     }
2757
2758   else if (bl->loc_type == bp_loc_hardware_watchpoint
2759            /* NOTE drow/2003-09-08: This state only exists for removing
2760               watchpoints.  It's not clear that it's necessary...  */
2761            && bl->owner->disposition != disp_del_at_next_stop)
2762     {
2763       int val;
2764
2765       gdb_assert (bl->owner->ops != NULL
2766                   && bl->owner->ops->insert_location != NULL);
2767
2768       val = bl->owner->ops->insert_location (bl);
2769
2770       /* If trying to set a read-watchpoint, and it turns out it's not
2771          supported, try emulating one with an access watchpoint.  */
2772       if (val == 1 && bl->watchpoint_type == hw_read)
2773         {
2774           struct bp_location *loc, **loc_temp;
2775
2776           /* But don't try to insert it, if there's already another
2777              hw_access location that would be considered a duplicate
2778              of this one.  */
2779           ALL_BP_LOCATIONS (loc, loc_temp)
2780             if (loc != bl
2781                 && loc->watchpoint_type == hw_access
2782                 && watchpoint_locations_match (bl, loc))
2783               {
2784                 bl->duplicate = 1;
2785                 bl->inserted = 1;
2786                 bl->target_info = loc->target_info;
2787                 bl->watchpoint_type = hw_access;
2788                 val = 0;
2789                 break;
2790               }
2791
2792           if (val == 1)
2793             {
2794               bl->watchpoint_type = hw_access;
2795               val = bl->owner->ops->insert_location (bl);
2796
2797               if (val)
2798                 /* Back to the original value.  */
2799                 bl->watchpoint_type = hw_read;
2800             }
2801         }
2802
2803       bl->inserted = (val == 0);
2804     }
2805
2806   else if (bl->owner->type == bp_catchpoint)
2807     {
2808       int val;
2809
2810       gdb_assert (bl->owner->ops != NULL
2811                   && bl->owner->ops->insert_location != NULL);
2812
2813       val = bl->owner->ops->insert_location (bl);
2814       if (val)
2815         {
2816           bl->owner->enable_state = bp_disabled;
2817
2818           if (val == 1)
2819             warning (_("\
2820 Error inserting catchpoint %d: Your system does not support this type\n\
2821 of catchpoint."), bl->owner->number);
2822           else
2823             warning (_("Error inserting catchpoint %d."), bl->owner->number);
2824         }
2825
2826       bl->inserted = (val == 0);
2827
2828       /* We've already printed an error message if there was a problem
2829          inserting this catchpoint, and we've disabled the catchpoint,
2830          so just return success.  */
2831       return 0;
2832     }
2833
2834   return 0;
2835 }
2836
2837 /* This function is called when program space PSPACE is about to be
2838    deleted.  It takes care of updating breakpoints to not reference
2839    PSPACE anymore.  */
2840
2841 void
2842 breakpoint_program_space_exit (struct program_space *pspace)
2843 {
2844   struct breakpoint *b, *b_temp;
2845   struct bp_location *loc, **loc_temp;
2846
2847   /* Remove any breakpoint that was set through this program space.  */
2848   ALL_BREAKPOINTS_SAFE (b, b_temp)
2849     {
2850       if (b->pspace == pspace)
2851         delete_breakpoint (b);
2852     }
2853
2854   /* Breakpoints set through other program spaces could have locations
2855      bound to PSPACE as well.  Remove those.  */
2856   ALL_BP_LOCATIONS (loc, loc_temp)
2857     {
2858       struct bp_location *tmp;
2859
2860       if (loc->pspace == pspace)
2861         {
2862           /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
2863           if (loc->owner->loc == loc)
2864             loc->owner->loc = loc->next;
2865           else
2866             for (tmp = loc->owner->loc; tmp->next != NULL; tmp = tmp->next)
2867               if (tmp->next == loc)
2868                 {
2869                   tmp->next = loc->next;
2870                   break;
2871                 }
2872         }
2873     }
2874
2875   /* Now update the global location list to permanently delete the
2876      removed locations above.  */
2877   update_global_location_list (UGLL_DONT_INSERT);
2878 }
2879
2880 /* Make sure all breakpoints are inserted in inferior.
2881    Throws exception on any error.
2882    A breakpoint that is already inserted won't be inserted
2883    again, so calling this function twice is safe.  */
2884 void
2885 insert_breakpoints (void)
2886 {
2887   struct breakpoint *bpt;
2888
2889   ALL_BREAKPOINTS (bpt)
2890     if (is_hardware_watchpoint (bpt))
2891       {
2892         struct watchpoint *w = (struct watchpoint *) bpt;
2893
2894         update_watchpoint (w, 0 /* don't reparse.  */);
2895       }
2896
2897   /* Updating watchpoints creates new locations, so update the global
2898      location list.  Explicitly tell ugll to insert locations and
2899      ignore breakpoints_always_inserted_mode.  */
2900   update_global_location_list (UGLL_INSERT);
2901 }
2902
2903 /* Invoke CALLBACK for each of bp_location.  */
2904
2905 void
2906 iterate_over_bp_locations (walk_bp_location_callback callback)
2907 {
2908   struct bp_location *loc, **loc_tmp;
2909
2910   ALL_BP_LOCATIONS (loc, loc_tmp)
2911     {
2912       callback (loc, NULL);
2913     }
2914 }
2915
2916 /* This is used when we need to synch breakpoint conditions between GDB and the
2917    target.  It is the case with deleting and disabling of breakpoints when using
2918    always-inserted mode.  */
2919
2920 static void
2921 update_inserted_breakpoint_locations (void)
2922 {
2923   struct bp_location *bl, **blp_tmp;
2924   int error_flag = 0;
2925   int val = 0;
2926   int disabled_breaks = 0;
2927   int hw_breakpoint_error = 0;
2928   int hw_bp_details_reported = 0;
2929
2930   string_file tmp_error_stream;
2931
2932   /* Explicitly mark the warning -- this will only be printed if
2933      there was an error.  */
2934   tmp_error_stream.puts ("Warning:\n");
2935
2936   scoped_restore_current_pspace_and_thread restore_pspace_thread;
2937
2938   ALL_BP_LOCATIONS (bl, blp_tmp)
2939     {
2940       /* We only want to update software breakpoints and hardware
2941          breakpoints.  */
2942       if (!is_breakpoint (bl->owner))
2943         continue;
2944
2945       /* We only want to update locations that are already inserted
2946          and need updating.  This is to avoid unwanted insertion during
2947          deletion of breakpoints.  */
2948       if (!bl->inserted || (bl->inserted && !bl->needs_update))
2949         continue;
2950
2951       switch_to_program_space_and_thread (bl->pspace);
2952
2953       /* For targets that support global breakpoints, there's no need
2954          to select an inferior to insert breakpoint to.  In fact, even
2955          if we aren't attached to any process yet, we should still
2956          insert breakpoints.  */
2957       if (!gdbarch_has_global_breakpoints (target_gdbarch ())
2958           && ptid_equal (inferior_ptid, null_ptid))
2959         continue;
2960
2961       val = insert_bp_location (bl, &tmp_error_stream, &disabled_breaks,
2962                                     &hw_breakpoint_error, &hw_bp_details_reported);
2963       if (val)
2964         error_flag = val;
2965     }
2966
2967   if (error_flag)
2968     {
2969       target_terminal::ours_for_output ();
2970       error_stream (tmp_error_stream);
2971     }
2972 }
2973
2974 /* Used when starting or continuing the program.  */
2975
2976 static void
2977 insert_breakpoint_locations (void)
2978 {
2979   struct breakpoint *bpt;
2980   struct bp_location *bl, **blp_tmp;
2981   int error_flag = 0;
2982   int val = 0;
2983   int disabled_breaks = 0;
2984   int hw_breakpoint_error = 0;
2985   int hw_bp_error_explained_already = 0;
2986
2987   string_file tmp_error_stream;
2988
2989   /* Explicitly mark the warning -- this will only be printed if
2990      there was an error.  */
2991   tmp_error_stream.puts ("Warning:\n");
2992
2993   scoped_restore_current_pspace_and_thread restore_pspace_thread;
2994
2995   ALL_BP_LOCATIONS (bl, blp_tmp)
2996     {
2997       if (!should_be_inserted (bl) || (bl->inserted && !bl->needs_update))
2998         continue;
2999
3000       /* There is no point inserting thread-specific breakpoints if
3001          the thread no longer exists.  ALL_BP_LOCATIONS bp_location
3002          has BL->OWNER always non-NULL.  */
3003       if (bl->owner->thread != -1
3004           && !valid_global_thread_id (bl->owner->thread))
3005         continue;
3006
3007       switch_to_program_space_and_thread (bl->pspace);
3008
3009       /* For targets that support global breakpoints, there's no need
3010          to select an inferior to insert breakpoint to.  In fact, even
3011          if we aren't attached to any process yet, we should still
3012          insert breakpoints.  */
3013       if (!gdbarch_has_global_breakpoints (target_gdbarch ())
3014           && ptid_equal (inferior_ptid, null_ptid))
3015         continue;
3016
3017       val = insert_bp_location (bl, &tmp_error_stream, &disabled_breaks,
3018                                     &hw_breakpoint_error, &hw_bp_error_explained_already);
3019       if (val)
3020         error_flag = val;
3021     }
3022
3023   /* If we failed to insert all locations of a watchpoint, remove
3024      them, as half-inserted watchpoint is of limited use.  */
3025   ALL_BREAKPOINTS (bpt)  
3026     {
3027       int some_failed = 0;
3028       struct bp_location *loc;
3029
3030       if (!is_hardware_watchpoint (bpt))
3031         continue;
3032
3033       if (!breakpoint_enabled (bpt))
3034         continue;
3035
3036       if (bpt->disposition == disp_del_at_next_stop)
3037         continue;
3038       
3039       for (loc = bpt->loc; loc; loc = loc->next)
3040         if (!loc->inserted && should_be_inserted (loc))
3041           {
3042             some_failed = 1;
3043             break;
3044           }
3045       if (some_failed)
3046         {
3047           for (loc = bpt->loc; loc; loc = loc->next)
3048             if (loc->inserted)
3049               remove_breakpoint (loc);
3050
3051           hw_breakpoint_error = 1;
3052           tmp_error_stream.printf ("Could not insert "
3053                                    "hardware watchpoint %d.\n",
3054                                    bpt->number);
3055           error_flag = -1;
3056         }
3057     }
3058
3059   if (error_flag)
3060     {
3061       /* If a hardware breakpoint or watchpoint was inserted, add a
3062          message about possibly exhausted resources.  */
3063       if (hw_breakpoint_error && !hw_bp_error_explained_already)
3064         {
3065           tmp_error_stream.printf ("Could not insert hardware breakpoints:\n\
3066 You may have requested too many hardware breakpoints/watchpoints.\n");
3067         }
3068       target_terminal::ours_for_output ();
3069       error_stream (tmp_error_stream);
3070     }
3071 }
3072
3073 /* Used when the program stops.
3074    Returns zero if successful, or non-zero if there was a problem
3075    removing a breakpoint location.  */
3076
3077 int
3078 remove_breakpoints (void)
3079 {
3080   struct bp_location *bl, **blp_tmp;
3081   int val = 0;
3082
3083   ALL_BP_LOCATIONS (bl, blp_tmp)
3084   {
3085     if (bl->inserted && !is_tracepoint (bl->owner))
3086       val |= remove_breakpoint (bl);
3087   }
3088   return val;
3089 }
3090
3091 /* When a thread exits, remove breakpoints that are related to
3092    that thread.  */
3093
3094 static void
3095 remove_threaded_breakpoints (struct thread_info *tp, int silent)
3096 {
3097   struct breakpoint *b, *b_tmp;
3098
3099   ALL_BREAKPOINTS_SAFE (b, b_tmp)
3100     {
3101       if (b->thread == tp->global_num && user_breakpoint_p (b))
3102         {
3103           b->disposition = disp_del_at_next_stop;
3104
3105           printf_filtered (_("\
3106 Thread-specific breakpoint %d deleted - thread %s no longer in the thread list.\n"),
3107                            b->number, print_thread_id (tp));
3108
3109           /* Hide it from the user.  */
3110           b->number = 0;
3111        }
3112     }
3113 }
3114
3115 /* Remove breakpoints of process PID.  */
3116
3117 int
3118 remove_breakpoints_pid (int pid)
3119 {
3120   struct bp_location *bl, **blp_tmp;
3121   int val;
3122   struct inferior *inf = find_inferior_pid (pid);
3123
3124   ALL_BP_LOCATIONS (bl, blp_tmp)
3125   {
3126     if (bl->pspace != inf->pspace)
3127       continue;
3128
3129     if (bl->inserted && !bl->target_info.persist)
3130       {
3131         val = remove_breakpoint (bl);
3132         if (val != 0)
3133           return val;
3134       }
3135   }
3136   return 0;
3137 }
3138
3139 static int internal_breakpoint_number = -1;
3140
3141 /* Set the breakpoint number of B, depending on the value of INTERNAL.
3142    If INTERNAL is non-zero, the breakpoint number will be populated
3143    from internal_breakpoint_number and that variable decremented.
3144    Otherwise the breakpoint number will be populated from
3145    breakpoint_count and that value incremented.  Internal breakpoints
3146    do not set the internal var bpnum.  */
3147 static void
3148 set_breakpoint_number (int internal, struct breakpoint *b)
3149 {
3150   if (internal)
3151     b->number = internal_breakpoint_number--;
3152   else
3153     {
3154       set_breakpoint_count (breakpoint_count + 1);
3155       b->number = breakpoint_count;
3156     }
3157 }
3158
3159 static struct breakpoint *
3160 create_internal_breakpoint (struct gdbarch *gdbarch,
3161                             CORE_ADDR address, enum bptype type,
3162                             const struct breakpoint_ops *ops)
3163 {
3164   symtab_and_line sal;
3165   sal.pc = address;
3166   sal.section = find_pc_overlay (sal.pc);
3167   sal.pspace = current_program_space;
3168
3169   breakpoint *b = set_raw_breakpoint (gdbarch, sal, type, ops);
3170   b->number = internal_breakpoint_number--;
3171   b->disposition = disp_donttouch;
3172
3173   return b;
3174 }
3175
3176 static const char *const longjmp_names[] =
3177   {
3178     "longjmp", "_longjmp", "siglongjmp", "_siglongjmp"
3179   };
3180 #define NUM_LONGJMP_NAMES ARRAY_SIZE(longjmp_names)
3181
3182 /* Per-objfile data private to breakpoint.c.  */
3183 struct breakpoint_objfile_data
3184 {
3185   /* Minimal symbol for "_ovly_debug_event" (if any).  */
3186   struct bound_minimal_symbol overlay_msym {};
3187
3188   /* Minimal symbol(s) for "longjmp", "siglongjmp", etc. (if any).  */
3189   struct bound_minimal_symbol longjmp_msym[NUM_LONGJMP_NAMES] {};
3190
3191   /* True if we have looked for longjmp probes.  */
3192   int longjmp_searched = 0;
3193
3194   /* SystemTap probe points for longjmp (if any).  These are non-owning
3195      references.  */
3196   std::vector<probe *> longjmp_probes;
3197
3198   /* Minimal symbol for "std::terminate()" (if any).  */
3199   struct bound_minimal_symbol terminate_msym {};
3200
3201   /* Minimal symbol for "_Unwind_DebugHook" (if any).  */
3202   struct bound_minimal_symbol exception_msym {};
3203
3204   /* True if we have looked for exception probes.  */
3205   int exception_searched = 0;
3206
3207   /* SystemTap probe points for unwinding (if any).  These are non-owning
3208      references.  */
3209   std::vector<probe *> exception_probes;
3210 };
3211
3212 static const struct objfile_data *breakpoint_objfile_key;
3213
3214 /* Minimal symbol not found sentinel.  */
3215 static struct minimal_symbol msym_not_found;
3216
3217 /* Returns TRUE if MSYM point to the "not found" sentinel.  */
3218
3219 static int
3220 msym_not_found_p (const struct minimal_symbol *msym)
3221 {
3222   return msym == &msym_not_found;
3223 }
3224
3225 /* Return per-objfile data needed by breakpoint.c.
3226    Allocate the data if necessary.  */
3227
3228 static struct breakpoint_objfile_data *
3229 get_breakpoint_objfile_data (struct objfile *objfile)
3230 {
3231   struct breakpoint_objfile_data *bp_objfile_data;
3232
3233   bp_objfile_data = ((struct breakpoint_objfile_data *)
3234                      objfile_data (objfile, breakpoint_objfile_key));
3235   if (bp_objfile_data == NULL)
3236     {
3237       bp_objfile_data = new breakpoint_objfile_data ();
3238       set_objfile_data (objfile, breakpoint_objfile_key, bp_objfile_data);
3239     }
3240   return bp_objfile_data;
3241 }
3242
3243 static void
3244 free_breakpoint_objfile_data (struct objfile *obj, void *data)
3245 {
3246   struct breakpoint_objfile_data *bp_objfile_data
3247     = (struct breakpoint_objfile_data *) data;
3248
3249   delete bp_objfile_data;
3250 }
3251
3252 static void
3253 create_overlay_event_breakpoint (void)
3254 {
3255   struct objfile *objfile;
3256   const char *const func_name = "_ovly_debug_event";
3257
3258   ALL_OBJFILES (objfile)
3259     {
3260       struct breakpoint *b;
3261       struct breakpoint_objfile_data *bp_objfile_data;
3262       CORE_ADDR addr;
3263       struct explicit_location explicit_loc;
3264
3265       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3266
3267       if (msym_not_found_p (bp_objfile_data->overlay_msym.minsym))
3268         continue;
3269
3270       if (bp_objfile_data->overlay_msym.minsym == NULL)
3271         {
3272           struct bound_minimal_symbol m;
3273
3274           m = lookup_minimal_symbol_text (func_name, objfile);
3275           if (m.minsym == NULL)
3276             {
3277               /* Avoid future lookups in this objfile.  */
3278               bp_objfile_data->overlay_msym.minsym = &msym_not_found;
3279               continue;
3280             }
3281           bp_objfile_data->overlay_msym = m;
3282         }
3283
3284       addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->overlay_msym);
3285       b = create_internal_breakpoint (get_objfile_arch (objfile), addr,
3286                                       bp_overlay_event,
3287                                       &internal_breakpoint_ops);
3288       initialize_explicit_location (&explicit_loc);
3289       explicit_loc.function_name = ASTRDUP (func_name);
3290       b->location = new_explicit_location (&explicit_loc);
3291
3292       if (overlay_debugging == ovly_auto)
3293         {
3294           b->enable_state = bp_enabled;
3295           overlay_events_enabled = 1;
3296         }
3297       else
3298        {
3299          b->enable_state = bp_disabled;
3300          overlay_events_enabled = 0;
3301        }
3302     }
3303 }
3304
3305 static void
3306 create_longjmp_master_breakpoint (void)
3307 {
3308   struct program_space *pspace;
3309
3310   scoped_restore_current_program_space restore_pspace;
3311
3312   ALL_PSPACES (pspace)
3313   {
3314     struct objfile *objfile;
3315
3316     set_current_program_space (pspace);
3317
3318     ALL_OBJFILES (objfile)
3319     {
3320       int i;
3321       struct gdbarch *gdbarch;
3322       struct breakpoint_objfile_data *bp_objfile_data;
3323
3324       gdbarch = get_objfile_arch (objfile);
3325
3326       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3327
3328       if (!bp_objfile_data->longjmp_searched)
3329         {
3330           std::vector<probe *> ret
3331             = find_probes_in_objfile (objfile, "libc", "longjmp");
3332
3333           if (!ret.empty ())
3334             {
3335               /* We are only interested in checking one element.  */
3336               probe *p = ret[0];
3337
3338               if (!can_evaluate_probe_arguments (p))
3339                 {
3340                   /* We cannot use the probe interface here, because it does
3341                      not know how to evaluate arguments.  */
3342                   ret.clear ();
3343                 }
3344             }
3345           bp_objfile_data->longjmp_probes = ret;
3346           bp_objfile_data->longjmp_searched = 1;
3347         }
3348
3349       if (!bp_objfile_data->longjmp_probes.empty ())
3350         {
3351           struct gdbarch *gdbarch = get_objfile_arch (objfile);
3352
3353           for (probe *p : bp_objfile_data->longjmp_probes)
3354             {
3355               struct breakpoint *b;
3356
3357               b = create_internal_breakpoint (gdbarch,
3358                                               get_probe_address (p, objfile),
3359                                               bp_longjmp_master,
3360                                               &internal_breakpoint_ops);
3361               b->location = new_probe_location ("-probe-stap libc:longjmp");
3362               b->enable_state = bp_disabled;
3363             }
3364
3365           continue;
3366         }
3367
3368       if (!gdbarch_get_longjmp_target_p (gdbarch))
3369         continue;
3370
3371       for (i = 0; i < NUM_LONGJMP_NAMES; i++)
3372         {
3373           struct breakpoint *b;
3374           const char *func_name;
3375           CORE_ADDR addr;
3376           struct explicit_location explicit_loc;
3377
3378           if (msym_not_found_p (bp_objfile_data->longjmp_msym[i].minsym))
3379             continue;
3380
3381           func_name = longjmp_names[i];
3382           if (bp_objfile_data->longjmp_msym[i].minsym == NULL)
3383             {
3384               struct bound_minimal_symbol m;
3385
3386               m = lookup_minimal_symbol_text (func_name, objfile);
3387               if (m.minsym == NULL)
3388                 {
3389                   /* Prevent future lookups in this objfile.  */
3390                   bp_objfile_data->longjmp_msym[i].minsym = &msym_not_found;
3391                   continue;
3392                 }
3393               bp_objfile_data->longjmp_msym[i] = m;
3394             }
3395
3396           addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->longjmp_msym[i]);
3397           b = create_internal_breakpoint (gdbarch, addr, bp_longjmp_master,
3398                                           &internal_breakpoint_ops);
3399           initialize_explicit_location (&explicit_loc);
3400           explicit_loc.function_name = ASTRDUP (func_name);
3401           b->location = new_explicit_location (&explicit_loc);
3402           b->enable_state = bp_disabled;
3403         }
3404     }
3405   }
3406 }
3407
3408 /* Create a master std::terminate breakpoint.  */
3409 static void
3410 create_std_terminate_master_breakpoint (void)
3411 {
3412   struct program_space *pspace;
3413   const char *const func_name = "std::terminate()";
3414
3415   scoped_restore_current_program_space restore_pspace;
3416
3417   ALL_PSPACES (pspace)
3418   {
3419     struct objfile *objfile;
3420     CORE_ADDR addr;
3421
3422     set_current_program_space (pspace);
3423
3424     ALL_OBJFILES (objfile)
3425     {
3426       struct breakpoint *b;
3427       struct breakpoint_objfile_data *bp_objfile_data;
3428       struct explicit_location explicit_loc;
3429
3430       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3431
3432       if (msym_not_found_p (bp_objfile_data->terminate_msym.minsym))
3433         continue;
3434
3435       if (bp_objfile_data->terminate_msym.minsym == NULL)
3436         {
3437           struct bound_minimal_symbol m;
3438
3439           m = lookup_minimal_symbol (func_name, NULL, objfile);
3440           if (m.minsym == NULL || (MSYMBOL_TYPE (m.minsym) != mst_text
3441                                    && MSYMBOL_TYPE (m.minsym) != mst_file_text))
3442             {
3443               /* Prevent future lookups in this objfile.  */
3444               bp_objfile_data->terminate_msym.minsym = &msym_not_found;
3445               continue;
3446             }
3447           bp_objfile_data->terminate_msym = m;
3448         }
3449
3450       addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->terminate_msym);
3451       b = create_internal_breakpoint (get_objfile_arch (objfile), addr,
3452                                       bp_std_terminate_master,
3453                                       &internal_breakpoint_ops);
3454       initialize_explicit_location (&explicit_loc);
3455       explicit_loc.function_name = ASTRDUP (func_name);
3456       b->location = new_explicit_location (&explicit_loc);
3457       b->enable_state = bp_disabled;
3458     }
3459   }
3460 }
3461
3462 /* Install a master breakpoint on the unwinder's debug hook.  */
3463
3464 static void
3465 create_exception_master_breakpoint (void)
3466 {
3467   struct objfile *objfile;
3468   const char *const func_name = "_Unwind_DebugHook";
3469
3470   ALL_OBJFILES (objfile)
3471     {
3472       struct breakpoint *b;
3473       struct gdbarch *gdbarch;
3474       struct breakpoint_objfile_data *bp_objfile_data;
3475       CORE_ADDR addr;
3476       struct explicit_location explicit_loc;
3477
3478       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3479
3480       /* We prefer the SystemTap probe point if it exists.  */
3481       if (!bp_objfile_data->exception_searched)
3482         {
3483           std::vector<probe *> ret
3484             = find_probes_in_objfile (objfile, "libgcc", "unwind");
3485
3486           if (!ret.empty ())
3487             {
3488               /* We are only interested in checking one element.  */
3489               probe *p = ret[0];
3490
3491               if (!can_evaluate_probe_arguments (p))
3492                 {
3493                   /* We cannot use the probe interface here, because it does
3494                      not know how to evaluate arguments.  */
3495                   ret.clear ();
3496                 }
3497             }
3498           bp_objfile_data->exception_probes = ret;
3499           bp_objfile_data->exception_searched = 1;
3500         }
3501
3502       if (!bp_objfile_data->exception_probes.empty ())
3503         {
3504           struct gdbarch *gdbarch = get_objfile_arch (objfile);
3505
3506           for (probe *p : bp_objfile_data->exception_probes)
3507             {
3508               struct breakpoint *b;
3509
3510               b = create_internal_breakpoint (gdbarch,
3511                                               get_probe_address (p, objfile),
3512                                               bp_exception_master,
3513                                               &internal_breakpoint_ops);
3514               b->location = new_probe_location ("-probe-stap libgcc:unwind");
3515               b->enable_state = bp_disabled;
3516             }
3517
3518           continue;
3519         }
3520
3521       /* Otherwise, try the hook function.  */
3522
3523       if (msym_not_found_p (bp_objfile_data->exception_msym.minsym))
3524         continue;
3525
3526       gdbarch = get_objfile_arch (objfile);
3527
3528       if (bp_objfile_data->exception_msym.minsym == NULL)
3529         {
3530           struct bound_minimal_symbol debug_hook;
3531
3532           debug_hook = lookup_minimal_symbol (func_name, NULL, objfile);
3533           if (debug_hook.minsym == NULL)
3534             {
3535               bp_objfile_data->exception_msym.minsym = &msym_not_found;
3536               continue;
3537             }
3538
3539           bp_objfile_data->exception_msym = debug_hook;
3540         }
3541
3542       addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->exception_msym);
3543       addr = gdbarch_convert_from_func_ptr_addr (gdbarch, addr,
3544                                                  &current_target);
3545       b = create_internal_breakpoint (gdbarch, addr, bp_exception_master,
3546                                       &internal_breakpoint_ops);
3547       initialize_explicit_location (&explicit_loc);
3548       explicit_loc.function_name = ASTRDUP (func_name);
3549       b->location = new_explicit_location (&explicit_loc);
3550       b->enable_state = bp_disabled;
3551     }
3552 }
3553
3554 /* Does B have a location spec?  */
3555
3556 static int
3557 breakpoint_event_location_empty_p (const struct breakpoint *b)
3558 {
3559   return b->location != NULL && event_location_empty_p (b->location.get ());
3560 }
3561
3562 void
3563 update_breakpoints_after_exec (void)
3564 {
3565   struct breakpoint *b, *b_tmp;
3566   struct bp_location *bploc, **bplocp_tmp;
3567
3568   /* We're about to delete breakpoints from GDB's lists.  If the
3569      INSERTED flag is true, GDB will try to lift the breakpoints by
3570      writing the breakpoints' "shadow contents" back into memory.  The
3571      "shadow contents" are NOT valid after an exec, so GDB should not
3572      do that.  Instead, the target is responsible from marking
3573      breakpoints out as soon as it detects an exec.  We don't do that
3574      here instead, because there may be other attempts to delete
3575      breakpoints after detecting an exec and before reaching here.  */
3576   ALL_BP_LOCATIONS (bploc, bplocp_tmp)
3577     if (bploc->pspace == current_program_space)
3578       gdb_assert (!bploc->inserted);
3579
3580   ALL_BREAKPOINTS_SAFE (b, b_tmp)
3581   {
3582     if (b->pspace != current_program_space)
3583       continue;
3584
3585     /* Solib breakpoints must be explicitly reset after an exec().  */
3586     if (b->type == bp_shlib_event)
3587       {
3588         delete_breakpoint (b);
3589         continue;
3590       }
3591
3592     /* JIT breakpoints must be explicitly reset after an exec().  */
3593     if (b->type == bp_jit_event)
3594       {
3595         delete_breakpoint (b);
3596         continue;
3597       }
3598
3599     /* Thread event breakpoints must be set anew after an exec(),
3600        as must overlay event and longjmp master breakpoints.  */
3601     if (b->type == bp_thread_event || b->type == bp_overlay_event
3602         || b->type == bp_longjmp_master || b->type == bp_std_terminate_master
3603         || b->type == bp_exception_master)
3604       {
3605         delete_breakpoint (b);
3606         continue;
3607       }
3608
3609     /* Step-resume breakpoints are meaningless after an exec().  */
3610     if (b->type == bp_step_resume || b->type == bp_hp_step_resume)
3611       {
3612         delete_breakpoint (b);
3613         continue;
3614       }
3615
3616     /* Just like single-step breakpoints.  */
3617     if (b->type == bp_single_step)
3618       {
3619         delete_breakpoint (b);
3620         continue;
3621       }
3622
3623     /* Longjmp and longjmp-resume breakpoints are also meaningless
3624        after an exec.  */
3625     if (b->type == bp_longjmp || b->type == bp_longjmp_resume
3626         || b->type == bp_longjmp_call_dummy
3627         || b->type == bp_exception || b->type == bp_exception_resume)
3628       {
3629         delete_breakpoint (b);
3630         continue;
3631       }
3632
3633     if (b->type == bp_catchpoint)
3634       {
3635         /* For now, none of the bp_catchpoint breakpoints need to
3636            do anything at this point.  In the future, if some of
3637            the catchpoints need to something, we will need to add
3638            a new method, and call this method from here.  */
3639         continue;
3640       }
3641
3642     /* bp_finish is a special case.  The only way we ought to be able
3643        to see one of these when an exec() has happened, is if the user
3644        caught a vfork, and then said "finish".  Ordinarily a finish just
3645        carries them to the call-site of the current callee, by setting
3646        a temporary bp there and resuming.  But in this case, the finish
3647        will carry them entirely through the vfork & exec.
3648
3649        We don't want to allow a bp_finish to remain inserted now.  But
3650        we can't safely delete it, 'cause finish_command has a handle to
3651        the bp on a bpstat, and will later want to delete it.  There's a
3652        chance (and I've seen it happen) that if we delete the bp_finish
3653        here, that its storage will get reused by the time finish_command
3654        gets 'round to deleting the "use to be a bp_finish" breakpoint.
3655        We really must allow finish_command to delete a bp_finish.
3656
3657        In the absence of a general solution for the "how do we know
3658        it's safe to delete something others may have handles to?"
3659        problem, what we'll do here is just uninsert the bp_finish, and
3660        let finish_command delete it.
3661
3662        (We know the bp_finish is "doomed" in the sense that it's
3663        momentary, and will be deleted as soon as finish_command sees
3664        the inferior stopped.  So it doesn't matter that the bp's
3665        address is probably bogus in the new a.out, unlike e.g., the
3666        solib breakpoints.)  */
3667
3668     if (b->type == bp_finish)
3669       {
3670         continue;
3671       }
3672
3673     /* Without a symbolic address, we have little hope of the
3674        pre-exec() address meaning the same thing in the post-exec()
3675        a.out.  */
3676     if (breakpoint_event_location_empty_p (b))
3677       {
3678         delete_breakpoint (b);
3679         continue;
3680       }
3681   }
3682 }
3683
3684 int
3685 detach_breakpoints (ptid_t ptid)
3686 {
3687   struct bp_location *bl, **blp_tmp;
3688   int val = 0;
3689   scoped_restore save_inferior_ptid = make_scoped_restore (&inferior_ptid);
3690   struct inferior *inf = current_inferior ();
3691
3692   if (ptid_get_pid (ptid) == ptid_get_pid (inferior_ptid))
3693     error (_("Cannot detach breakpoints of inferior_ptid"));
3694
3695   /* Set inferior_ptid; remove_breakpoint_1 uses this global.  */
3696   inferior_ptid = ptid;
3697   ALL_BP_LOCATIONS (bl, blp_tmp)
3698   {
3699     if (bl->pspace != inf->pspace)
3700       continue;
3701
3702     /* This function must physically remove breakpoints locations
3703        from the specified ptid, without modifying the breakpoint
3704        package's state.  Locations of type bp_loc_other are only
3705        maintained at GDB side.  So, there is no need to remove
3706        these bp_loc_other locations.  Moreover, removing these
3707        would modify the breakpoint package's state.  */
3708     if (bl->loc_type == bp_loc_other)
3709       continue;
3710
3711     if (bl->inserted)
3712       val |= remove_breakpoint_1 (bl, DETACH_BREAKPOINT);
3713   }
3714
3715   return val;
3716 }
3717
3718 /* Remove the breakpoint location BL from the current address space.
3719    Note that this is used to detach breakpoints from a child fork.
3720    When we get here, the child isn't in the inferior list, and neither
3721    do we have objects to represent its address space --- we should
3722    *not* look at bl->pspace->aspace here.  */
3723
3724 static int
3725 remove_breakpoint_1 (struct bp_location *bl, enum remove_bp_reason reason)
3726 {
3727   int val;
3728
3729   /* BL is never in moribund_locations by our callers.  */
3730   gdb_assert (bl->owner != NULL);
3731
3732   /* The type of none suggests that owner is actually deleted.
3733      This should not ever happen.  */
3734   gdb_assert (bl->owner->type != bp_none);
3735
3736   if (bl->loc_type == bp_loc_software_breakpoint
3737       || bl->loc_type == bp_loc_hardware_breakpoint)
3738     {
3739       /* "Normal" instruction breakpoint: either the standard
3740          trap-instruction bp (bp_breakpoint), or a
3741          bp_hardware_breakpoint.  */
3742
3743       /* First check to see if we have to handle an overlay.  */
3744       if (overlay_debugging == ovly_off
3745           || bl->section == NULL
3746           || !(section_is_overlay (bl->section)))
3747         {
3748           /* No overlay handling: just remove the breakpoint.  */
3749
3750           /* If we're trying to uninsert a memory breakpoint that we
3751              know is set in a dynamic object that is marked
3752              shlib_disabled, then either the dynamic object was
3753              removed with "remove-symbol-file" or with
3754              "nosharedlibrary".  In the former case, we don't know
3755              whether another dynamic object might have loaded over the
3756              breakpoint's address -- the user might well let us know
3757              about it next with add-symbol-file (the whole point of
3758              add-symbol-file is letting the user manually maintain a
3759              list of dynamically loaded objects).  If we have the
3760              breakpoint's shadow memory, that is, this is a software
3761              breakpoint managed by GDB, check whether the breakpoint
3762              is still inserted in memory, to avoid overwriting wrong
3763              code with stale saved shadow contents.  Note that HW
3764              breakpoints don't have shadow memory, as they're
3765              implemented using a mechanism that is not dependent on
3766              being able to modify the target's memory, and as such
3767              they should always be removed.  */
3768           if (bl->shlib_disabled
3769               && bl->target_info.shadow_len != 0
3770               && !memory_validate_breakpoint (bl->gdbarch, &bl->target_info))
3771             val = 0;
3772           else
3773             val = bl->owner->ops->remove_location (bl, reason);
3774         }
3775       else
3776         {
3777           /* This breakpoint is in an overlay section.
3778              Did we set a breakpoint at the LMA?  */
3779           if (!overlay_events_enabled)
3780               {
3781                 /* Yes -- overlay event support is not active, so we
3782                    should have set a breakpoint at the LMA.  Remove it.  
3783                 */
3784                 /* Ignore any failures: if the LMA is in ROM, we will
3785                    have already warned when we failed to insert it.  */
3786                 if (bl->loc_type == bp_loc_hardware_breakpoint)
3787                   target_remove_hw_breakpoint (bl->gdbarch,
3788                                                &bl->overlay_target_info);
3789                 else
3790                   target_remove_breakpoint (bl->gdbarch,
3791                                             &bl->overlay_target_info,
3792                                             reason);
3793               }
3794           /* Did we set a breakpoint at the VMA? 
3795              If so, we will have marked the breakpoint 'inserted'.  */
3796           if (bl->inserted)
3797             {
3798               /* Yes -- remove it.  Previously we did not bother to
3799                  remove the breakpoint if the section had been
3800                  unmapped, but let's not rely on that being safe.  We
3801                  don't know what the overlay manager might do.  */
3802
3803               /* However, we should remove *software* breakpoints only
3804                  if the section is still mapped, or else we overwrite
3805                  wrong code with the saved shadow contents.  */
3806               if (bl->loc_type == bp_loc_hardware_breakpoint
3807                   || section_is_mapped (bl->section))
3808                 val = bl->owner->ops->remove_location (bl, reason);
3809               else
3810                 val = 0;
3811             }
3812           else
3813             {
3814               /* No -- not inserted, so no need to remove.  No error.  */
3815               val = 0;
3816             }
3817         }
3818
3819       /* In some cases, we might not be able to remove a breakpoint in
3820          a shared library that has already been removed, but we have
3821          not yet processed the shlib unload event.  Similarly for an
3822          unloaded add-symbol-file object - the user might not yet have
3823          had the chance to remove-symbol-file it.  shlib_disabled will
3824          be set if the library/object has already been removed, but
3825          the breakpoint hasn't been uninserted yet, e.g., after
3826          "nosharedlibrary" or "remove-symbol-file" with breakpoints
3827          always-inserted mode.  */
3828       if (val
3829           && (bl->loc_type == bp_loc_software_breakpoint
3830               && (bl->shlib_disabled
3831                   || solib_name_from_address (bl->pspace, bl->address)
3832                   || shared_objfile_contains_address_p (bl->pspace,
3833                                                         bl->address))))
3834         val = 0;
3835
3836       if (val)
3837         return val;
3838       bl->inserted = (reason == DETACH_BREAKPOINT);
3839     }
3840   else if (bl->loc_type == bp_loc_hardware_watchpoint)
3841     {
3842       gdb_assert (bl->owner->ops != NULL
3843                   && bl->owner->ops->remove_location != NULL);
3844
3845       bl->inserted = (reason == DETACH_BREAKPOINT);
3846       bl->owner->ops->remove_location (bl, reason);
3847
3848       /* Failure to remove any of the hardware watchpoints comes here.  */
3849       if (reason == REMOVE_BREAKPOINT && bl->inserted)
3850         warning (_("Could not remove hardware watchpoint %d."),
3851                  bl->owner->number);
3852     }
3853   else if (bl->owner->type == bp_catchpoint
3854            && breakpoint_enabled (bl->owner)
3855            && !bl->duplicate)
3856     {
3857       gdb_assert (bl->owner->ops != NULL
3858                   && bl->owner->ops->remove_location != NULL);
3859
3860       val = bl->owner->ops->remove_location (bl, reason);
3861       if (val)
3862         return val;
3863
3864       bl->inserted = (reason == DETACH_BREAKPOINT);
3865     }
3866
3867   return 0;
3868 }
3869
3870 static int
3871 remove_breakpoint (struct bp_location *bl)
3872 {
3873   /* BL is never in moribund_locations by our callers.  */
3874   gdb_assert (bl->owner != NULL);
3875
3876   /* The type of none suggests that owner is actually deleted.
3877      This should not ever happen.  */
3878   gdb_assert (bl->owner->type != bp_none);
3879
3880   scoped_restore_current_pspace_and_thread restore_pspace_thread;
3881
3882   switch_to_program_space_and_thread (bl->pspace);
3883
3884   return remove_breakpoint_1 (bl, REMOVE_BREAKPOINT);
3885 }
3886
3887 /* Clear the "inserted" flag in all breakpoints.  */
3888
3889 void
3890 mark_breakpoints_out (void)
3891 {
3892   struct bp_location *bl, **blp_tmp;
3893
3894   ALL_BP_LOCATIONS (bl, blp_tmp)
3895     if (bl->pspace == current_program_space)
3896       bl->inserted = 0;
3897 }
3898
3899 /* Clear the "inserted" flag in all breakpoints and delete any
3900    breakpoints which should go away between runs of the program.
3901
3902    Plus other such housekeeping that has to be done for breakpoints
3903    between runs.
3904
3905    Note: this function gets called at the end of a run (by
3906    generic_mourn_inferior) and when a run begins (by
3907    init_wait_for_inferior).  */
3908
3909
3910
3911 void
3912 breakpoint_init_inferior (enum inf_context context)
3913 {
3914   struct breakpoint *b, *b_tmp;
3915   struct bp_location *bl;
3916   int ix;
3917   struct program_space *pspace = current_program_space;
3918
3919   /* If breakpoint locations are shared across processes, then there's
3920      nothing to do.  */
3921   if (gdbarch_has_global_breakpoints (target_gdbarch ()))
3922     return;
3923
3924   mark_breakpoints_out ();
3925
3926   ALL_BREAKPOINTS_SAFE (b, b_tmp)
3927   {
3928     if (b->loc && b->loc->pspace != pspace)
3929       continue;
3930
3931     switch (b->type)
3932       {
3933       case bp_call_dummy:
3934       case bp_longjmp_call_dummy:
3935
3936         /* If the call dummy breakpoint is at the entry point it will
3937            cause problems when the inferior is rerun, so we better get
3938            rid of it.  */
3939
3940       case bp_watchpoint_scope:
3941
3942         /* Also get rid of scope breakpoints.  */
3943
3944       case bp_shlib_event:
3945
3946         /* Also remove solib event breakpoints.  Their addresses may
3947            have changed since the last time we ran the program.
3948            Actually we may now be debugging against different target;
3949            and so the solib backend that installed this breakpoint may
3950            not be used in by the target.  E.g.,
3951
3952            (gdb) file prog-linux
3953            (gdb) run               # native linux target
3954            ...
3955            (gdb) kill
3956            (gdb) file prog-win.exe
3957            (gdb) tar rem :9999     # remote Windows gdbserver.
3958         */
3959
3960       case bp_step_resume:
3961
3962         /* Also remove step-resume breakpoints.  */
3963
3964       case bp_single_step:
3965
3966         /* Also remove single-step breakpoints.  */
3967
3968         delete_breakpoint (b);
3969         break;
3970
3971       case bp_watchpoint:
3972       case bp_hardware_watchpoint:
3973       case bp_read_watchpoint:
3974       case bp_access_watchpoint:
3975         {
3976           struct watchpoint *w = (struct watchpoint *) b;
3977
3978           /* Likewise for watchpoints on local expressions.  */
3979           if (w->exp_valid_block != NULL)
3980             delete_breakpoint (b);
3981           else
3982             {
3983               /* Get rid of existing locations, which are no longer
3984                  valid.  New ones will be created in
3985                  update_watchpoint, when the inferior is restarted.
3986                  The next update_global_location_list call will
3987                  garbage collect them.  */
3988               b->loc = NULL;
3989
3990               if (context == inf_starting)
3991                 {
3992                   /* Reset val field to force reread of starting value in
3993                      insert_breakpoints.  */
3994                   if (w->val)
3995                     value_free (w->val);
3996                   w->val = NULL;
3997                   w->val_valid = 0;
3998                 }
3999             }
4000         }
4001         break;
4002       default:
4003         break;
4004       }
4005   }
4006
4007   /* Get rid of the moribund locations.  */
4008   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, bl); ++ix)
4009     decref_bp_location (&bl);
4010   VEC_free (bp_location_p, moribund_locations);
4011 }
4012
4013 /* These functions concern about actual breakpoints inserted in the
4014    target --- to e.g. check if we need to do decr_pc adjustment or if
4015    we need to hop over the bkpt --- so we check for address space
4016    match, not program space.  */
4017
4018 /* breakpoint_here_p (PC) returns non-zero if an enabled breakpoint
4019    exists at PC.  It returns ordinary_breakpoint_here if it's an
4020    ordinary breakpoint, or permanent_breakpoint_here if it's a
4021    permanent breakpoint.
4022    - When continuing from a location with an ordinary breakpoint, we
4023      actually single step once before calling insert_breakpoints.
4024    - When continuing from a location with a permanent breakpoint, we
4025      need to use the `SKIP_PERMANENT_BREAKPOINT' macro, provided by
4026      the target, to advance the PC past the breakpoint.  */
4027
4028 enum breakpoint_here
4029 breakpoint_here_p (const address_space *aspace, CORE_ADDR pc)
4030 {
4031   struct bp_location *bl, **blp_tmp;
4032   int any_breakpoint_here = 0;
4033
4034   ALL_BP_LOCATIONS (bl, blp_tmp)
4035     {
4036       if (bl->loc_type != bp_loc_software_breakpoint
4037           && bl->loc_type != bp_loc_hardware_breakpoint)
4038         continue;
4039
4040       /* ALL_BP_LOCATIONS bp_location has BL->OWNER always non-NULL.  */
4041       if ((breakpoint_enabled (bl->owner)
4042            || bl->permanent)
4043           && breakpoint_location_address_match (bl, aspace, pc))
4044         {
4045           if (overlay_debugging 
4046               && section_is_overlay (bl->section)
4047               && !section_is_mapped (bl->section))
4048             continue;           /* unmapped overlay -- can't be a match */
4049           else if (bl->permanent)
4050             return permanent_breakpoint_here;
4051           else
4052             any_breakpoint_here = 1;
4053         }
4054     }
4055
4056   return any_breakpoint_here ? ordinary_breakpoint_here : no_breakpoint_here;
4057 }
4058
4059 /* See breakpoint.h.  */
4060
4061 int
4062 breakpoint_in_range_p (const address_space *aspace,
4063                        CORE_ADDR addr, ULONGEST len)
4064 {
4065   struct bp_location *bl, **blp_tmp;
4066
4067   ALL_BP_LOCATIONS (bl, blp_tmp)
4068     {
4069       if (bl->loc_type != bp_loc_software_breakpoint
4070           && bl->loc_type != bp_loc_hardware_breakpoint)
4071         continue;
4072
4073       if ((breakpoint_enabled (bl->owner)
4074            || bl->permanent)
4075           && breakpoint_location_address_range_overlap (bl, aspace,
4076                                                         addr, len))
4077         {
4078           if (overlay_debugging
4079               && section_is_overlay (bl->section)
4080               && !section_is_mapped (bl->section))
4081             {
4082               /* Unmapped overlay -- can't be a match.  */
4083               continue;
4084             }
4085
4086           return 1;
4087         }
4088     }
4089
4090   return 0;
4091 }
4092
4093 /* Return true if there's a moribund breakpoint at PC.  */
4094
4095 int
4096 moribund_breakpoint_here_p (const address_space *aspace, CORE_ADDR pc)
4097 {
4098   struct bp_location *loc;
4099   int ix;
4100
4101   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
4102     if (breakpoint_location_address_match (loc, aspace, pc))
4103       return 1;
4104
4105   return 0;
4106 }
4107
4108 /* Returns non-zero iff BL is inserted at PC, in address space
4109    ASPACE.  */
4110
4111 static int
4112 bp_location_inserted_here_p (struct bp_location *bl,
4113                              const address_space *aspace, CORE_ADDR pc)
4114 {
4115   if (bl->inserted
4116       && breakpoint_address_match (bl->pspace->aspace, bl->address,
4117                                    aspace, pc))
4118     {
4119       if (overlay_debugging
4120           && section_is_overlay (bl->section)
4121           && !section_is_mapped (bl->section))
4122         return 0;               /* unmapped overlay -- can't be a match */
4123       else
4124         return 1;
4125     }
4126   return 0;
4127 }
4128
4129 /* Returns non-zero iff there's a breakpoint inserted at PC.  */
4130
4131 int
4132 breakpoint_inserted_here_p (const address_space *aspace, CORE_ADDR pc)
4133 {
4134   struct bp_location **blp, **blp_tmp = NULL;
4135
4136   ALL_BP_LOCATIONS_AT_ADDR (blp, blp_tmp, pc)
4137     {
4138       struct bp_location *bl = *blp;
4139
4140       if (bl->loc_type != bp_loc_software_breakpoint
4141           && bl->loc_type != bp_loc_hardware_breakpoint)
4142         continue;
4143
4144       if (bp_location_inserted_here_p (bl, aspace, pc))
4145         return 1;
4146     }
4147   return 0;
4148 }
4149
4150 /* This function returns non-zero iff there is a software breakpoint
4151    inserted at PC.  */
4152
4153 int
4154 software_breakpoint_inserted_here_p (const address_space *aspace,
4155                                      CORE_ADDR pc)
4156 {
4157   struct bp_location **blp, **blp_tmp = NULL;
4158
4159   ALL_BP_LOCATIONS_AT_ADDR (blp, blp_tmp, pc)
4160     {
4161       struct bp_location *bl = *blp;
4162
4163       if (bl->loc_type != bp_loc_software_breakpoint)
4164         continue;
4165
4166       if (bp_location_inserted_here_p (bl, aspace, pc))
4167         return 1;
4168     }
4169
4170   return 0;
4171 }
4172
4173 /* See breakpoint.h.  */
4174
4175 int
4176 hardware_breakpoint_inserted_here_p (const address_space *aspace,
4177                                      CORE_ADDR pc)
4178 {
4179   struct bp_location **blp, **blp_tmp = NULL;
4180
4181   ALL_BP_LOCATIONS_AT_ADDR (blp, blp_tmp, pc)
4182     {
4183       struct bp_location *bl = *blp;
4184
4185       if (bl->loc_type != bp_loc_hardware_breakpoint)
4186         continue;
4187
4188       if (bp_location_inserted_here_p (bl, aspace, pc))
4189         return 1;
4190     }
4191
4192   return 0;
4193 }
4194
4195 int
4196 hardware_watchpoint_inserted_in_range (const address_space *aspace,
4197                                        CORE_ADDR addr, ULONGEST len)
4198 {
4199   struct breakpoint *bpt;
4200
4201   ALL_BREAKPOINTS (bpt)
4202     {
4203       struct bp_location *loc;
4204
4205       if (bpt->type != bp_hardware_watchpoint
4206           && bpt->type != bp_access_watchpoint)
4207         continue;
4208
4209       if (!breakpoint_enabled (bpt))
4210         continue;
4211
4212       for (loc = bpt->loc; loc; loc = loc->next)
4213         if (loc->pspace->aspace == aspace && loc->inserted)
4214           {
4215             CORE_ADDR l, h;
4216
4217             /* Check for intersection.  */
4218             l = std::max<CORE_ADDR> (loc->address, addr);
4219             h = std::min<CORE_ADDR> (loc->address + loc->length, addr + len);
4220             if (l < h)
4221               return 1;
4222           }
4223     }
4224   return 0;
4225 }
4226 \f
4227
4228 /* bpstat stuff.  External routines' interfaces are documented
4229    in breakpoint.h.  */
4230
4231 int
4232 is_catchpoint (struct breakpoint *ep)
4233 {
4234   return (ep->type == bp_catchpoint);
4235 }
4236
4237 /* Frees any storage that is part of a bpstat.  Does not walk the
4238    'next' chain.  */
4239
4240 bpstats::~bpstats ()
4241 {
4242   if (old_val != NULL)
4243     value_free (old_val);
4244   if (bp_location_at != NULL)
4245     decref_bp_location (&bp_location_at);
4246 }
4247
4248 /* Clear a bpstat so that it says we are not at any breakpoint.
4249    Also free any storage that is part of a bpstat.  */
4250
4251 void
4252 bpstat_clear (bpstat *bsp)
4253 {
4254   bpstat p;
4255   bpstat q;
4256
4257   if (bsp == 0)
4258     return;
4259   p = *bsp;
4260   while (p != NULL)
4261     {
4262       q = p->next;
4263       delete p;
4264       p = q;
4265     }
4266   *bsp = NULL;
4267 }
4268
4269 bpstats::bpstats (const bpstats &other)
4270   : next (NULL),
4271     bp_location_at (other.bp_location_at),
4272     breakpoint_at (other.breakpoint_at),
4273     commands (other.commands),
4274     old_val (other.old_val),
4275     print (other.print),
4276     stop (other.stop),
4277     print_it (other.print_it)
4278 {
4279   if (old_val != NULL)
4280     {
4281       old_val = value_copy (old_val);
4282       release_value (old_val);
4283     }
4284   incref_bp_location (bp_location_at);
4285 }
4286
4287 /* Return a copy of a bpstat.  Like "bs1 = bs2" but all storage that
4288    is part of the bpstat is copied as well.  */
4289
4290 bpstat
4291 bpstat_copy (bpstat bs)
4292 {
4293   bpstat p = NULL;
4294   bpstat tmp;
4295   bpstat retval = NULL;
4296
4297   if (bs == NULL)
4298     return bs;
4299
4300   for (; bs != NULL; bs = bs->next)
4301     {
4302       tmp = new bpstats (*bs);
4303
4304       if (p == NULL)
4305         /* This is the first thing in the chain.  */
4306         retval = tmp;
4307       else
4308         p->next = tmp;
4309       p = tmp;
4310     }
4311   p->next = NULL;
4312   return retval;
4313 }
4314
4315 /* Find the bpstat associated with this breakpoint.  */
4316
4317 bpstat
4318 bpstat_find_breakpoint (bpstat bsp, struct breakpoint *breakpoint)
4319 {
4320   if (bsp == NULL)
4321     return NULL;
4322
4323   for (; bsp != NULL; bsp = bsp->next)
4324     {
4325       if (bsp->breakpoint_at == breakpoint)
4326         return bsp;
4327     }
4328   return NULL;
4329 }
4330
4331 /* See breakpoint.h.  */
4332
4333 int
4334 bpstat_explains_signal (bpstat bsp, enum gdb_signal sig)
4335 {
4336   for (; bsp != NULL; bsp = bsp->next)
4337     {
4338       if (bsp->breakpoint_at == NULL)
4339         {
4340           /* A moribund location can never explain a signal other than
4341              GDB_SIGNAL_TRAP.  */
4342           if (sig == GDB_SIGNAL_TRAP)
4343             return 1;
4344         }
4345       else
4346         {
4347           if (bsp->breakpoint_at->ops->explains_signal (bsp->breakpoint_at,
4348                                                         sig))
4349             return 1;
4350         }
4351     }
4352
4353   return 0;
4354 }
4355
4356 /* Put in *NUM the breakpoint number of the first breakpoint we are
4357    stopped at.  *BSP upon return is a bpstat which points to the
4358    remaining breakpoints stopped at (but which is not guaranteed to be
4359    good for anything but further calls to bpstat_num).
4360
4361    Return 0 if passed a bpstat which does not indicate any breakpoints.
4362    Return -1 if stopped at a breakpoint that has been deleted since
4363    we set it.
4364    Return 1 otherwise.  */
4365
4366 int
4367 bpstat_num (bpstat *bsp, int *num)
4368 {
4369   struct breakpoint *b;
4370
4371   if ((*bsp) == NULL)
4372     return 0;                   /* No more breakpoint values */
4373
4374   /* We assume we'll never have several bpstats that correspond to a
4375      single breakpoint -- otherwise, this function might return the
4376      same number more than once and this will look ugly.  */
4377   b = (*bsp)->breakpoint_at;
4378   *bsp = (*bsp)->next;
4379   if (b == NULL)
4380     return -1;                  /* breakpoint that's been deleted since */
4381
4382   *num = b->number;             /* We have its number */
4383   return 1;
4384 }
4385
4386 /* See breakpoint.h.  */
4387
4388 void
4389 bpstat_clear_actions (void)
4390 {
4391   struct thread_info *tp;
4392   bpstat bs;
4393
4394   if (ptid_equal (inferior_ptid, null_ptid))
4395     return;
4396
4397   tp = find_thread_ptid (inferior_ptid);
4398   if (tp == NULL)
4399     return;
4400
4401   for (bs = tp->control.stop_bpstat; bs != NULL; bs = bs->next)
4402     {
4403       bs->commands = NULL;
4404
4405       if (bs->old_val != NULL)
4406         {
4407           value_free (bs->old_val);
4408           bs->old_val = NULL;
4409         }
4410     }
4411 }
4412
4413 /* Called when a command is about to proceed the inferior.  */
4414
4415 static void
4416 breakpoint_about_to_proceed (void)
4417 {
4418   if (!ptid_equal (inferior_ptid, null_ptid))
4419     {
4420       struct thread_info *tp = inferior_thread ();
4421
4422       /* Allow inferior function calls in breakpoint commands to not
4423          interrupt the command list.  When the call finishes
4424          successfully, the inferior will be standing at the same
4425          breakpoint as if nothing happened.  */
4426       if (tp->control.in_infcall)
4427         return;
4428     }
4429
4430   breakpoint_proceeded = 1;
4431 }
4432
4433 /* Return non-zero iff CMD as the first line of a command sequence is `silent'
4434    or its equivalent.  */
4435
4436 static int
4437 command_line_is_silent (struct command_line *cmd)
4438 {
4439   return cmd && (strcmp ("silent", cmd->line) == 0);
4440 }
4441
4442 /* Execute all the commands associated with all the breakpoints at
4443    this location.  Any of these commands could cause the process to
4444    proceed beyond this point, etc.  We look out for such changes by
4445    checking the global "breakpoint_proceeded" after each command.
4446
4447    Returns true if a breakpoint command resumed the inferior.  In that
4448    case, it is the caller's responsibility to recall it again with the
4449    bpstat of the current thread.  */
4450
4451 static int
4452 bpstat_do_actions_1 (bpstat *bsp)
4453 {
4454   bpstat bs;
4455   int again = 0;
4456
4457   /* Avoid endless recursion if a `source' command is contained
4458      in bs->commands.  */
4459   if (executing_breakpoint_commands)
4460     return 0;
4461
4462   scoped_restore save_executing
4463     = make_scoped_restore (&executing_breakpoint_commands, 1);
4464
4465   scoped_restore preventer = prevent_dont_repeat ();
4466
4467   /* This pointer will iterate over the list of bpstat's.  */
4468   bs = *bsp;
4469
4470   breakpoint_proceeded = 0;
4471   for (; bs != NULL; bs = bs->next)
4472     {
4473       struct command_line *cmd = NULL;
4474
4475       /* Take ownership of the BSP's command tree, if it has one.
4476
4477          The command tree could legitimately contain commands like
4478          'step' and 'next', which call clear_proceed_status, which
4479          frees stop_bpstat's command tree.  To make sure this doesn't
4480          free the tree we're executing out from under us, we need to
4481          take ownership of the tree ourselves.  Since a given bpstat's
4482          commands are only executed once, we don't need to copy it; we
4483          can clear the pointer in the bpstat, and make sure we free
4484          the tree when we're done.  */
4485       counted_command_line ccmd = bs->commands;
4486       bs->commands = NULL;
4487       if (ccmd != NULL)
4488         cmd = ccmd.get ();
4489       if (command_line_is_silent (cmd))
4490         {
4491           /* The action has been already done by bpstat_stop_status.  */
4492           cmd = cmd->next;
4493         }
4494
4495       while (cmd != NULL)
4496         {
4497           execute_control_command (cmd);
4498
4499           if (breakpoint_proceeded)
4500             break;
4501           else
4502             cmd = cmd->next;
4503         }
4504
4505       if (breakpoint_proceeded)
4506         {
4507           if (current_ui->async)
4508             /* If we are in async mode, then the target might be still
4509                running, not stopped at any breakpoint, so nothing for
4510                us to do here -- just return to the event loop.  */
4511             ;
4512           else
4513             /* In sync mode, when execute_control_command returns
4514                we're already standing on the next breakpoint.
4515                Breakpoint commands for that stop were not run, since
4516                execute_command does not run breakpoint commands --
4517                only command_line_handler does, but that one is not
4518                involved in execution of breakpoint commands.  So, we
4519                can now execute breakpoint commands.  It should be
4520                noted that making execute_command do bpstat actions is
4521                not an option -- in this case we'll have recursive
4522                invocation of bpstat for each breakpoint with a
4523                command, and can easily blow up GDB stack.  Instead, we
4524                return true, which will trigger the caller to recall us
4525                with the new stop_bpstat.  */
4526             again = 1;
4527           break;
4528         }
4529     }
4530   return again;
4531 }
4532
4533 void
4534 bpstat_do_actions (void)
4535 {
4536   struct cleanup *cleanup_if_error = make_bpstat_clear_actions_cleanup ();
4537
4538   /* Do any commands attached to breakpoint we are stopped at.  */
4539   while (!ptid_equal (inferior_ptid, null_ptid)
4540          && target_has_execution
4541          && !is_exited (inferior_ptid)
4542          && !is_executing (inferior_ptid))
4543     /* Since in sync mode, bpstat_do_actions may resume the inferior,
4544        and only return when it is stopped at the next breakpoint, we
4545        keep doing breakpoint actions until it returns false to
4546        indicate the inferior was not resumed.  */
4547     if (!bpstat_do_actions_1 (&inferior_thread ()->control.stop_bpstat))
4548       break;
4549
4550   discard_cleanups (cleanup_if_error);
4551 }
4552
4553 /* Print out the (old or new) value associated with a watchpoint.  */
4554
4555 static void
4556 watchpoint_value_print (struct value *val, struct ui_file *stream)
4557 {
4558   if (val == NULL)
4559     fprintf_unfiltered (stream, _("<unreadable>"));
4560   else
4561     {
4562       struct value_print_options opts;
4563       get_user_print_options (&opts);
4564       value_print (val, stream, &opts);
4565     }
4566 }
4567
4568 /* Print the "Thread ID hit" part of "Thread ID hit Breakpoint N" if
4569    debugging multiple threads.  */
4570
4571 void
4572 maybe_print_thread_hit_breakpoint (struct ui_out *uiout)
4573 {
4574   if (uiout->is_mi_like_p ())
4575     return;
4576
4577   uiout->text ("\n");
4578
4579   if (show_thread_that_caused_stop ())
4580     {
4581       const char *name;
4582       struct thread_info *thr = inferior_thread ();
4583
4584       uiout->text ("Thread ");
4585       uiout->field_fmt ("thread-id", "%s", print_thread_id (thr));
4586
4587       name = thr->name != NULL ? thr->name : target_thread_name (thr);
4588       if (name != NULL)
4589         {
4590           uiout->text (" \"");
4591           uiout->field_fmt ("name", "%s", name);
4592           uiout->text ("\"");
4593         }
4594
4595       uiout->text (" hit ");
4596     }
4597 }
4598
4599 /* Generic routine for printing messages indicating why we
4600    stopped.  The behavior of this function depends on the value
4601    'print_it' in the bpstat structure.  Under some circumstances we
4602    may decide not to print anything here and delegate the task to
4603    normal_stop().  */
4604
4605 static enum print_stop_action
4606 print_bp_stop_message (bpstat bs)
4607 {
4608   switch (bs->print_it)
4609     {
4610     case print_it_noop:
4611       /* Nothing should be printed for this bpstat entry.  */
4612       return PRINT_UNKNOWN;
4613       break;
4614
4615     case print_it_done:
4616       /* We still want to print the frame, but we already printed the
4617          relevant messages.  */
4618       return PRINT_SRC_AND_LOC;
4619       break;
4620
4621     case print_it_normal:
4622       {
4623         struct breakpoint *b = bs->breakpoint_at;
4624
4625         /* bs->breakpoint_at can be NULL if it was a momentary breakpoint
4626            which has since been deleted.  */
4627         if (b == NULL)
4628           return PRINT_UNKNOWN;
4629
4630         /* Normal case.  Call the breakpoint's print_it method.  */
4631         return b->ops->print_it (bs);
4632       }
4633       break;
4634
4635     default:
4636       internal_error (__FILE__, __LINE__,
4637                       _("print_bp_stop_message: unrecognized enum value"));
4638       break;
4639     }
4640 }
4641
4642 /* A helper function that prints a shared library stopped event.  */
4643
4644 static void
4645 print_solib_event (int is_catchpoint)
4646 {
4647   int any_deleted
4648     = !VEC_empty (char_ptr, current_program_space->deleted_solibs);
4649   int any_added
4650     = !VEC_empty (so_list_ptr, current_program_space->added_solibs);
4651
4652   if (!is_catchpoint)
4653     {
4654       if (any_added || any_deleted)
4655         current_uiout->text (_("Stopped due to shared library event:\n"));
4656       else
4657         current_uiout->text (_("Stopped due to shared library event (no "
4658                                "libraries added or removed)\n"));
4659     }
4660
4661   if (current_uiout->is_mi_like_p ())
4662     current_uiout->field_string ("reason",
4663                                  async_reason_lookup (EXEC_ASYNC_SOLIB_EVENT));
4664
4665   if (any_deleted)
4666     {
4667       char *name;
4668       int ix;
4669
4670       current_uiout->text (_("  Inferior unloaded "));
4671       ui_out_emit_list list_emitter (current_uiout, "removed");
4672       for (ix = 0;
4673            VEC_iterate (char_ptr, current_program_space->deleted_solibs,
4674                         ix, name);
4675            ++ix)
4676         {
4677           if (ix > 0)
4678             current_uiout->text ("    ");
4679           current_uiout->field_string ("library", name);
4680           current_uiout->text ("\n");
4681         }
4682     }
4683
4684   if (any_added)
4685     {
4686       struct so_list *iter;
4687       int ix;
4688
4689       current_uiout->text (_("  Inferior loaded "));
4690       ui_out_emit_list list_emitter (current_uiout, "added");
4691       for (ix = 0;
4692            VEC_iterate (so_list_ptr, current_program_space->added_solibs,
4693                         ix, iter);
4694            ++ix)
4695         {
4696           if (ix > 0)
4697             current_uiout->text ("    ");
4698           current_uiout->field_string ("library", iter->so_name);
4699           current_uiout->text ("\n");
4700         }
4701     }
4702 }
4703
4704 /* Print a message indicating what happened.  This is called from
4705    normal_stop().  The input to this routine is the head of the bpstat
4706    list - a list of the eventpoints that caused this stop.  KIND is
4707    the target_waitkind for the stopping event.  This
4708    routine calls the generic print routine for printing a message
4709    about reasons for stopping.  This will print (for example) the
4710    "Breakpoint n," part of the output.  The return value of this
4711    routine is one of:
4712
4713    PRINT_UNKNOWN: Means we printed nothing.
4714    PRINT_SRC_AND_LOC: Means we printed something, and expect subsequent
4715    code to print the location.  An example is 
4716    "Breakpoint 1, " which should be followed by
4717    the location.
4718    PRINT_SRC_ONLY: Means we printed something, but there is no need
4719    to also print the location part of the message.
4720    An example is the catch/throw messages, which
4721    don't require a location appended to the end.
4722    PRINT_NOTHING: We have done some printing and we don't need any 
4723    further info to be printed.  */
4724
4725 enum print_stop_action
4726 bpstat_print (bpstat bs, int kind)
4727 {
4728   enum print_stop_action val;
4729
4730   /* Maybe another breakpoint in the chain caused us to stop.
4731      (Currently all watchpoints go on the bpstat whether hit or not.
4732      That probably could (should) be changed, provided care is taken
4733      with respect to bpstat_explains_signal).  */
4734   for (; bs; bs = bs->next)
4735     {
4736       val = print_bp_stop_message (bs);
4737       if (val == PRINT_SRC_ONLY 
4738           || val == PRINT_SRC_AND_LOC 
4739           || val == PRINT_NOTHING)
4740         return val;
4741     }
4742
4743   /* If we had hit a shared library event breakpoint,
4744      print_bp_stop_message would print out this message.  If we hit an
4745      OS-level shared library event, do the same thing.  */
4746   if (kind == TARGET_WAITKIND_LOADED)
4747     {
4748       print_solib_event (0);
4749       return PRINT_NOTHING;
4750     }
4751
4752   /* We reached the end of the chain, or we got a null BS to start
4753      with and nothing was printed.  */
4754   return PRINT_UNKNOWN;
4755 }
4756
4757 /* Evaluate the boolean expression EXP and return the result.  */
4758
4759 static bool
4760 breakpoint_cond_eval (expression *exp)
4761 {
4762   struct value *mark = value_mark ();
4763   bool res = value_true (evaluate_expression (exp));
4764
4765   value_free_to_mark (mark);
4766   return res;
4767 }
4768
4769 /* Allocate a new bpstat.  Link it to the FIFO list by BS_LINK_POINTER.  */
4770
4771 bpstats::bpstats (struct bp_location *bl, bpstat **bs_link_pointer)
4772   : next (NULL),
4773     bp_location_at (bl),
4774     breakpoint_at (bl->owner),
4775     commands (NULL),
4776     old_val (NULL),
4777     print (0),
4778     stop (0),
4779     print_it (print_it_normal)
4780 {
4781   incref_bp_location (bl);
4782   **bs_link_pointer = this;
4783   *bs_link_pointer = &next;
4784 }
4785
4786 bpstats::bpstats ()
4787   : next (NULL),
4788     bp_location_at (NULL),
4789     breakpoint_at (NULL),
4790     commands (NULL),
4791     old_val (NULL),
4792     print (0),
4793     stop (0),
4794     print_it (print_it_normal)
4795 {
4796 }
4797 \f
4798 /* The target has stopped with waitstatus WS.  Check if any hardware
4799    watchpoints have triggered, according to the target.  */
4800
4801 int
4802 watchpoints_triggered (struct target_waitstatus *ws)
4803 {
4804   int stopped_by_watchpoint = target_stopped_by_watchpoint ();
4805   CORE_ADDR addr;
4806   struct breakpoint *b;
4807
4808   if (!stopped_by_watchpoint)
4809     {
4810       /* We were not stopped by a watchpoint.  Mark all watchpoints
4811          as not triggered.  */
4812       ALL_BREAKPOINTS (b)
4813         if (is_hardware_watchpoint (b))
4814           {
4815             struct watchpoint *w = (struct watchpoint *) b;
4816
4817             w->watchpoint_triggered = watch_triggered_no;
4818           }
4819
4820       return 0;
4821     }
4822
4823   if (!target_stopped_data_address (&current_target, &addr))
4824     {
4825       /* We were stopped by a watchpoint, but we don't know where.
4826          Mark all watchpoints as unknown.  */
4827       ALL_BREAKPOINTS (b)
4828         if (is_hardware_watchpoint (b))
4829           {
4830             struct watchpoint *w = (struct watchpoint *) b;
4831
4832             w->watchpoint_triggered = watch_triggered_unknown;
4833           }
4834
4835       return 1;
4836     }
4837
4838   /* The target could report the data address.  Mark watchpoints
4839      affected by this data address as triggered, and all others as not
4840      triggered.  */
4841
4842   ALL_BREAKPOINTS (b)
4843     if (is_hardware_watchpoint (b))
4844       {
4845         struct watchpoint *w = (struct watchpoint *) b;
4846         struct bp_location *loc;
4847
4848         w->watchpoint_triggered = watch_triggered_no;
4849         for (loc = b->loc; loc; loc = loc->next)
4850           {
4851             if (is_masked_watchpoint (b))
4852               {
4853                 CORE_ADDR newaddr = addr & w->hw_wp_mask;
4854                 CORE_ADDR start = loc->address & w->hw_wp_mask;
4855
4856                 if (newaddr == start)
4857                   {
4858                     w->watchpoint_triggered = watch_triggered_yes;
4859                     break;
4860                   }
4861               }
4862             /* Exact match not required.  Within range is sufficient.  */
4863             else if (target_watchpoint_addr_within_range (&current_target,
4864                                                          addr, loc->address,
4865                                                          loc->length))
4866               {
4867                 w->watchpoint_triggered = watch_triggered_yes;
4868                 break;
4869               }
4870           }
4871       }
4872
4873   return 1;
4874 }
4875
4876 /* Possible return values for watchpoint_check.  */
4877 enum wp_check_result
4878   {
4879     /* The watchpoint has been deleted.  */
4880     WP_DELETED = 1,
4881
4882     /* The value has changed.  */
4883     WP_VALUE_CHANGED = 2,
4884
4885     /* The value has not changed.  */
4886     WP_VALUE_NOT_CHANGED = 3,
4887
4888     /* Ignore this watchpoint, no matter if the value changed or not.  */
4889     WP_IGNORE = 4,
4890   };
4891
4892 #define BP_TEMPFLAG 1
4893 #define BP_HARDWAREFLAG 2
4894
4895 /* Evaluate watchpoint condition expression and check if its value
4896    changed.  */
4897
4898 static wp_check_result
4899 watchpoint_check (bpstat bs)
4900 {
4901   struct watchpoint *b;
4902   struct frame_info *fr;
4903   int within_current_scope;
4904
4905   /* BS is built from an existing struct breakpoint.  */
4906   gdb_assert (bs->breakpoint_at != NULL);
4907   b = (struct watchpoint *) bs->breakpoint_at;
4908
4909   /* If this is a local watchpoint, we only want to check if the
4910      watchpoint frame is in scope if the current thread is the thread
4911      that was used to create the watchpoint.  */
4912   if (!watchpoint_in_thread_scope (b))
4913     return WP_IGNORE;
4914
4915   if (b->exp_valid_block == NULL)
4916     within_current_scope = 1;
4917   else
4918     {
4919       struct frame_info *frame = get_current_frame ();
4920       struct gdbarch *frame_arch = get_frame_arch (frame);
4921       CORE_ADDR frame_pc = get_frame_pc (frame);
4922
4923       /* stack_frame_destroyed_p() returns a non-zero value if we're
4924          still in the function but the stack frame has already been
4925          invalidated.  Since we can't rely on the values of local
4926          variables after the stack has been destroyed, we are treating
4927          the watchpoint in that state as `not changed' without further
4928          checking.  Don't mark watchpoints as changed if the current
4929          frame is in an epilogue - even if they are in some other
4930          frame, our view of the stack is likely to be wrong and
4931          frame_find_by_id could error out.  */
4932       if (gdbarch_stack_frame_destroyed_p (frame_arch, frame_pc))
4933         return WP_IGNORE;
4934
4935       fr = frame_find_by_id (b->watchpoint_frame);
4936       within_current_scope = (fr != NULL);
4937
4938       /* If we've gotten confused in the unwinder, we might have
4939          returned a frame that can't describe this variable.  */
4940       if (within_current_scope)
4941         {
4942           struct symbol *function;
4943
4944           function = get_frame_function (fr);
4945           if (function == NULL
4946               || !contained_in (b->exp_valid_block,
4947                                 SYMBOL_BLOCK_VALUE (function)))
4948             within_current_scope = 0;
4949         }
4950
4951       if (within_current_scope)
4952         /* If we end up stopping, the current frame will get selected
4953            in normal_stop.  So this call to select_frame won't affect
4954            the user.  */
4955         select_frame (fr);
4956     }
4957
4958   if (within_current_scope)
4959     {
4960       /* We use value_{,free_to_}mark because it could be a *long*
4961          time before we return to the command level and call
4962          free_all_values.  We can't call free_all_values because we
4963          might be in the middle of evaluating a function call.  */
4964
4965       int pc = 0;
4966       struct value *mark;
4967       struct value *new_val;
4968
4969       if (is_masked_watchpoint (b))
4970         /* Since we don't know the exact trigger address (from
4971            stopped_data_address), just tell the user we've triggered
4972            a mask watchpoint.  */
4973         return WP_VALUE_CHANGED;
4974
4975       mark = value_mark ();
4976       fetch_subexp_value (b->exp.get (), &pc, &new_val, NULL, NULL, 0);
4977
4978       if (b->val_bitsize != 0)
4979         new_val = extract_bitfield_from_watchpoint_value (b, new_val);
4980
4981       /* We use value_equal_contents instead of value_equal because
4982          the latter coerces an array to a pointer, thus comparing just
4983          the address of the array instead of its contents.  This is
4984          not what we want.  */
4985       if ((b->val != NULL) != (new_val != NULL)
4986           || (b->val != NULL && !value_equal_contents (b->val, new_val)))
4987         {
4988           if (new_val != NULL)
4989             {
4990               release_value (new_val);
4991               value_free_to_mark (mark);
4992             }
4993           bs->old_val = b->val;
4994           b->val = new_val;
4995           b->val_valid = 1;
4996           return WP_VALUE_CHANGED;
4997         }
4998       else
4999         {
5000           /* Nothing changed.  */
5001           value_free_to_mark (mark);
5002           return WP_VALUE_NOT_CHANGED;
5003         }
5004     }
5005   else
5006     {
5007       /* This seems like the only logical thing to do because
5008          if we temporarily ignored the watchpoint, then when
5009          we reenter the block in which it is valid it contains
5010          garbage (in the case of a function, it may have two
5011          garbage values, one before and one after the prologue).
5012          So we can't even detect the first assignment to it and
5013          watch after that (since the garbage may or may not equal
5014          the first value assigned).  */
5015       /* We print all the stop information in
5016          breakpoint_ops->print_it, but in this case, by the time we
5017          call breakpoint_ops->print_it this bp will be deleted
5018          already.  So we have no choice but print the information
5019          here.  */
5020
5021       SWITCH_THRU_ALL_UIS ()
5022         {
5023           struct ui_out *uiout = current_uiout;
5024
5025           if (uiout->is_mi_like_p ())
5026             uiout->field_string
5027               ("reason", async_reason_lookup (EXEC_ASYNC_WATCHPOINT_SCOPE));
5028           uiout->text ("\nWatchpoint ");
5029           uiout->field_int ("wpnum", b->number);
5030           uiout->text (" deleted because the program has left the block in\n"
5031                        "which its expression is valid.\n");
5032         }
5033
5034       /* Make sure the watchpoint's commands aren't executed.  */
5035       b->commands = NULL;
5036       watchpoint_del_at_next_stop (b);
5037
5038       return WP_DELETED;
5039     }
5040 }
5041
5042 /* Return true if it looks like target has stopped due to hitting
5043    breakpoint location BL.  This function does not check if we should
5044    stop, only if BL explains the stop.  */
5045
5046 static int
5047 bpstat_check_location (const struct bp_location *bl,
5048                        const address_space *aspace, CORE_ADDR bp_addr,
5049                        const struct target_waitstatus *ws)
5050 {
5051   struct breakpoint *b = bl->owner;
5052
5053   /* BL is from an existing breakpoint.  */
5054   gdb_assert (b != NULL);
5055
5056   return b->ops->breakpoint_hit (bl, aspace, bp_addr, ws);
5057 }
5058
5059 /* Determine if the watched values have actually changed, and we
5060    should stop.  If not, set BS->stop to 0.  */
5061
5062 static void
5063 bpstat_check_watchpoint (bpstat bs)
5064 {
5065   const struct bp_location *bl;
5066   struct watchpoint *b;
5067
5068   /* BS is built for existing struct breakpoint.  */
5069   bl = bs->bp_location_at;
5070   gdb_assert (bl != NULL);
5071   b = (struct watchpoint *) bs->breakpoint_at;
5072   gdb_assert (b != NULL);
5073
5074     {
5075       int must_check_value = 0;
5076       
5077       if (b->type == bp_watchpoint)
5078         /* For a software watchpoint, we must always check the
5079            watched value.  */
5080         must_check_value = 1;
5081       else if (b->watchpoint_triggered == watch_triggered_yes)
5082         /* We have a hardware watchpoint (read, write, or access)
5083            and the target earlier reported an address watched by
5084            this watchpoint.  */
5085         must_check_value = 1;
5086       else if (b->watchpoint_triggered == watch_triggered_unknown
5087                && b->type == bp_hardware_watchpoint)
5088         /* We were stopped by a hardware watchpoint, but the target could
5089            not report the data address.  We must check the watchpoint's
5090            value.  Access and read watchpoints are out of luck; without
5091            a data address, we can't figure it out.  */
5092         must_check_value = 1;
5093
5094       if (must_check_value)
5095         {
5096           wp_check_result e;
5097
5098           TRY
5099             {
5100               e = watchpoint_check (bs);
5101             }
5102           CATCH (ex, RETURN_MASK_ALL)
5103             {
5104               exception_fprintf (gdb_stderr, ex,
5105                                  "Error evaluating expression "
5106                                  "for watchpoint %d\n",
5107                                  b->number);
5108
5109               SWITCH_THRU_ALL_UIS ()
5110                 {
5111                   printf_filtered (_("Watchpoint %d deleted.\n"),
5112                                    b->number);
5113                 }
5114               watchpoint_del_at_next_stop (b);
5115               e = WP_DELETED;
5116             }
5117           END_CATCH
5118
5119           switch (e)
5120             {
5121             case WP_DELETED:
5122               /* We've already printed what needs to be printed.  */
5123               bs->print_it = print_it_done;
5124               /* Stop.  */
5125               break;
5126             case WP_IGNORE:
5127               bs->print_it = print_it_noop;
5128               bs->stop = 0;
5129               break;
5130             case WP_VALUE_CHANGED:
5131               if (b->type == bp_read_watchpoint)
5132                 {
5133                   /* There are two cases to consider here:
5134
5135                      1. We're watching the triggered memory for reads.
5136                      In that case, trust the target, and always report
5137                      the watchpoint hit to the user.  Even though
5138                      reads don't cause value changes, the value may
5139                      have changed since the last time it was read, and
5140                      since we're not trapping writes, we will not see
5141                      those, and as such we should ignore our notion of
5142                      old value.
5143
5144                      2. We're watching the triggered memory for both
5145                      reads and writes.  There are two ways this may
5146                      happen:
5147
5148                      2.1. This is a target that can't break on data
5149                      reads only, but can break on accesses (reads or
5150                      writes), such as e.g., x86.  We detect this case
5151                      at the time we try to insert read watchpoints.
5152
5153                      2.2. Otherwise, the target supports read
5154                      watchpoints, but, the user set an access or write
5155                      watchpoint watching the same memory as this read
5156                      watchpoint.
5157
5158                      If we're watching memory writes as well as reads,
5159                      ignore watchpoint hits when we find that the
5160                      value hasn't changed, as reads don't cause
5161                      changes.  This still gives false positives when
5162                      the program writes the same value to memory as
5163                      what there was already in memory (we will confuse
5164                      it for a read), but it's much better than
5165                      nothing.  */
5166
5167                   int other_write_watchpoint = 0;
5168
5169                   if (bl->watchpoint_type == hw_read)
5170                     {
5171                       struct breakpoint *other_b;
5172
5173                       ALL_BREAKPOINTS (other_b)
5174                         if (other_b->type == bp_hardware_watchpoint
5175                             || other_b->type == bp_access_watchpoint)
5176                           {
5177                             struct watchpoint *other_w =
5178                               (struct watchpoint *) other_b;
5179
5180                             if (other_w->watchpoint_triggered
5181                                 == watch_triggered_yes)
5182                               {
5183                                 other_write_watchpoint = 1;
5184                                 break;
5185                               }
5186                           }
5187                     }
5188
5189                   if (other_write_watchpoint
5190                       || bl->watchpoint_type == hw_access)
5191                     {
5192                       /* We're watching the same memory for writes,
5193                          and the value changed since the last time we
5194                          updated it, so this trap must be for a write.
5195                          Ignore it.  */
5196                       bs->print_it = print_it_noop;
5197                       bs->stop = 0;
5198                     }
5199                 }
5200               break;
5201             case WP_VALUE_NOT_CHANGED:
5202               if (b->type == bp_hardware_watchpoint
5203                   || b->type == bp_watchpoint)
5204                 {
5205                   /* Don't stop: write watchpoints shouldn't fire if
5206                      the value hasn't changed.  */
5207                   bs->print_it = print_it_noop;
5208                   bs->stop = 0;
5209                 }
5210               /* Stop.  */
5211               break;
5212             default:
5213               /* Can't happen.  */
5214               break;
5215             }
5216         }
5217       else      /* must_check_value == 0 */
5218         {
5219           /* This is a case where some watchpoint(s) triggered, but
5220              not at the address of this watchpoint, or else no
5221              watchpoint triggered after all.  So don't print
5222              anything for this watchpoint.  */
5223           bs->print_it = print_it_noop;
5224           bs->stop = 0;
5225         }
5226     }
5227 }
5228
5229 /* For breakpoints that are currently marked as telling gdb to stop,
5230    check conditions (condition proper, frame, thread and ignore count)
5231    of breakpoint referred to by BS.  If we should not stop for this
5232    breakpoint, set BS->stop to 0.  */
5233
5234 static void
5235 bpstat_check_breakpoint_conditions (bpstat bs, ptid_t ptid)
5236 {
5237   const struct bp_location *bl;
5238   struct breakpoint *b;
5239   /* Assume stop.  */
5240   bool condition_result = true;
5241   struct expression *cond;
5242
5243   gdb_assert (bs->stop);
5244
5245   /* BS is built for existing struct breakpoint.  */
5246   bl = bs->bp_location_at;
5247   gdb_assert (bl != NULL);
5248   b = bs->breakpoint_at;
5249   gdb_assert (b != NULL);
5250
5251   /* Even if the target evaluated the condition on its end and notified GDB, we
5252      need to do so again since GDB does not know if we stopped due to a
5253      breakpoint or a single step breakpoint.  */
5254
5255   if (frame_id_p (b->frame_id)
5256       && !frame_id_eq (b->frame_id, get_stack_frame_id (get_current_frame ())))
5257     {
5258       bs->stop = 0;
5259       return;
5260     }
5261
5262   /* If this is a thread/task-specific breakpoint, don't waste cpu
5263      evaluating the condition if this isn't the specified
5264      thread/task.  */
5265   if ((b->thread != -1 && b->thread != ptid_to_global_thread_id (ptid))
5266       || (b->task != 0 && b->task != ada_get_task_number (ptid)))
5267
5268     {
5269       bs->stop = 0;
5270       return;
5271     }
5272
5273   /* Evaluate extension language breakpoints that have a "stop" method
5274      implemented.  */
5275   bs->stop = breakpoint_ext_lang_cond_says_stop (b);
5276
5277   if (is_watchpoint (b))
5278     {
5279       struct watchpoint *w = (struct watchpoint *) b;
5280
5281       cond = w->cond_exp.get ();
5282     }
5283   else
5284     cond = bl->cond.get ();
5285
5286   if (cond && b->disposition != disp_del_at_next_stop)
5287     {
5288       int within_current_scope = 1;
5289       struct watchpoint * w;
5290
5291       /* We use value_mark and value_free_to_mark because it could
5292          be a long time before we return to the command level and
5293          call free_all_values.  We can't call free_all_values
5294          because we might be in the middle of evaluating a
5295          function call.  */
5296       struct value *mark = value_mark ();
5297
5298       if (is_watchpoint (b))
5299         w = (struct watchpoint *) b;
5300       else
5301         w = NULL;
5302
5303       /* Need to select the frame, with all that implies so that
5304          the conditions will have the right context.  Because we
5305          use the frame, we will not see an inlined function's
5306          variables when we arrive at a breakpoint at the start
5307          of the inlined function; the current frame will be the
5308          call site.  */
5309       if (w == NULL || w->cond_exp_valid_block == NULL)
5310         select_frame (get_current_frame ());
5311       else
5312         {
5313           struct frame_info *frame;
5314
5315           /* For local watchpoint expressions, which particular
5316              instance of a local is being watched matters, so we
5317              keep track of the frame to evaluate the expression
5318              in.  To evaluate the condition however, it doesn't
5319              really matter which instantiation of the function
5320              where the condition makes sense triggers the
5321              watchpoint.  This allows an expression like "watch
5322              global if q > 10" set in `func', catch writes to
5323              global on all threads that call `func', or catch
5324              writes on all recursive calls of `func' by a single
5325              thread.  We simply always evaluate the condition in
5326              the innermost frame that's executing where it makes
5327              sense to evaluate the condition.  It seems
5328              intuitive.  */
5329           frame = block_innermost_frame (w->cond_exp_valid_block);
5330           if (frame != NULL)
5331             select_frame (frame);
5332           else
5333             within_current_scope = 0;
5334         }
5335       if (within_current_scope)
5336         {
5337           TRY
5338             {
5339               condition_result = breakpoint_cond_eval (cond);
5340             }
5341           CATCH (ex, RETURN_MASK_ALL)
5342             {
5343               exception_fprintf (gdb_stderr, ex,
5344                                  "Error in testing breakpoint condition:\n");
5345             }
5346           END_CATCH
5347         }
5348       else
5349         {
5350           warning (_("Watchpoint condition cannot be tested "
5351                      "in the current scope"));
5352           /* If we failed to set the right context for this
5353              watchpoint, unconditionally report it.  */
5354         }
5355       /* FIXME-someday, should give breakpoint #.  */
5356       value_free_to_mark (mark);
5357     }
5358
5359   if (cond && !condition_result)
5360     {
5361       bs->stop = 0;
5362     }
5363   else if (b->ignore_count > 0)
5364     {
5365       b->ignore_count--;
5366       bs->stop = 0;
5367       /* Increase the hit count even though we don't stop.  */
5368       ++(b->hit_count);
5369       observer_notify_breakpoint_modified (b);
5370     }   
5371 }
5372
5373 /* Returns true if we need to track moribund locations of LOC's type
5374    on the current target.  */
5375
5376 static int
5377 need_moribund_for_location_type (struct bp_location *loc)
5378 {
5379   return ((loc->loc_type == bp_loc_software_breakpoint
5380            && !target_supports_stopped_by_sw_breakpoint ())
5381           || (loc->loc_type == bp_loc_hardware_breakpoint
5382               && !target_supports_stopped_by_hw_breakpoint ()));
5383 }
5384
5385
5386 /* Get a bpstat associated with having just stopped at address
5387    BP_ADDR in thread PTID.
5388
5389    Determine whether we stopped at a breakpoint, etc, or whether we
5390    don't understand this stop.  Result is a chain of bpstat's such
5391    that:
5392
5393    if we don't understand the stop, the result is a null pointer.
5394
5395    if we understand why we stopped, the result is not null.
5396
5397    Each element of the chain refers to a particular breakpoint or
5398    watchpoint at which we have stopped.  (We may have stopped for
5399    several reasons concurrently.)
5400
5401    Each element of the chain has valid next, breakpoint_at,
5402    commands, FIXME??? fields.  */
5403
5404 bpstat
5405 bpstat_stop_status (const address_space *aspace,
5406                     CORE_ADDR bp_addr, ptid_t ptid,
5407                     const struct target_waitstatus *ws)
5408 {
5409   struct breakpoint *b = NULL;
5410   struct bp_location *bl;
5411   struct bp_location *loc;
5412   /* First item of allocated bpstat's.  */
5413   bpstat bs_head = NULL, *bs_link = &bs_head;
5414   /* Pointer to the last thing in the chain currently.  */
5415   bpstat bs;
5416   int ix;
5417   int need_remove_insert;
5418   int removed_any;
5419
5420   /* First, build the bpstat chain with locations that explain a
5421      target stop, while being careful to not set the target running,
5422      as that may invalidate locations (in particular watchpoint
5423      locations are recreated).  Resuming will happen here with
5424      breakpoint conditions or watchpoint expressions that include
5425      inferior function calls.  */
5426
5427   ALL_BREAKPOINTS (b)
5428     {
5429       if (!breakpoint_enabled (b))
5430         continue;
5431
5432       for (bl = b->loc; bl != NULL; bl = bl->next)
5433         {
5434           /* For hardware watchpoints, we look only at the first
5435              location.  The watchpoint_check function will work on the
5436              entire expression, not the individual locations.  For
5437              read watchpoints, the watchpoints_triggered function has
5438              checked all locations already.  */
5439           if (b->type == bp_hardware_watchpoint && bl != b->loc)
5440             break;
5441
5442           if (!bl->enabled || bl->shlib_disabled)
5443             continue;
5444
5445           if (!bpstat_check_location (bl, aspace, bp_addr, ws))
5446             continue;
5447
5448           /* Come here if it's a watchpoint, or if the break address
5449              matches.  */
5450
5451           bs = new bpstats (bl, &bs_link);      /* Alloc a bpstat to
5452                                                    explain stop.  */
5453
5454           /* Assume we stop.  Should we find a watchpoint that is not
5455              actually triggered, or if the condition of the breakpoint
5456              evaluates as false, we'll reset 'stop' to 0.  */
5457           bs->stop = 1;
5458           bs->print = 1;
5459
5460           /* If this is a scope breakpoint, mark the associated
5461              watchpoint as triggered so that we will handle the
5462              out-of-scope event.  We'll get to the watchpoint next
5463              iteration.  */
5464           if (b->type == bp_watchpoint_scope && b->related_breakpoint != b)
5465             {
5466               struct watchpoint *w = (struct watchpoint *) b->related_breakpoint;
5467
5468               w->watchpoint_triggered = watch_triggered_yes;
5469             }
5470         }
5471     }
5472
5473   /* Check if a moribund breakpoint explains the stop.  */
5474   if (!target_supports_stopped_by_sw_breakpoint ()
5475       || !target_supports_stopped_by_hw_breakpoint ())
5476     {
5477       for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
5478         {
5479           if (breakpoint_location_address_match (loc, aspace, bp_addr)
5480               && need_moribund_for_location_type (loc))
5481             {
5482               bs = new bpstats (loc, &bs_link);
5483               /* For hits of moribund locations, we should just proceed.  */
5484               bs->stop = 0;
5485               bs->print = 0;
5486               bs->print_it = print_it_noop;
5487             }
5488         }
5489     }
5490
5491   /* A bit of special processing for shlib breakpoints.  We need to
5492      process solib loading here, so that the lists of loaded and
5493      unloaded libraries are correct before we handle "catch load" and
5494      "catch unload".  */
5495   for (bs = bs_head; bs != NULL; bs = bs->next)
5496     {
5497       if (bs->breakpoint_at && bs->breakpoint_at->type == bp_shlib_event)
5498         {
5499           handle_solib_event ();
5500           break;
5501         }
5502     }
5503
5504   /* Now go through the locations that caused the target to stop, and
5505      check whether we're interested in reporting this stop to higher
5506      layers, or whether we should resume the target transparently.  */
5507
5508   removed_any = 0;
5509
5510   for (bs = bs_head; bs != NULL; bs = bs->next)
5511     {
5512       if (!bs->stop)
5513         continue;
5514
5515       b = bs->breakpoint_at;
5516       b->ops->check_status (bs);
5517       if (bs->stop)
5518         {
5519           bpstat_check_breakpoint_conditions (bs, ptid);
5520
5521           if (bs->stop)
5522             {
5523               ++(b->hit_count);
5524               observer_notify_breakpoint_modified (b);
5525
5526               /* We will stop here.  */
5527               if (b->disposition == disp_disable)
5528                 {
5529                   --(b->enable_count);
5530                   if (b->enable_count <= 0)
5531                     b->enable_state = bp_disabled;
5532                   removed_any = 1;
5533                 }
5534               if (b->silent)
5535                 bs->print = 0;
5536               bs->commands = b->commands;
5537               if (command_line_is_silent (bs->commands
5538                                           ? bs->commands.get () : NULL))
5539                 bs->print = 0;
5540
5541               b->ops->after_condition_true (bs);
5542             }
5543
5544         }
5545
5546       /* Print nothing for this entry if we don't stop or don't
5547          print.  */
5548       if (!bs->stop || !bs->print)
5549         bs->print_it = print_it_noop;
5550     }
5551
5552   /* If we aren't stopping, the value of some hardware watchpoint may
5553      not have changed, but the intermediate memory locations we are
5554      watching may have.  Don't bother if we're stopping; this will get
5555      done later.  */
5556   need_remove_insert = 0;
5557   if (! bpstat_causes_stop (bs_head))
5558     for (bs = bs_head; bs != NULL; bs = bs->next)
5559       if (!bs->stop
5560           && bs->breakpoint_at
5561           && is_hardware_watchpoint (bs->breakpoint_at))
5562         {
5563           struct watchpoint *w = (struct watchpoint *) bs->breakpoint_at;
5564
5565           update_watchpoint (w, 0 /* don't reparse.  */);
5566           need_remove_insert = 1;
5567         }
5568
5569   if (need_remove_insert)
5570     update_global_location_list (UGLL_MAY_INSERT);
5571   else if (removed_any)
5572     update_global_location_list (UGLL_DONT_INSERT);
5573
5574   return bs_head;
5575 }
5576
5577 static void
5578 handle_jit_event (void)
5579 {
5580   struct frame_info *frame;
5581   struct gdbarch *gdbarch;
5582
5583   if (debug_infrun)
5584     fprintf_unfiltered (gdb_stdlog, "handling bp_jit_event\n");
5585
5586   /* Switch terminal for any messages produced by
5587      breakpoint_re_set.  */
5588   target_terminal::ours_for_output ();
5589
5590   frame = get_current_frame ();
5591   gdbarch = get_frame_arch (frame);
5592
5593   jit_event_handler (gdbarch);
5594
5595   target_terminal::inferior ();
5596 }
5597
5598 /* Prepare WHAT final decision for infrun.  */
5599
5600 /* Decide what infrun needs to do with this bpstat.  */
5601
5602 struct bpstat_what
5603 bpstat_what (bpstat bs_head)
5604 {
5605   struct bpstat_what retval;
5606   bpstat bs;
5607
5608   retval.main_action = BPSTAT_WHAT_KEEP_CHECKING;
5609   retval.call_dummy = STOP_NONE;
5610   retval.is_longjmp = 0;
5611
5612   for (bs = bs_head; bs != NULL; bs = bs->next)
5613     {
5614       /* Extract this BS's action.  After processing each BS, we check
5615          if its action overrides all we've seem so far.  */
5616       enum bpstat_what_main_action this_action = BPSTAT_WHAT_KEEP_CHECKING;
5617       enum bptype bptype;
5618
5619       if (bs->breakpoint_at == NULL)
5620         {
5621           /* I suspect this can happen if it was a momentary
5622              breakpoint which has since been deleted.  */
5623           bptype = bp_none;
5624         }
5625       else
5626         bptype = bs->breakpoint_at->type;
5627
5628       switch (bptype)
5629         {
5630         case bp_none:
5631           break;
5632         case bp_breakpoint:
5633         case bp_hardware_breakpoint:
5634         case bp_single_step:
5635         case bp_until:
5636         case bp_finish:
5637         case bp_shlib_event:
5638           if (bs->stop)
5639             {
5640               if (bs->print)
5641                 this_action = BPSTAT_WHAT_STOP_NOISY;
5642               else
5643                 this_action = BPSTAT_WHAT_STOP_SILENT;
5644             }
5645           else
5646             this_action = BPSTAT_WHAT_SINGLE;
5647           break;
5648         case bp_watchpoint:
5649         case bp_hardware_watchpoint:
5650         case bp_read_watchpoint:
5651         case bp_access_watchpoint:
5652           if (bs->stop)
5653             {
5654               if (bs->print)
5655                 this_action = BPSTAT_WHAT_STOP_NOISY;
5656               else
5657                 this_action = BPSTAT_WHAT_STOP_SILENT;
5658             }
5659           else
5660             {
5661               /* There was a watchpoint, but we're not stopping.
5662                  This requires no further action.  */
5663             }
5664           break;
5665         case bp_longjmp:
5666         case bp_longjmp_call_dummy:
5667         case bp_exception:
5668           if (bs->stop)
5669             {
5670               this_action = BPSTAT_WHAT_SET_LONGJMP_RESUME;
5671               retval.is_longjmp = bptype != bp_exception;
5672             }
5673           else
5674             this_action = BPSTAT_WHAT_SINGLE;
5675           break;
5676         case bp_longjmp_resume:
5677         case bp_exception_resume:
5678           if (bs->stop)
5679             {
5680               this_action = BPSTAT_WHAT_CLEAR_LONGJMP_RESUME;
5681               retval.is_longjmp = bptype == bp_longjmp_resume;
5682             }
5683           else
5684             this_action = BPSTAT_WHAT_SINGLE;
5685           break;
5686         case bp_step_resume:
5687           if (bs->stop)
5688             this_action = BPSTAT_WHAT_STEP_RESUME;
5689           else
5690             {
5691               /* It is for the wrong frame.  */
5692               this_action = BPSTAT_WHAT_SINGLE;
5693             }
5694           break;
5695         case bp_hp_step_resume:
5696           if (bs->stop)
5697             this_action = BPSTAT_WHAT_HP_STEP_RESUME;
5698           else
5699             {
5700               /* It is for the wrong frame.  */
5701               this_action = BPSTAT_WHAT_SINGLE;
5702             }
5703           break;
5704         case bp_watchpoint_scope:
5705         case bp_thread_event:
5706         case bp_overlay_event:
5707         case bp_longjmp_master:
5708         case bp_std_terminate_master:
5709         case bp_exception_master:
5710           this_action = BPSTAT_WHAT_SINGLE;
5711           break;
5712         case bp_catchpoint:
5713           if (bs->stop)
5714             {
5715               if (bs->print)
5716                 this_action = BPSTAT_WHAT_STOP_NOISY;
5717               else
5718                 this_action = BPSTAT_WHAT_STOP_SILENT;
5719             }
5720           else
5721             {
5722               /* There was a catchpoint, but we're not stopping.
5723                  This requires no further action.  */
5724             }
5725           break;
5726         case bp_jit_event:
5727           this_action = BPSTAT_WHAT_SINGLE;
5728           break;
5729         case bp_call_dummy:
5730           /* Make sure the action is stop (silent or noisy),
5731              so infrun.c pops the dummy frame.  */
5732           retval.call_dummy = STOP_STACK_DUMMY;
5733           this_action = BPSTAT_WHAT_STOP_SILENT;
5734           break;
5735         case bp_std_terminate:
5736           /* Make sure the action is stop (silent or noisy),
5737              so infrun.c pops the dummy frame.  */
5738           retval.call_dummy = STOP_STD_TERMINATE;
5739           this_action = BPSTAT_WHAT_STOP_SILENT;
5740           break;
5741         case bp_tracepoint:
5742         case bp_fast_tracepoint:
5743         case bp_static_tracepoint:
5744           /* Tracepoint hits should not be reported back to GDB, and
5745              if one got through somehow, it should have been filtered
5746              out already.  */
5747           internal_error (__FILE__, __LINE__,
5748                           _("bpstat_what: tracepoint encountered"));
5749           break;
5750         case bp_gnu_ifunc_resolver:
5751           /* Step over it (and insert bp_gnu_ifunc_resolver_return).  */
5752           this_action = BPSTAT_WHAT_SINGLE;
5753           break;
5754         case bp_gnu_ifunc_resolver_return:
5755           /* The breakpoint will be removed, execution will restart from the
5756              PC of the former breakpoint.  */
5757           this_action = BPSTAT_WHAT_KEEP_CHECKING;
5758           break;
5759
5760         case bp_dprintf:
5761           if (bs->stop)
5762             this_action = BPSTAT_WHAT_STOP_SILENT;
5763           else
5764             this_action = BPSTAT_WHAT_SINGLE;
5765           break;
5766
5767         default:
5768           internal_error (__FILE__, __LINE__,
5769                           _("bpstat_what: unhandled bptype %d"), (int) bptype);
5770         }
5771
5772       retval.main_action = std::max (retval.main_action, this_action);
5773     }
5774
5775   return retval;
5776 }
5777
5778 void
5779 bpstat_run_callbacks (bpstat bs_head)
5780 {
5781   bpstat bs;
5782
5783   for (bs = bs_head; bs != NULL; bs = bs->next)
5784     {
5785       struct breakpoint *b = bs->breakpoint_at;
5786
5787       if (b == NULL)
5788         continue;
5789       switch (b->type)
5790         {
5791         case bp_jit_event:
5792           handle_jit_event ();
5793           break;
5794         case bp_gnu_ifunc_resolver:
5795           gnu_ifunc_resolver_stop (b);
5796           break;
5797         case bp_gnu_ifunc_resolver_return:
5798           gnu_ifunc_resolver_return_stop (b);
5799           break;
5800         }
5801     }
5802 }
5803
5804 /* Nonzero if we should step constantly (e.g. watchpoints on machines
5805    without hardware support).  This isn't related to a specific bpstat,
5806    just to things like whether watchpoints are set.  */
5807
5808 int
5809 bpstat_should_step (void)
5810 {
5811   struct breakpoint *b;
5812
5813   ALL_BREAKPOINTS (b)
5814     if (breakpoint_enabled (b) && b->type == bp_watchpoint && b->loc != NULL)
5815       return 1;
5816   return 0;
5817 }
5818
5819 int
5820 bpstat_causes_stop (bpstat bs)
5821 {
5822   for (; bs != NULL; bs = bs->next)
5823     if (bs->stop)
5824       return 1;
5825
5826   return 0;
5827 }
5828
5829 \f
5830
5831 /* Compute a string of spaces suitable to indent the next line
5832    so it starts at the position corresponding to the table column
5833    named COL_NAME in the currently active table of UIOUT.  */
5834
5835 static char *
5836 wrap_indent_at_field (struct ui_out *uiout, const char *col_name)
5837 {
5838   static char wrap_indent[80];
5839   int i, total_width, width, align;
5840   const char *text;
5841
5842   total_width = 0;
5843   for (i = 1; uiout->query_table_field (i, &width, &align, &text); i++)
5844     {
5845       if (strcmp (text, col_name) == 0)
5846         {
5847           gdb_assert (total_width < sizeof wrap_indent);
5848           memset (wrap_indent, ' ', total_width);
5849           wrap_indent[total_width] = 0;
5850
5851           return wrap_indent;
5852         }
5853
5854       total_width += width + 1;
5855     }
5856
5857   return NULL;
5858 }
5859
5860 /* Determine if the locations of this breakpoint will have their conditions
5861    evaluated by the target, host or a mix of both.  Returns the following:
5862
5863     "host": Host evals condition.
5864     "host or target": Host or Target evals condition.
5865     "target": Target evals condition.
5866 */
5867
5868 static const char *
5869 bp_condition_evaluator (struct breakpoint *b)
5870 {
5871   struct bp_location *bl;
5872   char host_evals = 0;
5873   char target_evals = 0;
5874
5875   if (!b)
5876     return NULL;
5877
5878   if (!is_breakpoint (b))
5879     return NULL;
5880
5881   if (gdb_evaluates_breakpoint_condition_p ()
5882       || !target_supports_evaluation_of_breakpoint_conditions ())
5883     return condition_evaluation_host;
5884
5885   for (bl = b->loc; bl; bl = bl->next)
5886     {
5887       if (bl->cond_bytecode)
5888         target_evals++;
5889       else
5890         host_evals++;
5891     }
5892
5893   if (host_evals && target_evals)
5894     return condition_evaluation_both;
5895   else if (target_evals)
5896     return condition_evaluation_target;
5897   else
5898     return condition_evaluation_host;
5899 }
5900
5901 /* Determine the breakpoint location's condition evaluator.  This is
5902    similar to bp_condition_evaluator, but for locations.  */
5903
5904 static const char *
5905 bp_location_condition_evaluator (struct bp_location *bl)
5906 {
5907   if (bl && !is_breakpoint (bl->owner))
5908     return NULL;
5909
5910   if (gdb_evaluates_breakpoint_condition_p ()
5911       || !target_supports_evaluation_of_breakpoint_conditions ())
5912     return condition_evaluation_host;
5913
5914   if (bl && bl->cond_bytecode)
5915     return condition_evaluation_target;
5916   else
5917     return condition_evaluation_host;
5918 }
5919
5920 /* Print the LOC location out of the list of B->LOC locations.  */
5921
5922 static void
5923 print_breakpoint_location (struct breakpoint *b,
5924                            struct bp_location *loc)
5925 {
5926   struct ui_out *uiout = current_uiout;
5927
5928   scoped_restore_current_program_space restore_pspace;
5929
5930   if (loc != NULL && loc->shlib_disabled)
5931     loc = NULL;
5932
5933   if (loc != NULL)
5934     set_current_program_space (loc->pspace);
5935
5936   if (b->display_canonical)
5937     uiout->field_string ("what", event_location_to_string (b->location.get ()));
5938   else if (loc && loc->symtab)
5939     {
5940       const struct symbol *sym = loc->symbol;
5941
5942       if (sym == NULL)
5943         sym = find_pc_sect_function (loc->address, loc->section);
5944
5945       if (sym)
5946         {
5947           uiout->text ("in ");
5948           uiout->field_string ("func", SYMBOL_PRINT_NAME (sym));
5949           uiout->text (" ");
5950           uiout->wrap_hint (wrap_indent_at_field (uiout, "what"));
5951           uiout->text ("at ");
5952         }
5953       uiout->field_string ("file",
5954                            symtab_to_filename_for_display (loc->symtab));
5955       uiout->text (":");
5956
5957       if (uiout->is_mi_like_p ())
5958         uiout->field_string ("fullname", symtab_to_fullname (loc->symtab));
5959       
5960       uiout->field_int ("line", loc->line_number);
5961     }
5962   else if (loc)
5963     {
5964       string_file stb;
5965
5966       print_address_symbolic (loc->gdbarch, loc->address, &stb,
5967                               demangle, "");
5968       uiout->field_stream ("at", stb);
5969     }
5970   else
5971     {
5972       uiout->field_string ("pending",
5973                            event_location_to_string (b->location.get ()));
5974       /* If extra_string is available, it could be holding a condition
5975          or dprintf arguments.  In either case, make sure it is printed,
5976          too, but only for non-MI streams.  */
5977       if (!uiout->is_mi_like_p () && b->extra_string != NULL)
5978         {
5979           if (b->type == bp_dprintf)
5980             uiout->text (",");
5981           else
5982             uiout->text (" ");
5983           uiout->text (b->extra_string);
5984         }
5985     }
5986
5987   if (loc && is_breakpoint (b)
5988       && breakpoint_condition_evaluation_mode () == condition_evaluation_target
5989       && bp_condition_evaluator (b) == condition_evaluation_both)
5990     {
5991       uiout->text (" (");
5992       uiout->field_string ("evaluated-by",
5993                            bp_location_condition_evaluator (loc));
5994       uiout->text (")");
5995     }
5996 }
5997
5998 static const char *
5999 bptype_string (enum bptype type)
6000 {
6001   struct ep_type_description
6002     {
6003       enum bptype type;
6004       const char *description;
6005     };
6006   static struct ep_type_description bptypes[] =
6007   {
6008     {bp_none, "?deleted?"},
6009     {bp_breakpoint, "breakpoint"},
6010     {bp_hardware_breakpoint, "hw breakpoint"},
6011     {bp_single_step, "sw single-step"},
6012     {bp_until, "until"},
6013     {bp_finish, "finish"},
6014     {bp_watchpoint, "watchpoint"},
6015     {bp_hardware_watchpoint, "hw watchpoint"},
6016     {bp_read_watchpoint, "read watchpoint"},
6017     {bp_access_watchpoint, "acc watchpoint"},
6018     {bp_longjmp, "longjmp"},
6019     {bp_longjmp_resume, "longjmp resume"},
6020     {bp_longjmp_call_dummy, "longjmp for call dummy"},
6021     {bp_exception, "exception"},
6022     {bp_exception_resume, "exception resume"},
6023     {bp_step_resume, "step resume"},
6024     {bp_hp_step_resume, "high-priority step resume"},
6025     {bp_watchpoint_scope, "watchpoint scope"},
6026     {bp_call_dummy, "call dummy"},
6027     {bp_std_terminate, "std::terminate"},
6028     {bp_shlib_event, "shlib events"},
6029     {bp_thread_event, "thread events"},
6030     {bp_overlay_event, "overlay events"},
6031     {bp_longjmp_master, "longjmp master"},
6032     {bp_std_terminate_master, "std::terminate master"},
6033     {bp_exception_master, "exception master"},
6034     {bp_catchpoint, "catchpoint"},
6035     {bp_tracepoint, "tracepoint"},
6036     {bp_fast_tracepoint, "fast tracepoint"},
6037     {bp_static_tracepoint, "static tracepoint"},
6038     {bp_dprintf, "dprintf"},
6039     {bp_jit_event, "jit events"},
6040     {bp_gnu_ifunc_resolver, "STT_GNU_IFUNC resolver"},
6041     {bp_gnu_ifunc_resolver_return, "STT_GNU_IFUNC resolver return"},
6042   };
6043
6044   if (((int) type >= (sizeof (bptypes) / sizeof (bptypes[0])))
6045       || ((int) type != bptypes[(int) type].type))
6046     internal_error (__FILE__, __LINE__,
6047                     _("bptypes table does not describe type #%d."),
6048                     (int) type);
6049
6050   return bptypes[(int) type].description;
6051 }
6052
6053 /* For MI, output a field named 'thread-groups' with a list as the value.
6054    For CLI, prefix the list with the string 'inf'. */
6055
6056 static void
6057 output_thread_groups (struct ui_out *uiout,
6058                       const char *field_name,
6059                       VEC(int) *inf_num,
6060                       int mi_only)
6061 {
6062   int is_mi = uiout->is_mi_like_p ();
6063   int inf;
6064   int i;
6065
6066   /* For backward compatibility, don't display inferiors in CLI unless
6067      there are several.  Always display them for MI. */
6068   if (!is_mi && mi_only)
6069     return;
6070
6071   ui_out_emit_list list_emitter (uiout, field_name);
6072
6073   for (i = 0; VEC_iterate (int, inf_num, i, inf); ++i)
6074     {
6075       if (is_mi)
6076         {
6077           char mi_group[10];
6078
6079           xsnprintf (mi_group, sizeof (mi_group), "i%d", inf);
6080           uiout->field_string (NULL, mi_group);
6081         }
6082       else
6083         {
6084           if (i == 0)
6085             uiout->text (" inf ");
6086           else
6087             uiout->text (", ");
6088         
6089           uiout->text (plongest (inf));
6090         }
6091     }
6092 }
6093
6094 /* Print B to gdb_stdout.  */
6095
6096 static void
6097 print_one_breakpoint_location (struct breakpoint *b,
6098                                struct bp_location *loc,
6099                                int loc_number,
6100                                struct bp_location **last_loc,
6101                                int allflag)
6102 {
6103   struct command_line *l;
6104   static char bpenables[] = "nynny";
6105
6106   struct ui_out *uiout = current_uiout;
6107   int header_of_multiple = 0;
6108   int part_of_multiple = (loc != NULL);
6109   struct value_print_options opts;
6110
6111   get_user_print_options (&opts);
6112
6113   gdb_assert (!loc || loc_number != 0);
6114   /* See comment in print_one_breakpoint concerning treatment of
6115      breakpoints with single disabled location.  */
6116   if (loc == NULL 
6117       && (b->loc != NULL 
6118           && (b->loc->next != NULL || !b->loc->enabled)))
6119     header_of_multiple = 1;
6120   if (loc == NULL)
6121     loc = b->loc;
6122
6123   annotate_record ();
6124
6125   /* 1 */
6126   annotate_field (0);
6127   if (part_of_multiple)
6128     {
6129       char *formatted;
6130       formatted = xstrprintf ("%d.%d", b->number, loc_number);
6131       uiout->field_string ("number", formatted);
6132       xfree (formatted);
6133     }
6134   else
6135     {
6136       uiout->field_int ("number", b->number);
6137     }
6138
6139   /* 2 */
6140   annotate_field (1);
6141   if (part_of_multiple)
6142     uiout->field_skip ("type");
6143   else
6144     uiout->field_string ("type", bptype_string (b->type));
6145
6146   /* 3 */
6147   annotate_field (2);
6148   if (part_of_multiple)
6149     uiout->field_skip ("disp");
6150   else
6151     uiout->field_string ("disp", bpdisp_text (b->disposition));
6152
6153
6154   /* 4 */
6155   annotate_field (3);
6156   if (part_of_multiple)
6157     uiout->field_string ("enabled", loc->enabled ? "y" : "n");
6158   else
6159     uiout->field_fmt ("enabled", "%c", bpenables[(int) b->enable_state]);
6160   uiout->spaces (2);
6161
6162   
6163   /* 5 and 6 */
6164   if (b->ops != NULL && b->ops->print_one != NULL)
6165     {
6166       /* Although the print_one can possibly print all locations,
6167          calling it here is not likely to get any nice result.  So,
6168          make sure there's just one location.  */
6169       gdb_assert (b->loc == NULL || b->loc->next == NULL);
6170       b->ops->print_one (b, last_loc);
6171     }
6172   else
6173     switch (b->type)
6174       {
6175       case bp_none:
6176         internal_error (__FILE__, __LINE__,
6177                         _("print_one_breakpoint: bp_none encountered\n"));
6178         break;
6179
6180       case bp_watchpoint:
6181       case bp_hardware_watchpoint:
6182       case bp_read_watchpoint:
6183       case bp_access_watchpoint:
6184         {
6185           struct watchpoint *w = (struct watchpoint *) b;
6186
6187           /* Field 4, the address, is omitted (which makes the columns
6188              not line up too nicely with the headers, but the effect
6189              is relatively readable).  */
6190           if (opts.addressprint)
6191             uiout->field_skip ("addr");
6192           annotate_field (5);
6193           uiout->field_string ("what", w->exp_string);
6194         }
6195         break;
6196
6197       case bp_breakpoint:
6198       case bp_hardware_breakpoint:
6199       case bp_single_step:
6200       case bp_until:
6201       case bp_finish:
6202       case bp_longjmp:
6203       case bp_longjmp_resume:
6204       case bp_longjmp_call_dummy:
6205       case bp_exception:
6206       case bp_exception_resume:
6207       case bp_step_resume:
6208       case bp_hp_step_resume:
6209       case bp_watchpoint_scope:
6210       case bp_call_dummy:
6211       case bp_std_terminate:
6212       case bp_shlib_event:
6213       case bp_thread_event:
6214       case bp_overlay_event:
6215       case bp_longjmp_master:
6216       case bp_std_terminate_master:
6217       case bp_exception_master:
6218       case bp_tracepoint:
6219       case bp_fast_tracepoint:
6220       case bp_static_tracepoint:
6221       case bp_dprintf:
6222       case bp_jit_event:
6223       case bp_gnu_ifunc_resolver:
6224       case bp_gnu_ifunc_resolver_return:
6225         if (opts.addressprint)
6226           {
6227             annotate_field (4);
6228             if (header_of_multiple)
6229               uiout->field_string ("addr", "<MULTIPLE>");
6230             else if (b->loc == NULL || loc->shlib_disabled)
6231               uiout->field_string ("addr", "<PENDING>");
6232             else
6233               uiout->field_core_addr ("addr",
6234                                       loc->gdbarch, loc->address);
6235           }
6236         annotate_field (5);
6237         if (!header_of_multiple)
6238           print_breakpoint_location (b, loc);
6239         if (b->loc)
6240           *last_loc = b->loc;
6241         break;
6242       }
6243
6244
6245   if (loc != NULL && !header_of_multiple)
6246     {
6247       struct inferior *inf;
6248       VEC(int) *inf_num = NULL;
6249       int mi_only = 1;
6250
6251       ALL_INFERIORS (inf)
6252         {
6253           if (inf->pspace == loc->pspace)
6254             VEC_safe_push (int, inf_num, inf->num);
6255         }
6256
6257         /* For backward compatibility, don't display inferiors in CLI unless
6258            there are several.  Always display for MI. */
6259         if (allflag
6260             || (!gdbarch_has_global_breakpoints (target_gdbarch ())
6261                 && (number_of_program_spaces () > 1
6262                     || number_of_inferiors () > 1)
6263                 /* LOC is for existing B, it cannot be in
6264                    moribund_locations and thus having NULL OWNER.  */
6265                 && loc->owner->type != bp_catchpoint))
6266         mi_only = 0;
6267       output_thread_groups (uiout, "thread-groups", inf_num, mi_only);
6268       VEC_free (int, inf_num);
6269     }
6270
6271   if (!part_of_multiple)
6272     {
6273       if (b->thread != -1)
6274         {
6275           /* FIXME: This seems to be redundant and lost here; see the
6276              "stop only in" line a little further down.  */
6277           uiout->text (" thread ");
6278           uiout->field_int ("thread", b->thread);
6279         }
6280       else if (b->task != 0)
6281         {
6282           uiout->text (" task ");
6283           uiout->field_int ("task", b->task);
6284         }
6285     }
6286
6287   uiout->text ("\n");
6288
6289   if (!part_of_multiple)
6290     b->ops->print_one_detail (b, uiout);
6291
6292   if (part_of_multiple && frame_id_p (b->frame_id))
6293     {
6294       annotate_field (6);
6295       uiout->text ("\tstop only in stack frame at ");
6296       /* FIXME: cagney/2002-12-01: Shouldn't be poking around inside
6297          the frame ID.  */
6298       uiout->field_core_addr ("frame",
6299                               b->gdbarch, b->frame_id.stack_addr);
6300       uiout->text ("\n");
6301     }
6302   
6303   if (!part_of_multiple && b->cond_string)
6304     {
6305       annotate_field (7);
6306       if (is_tracepoint (b))
6307         uiout->text ("\ttrace only if ");
6308       else
6309         uiout->text ("\tstop only if ");
6310       uiout->field_string ("cond", b->cond_string);
6311
6312       /* Print whether the target is doing the breakpoint's condition
6313          evaluation.  If GDB is doing the evaluation, don't print anything.  */
6314       if (is_breakpoint (b)
6315           && breakpoint_condition_evaluation_mode ()
6316           == condition_evaluation_target)
6317         {
6318           uiout->text (" (");
6319           uiout->field_string ("evaluated-by",
6320                                bp_condition_evaluator (b));
6321           uiout->text (" evals)");
6322         }
6323       uiout->text ("\n");
6324     }
6325
6326   if (!part_of_multiple && b->thread != -1)
6327     {
6328       /* FIXME should make an annotation for this.  */
6329       uiout->text ("\tstop only in thread ");
6330       if (uiout->is_mi_like_p ())
6331         uiout->field_int ("thread", b->thread);
6332       else
6333         {
6334           struct thread_info *thr = find_thread_global_id (b->thread);
6335
6336           uiout->field_string ("thread", print_thread_id (thr));
6337         }
6338       uiout->text ("\n");
6339     }
6340   
6341   if (!part_of_multiple)
6342     {
6343       if (b->hit_count)
6344         {
6345           /* FIXME should make an annotation for this.  */
6346           if (is_catchpoint (b))
6347             uiout->text ("\tcatchpoint");
6348           else if (is_tracepoint (b))
6349             uiout->text ("\ttracepoint");
6350           else
6351             uiout->text ("\tbreakpoint");
6352           uiout->text (" already hit ");
6353           uiout->field_int ("times", b->hit_count);
6354           if (b->hit_count == 1)
6355             uiout->text (" time\n");
6356           else
6357             uiout->text (" times\n");
6358         }
6359       else
6360         {
6361           /* Output the count also if it is zero, but only if this is mi.  */
6362           if (uiout->is_mi_like_p ())
6363             uiout->field_int ("times", b->hit_count);
6364         }
6365     }
6366
6367   if (!part_of_multiple && b->ignore_count)
6368     {
6369       annotate_field (8);
6370       uiout->text ("\tignore next ");
6371       uiout->field_int ("ignore", b->ignore_count);
6372       uiout->text (" hits\n");
6373     }
6374
6375   /* Note that an enable count of 1 corresponds to "enable once"
6376      behavior, which is reported by the combination of enablement and
6377      disposition, so we don't need to mention it here.  */
6378   if (!part_of_multiple && b->enable_count > 1)
6379     {
6380       annotate_field (8);
6381       uiout->text ("\tdisable after ");
6382       /* Tweak the wording to clarify that ignore and enable counts
6383          are distinct, and have additive effect.  */
6384       if (b->ignore_count)
6385         uiout->text ("additional ");
6386       else
6387         uiout->text ("next ");
6388       uiout->field_int ("enable", b->enable_count);
6389       uiout->text (" hits\n");
6390     }
6391
6392   if (!part_of_multiple && is_tracepoint (b))
6393     {
6394       struct tracepoint *tp = (struct tracepoint *) b;
6395
6396       if (tp->traceframe_usage)
6397         {
6398           uiout->text ("\ttrace buffer usage ");
6399           uiout->field_int ("traceframe-usage", tp->traceframe_usage);
6400           uiout->text (" bytes\n");
6401         }
6402     }
6403
6404   l = b->commands ? b->commands.get () : NULL;
6405   if (!part_of_multiple && l)
6406     {
6407       annotate_field (9);
6408       ui_out_emit_tuple tuple_emitter (uiout, "script");
6409       print_command_lines (uiout, l, 4);
6410     }
6411
6412   if (is_tracepoint (b))
6413     {
6414       struct tracepoint *t = (struct tracepoint *) b;
6415
6416       if (!part_of_multiple && t->pass_count)
6417         {
6418           annotate_field (10);
6419           uiout->text ("\tpass count ");
6420           uiout->field_int ("pass", t->pass_count);
6421           uiout->text (" \n");
6422         }
6423
6424       /* Don't display it when tracepoint or tracepoint location is
6425          pending.   */
6426       if (!header_of_multiple && loc != NULL && !loc->shlib_disabled)
6427         {
6428           annotate_field (11);
6429
6430           if (uiout->is_mi_like_p ())
6431             uiout->field_string ("installed",
6432                                  loc->inserted ? "y" : "n");
6433           else
6434             {
6435               if (loc->inserted)
6436                 uiout->text ("\t");
6437               else
6438                 uiout->text ("\tnot ");
6439               uiout->text ("installed on target\n");
6440             }
6441         }
6442     }
6443
6444   if (uiout->is_mi_like_p () && !part_of_multiple)
6445     {
6446       if (is_watchpoint (b))
6447         {
6448           struct watchpoint *w = (struct watchpoint *) b;
6449
6450           uiout->field_string ("original-location", w->exp_string);
6451         }
6452       else if (b->location != NULL
6453                && event_location_to_string (b->location.get ()) != NULL)
6454         uiout->field_string ("original-location",
6455                              event_location_to_string (b->location.get ()));
6456     }
6457 }
6458
6459 static void
6460 print_one_breakpoint (struct breakpoint *b,
6461                       struct bp_location **last_loc, 
6462                       int allflag)
6463 {
6464   struct ui_out *uiout = current_uiout;
6465
6466   {
6467     ui_out_emit_tuple tuple_emitter (uiout, "bkpt");
6468
6469     print_one_breakpoint_location (b, NULL, 0, last_loc, allflag);
6470   }
6471
6472   /* If this breakpoint has custom print function,
6473      it's already printed.  Otherwise, print individual
6474      locations, if any.  */
6475   if (b->ops == NULL || b->ops->print_one == NULL)
6476     {
6477       /* If breakpoint has a single location that is disabled, we
6478          print it as if it had several locations, since otherwise it's
6479          hard to represent "breakpoint enabled, location disabled"
6480          situation.
6481
6482          Note that while hardware watchpoints have several locations
6483          internally, that's not a property exposed to user.  */
6484       if (b->loc 
6485           && !is_hardware_watchpoint (b)
6486           && (b->loc->next || !b->loc->enabled))
6487         {
6488           struct bp_location *loc;
6489           int n = 1;
6490
6491           for (loc = b->loc; loc; loc = loc->next, ++n)
6492             {
6493               ui_out_emit_tuple tuple_emitter (uiout, NULL);
6494               print_one_breakpoint_location (b, loc, n, last_loc, allflag);
6495             }
6496         }
6497     }
6498 }
6499
6500 static int
6501 breakpoint_address_bits (struct breakpoint *b)
6502 {
6503   int print_address_bits = 0;
6504   struct bp_location *loc;
6505
6506   /* Software watchpoints that aren't watching memory don't have an
6507      address to print.  */
6508   if (is_no_memory_software_watchpoint (b))
6509     return 0;
6510
6511   for (loc = b->loc; loc; loc = loc->next)
6512     {
6513       int addr_bit;
6514
6515       addr_bit = gdbarch_addr_bit (loc->gdbarch);
6516       if (addr_bit > print_address_bits)
6517         print_address_bits = addr_bit;
6518     }
6519
6520   return print_address_bits;
6521 }
6522
6523 /* See breakpoint.h.  */
6524
6525 void
6526 print_breakpoint (breakpoint *b)
6527 {
6528   struct bp_location *dummy_loc = NULL;
6529   print_one_breakpoint (b, &dummy_loc, 0);
6530 }
6531
6532 /* Return true if this breakpoint was set by the user, false if it is
6533    internal or momentary.  */
6534
6535 int
6536 user_breakpoint_p (struct breakpoint *b)
6537 {
6538   return b->number > 0;
6539 }
6540
6541 /* See breakpoint.h.  */
6542
6543 int
6544 pending_breakpoint_p (struct breakpoint *b)
6545 {
6546   return b->loc == NULL;
6547 }
6548
6549 /* Print information on user settable breakpoint (watchpoint, etc)
6550    number BNUM.  If BNUM is -1 print all user-settable breakpoints.
6551    If ALLFLAG is non-zero, include non-user-settable breakpoints.  If
6552    FILTER is non-NULL, call it on each breakpoint and only include the
6553    ones for which it returns non-zero.  Return the total number of
6554    breakpoints listed.  */
6555
6556 static int
6557 breakpoint_1 (const char *args, int allflag, 
6558               int (*filter) (const struct breakpoint *))
6559 {
6560   struct breakpoint *b;
6561   struct bp_location *last_loc = NULL;
6562   int nr_printable_breakpoints;
6563   struct value_print_options opts;
6564   int print_address_bits = 0;
6565   int print_type_col_width = 14;
6566   struct ui_out *uiout = current_uiout;
6567
6568   get_user_print_options (&opts);
6569
6570   /* Compute the number of rows in the table, as well as the size
6571      required for address fields.  */
6572   nr_printable_breakpoints = 0;
6573   ALL_BREAKPOINTS (b)
6574     {
6575       /* If we have a filter, only list the breakpoints it accepts.  */
6576       if (filter && !filter (b))
6577         continue;
6578
6579       /* If we have an "args" string, it is a list of breakpoints to 
6580          accept.  Skip the others.  */
6581       if (args != NULL && *args != '\0')
6582         {
6583           if (allflag && parse_and_eval_long (args) != b->number)
6584             continue;
6585           if (!allflag && !number_is_in_list (args, b->number))
6586             continue;
6587         }
6588
6589       if (allflag || user_breakpoint_p (b))
6590         {
6591           int addr_bit, type_len;
6592
6593           addr_bit = breakpoint_address_bits (b);
6594           if (addr_bit > print_address_bits)
6595             print_address_bits = addr_bit;
6596
6597           type_len = strlen (bptype_string (b->type));
6598           if (type_len > print_type_col_width)
6599             print_type_col_width = type_len;
6600
6601           nr_printable_breakpoints++;
6602         }
6603     }
6604
6605   {
6606     ui_out_emit_table table_emitter (uiout,
6607                                      opts.addressprint ? 6 : 5,
6608                                      nr_printable_breakpoints,
6609                                      "BreakpointTable");
6610
6611     if (nr_printable_breakpoints > 0)
6612       annotate_breakpoints_headers ();
6613     if (nr_printable_breakpoints > 0)
6614       annotate_field (0);
6615     uiout->table_header (7, ui_left, "number", "Num"); /* 1 */
6616     if (nr_printable_breakpoints > 0)
6617       annotate_field (1);
6618     uiout->table_header (print_type_col_width, ui_left, "type", "Type"); /* 2 */
6619     if (nr_printable_breakpoints > 0)
6620       annotate_field (2);
6621     uiout->table_header (4, ui_left, "disp", "Disp"); /* 3 */
6622     if (nr_printable_breakpoints > 0)
6623       annotate_field (3);
6624     uiout->table_header (3, ui_left, "enabled", "Enb"); /* 4 */
6625     if (opts.addressprint)
6626       {
6627         if (nr_printable_breakpoints > 0)
6628           annotate_field (4);
6629         if (print_address_bits <= 32)
6630           uiout->table_header (10, ui_left, "addr", "Address"); /* 5 */
6631         else
6632           uiout->table_header (18, ui_left, "addr", "Address"); /* 5 */
6633       }
6634     if (nr_printable_breakpoints > 0)
6635       annotate_field (5);
6636     uiout->table_header (40, ui_noalign, "what", "What"); /* 6 */
6637     uiout->table_body ();
6638     if (nr_printable_breakpoints > 0)
6639       annotate_breakpoints_table ();
6640
6641     ALL_BREAKPOINTS (b)
6642       {
6643         QUIT;
6644         /* If we have a filter, only list the breakpoints it accepts.  */
6645         if (filter && !filter (b))
6646           continue;
6647
6648         /* If we have an "args" string, it is a list of breakpoints to 
6649            accept.  Skip the others.  */
6650
6651         if (args != NULL && *args != '\0')
6652           {
6653             if (allflag)        /* maintenance info breakpoint */
6654               {
6655                 if (parse_and_eval_long (args) != b->number)
6656                   continue;
6657               }
6658             else                /* all others */
6659               {
6660                 if (!number_is_in_list (args, b->number))
6661                   continue;
6662               }
6663           }
6664         /* We only print out user settable breakpoints unless the
6665            allflag is set.  */
6666         if (allflag || user_breakpoint_p (b))
6667           print_one_breakpoint (b, &last_loc, allflag);
6668       }
6669   }
6670
6671   if (nr_printable_breakpoints == 0)
6672     {
6673       /* If there's a filter, let the caller decide how to report
6674          empty list.  */
6675       if (!filter)
6676         {
6677           if (args == NULL || *args == '\0')
6678             uiout->message ("No breakpoints or watchpoints.\n");
6679           else
6680             uiout->message ("No breakpoint or watchpoint matching '%s'.\n",
6681                             args);
6682         }
6683     }
6684   else
6685     {
6686       if (last_loc && !server_command)
6687         set_next_address (last_loc->gdbarch, last_loc->address);
6688     }
6689
6690   /* FIXME?  Should this be moved up so that it is only called when
6691      there have been breakpoints? */
6692   annotate_breakpoints_table_end ();
6693
6694   return nr_printable_breakpoints;
6695 }
6696
6697 /* Display the value of default-collect in a way that is generally
6698    compatible with the breakpoint list.  */
6699
6700 static void
6701 default_collect_info (void)
6702 {
6703   struct ui_out *uiout = current_uiout;
6704
6705   /* If it has no value (which is frequently the case), say nothing; a
6706      message like "No default-collect." gets in user's face when it's
6707      not wanted.  */
6708   if (!*default_collect)
6709     return;
6710
6711   /* The following phrase lines up nicely with per-tracepoint collect
6712      actions.  */
6713   uiout->text ("default collect ");
6714   uiout->field_string ("default-collect", default_collect);
6715   uiout->text (" \n");
6716 }
6717   
6718 static void
6719 info_breakpoints_command (char *args, int from_tty)
6720 {
6721   breakpoint_1 (args, 0, NULL);
6722
6723   default_collect_info ();
6724 }
6725
6726 static void
6727 info_watchpoints_command (char *args, int from_tty)
6728 {
6729   int num_printed = breakpoint_1 (args, 0, is_watchpoint);
6730   struct ui_out *uiout = current_uiout;
6731
6732   if (num_printed == 0)
6733     {
6734       if (args == NULL || *args == '\0')
6735         uiout->message ("No watchpoints.\n");
6736       else
6737         uiout->message ("No watchpoint matching '%s'.\n", args);
6738     }
6739 }
6740
6741 static void
6742 maintenance_info_breakpoints (const char *args, int from_tty)
6743 {
6744   breakpoint_1 (args, 1, NULL);
6745
6746   default_collect_info ();
6747 }
6748
6749 static int
6750 breakpoint_has_pc (struct breakpoint *b,
6751                    struct program_space *pspace,
6752                    CORE_ADDR pc, struct obj_section *section)
6753 {
6754   struct bp_location *bl = b->loc;
6755
6756   for (; bl; bl = bl->next)
6757     {
6758       if (bl->pspace == pspace
6759           && bl->address == pc
6760           && (!overlay_debugging || bl->section == section))
6761         return 1;         
6762     }
6763   return 0;
6764 }
6765
6766 /* Print a message describing any user-breakpoints set at PC.  This
6767    concerns with logical breakpoints, so we match program spaces, not
6768    address spaces.  */
6769
6770 static void
6771 describe_other_breakpoints (struct gdbarch *gdbarch,
6772                             struct program_space *pspace, CORE_ADDR pc,
6773                             struct obj_section *section, int thread)
6774 {
6775   int others = 0;
6776   struct breakpoint *b;
6777
6778   ALL_BREAKPOINTS (b)
6779     others += (user_breakpoint_p (b)
6780                && breakpoint_has_pc (b, pspace, pc, section));
6781   if (others > 0)
6782     {
6783       if (others == 1)
6784         printf_filtered (_("Note: breakpoint "));
6785       else /* if (others == ???) */
6786         printf_filtered (_("Note: breakpoints "));
6787       ALL_BREAKPOINTS (b)
6788         if (user_breakpoint_p (b) && breakpoint_has_pc (b, pspace, pc, section))
6789           {
6790             others--;
6791             printf_filtered ("%d", b->number);
6792             if (b->thread == -1 && thread != -1)
6793               printf_filtered (" (all threads)");
6794             else if (b->thread != -1)
6795               printf_filtered (" (thread %d)", b->thread);
6796             printf_filtered ("%s%s ",
6797                              ((b->enable_state == bp_disabled
6798                                || b->enable_state == bp_call_disabled)
6799                               ? " (disabled)"
6800                               : ""),
6801                              (others > 1) ? "," 
6802                              : ((others == 1) ? " and" : ""));
6803           }
6804       printf_filtered (_("also set at pc "));
6805       fputs_filtered (paddress (gdbarch, pc), gdb_stdout);
6806       printf_filtered (".\n");
6807     }
6808 }
6809 \f
6810
6811 /* Return true iff it is meaningful to use the address member of
6812    BPT locations.  For some breakpoint types, the locations' address members
6813    are irrelevant and it makes no sense to attempt to compare them to other
6814    addresses (or use them for any other purpose either).
6815
6816    More specifically, each of the following breakpoint types will
6817    always have a zero valued location address and we don't want to mark
6818    breakpoints of any of these types to be a duplicate of an actual
6819    breakpoint location at address zero:
6820
6821       bp_watchpoint
6822       bp_catchpoint
6823
6824 */
6825
6826 static int
6827 breakpoint_address_is_meaningful (struct breakpoint *bpt)
6828 {
6829   enum bptype type = bpt->type;
6830
6831   return (type != bp_watchpoint && type != bp_catchpoint);
6832 }
6833
6834 /* Assuming LOC1 and LOC2's owners are hardware watchpoints, returns
6835    true if LOC1 and LOC2 represent the same watchpoint location.  */
6836
6837 static int
6838 watchpoint_locations_match (struct bp_location *loc1, 
6839                             struct bp_location *loc2)
6840 {
6841   struct watchpoint *w1 = (struct watchpoint *) loc1->owner;
6842   struct watchpoint *w2 = (struct watchpoint *) loc2->owner;
6843
6844   /* Both of them must exist.  */
6845   gdb_assert (w1 != NULL);
6846   gdb_assert (w2 != NULL);
6847
6848   /* If the target can evaluate the condition expression in hardware,
6849      then we we need to insert both watchpoints even if they are at
6850      the same place.  Otherwise the watchpoint will only trigger when
6851      the condition of whichever watchpoint was inserted evaluates to
6852      true, not giving a chance for GDB to check the condition of the
6853      other watchpoint.  */
6854   if ((w1->cond_exp
6855        && target_can_accel_watchpoint_condition (loc1->address, 
6856                                                  loc1->length,
6857                                                  loc1->watchpoint_type,
6858                                                  w1->cond_exp.get ()))
6859       || (w2->cond_exp
6860           && target_can_accel_watchpoint_condition (loc2->address, 
6861                                                     loc2->length,
6862                                                     loc2->watchpoint_type,
6863                                                     w2->cond_exp.get ())))
6864     return 0;
6865
6866   /* Note that this checks the owner's type, not the location's.  In
6867      case the target does not support read watchpoints, but does
6868      support access watchpoints, we'll have bp_read_watchpoint
6869      watchpoints with hw_access locations.  Those should be considered
6870      duplicates of hw_read locations.  The hw_read locations will
6871      become hw_access locations later.  */
6872   return (loc1->owner->type == loc2->owner->type
6873           && loc1->pspace->aspace == loc2->pspace->aspace
6874           && loc1->address == loc2->address
6875           && loc1->length == loc2->length);
6876 }
6877
6878 /* See breakpoint.h.  */
6879
6880 int
6881 breakpoint_address_match (const address_space *aspace1, CORE_ADDR addr1,
6882                           const address_space *aspace2, CORE_ADDR addr2)
6883 {
6884   return ((gdbarch_has_global_breakpoints (target_gdbarch ())
6885            || aspace1 == aspace2)
6886           && addr1 == addr2);
6887 }
6888
6889 /* Returns true if {ASPACE2,ADDR2} falls within the range determined by
6890    {ASPACE1,ADDR1,LEN1}.  In most targets, this can only be true if ASPACE1
6891    matches ASPACE2.  On targets that have global breakpoints, the address
6892    space doesn't really matter.  */
6893
6894 static int
6895 breakpoint_address_match_range (const address_space *aspace1,
6896                                 CORE_ADDR addr1,
6897                                 int len1, const address_space *aspace2,
6898                                 CORE_ADDR addr2)
6899 {
6900   return ((gdbarch_has_global_breakpoints (target_gdbarch ())
6901            || aspace1 == aspace2)
6902           && addr2 >= addr1 && addr2 < addr1 + len1);
6903 }
6904
6905 /* Returns true if {ASPACE,ADDR} matches the breakpoint BL.  BL may be
6906    a ranged breakpoint.  In most targets, a match happens only if ASPACE
6907    matches the breakpoint's address space.  On targets that have global
6908    breakpoints, the address space doesn't really matter.  */
6909
6910 static int
6911 breakpoint_location_address_match (struct bp_location *bl,
6912                                    const address_space *aspace,
6913                                    CORE_ADDR addr)
6914 {
6915   return (breakpoint_address_match (bl->pspace->aspace, bl->address,
6916                                     aspace, addr)
6917           || (bl->length
6918               && breakpoint_address_match_range (bl->pspace->aspace,
6919                                                  bl->address, bl->length,
6920                                                  aspace, addr)));
6921 }
6922
6923 /* Returns true if the [ADDR,ADDR+LEN) range in ASPACE overlaps
6924    breakpoint BL.  BL may be a ranged breakpoint.  In most targets, a
6925    match happens only if ASPACE matches the breakpoint's address
6926    space.  On targets that have global breakpoints, the address space
6927    doesn't really matter.  */
6928
6929 static int
6930 breakpoint_location_address_range_overlap (struct bp_location *bl,
6931                                            const address_space *aspace,
6932                                            CORE_ADDR addr, int len)
6933 {
6934   if (gdbarch_has_global_breakpoints (target_gdbarch ())
6935       || bl->pspace->aspace == aspace)
6936     {
6937       int bl_len = bl->length != 0 ? bl->length : 1;
6938
6939       if (mem_ranges_overlap (addr, len, bl->address, bl_len))
6940         return 1;
6941     }
6942   return 0;
6943 }
6944
6945 /* If LOC1 and LOC2's owners are not tracepoints, returns false directly.
6946    Then, if LOC1 and LOC2 represent the same tracepoint location, returns
6947    true, otherwise returns false.  */
6948
6949 static int
6950 tracepoint_locations_match (struct bp_location *loc1,
6951                             struct bp_location *loc2)
6952 {
6953   if (is_tracepoint (loc1->owner) && is_tracepoint (loc2->owner))
6954     /* Since tracepoint locations are never duplicated with others', tracepoint
6955        locations at the same address of different tracepoints are regarded as
6956        different locations.  */
6957     return (loc1->address == loc2->address && loc1->owner == loc2->owner);
6958   else
6959     return 0;
6960 }
6961
6962 /* Assuming LOC1 and LOC2's types' have meaningful target addresses
6963    (breakpoint_address_is_meaningful), returns true if LOC1 and LOC2
6964    represent the same location.  */
6965
6966 static int
6967 breakpoint_locations_match (struct bp_location *loc1, 
6968                             struct bp_location *loc2)
6969 {
6970   int hw_point1, hw_point2;
6971
6972   /* Both of them must not be in moribund_locations.  */
6973   gdb_assert (loc1->owner != NULL);
6974   gdb_assert (loc2->owner != NULL);
6975
6976   hw_point1 = is_hardware_watchpoint (loc1->owner);
6977   hw_point2 = is_hardware_watchpoint (loc2->owner);
6978
6979   if (hw_point1 != hw_point2)
6980     return 0;
6981   else if (hw_point1)
6982     return watchpoint_locations_match (loc1, loc2);
6983   else if (is_tracepoint (loc1->owner) || is_tracepoint (loc2->owner))
6984     return tracepoint_locations_match (loc1, loc2);
6985   else
6986     /* We compare bp_location.length in order to cover ranged breakpoints.  */
6987     return (breakpoint_address_match (loc1->pspace->aspace, loc1->address,
6988                                      loc2->pspace->aspace, loc2->address)
6989             && loc1->length == loc2->length);
6990 }
6991
6992 static void
6993 breakpoint_adjustment_warning (CORE_ADDR from_addr, CORE_ADDR to_addr,
6994                                int bnum, int have_bnum)
6995 {
6996   /* The longest string possibly returned by hex_string_custom
6997      is 50 chars.  These must be at least that big for safety.  */
6998   char astr1[64];
6999   char astr2[64];
7000
7001   strcpy (astr1, hex_string_custom ((unsigned long) from_addr, 8));
7002   strcpy (astr2, hex_string_custom ((unsigned long) to_addr, 8));
7003   if (have_bnum)
7004     warning (_("Breakpoint %d address previously adjusted from %s to %s."),
7005              bnum, astr1, astr2);
7006   else
7007     warning (_("Breakpoint address adjusted from %s to %s."), astr1, astr2);
7008 }
7009
7010 /* Adjust a breakpoint's address to account for architectural
7011    constraints on breakpoint placement.  Return the adjusted address.
7012    Note: Very few targets require this kind of adjustment.  For most
7013    targets, this function is simply the identity function.  */
7014
7015 static CORE_ADDR
7016 adjust_breakpoint_address (struct gdbarch *gdbarch,
7017                            CORE_ADDR bpaddr, enum bptype bptype)
7018 {
7019   if (!gdbarch_adjust_breakpoint_address_p (gdbarch))
7020     {
7021       /* Very few targets need any kind of breakpoint adjustment.  */
7022       return bpaddr;
7023     }
7024   else if (bptype == bp_watchpoint
7025            || bptype == bp_hardware_watchpoint
7026            || bptype == bp_read_watchpoint
7027            || bptype == bp_access_watchpoint
7028            || bptype == bp_catchpoint)
7029     {
7030       /* Watchpoints and the various bp_catch_* eventpoints should not
7031          have their addresses modified.  */
7032       return bpaddr;
7033     }
7034   else if (bptype == bp_single_step)
7035     {
7036       /* Single-step breakpoints should not have their addresses
7037          modified.  If there's any architectural constrain that
7038          applies to this address, then it should have already been
7039          taken into account when the breakpoint was created in the
7040          first place.  If we didn't do this, stepping through e.g.,
7041          Thumb-2 IT blocks would break.  */
7042       return bpaddr;
7043     }
7044   else
7045     {
7046       CORE_ADDR adjusted_bpaddr;
7047
7048       /* Some targets have architectural constraints on the placement
7049          of breakpoint instructions.  Obtain the adjusted address.  */
7050       adjusted_bpaddr = gdbarch_adjust_breakpoint_address (gdbarch, bpaddr);
7051
7052       /* An adjusted breakpoint address can significantly alter
7053          a user's expectations.  Print a warning if an adjustment
7054          is required.  */
7055       if (adjusted_bpaddr != bpaddr)
7056         breakpoint_adjustment_warning (bpaddr, adjusted_bpaddr, 0, 0);
7057
7058       return adjusted_bpaddr;
7059     }
7060 }
7061
7062 bp_location::bp_location (const bp_location_ops *ops, breakpoint *owner)
7063 {
7064   bp_location *loc = this;
7065
7066   gdb_assert (ops != NULL);
7067
7068   loc->ops = ops;
7069   loc->owner = owner;
7070   loc->cond_bytecode = NULL;
7071   loc->shlib_disabled = 0;
7072   loc->enabled = 1;
7073
7074   switch (owner->type)
7075     {
7076     case bp_breakpoint:
7077     case bp_single_step:
7078     case bp_until:
7079     case bp_finish:
7080     case bp_longjmp:
7081     case bp_longjmp_resume:
7082     case bp_longjmp_call_dummy:
7083     case bp_exception:
7084     case bp_exception_resume:
7085     case bp_step_resume:
7086     case bp_hp_step_resume:
7087     case bp_watchpoint_scope:
7088     case bp_call_dummy:
7089     case bp_std_terminate:
7090     case bp_shlib_event:
7091     case bp_thread_event:
7092     case bp_overlay_event:
7093     case bp_jit_event:
7094     case bp_longjmp_master:
7095     case bp_std_terminate_master:
7096     case bp_exception_master:
7097     case bp_gnu_ifunc_resolver:
7098     case bp_gnu_ifunc_resolver_return:
7099     case bp_dprintf:
7100       loc->loc_type = bp_loc_software_breakpoint;
7101       mark_breakpoint_location_modified (loc);
7102       break;
7103     case bp_hardware_breakpoint:
7104       loc->loc_type = bp_loc_hardware_breakpoint;
7105       mark_breakpoint_location_modified (loc);
7106       break;
7107     case bp_hardware_watchpoint:
7108     case bp_read_watchpoint:
7109     case bp_access_watchpoint:
7110       loc->loc_type = bp_loc_hardware_watchpoint;
7111       break;
7112     case bp_watchpoint:
7113     case bp_catchpoint:
7114     case bp_tracepoint:
7115     case bp_fast_tracepoint:
7116     case bp_static_tracepoint:
7117       loc->loc_type = bp_loc_other;
7118       break;
7119     default:
7120       internal_error (__FILE__, __LINE__, _("unknown breakpoint type"));
7121     }
7122
7123   loc->refc = 1;
7124 }
7125
7126 /* Allocate a struct bp_location.  */
7127
7128 static struct bp_location *
7129 allocate_bp_location (struct breakpoint *bpt)
7130 {
7131   return bpt->ops->allocate_location (bpt);
7132 }
7133
7134 static void
7135 free_bp_location (struct bp_location *loc)
7136 {
7137   loc->ops->dtor (loc);
7138   delete loc;
7139 }
7140
7141 /* Increment reference count.  */
7142
7143 static void
7144 incref_bp_location (struct bp_location *bl)
7145 {
7146   ++bl->refc;
7147 }
7148
7149 /* Decrement reference count.  If the reference count reaches 0,
7150    destroy the bp_location.  Sets *BLP to NULL.  */
7151
7152 static void
7153 decref_bp_location (struct bp_location **blp)
7154 {
7155   gdb_assert ((*blp)->refc > 0);
7156
7157   if (--(*blp)->refc == 0)
7158     free_bp_location (*blp);
7159   *blp = NULL;
7160 }
7161
7162 /* Add breakpoint B at the end of the global breakpoint chain.  */
7163
7164 static breakpoint *
7165 add_to_breakpoint_chain (std::unique_ptr<breakpoint> &&b)
7166 {
7167   struct breakpoint *b1;
7168   struct breakpoint *result = b.get ();
7169
7170   /* Add this breakpoint to the end of the chain so that a list of
7171      breakpoints will come out in order of increasing numbers.  */
7172
7173   b1 = breakpoint_chain;
7174   if (b1 == 0)
7175     breakpoint_chain = b.release ();
7176   else
7177     {
7178       while (b1->next)
7179         b1 = b1->next;
7180       b1->next = b.release ();
7181     }
7182
7183   return result;
7184 }
7185
7186 /* Initializes breakpoint B with type BPTYPE and no locations yet.  */
7187
7188 static void
7189 init_raw_breakpoint_without_location (struct breakpoint *b,
7190                                       struct gdbarch *gdbarch,
7191                                       enum bptype bptype,
7192                                       const struct breakpoint_ops *ops)
7193 {
7194   gdb_assert (ops != NULL);
7195
7196   b->ops = ops;
7197   b->type = bptype;
7198   b->gdbarch = gdbarch;
7199   b->language = current_language->la_language;
7200   b->input_radix = input_radix;
7201   b->related_breakpoint = b;
7202 }
7203
7204 /* Helper to set_raw_breakpoint below.  Creates a breakpoint
7205    that has type BPTYPE and has no locations as yet.  */
7206
7207 static struct breakpoint *
7208 set_raw_breakpoint_without_location (struct gdbarch *gdbarch,
7209                                      enum bptype bptype,
7210                                      const struct breakpoint_ops *ops)
7211 {
7212   std::unique_ptr<breakpoint> b = new_breakpoint_from_type (bptype);
7213
7214   init_raw_breakpoint_without_location (b.get (), gdbarch, bptype, ops);
7215   return add_to_breakpoint_chain (std::move (b));
7216 }
7217
7218 /* Initialize loc->function_name.  EXPLICIT_LOC says no indirect function
7219    resolutions should be made as the user specified the location explicitly
7220    enough.  */
7221
7222 static void
7223 set_breakpoint_location_function (struct bp_location *loc, int explicit_loc)
7224 {
7225   gdb_assert (loc->owner != NULL);
7226
7227   if (loc->owner->type == bp_breakpoint
7228       || loc->owner->type == bp_hardware_breakpoint
7229       || is_tracepoint (loc->owner))
7230     {
7231       int is_gnu_ifunc;
7232       const char *function_name;
7233       CORE_ADDR func_addr;
7234
7235       find_pc_partial_function_gnu_ifunc (loc->address, &function_name,
7236                                           &func_addr, NULL, &is_gnu_ifunc);
7237
7238       if (is_gnu_ifunc && !explicit_loc)
7239         {
7240           struct breakpoint *b = loc->owner;
7241
7242           gdb_assert (loc->pspace == current_program_space);
7243           if (gnu_ifunc_resolve_name (function_name,
7244                                       &loc->requested_address))
7245             {
7246               /* Recalculate ADDRESS based on new REQUESTED_ADDRESS.  */
7247               loc->address = adjust_breakpoint_address (loc->gdbarch,
7248                                                         loc->requested_address,
7249                                                         b->type);
7250             }
7251           else if (b->type == bp_breakpoint && b->loc == loc
7252                    && loc->next == NULL && b->related_breakpoint == b)
7253             {
7254               /* Create only the whole new breakpoint of this type but do not
7255                  mess more complicated breakpoints with multiple locations.  */
7256               b->type = bp_gnu_ifunc_resolver;
7257               /* Remember the resolver's address for use by the return
7258                  breakpoint.  */
7259               loc->related_address = func_addr;
7260             }
7261         }
7262
7263       if (function_name)
7264         loc->function_name = xstrdup (function_name);
7265     }
7266 }
7267
7268 /* Attempt to determine architecture of location identified by SAL.  */
7269 struct gdbarch *
7270 get_sal_arch (struct symtab_and_line sal)
7271 {
7272   if (sal.section)
7273     return get_objfile_arch (sal.section->objfile);
7274   if (sal.symtab)
7275     return get_objfile_arch (SYMTAB_OBJFILE (sal.symtab));
7276
7277   return NULL;
7278 }
7279
7280 /* Low level routine for partially initializing a breakpoint of type
7281    BPTYPE.  The newly created breakpoint's address, section, source
7282    file name, and line number are provided by SAL.
7283
7284    It is expected that the caller will complete the initialization of
7285    the newly created breakpoint struct as well as output any status
7286    information regarding the creation of a new breakpoint.  */
7287
7288 static void
7289 init_raw_breakpoint (struct breakpoint *b, struct gdbarch *gdbarch,
7290                      struct symtab_and_line sal, enum bptype bptype,
7291                      const struct breakpoint_ops *ops)
7292 {
7293   init_raw_breakpoint_without_location (b, gdbarch, bptype, ops);
7294
7295   add_location_to_breakpoint (b, &sal);
7296
7297   if (bptype != bp_catchpoint)
7298     gdb_assert (sal.pspace != NULL);
7299
7300   /* Store the program space that was used to set the breakpoint,
7301      except for ordinary breakpoints, which are independent of the
7302      program space.  */
7303   if (bptype != bp_breakpoint && bptype != bp_hardware_breakpoint)
7304     b->pspace = sal.pspace;
7305 }
7306
7307 /* set_raw_breakpoint is a low level routine for allocating and
7308    partially initializing a breakpoint of type BPTYPE.  The newly
7309    created breakpoint's address, section, source file name, and line
7310    number are provided by SAL.  The newly created and partially
7311    initialized breakpoint is added to the breakpoint chain and
7312    is also returned as the value of this function.
7313
7314    It is expected that the caller will complete the initialization of
7315    the newly created breakpoint struct as well as output any status
7316    information regarding the creation of a new breakpoint.  In
7317    particular, set_raw_breakpoint does NOT set the breakpoint
7318    number!  Care should be taken to not allow an error to occur
7319    prior to completing the initialization of the breakpoint.  If this
7320    should happen, a bogus breakpoint will be left on the chain.  */
7321
7322 struct breakpoint *
7323 set_raw_breakpoint (struct gdbarch *gdbarch,
7324                     struct symtab_and_line sal, enum bptype bptype,
7325                     const struct breakpoint_ops *ops)
7326 {
7327   std::unique_ptr<breakpoint> b = new_breakpoint_from_type (bptype);
7328
7329   init_raw_breakpoint (b.get (), gdbarch, sal, bptype, ops);
7330   return add_to_breakpoint_chain (std::move (b));
7331 }
7332
7333 /* Call this routine when stepping and nexting to enable a breakpoint
7334    if we do a longjmp() or 'throw' in TP.  FRAME is the frame which
7335    initiated the operation.  */
7336
7337 void
7338 set_longjmp_breakpoint (struct thread_info *tp, struct frame_id frame)
7339 {
7340   struct breakpoint *b, *b_tmp;
7341   int thread = tp->global_num;
7342
7343   /* To avoid having to rescan all objfile symbols at every step,
7344      we maintain a list of continually-inserted but always disabled
7345      longjmp "master" breakpoints.  Here, we simply create momentary
7346      clones of those and enable them for the requested thread.  */
7347   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7348     if (b->pspace == current_program_space
7349         && (b->type == bp_longjmp_master
7350             || b->type == bp_exception_master))
7351       {
7352         enum bptype type = b->type == bp_longjmp_master ? bp_longjmp : bp_exception;
7353         struct breakpoint *clone;
7354
7355         /* longjmp_breakpoint_ops ensures INITIATING_FRAME is cleared again
7356            after their removal.  */
7357         clone = momentary_breakpoint_from_master (b, type,
7358                                                   &momentary_breakpoint_ops, 1);
7359         clone->thread = thread;
7360       }
7361
7362   tp->initiating_frame = frame;
7363 }
7364
7365 /* Delete all longjmp breakpoints from THREAD.  */
7366 void
7367 delete_longjmp_breakpoint (int thread)
7368 {
7369   struct breakpoint *b, *b_tmp;
7370
7371   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7372     if (b->type == bp_longjmp || b->type == bp_exception)
7373       {
7374         if (b->thread == thread)
7375           delete_breakpoint (b);
7376       }
7377 }
7378
7379 void
7380 delete_longjmp_breakpoint_at_next_stop (int thread)
7381 {
7382   struct breakpoint *b, *b_tmp;
7383
7384   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7385     if (b->type == bp_longjmp || b->type == bp_exception)
7386       {
7387         if (b->thread == thread)
7388           b->disposition = disp_del_at_next_stop;
7389       }
7390 }
7391
7392 /* Place breakpoints of type bp_longjmp_call_dummy to catch longjmp for
7393    INFERIOR_PTID thread.  Chain them all by RELATED_BREAKPOINT and return
7394    pointer to any of them.  Return NULL if this system cannot place longjmp
7395    breakpoints.  */
7396
7397 struct breakpoint *
7398 set_longjmp_breakpoint_for_call_dummy (void)
7399 {
7400   struct breakpoint *b, *retval = NULL;
7401
7402   ALL_BREAKPOINTS (b)
7403     if (b->pspace == current_program_space && b->type == bp_longjmp_master)
7404       {
7405         struct breakpoint *new_b;
7406
7407         new_b = momentary_breakpoint_from_master (b, bp_longjmp_call_dummy,
7408                                                   &momentary_breakpoint_ops,
7409                                                   1);
7410         new_b->thread = ptid_to_global_thread_id (inferior_ptid);
7411
7412         /* Link NEW_B into the chain of RETVAL breakpoints.  */
7413
7414         gdb_assert (new_b->related_breakpoint == new_b);
7415         if (retval == NULL)
7416           retval = new_b;
7417         new_b->related_breakpoint = retval;
7418         while (retval->related_breakpoint != new_b->related_breakpoint)
7419           retval = retval->related_breakpoint;
7420         retval->related_breakpoint = new_b;
7421       }
7422
7423   return retval;
7424 }
7425
7426 /* Verify all existing dummy frames and their associated breakpoints for
7427    TP.  Remove those which can no longer be found in the current frame
7428    stack.
7429
7430    You should call this function only at places where it is safe to currently
7431    unwind the whole stack.  Failed stack unwind would discard live dummy
7432    frames.  */
7433
7434 void
7435 check_longjmp_breakpoint_for_call_dummy (struct thread_info *tp)
7436 {
7437   struct breakpoint *b, *b_tmp;
7438
7439   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7440     if (b->type == bp_longjmp_call_dummy && b->thread == tp->global_num)
7441       {
7442         struct breakpoint *dummy_b = b->related_breakpoint;
7443
7444         while (dummy_b != b && dummy_b->type != bp_call_dummy)
7445           dummy_b = dummy_b->related_breakpoint;
7446         if (dummy_b->type != bp_call_dummy
7447             || frame_find_by_id (dummy_b->frame_id) != NULL)
7448           continue;
7449         
7450         dummy_frame_discard (dummy_b->frame_id, tp->ptid);
7451
7452         while (b->related_breakpoint != b)
7453           {
7454             if (b_tmp == b->related_breakpoint)
7455               b_tmp = b->related_breakpoint->next;
7456             delete_breakpoint (b->related_breakpoint);
7457           }
7458         delete_breakpoint (b);
7459       }
7460 }
7461
7462 void
7463 enable_overlay_breakpoints (void)
7464 {
7465   struct breakpoint *b;
7466
7467   ALL_BREAKPOINTS (b)
7468     if (b->type == bp_overlay_event)
7469     {
7470       b->enable_state = bp_enabled;
7471       update_global_location_list (UGLL_MAY_INSERT);
7472       overlay_events_enabled = 1;
7473     }
7474 }
7475
7476 void
7477 disable_overlay_breakpoints (void)
7478 {
7479   struct breakpoint *b;
7480
7481   ALL_BREAKPOINTS (b)
7482     if (b->type == bp_overlay_event)
7483     {
7484       b->enable_state = bp_disabled;
7485       update_global_location_list (UGLL_DONT_INSERT);
7486       overlay_events_enabled = 0;
7487     }
7488 }
7489
7490 /* Set an active std::terminate breakpoint for each std::terminate
7491    master breakpoint.  */
7492 void
7493 set_std_terminate_breakpoint (void)
7494 {
7495   struct breakpoint *b, *b_tmp;
7496
7497   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7498     if (b->pspace == current_program_space
7499         && b->type == bp_std_terminate_master)
7500       {
7501         momentary_breakpoint_from_master (b, bp_std_terminate,
7502                                           &momentary_breakpoint_ops, 1);
7503       }
7504 }
7505
7506 /* Delete all the std::terminate breakpoints.  */
7507 void
7508 delete_std_terminate_breakpoint (void)
7509 {
7510   struct breakpoint *b, *b_tmp;
7511
7512   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7513     if (b->type == bp_std_terminate)
7514       delete_breakpoint (b);
7515 }
7516
7517 struct breakpoint *
7518 create_thread_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7519 {
7520   struct breakpoint *b;
7521
7522   b = create_internal_breakpoint (gdbarch, address, bp_thread_event,
7523                                   &internal_breakpoint_ops);
7524
7525   b->enable_state = bp_enabled;
7526   /* location has to be used or breakpoint_re_set will delete me.  */
7527   b->location = new_address_location (b->loc->address, NULL, 0);
7528
7529   update_global_location_list_nothrow (UGLL_MAY_INSERT);
7530
7531   return b;
7532 }
7533
7534 struct lang_and_radix
7535   {
7536     enum language lang;
7537     int radix;
7538   };
7539
7540 /* Create a breakpoint for JIT code registration and unregistration.  */
7541
7542 struct breakpoint *
7543 create_jit_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7544 {
7545   return create_internal_breakpoint (gdbarch, address, bp_jit_event,
7546                                      &internal_breakpoint_ops);
7547 }
7548
7549 /* Remove JIT code registration and unregistration breakpoint(s).  */
7550
7551 void
7552 remove_jit_event_breakpoints (void)
7553 {
7554   struct breakpoint *b, *b_tmp;
7555
7556   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7557     if (b->type == bp_jit_event
7558         && b->loc->pspace == current_program_space)
7559       delete_breakpoint (b);
7560 }
7561
7562 void
7563 remove_solib_event_breakpoints (void)
7564 {
7565   struct breakpoint *b, *b_tmp;
7566
7567   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7568     if (b->type == bp_shlib_event
7569         && b->loc->pspace == current_program_space)
7570       delete_breakpoint (b);
7571 }
7572
7573 /* See breakpoint.h.  */
7574
7575 void
7576 remove_solib_event_breakpoints_at_next_stop (void)
7577 {
7578   struct breakpoint *b, *b_tmp;
7579
7580   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7581     if (b->type == bp_shlib_event
7582         && b->loc->pspace == current_program_space)
7583       b->disposition = disp_del_at_next_stop;
7584 }
7585
7586 /* Helper for create_solib_event_breakpoint /
7587    create_and_insert_solib_event_breakpoint.  Allows specifying which
7588    INSERT_MODE to pass through to update_global_location_list.  */
7589
7590 static struct breakpoint *
7591 create_solib_event_breakpoint_1 (struct gdbarch *gdbarch, CORE_ADDR address,
7592                                  enum ugll_insert_mode insert_mode)
7593 {
7594   struct breakpoint *b;
7595
7596   b = create_internal_breakpoint (gdbarch, address, bp_shlib_event,
7597                                   &internal_breakpoint_ops);
7598   update_global_location_list_nothrow (insert_mode);
7599   return b;
7600 }
7601
7602 struct breakpoint *
7603 create_solib_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7604 {
7605   return create_solib_event_breakpoint_1 (gdbarch, address, UGLL_MAY_INSERT);
7606 }
7607
7608 /* See breakpoint.h.  */
7609
7610 struct breakpoint *
7611 create_and_insert_solib_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7612 {
7613   struct breakpoint *b;
7614
7615   /* Explicitly tell update_global_location_list to insert
7616      locations.  */
7617   b = create_solib_event_breakpoint_1 (gdbarch, address, UGLL_INSERT);
7618   if (!b->loc->inserted)
7619     {
7620       delete_breakpoint (b);
7621       return NULL;
7622     }
7623   return b;
7624 }
7625
7626 /* Disable any breakpoints that are on code in shared libraries.  Only
7627    apply to enabled breakpoints, disabled ones can just stay disabled.  */
7628
7629 void
7630 disable_breakpoints_in_shlibs (void)
7631 {
7632   struct bp_location *loc, **locp_tmp;
7633
7634   ALL_BP_LOCATIONS (loc, locp_tmp)
7635   {
7636     /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
7637     struct breakpoint *b = loc->owner;
7638
7639     /* We apply the check to all breakpoints, including disabled for
7640        those with loc->duplicate set.  This is so that when breakpoint
7641        becomes enabled, or the duplicate is removed, gdb will try to
7642        insert all breakpoints.  If we don't set shlib_disabled here,
7643        we'll try to insert those breakpoints and fail.  */
7644     if (((b->type == bp_breakpoint)
7645          || (b->type == bp_jit_event)
7646          || (b->type == bp_hardware_breakpoint)
7647          || (is_tracepoint (b)))
7648         && loc->pspace == current_program_space
7649         && !loc->shlib_disabled
7650         && solib_name_from_address (loc->pspace, loc->address)
7651         )
7652       {
7653         loc->shlib_disabled = 1;
7654       }
7655   }
7656 }
7657
7658 /* Disable any breakpoints and tracepoints that are in SOLIB upon
7659    notification of unloaded_shlib.  Only apply to enabled breakpoints,
7660    disabled ones can just stay disabled.  */
7661
7662 static void
7663 disable_breakpoints_in_unloaded_shlib (struct so_list *solib)
7664 {
7665   struct bp_location *loc, **locp_tmp;
7666   int disabled_shlib_breaks = 0;
7667
7668   ALL_BP_LOCATIONS (loc, locp_tmp)
7669   {
7670     /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
7671     struct breakpoint *b = loc->owner;
7672
7673     if (solib->pspace == loc->pspace
7674         && !loc->shlib_disabled
7675         && (((b->type == bp_breakpoint
7676               || b->type == bp_jit_event
7677               || b->type == bp_hardware_breakpoint)
7678              && (loc->loc_type == bp_loc_hardware_breakpoint
7679                  || loc->loc_type == bp_loc_software_breakpoint))
7680             || is_tracepoint (b))
7681         && solib_contains_address_p (solib, loc->address))
7682       {
7683         loc->shlib_disabled = 1;
7684         /* At this point, we cannot rely on remove_breakpoint
7685            succeeding so we must mark the breakpoint as not inserted
7686            to prevent future errors occurring in remove_breakpoints.  */
7687         loc->inserted = 0;
7688
7689         /* This may cause duplicate notifications for the same breakpoint.  */
7690         observer_notify_breakpoint_modified (b);
7691
7692         if (!disabled_shlib_breaks)
7693           {
7694             target_terminal::ours_for_output ();
7695             warning (_("Temporarily disabling breakpoints "
7696                        "for unloaded shared library \"%s\""),
7697                      solib->so_name);
7698           }
7699         disabled_shlib_breaks = 1;
7700       }
7701   }
7702 }
7703
7704 /* Disable any breakpoints and tracepoints in OBJFILE upon
7705    notification of free_objfile.  Only apply to enabled breakpoints,
7706    disabled ones can just stay disabled.  */
7707
7708 static void
7709 disable_breakpoints_in_freed_objfile (struct objfile *objfile)
7710 {
7711   struct breakpoint *b;
7712
7713   if (objfile == NULL)
7714     return;
7715
7716   /* OBJF_SHARED|OBJF_USERLOADED objfiles are dynamic modules manually
7717      managed by the user with add-symbol-file/remove-symbol-file.
7718      Similarly to how breakpoints in shared libraries are handled in
7719      response to "nosharedlibrary", mark breakpoints in such modules
7720      shlib_disabled so they end up uninserted on the next global
7721      location list update.  Shared libraries not loaded by the user
7722      aren't handled here -- they're already handled in
7723      disable_breakpoints_in_unloaded_shlib, called by solib.c's
7724      solib_unloaded observer.  We skip objfiles that are not
7725      OBJF_SHARED as those aren't considered dynamic objects (e.g. the
7726      main objfile).  */
7727   if ((objfile->flags & OBJF_SHARED) == 0
7728       || (objfile->flags & OBJF_USERLOADED) == 0)
7729     return;
7730
7731   ALL_BREAKPOINTS (b)
7732     {
7733       struct bp_location *loc;
7734       int bp_modified = 0;
7735
7736       if (!is_breakpoint (b) && !is_tracepoint (b))
7737         continue;
7738
7739       for (loc = b->loc; loc != NULL; loc = loc->next)
7740         {
7741           CORE_ADDR loc_addr = loc->address;
7742
7743           if (loc->loc_type != bp_loc_hardware_breakpoint
7744               && loc->loc_type != bp_loc_software_breakpoint)
7745             continue;
7746
7747           if (loc->shlib_disabled != 0)
7748             continue;
7749
7750           if (objfile->pspace != loc->pspace)
7751             continue;
7752
7753           if (loc->loc_type != bp_loc_hardware_breakpoint
7754               && loc->loc_type != bp_loc_software_breakpoint)
7755             continue;
7756
7757           if (is_addr_in_objfile (loc_addr, objfile))
7758             {
7759               loc->shlib_disabled = 1;
7760               /* At this point, we don't know whether the object was
7761                  unmapped from the inferior or not, so leave the
7762                  inserted flag alone.  We'll handle failure to
7763                  uninsert quietly, in case the object was indeed
7764                  unmapped.  */
7765
7766               mark_breakpoint_location_modified (loc);
7767
7768               bp_modified = 1;
7769             }
7770         }
7771
7772       if (bp_modified)
7773         observer_notify_breakpoint_modified (b);
7774     }
7775 }
7776
7777 /* FORK & VFORK catchpoints.  */
7778
7779 /* An instance of this type is used to represent a fork or vfork
7780    catchpoint.  A breakpoint is really of this type iff its ops pointer points
7781    to CATCH_FORK_BREAKPOINT_OPS.  */
7782
7783 struct fork_catchpoint : public breakpoint
7784 {
7785   /* Process id of a child process whose forking triggered this
7786      catchpoint.  This field is only valid immediately after this
7787      catchpoint has triggered.  */
7788   ptid_t forked_inferior_pid;
7789 };
7790
7791 /* Implement the "insert" breakpoint_ops method for fork
7792    catchpoints.  */
7793
7794 static int
7795 insert_catch_fork (struct bp_location *bl)
7796 {
7797   return target_insert_fork_catchpoint (ptid_get_pid (inferior_ptid));
7798 }
7799
7800 /* Implement the "remove" breakpoint_ops method for fork
7801    catchpoints.  */
7802
7803 static int
7804 remove_catch_fork (struct bp_location *bl, enum remove_bp_reason reason)
7805 {
7806   return target_remove_fork_catchpoint (ptid_get_pid (inferior_ptid));
7807 }
7808
7809 /* Implement the "breakpoint_hit" breakpoint_ops method for fork
7810    catchpoints.  */
7811
7812 static int
7813 breakpoint_hit_catch_fork (const struct bp_location *bl,
7814                            const address_space *aspace, CORE_ADDR bp_addr,
7815                            const struct target_waitstatus *ws)
7816 {
7817   struct fork_catchpoint *c = (struct fork_catchpoint *) bl->owner;
7818
7819   if (ws->kind != TARGET_WAITKIND_FORKED)
7820     return 0;
7821
7822   c->forked_inferior_pid = ws->value.related_pid;
7823   return 1;
7824 }
7825
7826 /* Implement the "print_it" breakpoint_ops method for fork
7827    catchpoints.  */
7828
7829 static enum print_stop_action
7830 print_it_catch_fork (bpstat bs)
7831 {
7832   struct ui_out *uiout = current_uiout;
7833   struct breakpoint *b = bs->breakpoint_at;
7834   struct fork_catchpoint *c = (struct fork_catchpoint *) bs->breakpoint_at;
7835
7836   annotate_catchpoint (b->number);
7837   maybe_print_thread_hit_breakpoint (uiout);
7838   if (b->disposition == disp_del)
7839     uiout->text ("Temporary catchpoint ");
7840   else
7841     uiout->text ("Catchpoint ");
7842   if (uiout->is_mi_like_p ())
7843     {
7844       uiout->field_string ("reason", async_reason_lookup (EXEC_ASYNC_FORK));
7845       uiout->field_string ("disp", bpdisp_text (b->disposition));
7846     }
7847   uiout->field_int ("bkptno", b->number);
7848   uiout->text (" (forked process ");
7849   uiout->field_int ("newpid", ptid_get_pid (c->forked_inferior_pid));
7850   uiout->text ("), ");
7851   return PRINT_SRC_AND_LOC;
7852 }
7853
7854 /* Implement the "print_one" breakpoint_ops method for fork
7855    catchpoints.  */
7856
7857 static void
7858 print_one_catch_fork (struct breakpoint *b, struct bp_location **last_loc)
7859 {
7860   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
7861   struct value_print_options opts;
7862   struct ui_out *uiout = current_uiout;
7863
7864   get_user_print_options (&opts);
7865
7866   /* Field 4, the address, is omitted (which makes the columns not
7867      line up too nicely with the headers, but the effect is relatively
7868      readable).  */
7869   if (opts.addressprint)
7870     uiout->field_skip ("addr");
7871   annotate_field (5);
7872   uiout->text ("fork");
7873   if (!ptid_equal (c->forked_inferior_pid, null_ptid))
7874     {
7875       uiout->text (", process ");
7876       uiout->field_int ("what", ptid_get_pid (c->forked_inferior_pid));
7877       uiout->spaces (1);
7878     }
7879
7880   if (uiout->is_mi_like_p ())
7881     uiout->field_string ("catch-type", "fork");
7882 }
7883
7884 /* Implement the "print_mention" breakpoint_ops method for fork
7885    catchpoints.  */
7886
7887 static void
7888 print_mention_catch_fork (struct breakpoint *b)
7889 {
7890   printf_filtered (_("Catchpoint %d (fork)"), b->number);
7891 }
7892
7893 /* Implement the "print_recreate" breakpoint_ops method for fork
7894    catchpoints.  */
7895
7896 static void
7897 print_recreate_catch_fork (struct breakpoint *b, struct ui_file *fp)
7898 {
7899   fprintf_unfiltered (fp, "catch fork");
7900   print_recreate_thread (b, fp);
7901 }
7902
7903 /* The breakpoint_ops structure to be used in fork catchpoints.  */
7904
7905 static struct breakpoint_ops catch_fork_breakpoint_ops;
7906
7907 /* Implement the "insert" breakpoint_ops method for vfork
7908    catchpoints.  */
7909
7910 static int
7911 insert_catch_vfork (struct bp_location *bl)
7912 {
7913   return target_insert_vfork_catchpoint (ptid_get_pid (inferior_ptid));
7914 }
7915
7916 /* Implement the "remove" breakpoint_ops method for vfork
7917    catchpoints.  */
7918
7919 static int
7920 remove_catch_vfork (struct bp_location *bl, enum remove_bp_reason reason)
7921 {
7922   return target_remove_vfork_catchpoint (ptid_get_pid (inferior_ptid));
7923 }
7924
7925 /* Implement the "breakpoint_hit" breakpoint_ops method for vfork
7926    catchpoints.  */
7927
7928 static int
7929 breakpoint_hit_catch_vfork (const struct bp_location *bl,
7930                             const address_space *aspace, CORE_ADDR bp_addr,
7931                             const struct target_waitstatus *ws)
7932 {
7933   struct fork_catchpoint *c = (struct fork_catchpoint *) bl->owner;
7934
7935   if (ws->kind != TARGET_WAITKIND_VFORKED)
7936     return 0;
7937
7938   c->forked_inferior_pid = ws->value.related_pid;
7939   return 1;
7940 }
7941
7942 /* Implement the "print_it" breakpoint_ops method for vfork
7943    catchpoints.  */
7944
7945 static enum print_stop_action
7946 print_it_catch_vfork (bpstat bs)
7947 {
7948   struct ui_out *uiout = current_uiout;
7949   struct breakpoint *b = bs->breakpoint_at;
7950   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
7951
7952   annotate_catchpoint (b->number);
7953   maybe_print_thread_hit_breakpoint (uiout);
7954   if (b->disposition == disp_del)
7955     uiout->text ("Temporary catchpoint ");
7956   else
7957     uiout->text ("Catchpoint ");
7958   if (uiout->is_mi_like_p ())
7959     {
7960       uiout->field_string ("reason", async_reason_lookup (EXEC_ASYNC_VFORK));
7961       uiout->field_string ("disp", bpdisp_text (b->disposition));
7962     }
7963   uiout->field_int ("bkptno", b->number);
7964   uiout->text (" (vforked process ");
7965   uiout->field_int ("newpid", ptid_get_pid (c->forked_inferior_pid));
7966   uiout->text ("), ");
7967   return PRINT_SRC_AND_LOC;
7968 }
7969
7970 /* Implement the "print_one" breakpoint_ops method for vfork
7971    catchpoints.  */
7972
7973 static void
7974 print_one_catch_vfork (struct breakpoint *b, struct bp_location **last_loc)
7975 {
7976   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
7977   struct value_print_options opts;
7978   struct ui_out *uiout = current_uiout;
7979
7980   get_user_print_options (&opts);
7981   /* Field 4, the address, is omitted (which makes the columns not
7982      line up too nicely with the headers, but the effect is relatively
7983      readable).  */
7984   if (opts.addressprint)
7985     uiout->field_skip ("addr");
7986   annotate_field (5);
7987   uiout->text ("vfork");
7988   if (!ptid_equal (c->forked_inferior_pid, null_ptid))
7989     {
7990       uiout->text (", process ");
7991       uiout->field_int ("what", ptid_get_pid (c->forked_inferior_pid));
7992       uiout->spaces (1);
7993     }
7994
7995   if (uiout->is_mi_like_p ())
7996     uiout->field_string ("catch-type", "vfork");
7997 }
7998
7999 /* Implement the "print_mention" breakpoint_ops method for vfork
8000    catchpoints.  */
8001
8002 static void
8003 print_mention_catch_vfork (struct breakpoint *b)
8004 {
8005   printf_filtered (_("Catchpoint %d (vfork)"), b->number);
8006 }
8007
8008 /* Implement the "print_recreate" breakpoint_ops method for vfork
8009    catchpoints.  */
8010
8011 static void
8012 print_recreate_catch_vfork (struct breakpoint *b, struct ui_file *fp)
8013 {
8014   fprintf_unfiltered (fp, "catch vfork");
8015   print_recreate_thread (b, fp);
8016 }
8017
8018 /* The breakpoint_ops structure to be used in vfork catchpoints.  */
8019
8020 static struct breakpoint_ops catch_vfork_breakpoint_ops;
8021
8022 /* An instance of this type is used to represent an solib catchpoint.
8023    A breakpoint is really of this type iff its ops pointer points to
8024    CATCH_SOLIB_BREAKPOINT_OPS.  */
8025
8026 struct solib_catchpoint : public breakpoint
8027 {
8028   ~solib_catchpoint () override;
8029
8030   /* True for "catch load", false for "catch unload".  */
8031   unsigned char is_load;
8032
8033   /* Regular expression to match, if any.  COMPILED is only valid when
8034      REGEX is non-NULL.  */
8035   char *regex;
8036   std::unique_ptr<compiled_regex> compiled;
8037 };
8038
8039 solib_catchpoint::~solib_catchpoint ()
8040 {
8041   xfree (this->regex);
8042 }
8043
8044 static int
8045 insert_catch_solib (struct bp_location *ignore)
8046 {
8047   return 0;
8048 }
8049
8050 static int
8051 remove_catch_solib (struct bp_location *ignore, enum remove_bp_reason reason)
8052 {
8053   return 0;
8054 }
8055
8056 static int
8057 breakpoint_hit_catch_solib (const struct bp_location *bl,
8058                             const address_space *aspace,
8059                             CORE_ADDR bp_addr,
8060                             const struct target_waitstatus *ws)
8061 {
8062   struct solib_catchpoint *self = (struct solib_catchpoint *) bl->owner;
8063   struct breakpoint *other;
8064
8065   if (ws->kind == TARGET_WAITKIND_LOADED)
8066     return 1;
8067
8068   ALL_BREAKPOINTS (other)
8069   {
8070     struct bp_location *other_bl;
8071
8072     if (other == bl->owner)
8073       continue;
8074
8075     if (other->type != bp_shlib_event)
8076       continue;
8077
8078     if (self->pspace != NULL && other->pspace != self->pspace)
8079       continue;
8080
8081     for (other_bl = other->loc; other_bl != NULL; other_bl = other_bl->next)
8082       {
8083         if (other->ops->breakpoint_hit (other_bl, aspace, bp_addr, ws))
8084           return 1;
8085       }
8086   }
8087
8088   return 0;
8089 }
8090
8091 static void
8092 check_status_catch_solib (struct bpstats *bs)
8093 {
8094   struct solib_catchpoint *self
8095     = (struct solib_catchpoint *) bs->breakpoint_at;
8096   int ix;
8097
8098   if (self->is_load)
8099     {
8100       struct so_list *iter;
8101
8102       for (ix = 0;
8103            VEC_iterate (so_list_ptr, current_program_space->added_solibs,
8104                         ix, iter);
8105            ++ix)
8106         {
8107           if (!self->regex
8108               || self->compiled->exec (iter->so_name, 0, NULL, 0) == 0)
8109             return;
8110         }
8111     }
8112   else
8113     {
8114       char *iter;
8115
8116       for (ix = 0;
8117            VEC_iterate (char_ptr, current_program_space->deleted_solibs,
8118                         ix, iter);
8119            ++ix)
8120         {
8121           if (!self->regex
8122               || self->compiled->exec (iter, 0, NULL, 0) == 0)
8123             return;
8124         }
8125     }
8126
8127   bs->stop = 0;
8128   bs->print_it = print_it_noop;
8129 }
8130
8131 static enum print_stop_action
8132 print_it_catch_solib (bpstat bs)
8133 {
8134   struct breakpoint *b = bs->breakpoint_at;
8135   struct ui_out *uiout = current_uiout;
8136
8137   annotate_catchpoint (b->number);
8138   maybe_print_thread_hit_breakpoint (uiout);
8139   if (b->disposition == disp_del)
8140     uiout->text ("Temporary catchpoint ");
8141   else
8142     uiout->text ("Catchpoint ");
8143   uiout->field_int ("bkptno", b->number);
8144   uiout->text ("\n");
8145   if (uiout->is_mi_like_p ())
8146     uiout->field_string ("disp", bpdisp_text (b->disposition));
8147   print_solib_event (1);
8148   return PRINT_SRC_AND_LOC;
8149 }
8150
8151 static void
8152 print_one_catch_solib (struct breakpoint *b, struct bp_location **locs)
8153 {
8154   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8155   struct value_print_options opts;
8156   struct ui_out *uiout = current_uiout;
8157   char *msg;
8158
8159   get_user_print_options (&opts);
8160   /* Field 4, the address, is omitted (which makes the columns not
8161      line up too nicely with the headers, but the effect is relatively
8162      readable).  */
8163   if (opts.addressprint)
8164     {
8165       annotate_field (4);
8166       uiout->field_skip ("addr");
8167     }
8168
8169   annotate_field (5);
8170   if (self->is_load)
8171     {
8172       if (self->regex)
8173         msg = xstrprintf (_("load of library matching %s"), self->regex);
8174       else
8175         msg = xstrdup (_("load of library"));
8176     }
8177   else
8178     {
8179       if (self->regex)
8180         msg = xstrprintf (_("unload of library matching %s"), self->regex);
8181       else
8182         msg = xstrdup (_("unload of library"));
8183     }
8184   uiout->field_string ("what", msg);
8185   xfree (msg);
8186
8187   if (uiout->is_mi_like_p ())
8188     uiout->field_string ("catch-type", self->is_load ? "load" : "unload");
8189 }
8190
8191 static void
8192 print_mention_catch_solib (struct breakpoint *b)
8193 {
8194   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8195
8196   printf_filtered (_("Catchpoint %d (%s)"), b->number,
8197                    self->is_load ? "load" : "unload");
8198 }
8199
8200 static void
8201 print_recreate_catch_solib (struct breakpoint *b, struct ui_file *fp)
8202 {
8203   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8204
8205   fprintf_unfiltered (fp, "%s %s",
8206                       b->disposition == disp_del ? "tcatch" : "catch",
8207                       self->is_load ? "load" : "unload");
8208   if (self->regex)
8209     fprintf_unfiltered (fp, " %s", self->regex);
8210   fprintf_unfiltered (fp, "\n");
8211 }
8212
8213 static struct breakpoint_ops catch_solib_breakpoint_ops;
8214
8215 /* Shared helper function (MI and CLI) for creating and installing
8216    a shared object event catchpoint.  If IS_LOAD is non-zero then
8217    the events to be caught are load events, otherwise they are
8218    unload events.  If IS_TEMP is non-zero the catchpoint is a
8219    temporary one.  If ENABLED is non-zero the catchpoint is
8220    created in an enabled state.  */
8221
8222 void
8223 add_solib_catchpoint (const char *arg, int is_load, int is_temp, int enabled)
8224 {
8225   struct gdbarch *gdbarch = get_current_arch ();
8226
8227   if (!arg)
8228     arg = "";
8229   arg = skip_spaces (arg);
8230
8231   std::unique_ptr<solib_catchpoint> c (new solib_catchpoint ());
8232
8233   if (*arg != '\0')
8234     {
8235       c->compiled.reset (new compiled_regex (arg, REG_NOSUB,
8236                                              _("Invalid regexp")));
8237       c->regex = xstrdup (arg);
8238     }
8239
8240   c->is_load = is_load;
8241   init_catchpoint (c.get (), gdbarch, is_temp, NULL,
8242                    &catch_solib_breakpoint_ops);
8243
8244   c->enable_state = enabled ? bp_enabled : bp_disabled;
8245
8246   install_breakpoint (0, std::move (c), 1);
8247 }
8248
8249 /* A helper function that does all the work for "catch load" and
8250    "catch unload".  */
8251
8252 static void
8253 catch_load_or_unload (char *arg, int from_tty, int is_load,
8254                       struct cmd_list_element *command)
8255 {
8256   int tempflag;
8257   const int enabled = 1;
8258
8259   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
8260
8261   add_solib_catchpoint (arg, is_load, tempflag, enabled);
8262 }
8263
8264 static void
8265 catch_load_command_1 (char *arg, int from_tty,
8266                       struct cmd_list_element *command)
8267 {
8268   catch_load_or_unload (arg, from_tty, 1, command);
8269 }
8270
8271 static void
8272 catch_unload_command_1 (char *arg, int from_tty,
8273                         struct cmd_list_element *command)
8274 {
8275   catch_load_or_unload (arg, from_tty, 0, command);
8276 }
8277
8278 /* Initialize a new breakpoint of the bp_catchpoint kind.  If TEMPFLAG
8279    is non-zero, then make the breakpoint temporary.  If COND_STRING is
8280    not NULL, then store it in the breakpoint.  OPS, if not NULL, is
8281    the breakpoint_ops structure associated to the catchpoint.  */
8282
8283 void
8284 init_catchpoint (struct breakpoint *b,
8285                  struct gdbarch *gdbarch, int tempflag,
8286                  const char *cond_string,
8287                  const struct breakpoint_ops *ops)
8288 {
8289   symtab_and_line sal;
8290   sal.pspace = current_program_space;
8291
8292   init_raw_breakpoint (b, gdbarch, sal, bp_catchpoint, ops);
8293
8294   b->cond_string = (cond_string == NULL) ? NULL : xstrdup (cond_string);
8295   b->disposition = tempflag ? disp_del : disp_donttouch;
8296 }
8297
8298 void
8299 install_breakpoint (int internal, std::unique_ptr<breakpoint> &&arg, int update_gll)
8300 {
8301   breakpoint *b = add_to_breakpoint_chain (std::move (arg));
8302   set_breakpoint_number (internal, b);
8303   if (is_tracepoint (b))
8304     set_tracepoint_count (breakpoint_count);
8305   if (!internal)
8306     mention (b);
8307   observer_notify_breakpoint_created (b);
8308
8309   if (update_gll)
8310     update_global_location_list (UGLL_MAY_INSERT);
8311 }
8312
8313 static void
8314 create_fork_vfork_event_catchpoint (struct gdbarch *gdbarch,
8315                                     int tempflag, const char *cond_string,
8316                                     const struct breakpoint_ops *ops)
8317 {
8318   std::unique_ptr<fork_catchpoint> c (new fork_catchpoint ());
8319
8320   init_catchpoint (c.get (), gdbarch, tempflag, cond_string, ops);
8321
8322   c->forked_inferior_pid = null_ptid;
8323
8324   install_breakpoint (0, std::move (c), 1);
8325 }
8326
8327 /* Exec catchpoints.  */
8328
8329 /* An instance of this type is used to represent an exec catchpoint.
8330    A breakpoint is really of this type iff its ops pointer points to
8331    CATCH_EXEC_BREAKPOINT_OPS.  */
8332
8333 struct exec_catchpoint : public breakpoint
8334 {
8335   ~exec_catchpoint () override;
8336
8337   /* Filename of a program whose exec triggered this catchpoint.
8338      This field is only valid immediately after this catchpoint has
8339      triggered.  */
8340   char *exec_pathname;
8341 };
8342
8343 /* Exec catchpoint destructor.  */
8344
8345 exec_catchpoint::~exec_catchpoint ()
8346 {
8347   xfree (this->exec_pathname);
8348 }
8349
8350 static int
8351 insert_catch_exec (struct bp_location *bl)
8352 {
8353   return target_insert_exec_catchpoint (ptid_get_pid (inferior_ptid));
8354 }
8355
8356 static int
8357 remove_catch_exec (struct bp_location *bl, enum remove_bp_reason reason)
8358 {
8359   return target_remove_exec_catchpoint (ptid_get_pid (inferior_ptid));
8360 }
8361
8362 static int
8363 breakpoint_hit_catch_exec (const struct bp_location *bl,
8364                            const address_space *aspace, CORE_ADDR bp_addr,
8365                            const struct target_waitstatus *ws)
8366 {
8367   struct exec_catchpoint *c = (struct exec_catchpoint *) bl->owner;
8368
8369   if (ws->kind != TARGET_WAITKIND_EXECD)
8370     return 0;
8371
8372   c->exec_pathname = xstrdup (ws->value.execd_pathname);
8373   return 1;
8374 }
8375
8376 static enum print_stop_action
8377 print_it_catch_exec (bpstat bs)
8378 {
8379   struct ui_out *uiout = current_uiout;
8380   struct breakpoint *b = bs->breakpoint_at;
8381   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
8382
8383   annotate_catchpoint (b->number);
8384   maybe_print_thread_hit_breakpoint (uiout);
8385   if (b->disposition == disp_del)
8386     uiout->text ("Temporary catchpoint ");
8387   else
8388     uiout->text ("Catchpoint ");
8389   if (uiout->is_mi_like_p ())
8390     {
8391       uiout->field_string ("reason", async_reason_lookup (EXEC_ASYNC_EXEC));
8392       uiout->field_string ("disp", bpdisp_text (b->disposition));
8393     }
8394   uiout->field_int ("bkptno", b->number);
8395   uiout->text (" (exec'd ");
8396   uiout->field_string ("new-exec", c->exec_pathname);
8397   uiout->text ("), ");
8398
8399   return PRINT_SRC_AND_LOC;
8400 }
8401
8402 static void
8403 print_one_catch_exec (struct breakpoint *b, struct bp_location **last_loc)
8404 {
8405   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
8406   struct value_print_options opts;
8407   struct ui_out *uiout = current_uiout;
8408
8409   get_user_print_options (&opts);
8410
8411   /* Field 4, the address, is omitted (which makes the columns
8412      not line up too nicely with the headers, but the effect
8413      is relatively readable).  */
8414   if (opts.addressprint)
8415     uiout->field_skip ("addr");
8416   annotate_field (5);
8417   uiout->text ("exec");
8418   if (c->exec_pathname != NULL)
8419     {
8420       uiout->text (", program \"");
8421       uiout->field_string ("what", c->exec_pathname);
8422       uiout->text ("\" ");
8423     }
8424
8425   if (uiout->is_mi_like_p ())
8426     uiout->field_string ("catch-type", "exec");
8427 }
8428
8429 static void
8430 print_mention_catch_exec (struct breakpoint *b)
8431 {
8432   printf_filtered (_("Catchpoint %d (exec)"), b->number);
8433 }
8434
8435 /* Implement the "print_recreate" breakpoint_ops method for exec
8436    catchpoints.  */
8437
8438 static void
8439 print_recreate_catch_exec (struct breakpoint *b, struct ui_file *fp)
8440 {
8441   fprintf_unfiltered (fp, "catch exec");
8442   print_recreate_thread (b, fp);
8443 }
8444
8445 static struct breakpoint_ops catch_exec_breakpoint_ops;
8446
8447 static int
8448 hw_breakpoint_used_count (void)
8449 {
8450   int i = 0;
8451   struct breakpoint *b;
8452   struct bp_location *bl;
8453
8454   ALL_BREAKPOINTS (b)
8455   {
8456     if (b->type == bp_hardware_breakpoint && breakpoint_enabled (b))
8457       for (bl = b->loc; bl; bl = bl->next)
8458         {
8459           /* Special types of hardware breakpoints may use more than
8460              one register.  */
8461           i += b->ops->resources_needed (bl);
8462         }
8463   }
8464
8465   return i;
8466 }
8467
8468 /* Returns the resources B would use if it were a hardware
8469    watchpoint.  */
8470
8471 static int
8472 hw_watchpoint_use_count (struct breakpoint *b)
8473 {
8474   int i = 0;
8475   struct bp_location *bl;
8476
8477   if (!breakpoint_enabled (b))
8478     return 0;
8479
8480   for (bl = b->loc; bl; bl = bl->next)
8481     {
8482       /* Special types of hardware watchpoints may use more than
8483          one register.  */
8484       i += b->ops->resources_needed (bl);
8485     }
8486
8487   return i;
8488 }
8489
8490 /* Returns the sum the used resources of all hardware watchpoints of
8491    type TYPE in the breakpoints list.  Also returns in OTHER_TYPE_USED
8492    the sum of the used resources of all hardware watchpoints of other
8493    types _not_ TYPE.  */
8494
8495 static int
8496 hw_watchpoint_used_count_others (struct breakpoint *except,
8497                                  enum bptype type, int *other_type_used)
8498 {
8499   int i = 0;
8500   struct breakpoint *b;
8501
8502   *other_type_used = 0;
8503   ALL_BREAKPOINTS (b)
8504     {
8505       if (b == except)
8506         continue;
8507       if (!breakpoint_enabled (b))
8508         continue;
8509
8510       if (b->type == type)
8511         i += hw_watchpoint_use_count (b);
8512       else if (is_hardware_watchpoint (b))
8513         *other_type_used = 1;
8514     }
8515
8516   return i;
8517 }
8518
8519 void
8520 disable_watchpoints_before_interactive_call_start (void)
8521 {
8522   struct breakpoint *b;
8523
8524   ALL_BREAKPOINTS (b)
8525   {
8526     if (is_watchpoint (b) && breakpoint_enabled (b))
8527       {
8528         b->enable_state = bp_call_disabled;
8529         update_global_location_list (UGLL_DONT_INSERT);
8530       }
8531   }
8532 }
8533
8534 void
8535 enable_watchpoints_after_interactive_call_stop (void)
8536 {
8537   struct breakpoint *b;
8538
8539   ALL_BREAKPOINTS (b)
8540   {
8541     if (is_watchpoint (b) && b->enable_state == bp_call_disabled)
8542       {
8543         b->enable_state = bp_enabled;
8544         update_global_location_list (UGLL_MAY_INSERT);
8545       }
8546   }
8547 }
8548
8549 void
8550 disable_breakpoints_before_startup (void)
8551 {
8552   current_program_space->executing_startup = 1;
8553   update_global_location_list (UGLL_DONT_INSERT);
8554 }
8555
8556 void
8557 enable_breakpoints_after_startup (void)
8558 {
8559   current_program_space->executing_startup = 0;
8560   breakpoint_re_set ();
8561 }
8562
8563 /* Create a new single-step breakpoint for thread THREAD, with no
8564    locations.  */
8565
8566 static struct breakpoint *
8567 new_single_step_breakpoint (int thread, struct gdbarch *gdbarch)
8568 {
8569   std::unique_ptr<breakpoint> b (new breakpoint ());
8570
8571   init_raw_breakpoint_without_location (b.get (), gdbarch, bp_single_step,
8572                                         &momentary_breakpoint_ops);
8573
8574   b->disposition = disp_donttouch;
8575   b->frame_id = null_frame_id;
8576
8577   b->thread = thread;
8578   gdb_assert (b->thread != 0);
8579
8580   return add_to_breakpoint_chain (std::move (b));
8581 }
8582
8583 /* Set a momentary breakpoint of type TYPE at address specified by
8584    SAL.  If FRAME_ID is valid, the breakpoint is restricted to that
8585    frame.  */
8586
8587 struct breakpoint *
8588 set_momentary_breakpoint (struct gdbarch *gdbarch, struct symtab_and_line sal,
8589                           struct frame_id frame_id, enum bptype type)
8590 {
8591   struct breakpoint *b;
8592
8593   /* If FRAME_ID is valid, it should be a real frame, not an inlined or
8594      tail-called one.  */
8595   gdb_assert (!frame_id_artificial_p (frame_id));
8596
8597   b = set_raw_breakpoint (gdbarch, sal, type, &momentary_breakpoint_ops);
8598   b->enable_state = bp_enabled;
8599   b->disposition = disp_donttouch;
8600   b->frame_id = frame_id;
8601
8602   /* If we're debugging a multi-threaded program, then we want
8603      momentary breakpoints to be active in only a single thread of
8604      control.  */
8605   if (in_thread_list (inferior_ptid))
8606     b->thread = ptid_to_global_thread_id (inferior_ptid);
8607
8608   update_global_location_list_nothrow (UGLL_MAY_INSERT);
8609
8610   return b;
8611 }
8612
8613 /* Make a momentary breakpoint based on the master breakpoint ORIG.
8614    The new breakpoint will have type TYPE, use OPS as its
8615    breakpoint_ops, and will set enabled to LOC_ENABLED.  */
8616
8617 static struct breakpoint *
8618 momentary_breakpoint_from_master (struct breakpoint *orig,
8619                                   enum bptype type,
8620                                   const struct breakpoint_ops *ops,
8621                                   int loc_enabled)
8622 {
8623   struct breakpoint *copy;
8624
8625   copy = set_raw_breakpoint_without_location (orig->gdbarch, type, ops);
8626   copy->loc = allocate_bp_location (copy);
8627   set_breakpoint_location_function (copy->loc, 1);
8628
8629   copy->loc->gdbarch = orig->loc->gdbarch;
8630   copy->loc->requested_address = orig->loc->requested_address;
8631   copy->loc->address = orig->loc->address;
8632   copy->loc->section = orig->loc->section;
8633   copy->loc->pspace = orig->loc->pspace;
8634   copy->loc->probe = orig->loc->probe;
8635   copy->loc->line_number = orig->loc->line_number;
8636   copy->loc->symtab = orig->loc->symtab;
8637   copy->loc->enabled = loc_enabled;
8638   copy->frame_id = orig->frame_id;
8639   copy->thread = orig->thread;
8640   copy->pspace = orig->pspace;
8641
8642   copy->enable_state = bp_enabled;
8643   copy->disposition = disp_donttouch;
8644   copy->number = internal_breakpoint_number--;
8645
8646   update_global_location_list_nothrow (UGLL_DONT_INSERT);
8647   return copy;
8648 }
8649
8650 /* Make a deep copy of momentary breakpoint ORIG.  Returns NULL if
8651    ORIG is NULL.  */
8652
8653 struct breakpoint *
8654 clone_momentary_breakpoint (struct breakpoint *orig)
8655 {
8656   /* If there's nothing to clone, then return nothing.  */
8657   if (orig == NULL)
8658     return NULL;
8659
8660   return momentary_breakpoint_from_master (orig, orig->type, orig->ops, 0);
8661 }
8662
8663 struct breakpoint *
8664 set_momentary_breakpoint_at_pc (struct gdbarch *gdbarch, CORE_ADDR pc,
8665                                 enum bptype type)
8666 {
8667   struct symtab_and_line sal;
8668
8669   sal = find_pc_line (pc, 0);
8670   sal.pc = pc;
8671   sal.section = find_pc_overlay (pc);
8672   sal.explicit_pc = 1;
8673
8674   return set_momentary_breakpoint (gdbarch, sal, null_frame_id, type);
8675 }
8676 \f
8677
8678 /* Tell the user we have just set a breakpoint B.  */
8679
8680 static void
8681 mention (struct breakpoint *b)
8682 {
8683   b->ops->print_mention (b);
8684   if (current_uiout->is_mi_like_p ())
8685     return;
8686   printf_filtered ("\n");
8687 }
8688 \f
8689
8690 static int bp_loc_is_permanent (struct bp_location *loc);
8691
8692 static struct bp_location *
8693 add_location_to_breakpoint (struct breakpoint *b,
8694                             const struct symtab_and_line *sal)
8695 {
8696   struct bp_location *loc, **tmp;
8697   CORE_ADDR adjusted_address;
8698   struct gdbarch *loc_gdbarch = get_sal_arch (*sal);
8699
8700   if (loc_gdbarch == NULL)
8701     loc_gdbarch = b->gdbarch;
8702
8703   /* Adjust the breakpoint's address prior to allocating a location.
8704      Once we call allocate_bp_location(), that mostly uninitialized
8705      location will be placed on the location chain.  Adjustment of the
8706      breakpoint may cause target_read_memory() to be called and we do
8707      not want its scan of the location chain to find a breakpoint and
8708      location that's only been partially initialized.  */
8709   adjusted_address = adjust_breakpoint_address (loc_gdbarch,
8710                                                 sal->pc, b->type);
8711
8712   /* Sort the locations by their ADDRESS.  */
8713   loc = allocate_bp_location (b);
8714   for (tmp = &(b->loc); *tmp != NULL && (*tmp)->address <= adjusted_address;
8715        tmp = &((*tmp)->next))
8716     ;
8717   loc->next = *tmp;
8718   *tmp = loc;
8719
8720   loc->requested_address = sal->pc;
8721   loc->address = adjusted_address;
8722   loc->pspace = sal->pspace;
8723   loc->probe.probe = sal->probe;
8724   loc->probe.objfile = sal->objfile;
8725   gdb_assert (loc->pspace != NULL);
8726   loc->section = sal->section;
8727   loc->gdbarch = loc_gdbarch;
8728   loc->line_number = sal->line;
8729   loc->symtab = sal->symtab;
8730   loc->symbol = sal->symbol;
8731
8732   set_breakpoint_location_function (loc,
8733                                     sal->explicit_pc || sal->explicit_line);
8734
8735   /* While by definition, permanent breakpoints are already present in the
8736      code, we don't mark the location as inserted.  Normally one would expect
8737      that GDB could rely on that breakpoint instruction to stop the program,
8738      thus removing the need to insert its own breakpoint, except that executing
8739      the breakpoint instruction can kill the target instead of reporting a
8740      SIGTRAP.  E.g., on SPARC, when interrupts are disabled, executing the
8741      instruction resets the CPU, so QEMU 2.0.0 for SPARC correspondingly dies
8742      with "Trap 0x02 while interrupts disabled, Error state".  Letting the
8743      breakpoint be inserted normally results in QEMU knowing about the GDB
8744      breakpoint, and thus trap before the breakpoint instruction is executed.
8745      (If GDB later needs to continue execution past the permanent breakpoint,
8746      it manually increments the PC, thus avoiding executing the breakpoint
8747      instruction.)  */
8748   if (bp_loc_is_permanent (loc))
8749     loc->permanent = 1;
8750
8751   return loc;
8752 }
8753 \f
8754
8755 /* See breakpoint.h.  */
8756
8757 int
8758 program_breakpoint_here_p (struct gdbarch *gdbarch, CORE_ADDR address)
8759 {
8760   int len;
8761   CORE_ADDR addr;
8762   const gdb_byte *bpoint;
8763   gdb_byte *target_mem;
8764
8765   addr = address;
8766   bpoint = gdbarch_breakpoint_from_pc (gdbarch, &addr, &len);
8767
8768   /* Software breakpoints unsupported?  */
8769   if (bpoint == NULL)
8770     return 0;
8771
8772   target_mem = (gdb_byte *) alloca (len);
8773
8774   /* Enable the automatic memory restoration from breakpoints while
8775      we read the memory.  Otherwise we could say about our temporary
8776      breakpoints they are permanent.  */
8777   scoped_restore restore_memory
8778     = make_scoped_restore_show_memory_breakpoints (0);
8779
8780   if (target_read_memory (address, target_mem, len) == 0
8781       && memcmp (target_mem, bpoint, len) == 0)
8782     return 1;
8783
8784   return 0;
8785 }
8786
8787 /* Return 1 if LOC is pointing to a permanent breakpoint,
8788    return 0 otherwise.  */
8789
8790 static int
8791 bp_loc_is_permanent (struct bp_location *loc)
8792 {
8793   gdb_assert (loc != NULL);
8794
8795   /* If we have a catchpoint or a watchpoint, just return 0.  We should not
8796      attempt to read from the addresses the locations of these breakpoint types
8797      point to.  program_breakpoint_here_p, below, will attempt to read
8798      memory.  */
8799   if (!breakpoint_address_is_meaningful (loc->owner))
8800     return 0;
8801
8802   scoped_restore_current_pspace_and_thread restore_pspace_thread;
8803   switch_to_program_space_and_thread (loc->pspace);
8804   return program_breakpoint_here_p (loc->gdbarch, loc->address);
8805 }
8806
8807 /* Build a command list for the dprintf corresponding to the current
8808    settings of the dprintf style options.  */
8809
8810 static void
8811 update_dprintf_command_list (struct breakpoint *b)
8812 {
8813   char *dprintf_args = b->extra_string;
8814   char *printf_line = NULL;
8815
8816   if (!dprintf_args)
8817     return;
8818
8819   dprintf_args = skip_spaces (dprintf_args);
8820
8821   /* Allow a comma, as it may have terminated a location, but don't
8822      insist on it.  */
8823   if (*dprintf_args == ',')
8824     ++dprintf_args;
8825   dprintf_args = skip_spaces (dprintf_args);
8826
8827   if (*dprintf_args != '"')
8828     error (_("Bad format string, missing '\"'."));
8829
8830   if (strcmp (dprintf_style, dprintf_style_gdb) == 0)
8831     printf_line = xstrprintf ("printf %s", dprintf_args);
8832   else if (strcmp (dprintf_style, dprintf_style_call) == 0)
8833     {
8834       if (!dprintf_function)
8835         error (_("No function supplied for dprintf call"));
8836
8837       if (dprintf_channel && strlen (dprintf_channel) > 0)
8838         printf_line = xstrprintf ("call (void) %s (%s,%s)",
8839                                   dprintf_function,
8840                                   dprintf_channel,
8841                                   dprintf_args);
8842       else
8843         printf_line = xstrprintf ("call (void) %s (%s)",
8844                                   dprintf_function,
8845                                   dprintf_args);
8846     }
8847   else if (strcmp (dprintf_style, dprintf_style_agent) == 0)
8848     {
8849       if (target_can_run_breakpoint_commands ())
8850         printf_line = xstrprintf ("agent-printf %s", dprintf_args);
8851       else
8852         {
8853           warning (_("Target cannot run dprintf commands, falling back to GDB printf"));
8854           printf_line = xstrprintf ("printf %s", dprintf_args);
8855         }
8856     }
8857   else
8858     internal_error (__FILE__, __LINE__,
8859                     _("Invalid dprintf style."));
8860
8861   gdb_assert (printf_line != NULL);
8862   /* Manufacture a printf sequence.  */
8863   {
8864     struct command_line *printf_cmd_line = XNEW (struct command_line);
8865
8866     printf_cmd_line->control_type = simple_control;
8867     printf_cmd_line->body_count = 0;
8868     printf_cmd_line->body_list = NULL;
8869     printf_cmd_line->next = NULL;
8870     printf_cmd_line->line = printf_line;
8871
8872     breakpoint_set_commands (b, command_line_up (printf_cmd_line));
8873   }
8874 }
8875
8876 /* Update all dprintf commands, making their command lists reflect
8877    current style settings.  */
8878
8879 static void
8880 update_dprintf_commands (char *args, int from_tty,
8881                          struct cmd_list_element *c)
8882 {
8883   struct breakpoint *b;
8884
8885   ALL_BREAKPOINTS (b)
8886     {
8887       if (b->type == bp_dprintf)
8888         update_dprintf_command_list (b);
8889     }
8890 }
8891
8892 /* Create a breakpoint with SAL as location.  Use LOCATION
8893    as a description of the location, and COND_STRING
8894    as condition expression.  If LOCATION is NULL then create an
8895    "address location" from the address in the SAL.  */
8896
8897 static void
8898 init_breakpoint_sal (struct breakpoint *b, struct gdbarch *gdbarch,
8899                      gdb::array_view<const symtab_and_line> sals,
8900                      event_location_up &&location,
8901                      gdb::unique_xmalloc_ptr<char> filter,
8902                      gdb::unique_xmalloc_ptr<char> cond_string,
8903                      gdb::unique_xmalloc_ptr<char> extra_string,
8904                      enum bptype type, enum bpdisp disposition,
8905                      int thread, int task, int ignore_count,
8906                      const struct breakpoint_ops *ops, int from_tty,
8907                      int enabled, int internal, unsigned flags,
8908                      int display_canonical)
8909 {
8910   int i;
8911
8912   if (type == bp_hardware_breakpoint)
8913     {
8914       int target_resources_ok;
8915
8916       i = hw_breakpoint_used_count ();
8917       target_resources_ok =
8918         target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
8919                                             i + 1, 0);
8920       if (target_resources_ok == 0)
8921         error (_("No hardware breakpoint support in the target."));
8922       else if (target_resources_ok < 0)
8923         error (_("Hardware breakpoints used exceeds limit."));
8924     }
8925
8926   gdb_assert (!sals.empty ());
8927
8928   for (const auto &sal : sals)
8929     {
8930       struct bp_location *loc;
8931
8932       if (from_tty)
8933         {
8934           struct gdbarch *loc_gdbarch = get_sal_arch (sal);
8935           if (!loc_gdbarch)
8936             loc_gdbarch = gdbarch;
8937
8938           describe_other_breakpoints (loc_gdbarch,
8939                                       sal.pspace, sal.pc, sal.section, thread);
8940         }
8941
8942       if (&sal == &sals[0])
8943         {
8944           init_raw_breakpoint (b, gdbarch, sal, type, ops);
8945           b->thread = thread;
8946           b->task = task;
8947
8948           b->cond_string = cond_string.release ();
8949           b->extra_string = extra_string.release ();
8950           b->ignore_count = ignore_count;
8951           b->enable_state = enabled ? bp_enabled : bp_disabled;
8952           b->disposition = disposition;
8953
8954           if ((flags & CREATE_BREAKPOINT_FLAGS_INSERTED) != 0)
8955             b->loc->inserted = 1;
8956
8957           if (type == bp_static_tracepoint)
8958             {
8959               struct tracepoint *t = (struct tracepoint *) b;
8960               struct static_tracepoint_marker marker;
8961
8962               if (strace_marker_p (b))
8963                 {
8964                   /* We already know the marker exists, otherwise, we
8965                      wouldn't see a sal for it.  */
8966                   const char *p
8967                     = &event_location_to_string (b->location.get ())[3];
8968                   const char *endp;
8969                   char *marker_str;
8970
8971                   p = skip_spaces (p);
8972
8973                   endp = skip_to_space (p);
8974
8975                   marker_str = savestring (p, endp - p);
8976                   t->static_trace_marker_id = marker_str;
8977
8978                   printf_filtered (_("Probed static tracepoint "
8979                                      "marker \"%s\"\n"),
8980                                    t->static_trace_marker_id);
8981                 }
8982               else if (target_static_tracepoint_marker_at (sal.pc, &marker))
8983                 {
8984                   t->static_trace_marker_id = xstrdup (marker.str_id);
8985                   release_static_tracepoint_marker (&marker);
8986
8987                   printf_filtered (_("Probed static tracepoint "
8988                                      "marker \"%s\"\n"),
8989                                    t->static_trace_marker_id);
8990                 }
8991               else
8992                 warning (_("Couldn't determine the static "
8993                            "tracepoint marker to probe"));
8994             }
8995
8996           loc = b->loc;
8997         }
8998       else
8999         {
9000           loc = add_location_to_breakpoint (b, &sal);
9001           if ((flags & CREATE_BREAKPOINT_FLAGS_INSERTED) != 0)
9002             loc->inserted = 1;
9003         }
9004
9005       if (b->cond_string)
9006         {
9007           const char *arg = b->cond_string;
9008
9009           loc->cond = parse_exp_1 (&arg, loc->address,
9010                                    block_for_pc (loc->address), 0);
9011           if (*arg)
9012               error (_("Garbage '%s' follows condition"), arg);
9013         }
9014
9015       /* Dynamic printf requires and uses additional arguments on the
9016          command line, otherwise it's an error.  */
9017       if (type == bp_dprintf)
9018         {
9019           if (b->extra_string)
9020             update_dprintf_command_list (b);
9021           else
9022             error (_("Format string required"));
9023         }
9024       else if (b->extra_string)
9025         error (_("Garbage '%s' at end of command"), b->extra_string);
9026     }
9027
9028   b->display_canonical = display_canonical;
9029   if (location != NULL)
9030     b->location = std::move (location);
9031   else
9032     b->location = new_address_location (b->loc->address, NULL, 0);
9033   b->filter = filter.release ();
9034 }
9035
9036 static void
9037 create_breakpoint_sal (struct gdbarch *gdbarch,
9038                        gdb::array_view<const symtab_and_line> sals,
9039                        event_location_up &&location,
9040                        gdb::unique_xmalloc_ptr<char> filter,
9041                        gdb::unique_xmalloc_ptr<char> cond_string,
9042                        gdb::unique_xmalloc_ptr<char> extra_string,
9043                        enum bptype type, enum bpdisp disposition,
9044                        int thread, int task, int ignore_count,
9045                        const struct breakpoint_ops *ops, int from_tty,
9046                        int enabled, int internal, unsigned flags,
9047                        int display_canonical)
9048 {
9049   std::unique_ptr<breakpoint> b = new_breakpoint_from_type (type);
9050
9051   init_breakpoint_sal (b.get (), gdbarch,
9052                        sals, std::move (location),
9053                        std::move (filter),
9054                        std::move (cond_string),
9055                        std::move (extra_string),
9056                        type, disposition,
9057                        thread, task, ignore_count,
9058                        ops, from_tty,
9059                        enabled, internal, flags,
9060                        display_canonical);
9061
9062   install_breakpoint (internal, std::move (b), 0);
9063 }
9064
9065 /* Add SALS.nelts breakpoints to the breakpoint table.  For each
9066    SALS.sal[i] breakpoint, include the corresponding ADDR_STRING[i]
9067    value.  COND_STRING, if not NULL, specified the condition to be
9068    used for all breakpoints.  Essentially the only case where
9069    SALS.nelts is not 1 is when we set a breakpoint on an overloaded
9070    function.  In that case, it's still not possible to specify
9071    separate conditions for different overloaded functions, so
9072    we take just a single condition string.
9073    
9074    NOTE: If the function succeeds, the caller is expected to cleanup
9075    the arrays ADDR_STRING, COND_STRING, and SALS (but not the
9076    array contents).  If the function fails (error() is called), the
9077    caller is expected to cleanups both the ADDR_STRING, COND_STRING,
9078    COND and SALS arrays and each of those arrays contents.  */
9079
9080 static void
9081 create_breakpoints_sal (struct gdbarch *gdbarch,
9082                         struct linespec_result *canonical,
9083                         gdb::unique_xmalloc_ptr<char> cond_string,
9084                         gdb::unique_xmalloc_ptr<char> extra_string,
9085                         enum bptype type, enum bpdisp disposition,
9086                         int thread, int task, int ignore_count,
9087                         const struct breakpoint_ops *ops, int from_tty,
9088                         int enabled, int internal, unsigned flags)
9089 {
9090   if (canonical->pre_expanded)
9091     gdb_assert (canonical->lsals.size () == 1);
9092
9093   for (const auto &lsal : canonical->lsals)
9094     {
9095       /* Note that 'location' can be NULL in the case of a plain
9096          'break', without arguments.  */
9097       event_location_up location
9098         = (canonical->location != NULL
9099            ? copy_event_location (canonical->location.get ()) : NULL);
9100       gdb::unique_xmalloc_ptr<char> filter_string
9101         (lsal.canonical != NULL ? xstrdup (lsal.canonical) : NULL);
9102
9103       create_breakpoint_sal (gdbarch, lsal.sals,
9104                              std::move (location),
9105                              std::move (filter_string),
9106                              std::move (cond_string),
9107                              std::move (extra_string),
9108                              type, disposition,
9109                              thread, task, ignore_count, ops,
9110                              from_tty, enabled, internal, flags,
9111                              canonical->special_display);
9112     }
9113 }
9114
9115 /* Parse LOCATION which is assumed to be a SAL specification possibly
9116    followed by conditionals.  On return, SALS contains an array of SAL
9117    addresses found.  LOCATION points to the end of the SAL (for
9118    linespec locations).
9119
9120    The array and the line spec strings are allocated on the heap, it is
9121    the caller's responsibility to free them.  */
9122
9123 static void
9124 parse_breakpoint_sals (const struct event_location *location,
9125                        struct linespec_result *canonical)
9126 {
9127   struct symtab_and_line cursal;
9128
9129   if (event_location_type (location) == LINESPEC_LOCATION)
9130     {
9131       const char *address = get_linespec_location (location);
9132
9133       if (address == NULL)
9134         {
9135           /* The last displayed codepoint, if it's valid, is our default
9136              breakpoint address.  */
9137           if (last_displayed_sal_is_valid ())
9138             {
9139               /* Set sal's pspace, pc, symtab, and line to the values
9140                  corresponding to the last call to print_frame_info.
9141                  Be sure to reinitialize LINE with NOTCURRENT == 0
9142                  as the breakpoint line number is inappropriate otherwise.
9143                  find_pc_line would adjust PC, re-set it back.  */
9144               symtab_and_line sal = get_last_displayed_sal ();
9145               CORE_ADDR pc = sal.pc;
9146
9147               sal = find_pc_line (pc, 0);
9148
9149               /* "break" without arguments is equivalent to "break *PC"
9150                  where PC is the last displayed codepoint's address.  So
9151                  make sure to set sal.explicit_pc to prevent GDB from
9152                  trying to expand the list of sals to include all other
9153                  instances with the same symtab and line.  */
9154               sal.pc = pc;
9155               sal.explicit_pc = 1;
9156
9157               struct linespec_sals lsal;
9158               lsal.sals = {sal};
9159               lsal.canonical = NULL;
9160
9161               canonical->lsals.push_back (std::move (lsal));
9162               return;
9163             }
9164           else
9165             error (_("No default breakpoint address now."));
9166         }
9167     }
9168
9169   /* Force almost all breakpoints to be in terms of the
9170      current_source_symtab (which is decode_line_1's default).
9171      This should produce the results we want almost all of the
9172      time while leaving default_breakpoint_* alone.
9173
9174      ObjC: However, don't match an Objective-C method name which
9175      may have a '+' or '-' succeeded by a '['.  */
9176   cursal = get_current_source_symtab_and_line ();
9177   if (last_displayed_sal_is_valid ())
9178     {
9179       const char *address = NULL;
9180
9181       if (event_location_type (location) == LINESPEC_LOCATION)
9182         address = get_linespec_location (location);
9183
9184       if (!cursal.symtab
9185           || (address != NULL
9186               && strchr ("+-", address[0]) != NULL
9187               && address[1] != '['))
9188         {
9189           decode_line_full (location, DECODE_LINE_FUNFIRSTLINE, NULL,
9190                             get_last_displayed_symtab (),
9191                             get_last_displayed_line (),
9192                             canonical, NULL, NULL);
9193           return;
9194         }
9195     }
9196
9197   decode_line_full (location, DECODE_LINE_FUNFIRSTLINE, NULL,
9198                     cursal.symtab, cursal.line, canonical, NULL, NULL);
9199 }
9200
9201
9202 /* Convert each SAL into a real PC.  Verify that the PC can be
9203    inserted as a breakpoint.  If it can't throw an error.  */
9204
9205 static void
9206 breakpoint_sals_to_pc (std::vector<symtab_and_line> &sals)
9207 {    
9208   for (auto &sal : sals)
9209     resolve_sal_pc (&sal);
9210 }
9211
9212 /* Fast tracepoints may have restrictions on valid locations.  For
9213    instance, a fast tracepoint using a jump instead of a trap will
9214    likely have to overwrite more bytes than a trap would, and so can
9215    only be placed where the instruction is longer than the jump, or a
9216    multi-instruction sequence does not have a jump into the middle of
9217    it, etc.  */
9218
9219 static void
9220 check_fast_tracepoint_sals (struct gdbarch *gdbarch,
9221                             gdb::array_view<const symtab_and_line> sals)
9222 {
9223   int rslt;
9224   char *msg;
9225   struct cleanup *old_chain;
9226
9227   for (const auto &sal : sals)
9228     {
9229       struct gdbarch *sarch;
9230
9231       sarch = get_sal_arch (sal);
9232       /* We fall back to GDBARCH if there is no architecture
9233          associated with SAL.  */
9234       if (sarch == NULL)
9235         sarch = gdbarch;
9236       rslt = gdbarch_fast_tracepoint_valid_at (sarch, sal.pc, &msg);
9237       old_chain = make_cleanup (xfree, msg);
9238
9239       if (!rslt)
9240         error (_("May not have a fast tracepoint at %s%s"),
9241                paddress (sarch, sal.pc), (msg ? msg : ""));
9242
9243       do_cleanups (old_chain);
9244     }
9245 }
9246
9247 /* Given TOK, a string specification of condition and thread, as
9248    accepted by the 'break' command, extract the condition
9249    string and thread number and set *COND_STRING and *THREAD.
9250    PC identifies the context at which the condition should be parsed.
9251    If no condition is found, *COND_STRING is set to NULL.
9252    If no thread is found, *THREAD is set to -1.  */
9253
9254 static void
9255 find_condition_and_thread (const char *tok, CORE_ADDR pc,
9256                            char **cond_string, int *thread, int *task,
9257                            char **rest)
9258 {
9259   *cond_string = NULL;
9260   *thread = -1;
9261   *task = 0;
9262   *rest = NULL;
9263
9264   while (tok && *tok)
9265     {
9266       const char *end_tok;
9267       int toklen;
9268       const char *cond_start = NULL;
9269       const char *cond_end = NULL;
9270
9271       tok = skip_spaces (tok);
9272
9273       if ((*tok == '"' || *tok == ',') && rest)
9274         {
9275           *rest = savestring (tok, strlen (tok));
9276           return;
9277         }
9278
9279       end_tok = skip_to_space (tok);
9280
9281       toklen = end_tok - tok;
9282
9283       if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
9284         {
9285           tok = cond_start = end_tok + 1;
9286           parse_exp_1 (&tok, pc, block_for_pc (pc), 0);
9287           cond_end = tok;
9288           *cond_string = savestring (cond_start, cond_end - cond_start);
9289         }
9290       else if (toklen >= 1 && strncmp (tok, "thread", toklen) == 0)
9291         {
9292           const char *tmptok;
9293           struct thread_info *thr;
9294
9295           tok = end_tok + 1;
9296           thr = parse_thread_id (tok, &tmptok);
9297           if (tok == tmptok)
9298             error (_("Junk after thread keyword."));
9299           *thread = thr->global_num;
9300           tok = tmptok;
9301         }
9302       else if (toklen >= 1 && strncmp (tok, "task", toklen) == 0)
9303         {
9304           char *tmptok;
9305
9306           tok = end_tok + 1;
9307           *task = strtol (tok, &tmptok, 0);
9308           if (tok == tmptok)
9309             error (_("Junk after task keyword."));
9310           if (!valid_task_id (*task))
9311             error (_("Unknown task %d."), *task);
9312           tok = tmptok;
9313         }
9314       else if (rest)
9315         {
9316           *rest = savestring (tok, strlen (tok));
9317           return;
9318         }
9319       else
9320         error (_("Junk at end of arguments."));
9321     }
9322 }
9323
9324 /* Decode a static tracepoint marker spec.  */
9325
9326 static std::vector<symtab_and_line>
9327 decode_static_tracepoint_spec (const char **arg_p)
9328 {
9329   VEC(static_tracepoint_marker_p) *markers = NULL;
9330   const char *p = &(*arg_p)[3];
9331   const char *endp;
9332   int i;
9333
9334   p = skip_spaces (p);
9335
9336   endp = skip_to_space (p);
9337
9338   std::string marker_str (p, endp - p);
9339
9340   markers = target_static_tracepoint_markers_by_strid (marker_str.c_str ());
9341   if (VEC_empty(static_tracepoint_marker_p, markers))
9342     error (_("No known static tracepoint marker named %s"),
9343            marker_str.c_str ());
9344
9345   std::vector<symtab_and_line> sals;
9346   sals.reserve (VEC_length(static_tracepoint_marker_p, markers));
9347
9348   for (i = 0; i < VEC_length(static_tracepoint_marker_p, markers); i++)
9349     {
9350       struct static_tracepoint_marker *marker;
9351
9352       marker = VEC_index (static_tracepoint_marker_p, markers, i);
9353
9354       symtab_and_line sal = find_pc_line (marker->address, 0);
9355       sal.pc = marker->address;
9356       sals.push_back (sal);
9357
9358       release_static_tracepoint_marker (marker);
9359     }
9360
9361   *arg_p = endp;
9362   return sals;
9363 }
9364
9365 /* See breakpoint.h.  */
9366
9367 int
9368 create_breakpoint (struct gdbarch *gdbarch,
9369                    const struct event_location *location,
9370                    const char *cond_string,
9371                    int thread, const char *extra_string,
9372                    int parse_extra,
9373                    int tempflag, enum bptype type_wanted,
9374                    int ignore_count,
9375                    enum auto_boolean pending_break_support,
9376                    const struct breakpoint_ops *ops,
9377                    int from_tty, int enabled, int internal,
9378                    unsigned flags)
9379 {
9380   struct linespec_result canonical;
9381   struct cleanup *bkpt_chain = NULL;
9382   int pending = 0;
9383   int task = 0;
9384   int prev_bkpt_count = breakpoint_count;
9385
9386   gdb_assert (ops != NULL);
9387
9388   /* If extra_string isn't useful, set it to NULL.  */
9389   if (extra_string != NULL && *extra_string == '\0')
9390     extra_string = NULL;
9391
9392   TRY
9393     {
9394       ops->create_sals_from_location (location, &canonical, type_wanted);
9395     }
9396   CATCH (e, RETURN_MASK_ERROR)
9397     {
9398       /* If caller is interested in rc value from parse, set
9399          value.  */
9400       if (e.error == NOT_FOUND_ERROR)
9401         {
9402           /* If pending breakpoint support is turned off, throw
9403              error.  */
9404
9405           if (pending_break_support == AUTO_BOOLEAN_FALSE)
9406             throw_exception (e);
9407
9408           exception_print (gdb_stderr, e);
9409
9410           /* If pending breakpoint support is auto query and the user
9411              selects no, then simply return the error code.  */
9412           if (pending_break_support == AUTO_BOOLEAN_AUTO
9413               && !nquery (_("Make %s pending on future shared library load? "),
9414                           bptype_string (type_wanted)))
9415             return 0;
9416
9417           /* At this point, either the user was queried about setting
9418              a pending breakpoint and selected yes, or pending
9419              breakpoint behavior is on and thus a pending breakpoint
9420              is defaulted on behalf of the user.  */
9421           pending = 1;
9422         }
9423       else
9424         throw_exception (e);
9425     }
9426   END_CATCH
9427
9428   if (!pending && canonical.lsals.empty ())
9429     return 0;
9430
9431   /* ----------------------------- SNIP -----------------------------
9432      Anything added to the cleanup chain beyond this point is assumed
9433      to be part of a breakpoint.  If the breakpoint create succeeds
9434      then the memory is not reclaimed.  */
9435   bkpt_chain = make_cleanup (null_cleanup, 0);
9436
9437   /* Resolve all line numbers to PC's and verify that the addresses
9438      are ok for the target.  */
9439   if (!pending)
9440     {
9441       for (auto &lsal : canonical.lsals)
9442         breakpoint_sals_to_pc (lsal.sals);
9443     }
9444
9445   /* Fast tracepoints may have additional restrictions on location.  */
9446   if (!pending && type_wanted == bp_fast_tracepoint)
9447     {
9448       for (const auto &lsal : canonical.lsals)
9449         check_fast_tracepoint_sals (gdbarch, lsal.sals);
9450     }
9451
9452   /* Verify that condition can be parsed, before setting any
9453      breakpoints.  Allocate a separate condition expression for each
9454      breakpoint.  */
9455   if (!pending)
9456     {
9457       gdb::unique_xmalloc_ptr<char> cond_string_copy;
9458       gdb::unique_xmalloc_ptr<char> extra_string_copy;
9459
9460       if (parse_extra)
9461         {
9462           char *rest;
9463           char *cond;
9464
9465           const linespec_sals &lsal = canonical.lsals[0];
9466
9467           /* Here we only parse 'arg' to separate condition
9468              from thread number, so parsing in context of first
9469              sal is OK.  When setting the breakpoint we'll
9470              re-parse it in context of each sal.  */
9471
9472           find_condition_and_thread (extra_string, lsal.sals[0].pc,
9473                                      &cond, &thread, &task, &rest);
9474           cond_string_copy.reset (cond);
9475           extra_string_copy.reset (rest);
9476         }
9477       else
9478         {
9479           if (type_wanted != bp_dprintf
9480               && extra_string != NULL && *extra_string != '\0')
9481                 error (_("Garbage '%s' at end of location"), extra_string);
9482
9483           /* Create a private copy of condition string.  */
9484           if (cond_string)
9485             cond_string_copy.reset (xstrdup (cond_string));
9486           /* Create a private copy of any extra string.  */
9487           if (extra_string)
9488             extra_string_copy.reset (xstrdup (extra_string));
9489         }
9490
9491       ops->create_breakpoints_sal (gdbarch, &canonical,
9492                                    std::move (cond_string_copy),
9493                                    std::move (extra_string_copy),
9494                                    type_wanted,
9495                                    tempflag ? disp_del : disp_donttouch,
9496                                    thread, task, ignore_count, ops,
9497                                    from_tty, enabled, internal, flags);
9498     }
9499   else
9500     {
9501       std::unique_ptr <breakpoint> b = new_breakpoint_from_type (type_wanted);
9502
9503       init_raw_breakpoint_without_location (b.get (), gdbarch, type_wanted, ops);
9504       b->location = copy_event_location (location);
9505
9506       if (parse_extra)
9507         b->cond_string = NULL;
9508       else
9509         {
9510           /* Create a private copy of condition string.  */
9511           b->cond_string = cond_string != NULL ? xstrdup (cond_string) : NULL;
9512           b->thread = thread;
9513         }
9514
9515       /* Create a private copy of any extra string.  */
9516       b->extra_string = extra_string != NULL ? xstrdup (extra_string) : NULL;
9517       b->ignore_count = ignore_count;
9518       b->disposition = tempflag ? disp_del : disp_donttouch;
9519       b->condition_not_parsed = 1;
9520       b->enable_state = enabled ? bp_enabled : bp_disabled;
9521       if ((type_wanted != bp_breakpoint
9522            && type_wanted != bp_hardware_breakpoint) || thread != -1)
9523         b->pspace = current_program_space;
9524
9525       install_breakpoint (internal, std::move (b), 0);
9526     }
9527   
9528   if (canonical.lsals.size () > 1)
9529     {
9530       warning (_("Multiple breakpoints were set.\nUse the "
9531                  "\"delete\" command to delete unwanted breakpoints."));
9532       prev_breakpoint_count = prev_bkpt_count;
9533     }
9534
9535   /* That's it.  Discard the cleanups for data inserted into the
9536      breakpoint.  */
9537   discard_cleanups (bkpt_chain);
9538
9539   /* error call may happen here - have BKPT_CHAIN already discarded.  */
9540   update_global_location_list (UGLL_MAY_INSERT);
9541
9542   return 1;
9543 }
9544
9545 /* Set a breakpoint.
9546    ARG is a string describing breakpoint address,
9547    condition, and thread.
9548    FLAG specifies if a breakpoint is hardware on,
9549    and if breakpoint is temporary, using BP_HARDWARE_FLAG
9550    and BP_TEMPFLAG.  */
9551
9552 static void
9553 break_command_1 (const char *arg, int flag, int from_tty)
9554 {
9555   int tempflag = flag & BP_TEMPFLAG;
9556   enum bptype type_wanted = (flag & BP_HARDWAREFLAG
9557                              ? bp_hardware_breakpoint
9558                              : bp_breakpoint);
9559   struct breakpoint_ops *ops;
9560
9561   event_location_up location = string_to_event_location (&arg, current_language);
9562
9563   /* Matching breakpoints on probes.  */
9564   if (location != NULL
9565       && event_location_type (location.get ()) == PROBE_LOCATION)
9566     ops = &bkpt_probe_breakpoint_ops;
9567   else
9568     ops = &bkpt_breakpoint_ops;
9569
9570   create_breakpoint (get_current_arch (),
9571                      location.get (),
9572                      NULL, 0, arg, 1 /* parse arg */,
9573                      tempflag, type_wanted,
9574                      0 /* Ignore count */,
9575                      pending_break_support,
9576                      ops,
9577                      from_tty,
9578                      1 /* enabled */,
9579                      0 /* internal */,
9580                      0);
9581 }
9582
9583 /* Helper function for break_command_1 and disassemble_command.  */
9584
9585 void
9586 resolve_sal_pc (struct symtab_and_line *sal)
9587 {
9588   CORE_ADDR pc;
9589
9590   if (sal->pc == 0 && sal->symtab != NULL)
9591     {
9592       if (!find_line_pc (sal->symtab, sal->line, &pc))
9593         error (_("No line %d in file \"%s\"."),
9594                sal->line, symtab_to_filename_for_display (sal->symtab));
9595       sal->pc = pc;
9596
9597       /* If this SAL corresponds to a breakpoint inserted using a line
9598          number, then skip the function prologue if necessary.  */
9599       if (sal->explicit_line)
9600         skip_prologue_sal (sal);
9601     }
9602
9603   if (sal->section == 0 && sal->symtab != NULL)
9604     {
9605       const struct blockvector *bv;
9606       const struct block *b;
9607       struct symbol *sym;
9608
9609       bv = blockvector_for_pc_sect (sal->pc, 0, &b,
9610                                     SYMTAB_COMPUNIT (sal->symtab));
9611       if (bv != NULL)
9612         {
9613           sym = block_linkage_function (b);
9614           if (sym != NULL)
9615             {
9616               fixup_symbol_section (sym, SYMTAB_OBJFILE (sal->symtab));
9617               sal->section = SYMBOL_OBJ_SECTION (SYMTAB_OBJFILE (sal->symtab),
9618                                                  sym);
9619             }
9620           else
9621             {
9622               /* It really is worthwhile to have the section, so we'll
9623                  just have to look harder. This case can be executed
9624                  if we have line numbers but no functions (as can
9625                  happen in assembly source).  */
9626
9627               scoped_restore_current_pspace_and_thread restore_pspace_thread;
9628               switch_to_program_space_and_thread (sal->pspace);
9629
9630               bound_minimal_symbol msym = lookup_minimal_symbol_by_pc (sal->pc);
9631               if (msym.minsym)
9632                 sal->section = MSYMBOL_OBJ_SECTION (msym.objfile, msym.minsym);
9633             }
9634         }
9635     }
9636 }
9637
9638 void
9639 break_command (char *arg, int from_tty)
9640 {
9641   break_command_1 (arg, 0, from_tty);
9642 }
9643
9644 void
9645 tbreak_command (char *arg, int from_tty)
9646 {
9647   break_command_1 (arg, BP_TEMPFLAG, from_tty);
9648 }
9649
9650 static void
9651 hbreak_command (char *arg, int from_tty)
9652 {
9653   break_command_1 (arg, BP_HARDWAREFLAG, from_tty);
9654 }
9655
9656 static void
9657 thbreak_command (char *arg, int from_tty)
9658 {
9659   break_command_1 (arg, (BP_TEMPFLAG | BP_HARDWAREFLAG), from_tty);
9660 }
9661
9662 static void
9663 stop_command (char *arg, int from_tty)
9664 {
9665   printf_filtered (_("Specify the type of breakpoint to set.\n\
9666 Usage: stop in <function | address>\n\
9667        stop at <line>\n"));
9668 }
9669
9670 static void
9671 stopin_command (const char *arg, int from_tty)
9672 {
9673   int badInput = 0;
9674
9675   if (arg == (char *) NULL)
9676     badInput = 1;
9677   else if (*arg != '*')
9678     {
9679       const char *argptr = arg;
9680       int hasColon = 0;
9681
9682       /* Look for a ':'.  If this is a line number specification, then
9683          say it is bad, otherwise, it should be an address or
9684          function/method name.  */
9685       while (*argptr && !hasColon)
9686         {
9687           hasColon = (*argptr == ':');
9688           argptr++;
9689         }
9690
9691       if (hasColon)
9692         badInput = (*argptr != ':');    /* Not a class::method */
9693       else
9694         badInput = isdigit (*arg);      /* a simple line number */
9695     }
9696
9697   if (badInput)
9698     printf_filtered (_("Usage: stop in <function | address>\n"));
9699   else
9700     break_command_1 (arg, 0, from_tty);
9701 }
9702
9703 static void
9704 stopat_command (const char *arg, int from_tty)
9705 {
9706   int badInput = 0;
9707
9708   if (arg == (char *) NULL || *arg == '*')      /* no line number */
9709     badInput = 1;
9710   else
9711     {
9712       const char *argptr = arg;
9713       int hasColon = 0;
9714
9715       /* Look for a ':'.  If there is a '::' then get out, otherwise
9716          it is probably a line number.  */
9717       while (*argptr && !hasColon)
9718         {
9719           hasColon = (*argptr == ':');
9720           argptr++;
9721         }
9722
9723       if (hasColon)
9724         badInput = (*argptr == ':');    /* we have class::method */
9725       else
9726         badInput = !isdigit (*arg);     /* not a line number */
9727     }
9728
9729   if (badInput)
9730     printf_filtered (_("Usage: stop at <line>\n"));
9731   else
9732     break_command_1 (arg, 0, from_tty);
9733 }
9734
9735 /* The dynamic printf command is mostly like a regular breakpoint, but
9736    with a prewired command list consisting of a single output command,
9737    built from extra arguments supplied on the dprintf command
9738    line.  */
9739
9740 static void
9741 dprintf_command (char *arg_in, int from_tty)
9742 {
9743   const char *arg = arg_in;
9744   event_location_up location = string_to_event_location (&arg, current_language);
9745
9746   /* If non-NULL, ARG should have been advanced past the location;
9747      the next character must be ','.  */
9748   if (arg != NULL)
9749     {
9750       if (arg[0] != ',' || arg[1] == '\0')
9751         error (_("Format string required"));
9752       else
9753         {
9754           /* Skip the comma.  */
9755           ++arg;
9756         }
9757     }
9758
9759   create_breakpoint (get_current_arch (),
9760                      location.get (),
9761                      NULL, 0, arg, 1 /* parse arg */,
9762                      0, bp_dprintf,
9763                      0 /* Ignore count */,
9764                      pending_break_support,
9765                      &dprintf_breakpoint_ops,
9766                      from_tty,
9767                      1 /* enabled */,
9768                      0 /* internal */,
9769                      0);
9770 }
9771
9772 static void
9773 agent_printf_command (char *arg, int from_tty)
9774 {
9775   error (_("May only run agent-printf on the target"));
9776 }
9777
9778 /* Implement the "breakpoint_hit" breakpoint_ops method for
9779    ranged breakpoints.  */
9780
9781 static int
9782 breakpoint_hit_ranged_breakpoint (const struct bp_location *bl,
9783                                   const address_space *aspace,
9784                                   CORE_ADDR bp_addr,
9785                                   const struct target_waitstatus *ws)
9786 {
9787   if (ws->kind != TARGET_WAITKIND_STOPPED
9788       || ws->value.sig != GDB_SIGNAL_TRAP)
9789     return 0;
9790
9791   return breakpoint_address_match_range (bl->pspace->aspace, bl->address,
9792                                          bl->length, aspace, bp_addr);
9793 }
9794
9795 /* Implement the "resources_needed" breakpoint_ops method for
9796    ranged breakpoints.  */
9797
9798 static int
9799 resources_needed_ranged_breakpoint (const struct bp_location *bl)
9800 {
9801   return target_ranged_break_num_registers ();
9802 }
9803
9804 /* Implement the "print_it" breakpoint_ops method for
9805    ranged breakpoints.  */
9806
9807 static enum print_stop_action
9808 print_it_ranged_breakpoint (bpstat bs)
9809 {
9810   struct breakpoint *b = bs->breakpoint_at;
9811   struct bp_location *bl = b->loc;
9812   struct ui_out *uiout = current_uiout;
9813
9814   gdb_assert (b->type == bp_hardware_breakpoint);
9815
9816   /* Ranged breakpoints have only one location.  */
9817   gdb_assert (bl && bl->next == NULL);
9818
9819   annotate_breakpoint (b->number);
9820
9821   maybe_print_thread_hit_breakpoint (uiout);
9822
9823   if (b->disposition == disp_del)
9824     uiout->text ("Temporary ranged breakpoint ");
9825   else
9826     uiout->text ("Ranged breakpoint ");
9827   if (uiout->is_mi_like_p ())
9828     {
9829       uiout->field_string ("reason",
9830                       async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
9831       uiout->field_string ("disp", bpdisp_text (b->disposition));
9832     }
9833   uiout->field_int ("bkptno", b->number);
9834   uiout->text (", ");
9835
9836   return PRINT_SRC_AND_LOC;
9837 }
9838
9839 /* Implement the "print_one" breakpoint_ops method for
9840    ranged breakpoints.  */
9841
9842 static void
9843 print_one_ranged_breakpoint (struct breakpoint *b,
9844                              struct bp_location **last_loc)
9845 {
9846   struct bp_location *bl = b->loc;
9847   struct value_print_options opts;
9848   struct ui_out *uiout = current_uiout;
9849
9850   /* Ranged breakpoints have only one location.  */
9851   gdb_assert (bl && bl->next == NULL);
9852
9853   get_user_print_options (&opts);
9854
9855   if (opts.addressprint)
9856     /* We don't print the address range here, it will be printed later
9857        by print_one_detail_ranged_breakpoint.  */
9858     uiout->field_skip ("addr");
9859   annotate_field (5);
9860   print_breakpoint_location (b, bl);
9861   *last_loc = bl;
9862 }
9863
9864 /* Implement the "print_one_detail" breakpoint_ops method for
9865    ranged breakpoints.  */
9866
9867 static void
9868 print_one_detail_ranged_breakpoint (const struct breakpoint *b,
9869                                     struct ui_out *uiout)
9870 {
9871   CORE_ADDR address_start, address_end;
9872   struct bp_location *bl = b->loc;
9873   string_file stb;
9874
9875   gdb_assert (bl);
9876
9877   address_start = bl->address;
9878   address_end = address_start + bl->length - 1;
9879
9880   uiout->text ("\taddress range: ");
9881   stb.printf ("[%s, %s]",
9882               print_core_address (bl->gdbarch, address_start),
9883               print_core_address (bl->gdbarch, address_end));
9884   uiout->field_stream ("addr", stb);
9885   uiout->text ("\n");
9886 }
9887
9888 /* Implement the "print_mention" breakpoint_ops method for
9889    ranged breakpoints.  */
9890
9891 static void
9892 print_mention_ranged_breakpoint (struct breakpoint *b)
9893 {
9894   struct bp_location *bl = b->loc;
9895   struct ui_out *uiout = current_uiout;
9896
9897   gdb_assert (bl);
9898   gdb_assert (b->type == bp_hardware_breakpoint);
9899
9900   if (uiout->is_mi_like_p ())
9901     return;
9902
9903   printf_filtered (_("Hardware assisted ranged breakpoint %d from %s to %s."),
9904                    b->number, paddress (bl->gdbarch, bl->address),
9905                    paddress (bl->gdbarch, bl->address + bl->length - 1));
9906 }
9907
9908 /* Implement the "print_recreate" breakpoint_ops method for
9909    ranged breakpoints.  */
9910
9911 static void
9912 print_recreate_ranged_breakpoint (struct breakpoint *b, struct ui_file *fp)
9913 {
9914   fprintf_unfiltered (fp, "break-range %s, %s",
9915                       event_location_to_string (b->location.get ()),
9916                       event_location_to_string (b->location_range_end.get ()));
9917   print_recreate_thread (b, fp);
9918 }
9919
9920 /* The breakpoint_ops structure to be used in ranged breakpoints.  */
9921
9922 static struct breakpoint_ops ranged_breakpoint_ops;
9923
9924 /* Find the address where the end of the breakpoint range should be
9925    placed, given the SAL of the end of the range.  This is so that if
9926    the user provides a line number, the end of the range is set to the
9927    last instruction of the given line.  */
9928
9929 static CORE_ADDR
9930 find_breakpoint_range_end (struct symtab_and_line sal)
9931 {
9932   CORE_ADDR end;
9933
9934   /* If the user provided a PC value, use it.  Otherwise,
9935      find the address of the end of the given location.  */
9936   if (sal.explicit_pc)
9937     end = sal.pc;
9938   else
9939     {
9940       int ret;
9941       CORE_ADDR start;
9942
9943       ret = find_line_pc_range (sal, &start, &end);
9944       if (!ret)
9945         error (_("Could not find location of the end of the range."));
9946
9947       /* find_line_pc_range returns the start of the next line.  */
9948       end--;
9949     }
9950
9951   return end;
9952 }
9953
9954 /* Implement the "break-range" CLI command.  */
9955
9956 static void
9957 break_range_command (char *arg_in, int from_tty)
9958 {
9959   const char *arg = arg_in;
9960   const char *arg_start;
9961   struct linespec_result canonical_start, canonical_end;
9962   int bp_count, can_use_bp, length;
9963   CORE_ADDR end;
9964   struct breakpoint *b;
9965
9966   /* We don't support software ranged breakpoints.  */
9967   if (target_ranged_break_num_registers () < 0)
9968     error (_("This target does not support hardware ranged breakpoints."));
9969
9970   bp_count = hw_breakpoint_used_count ();
9971   bp_count += target_ranged_break_num_registers ();
9972   can_use_bp = target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
9973                                                    bp_count, 0);
9974   if (can_use_bp < 0)
9975     error (_("Hardware breakpoints used exceeds limit."));
9976
9977   arg = skip_spaces (arg);
9978   if (arg == NULL || arg[0] == '\0')
9979     error(_("No address range specified."));
9980
9981   arg_start = arg;
9982   event_location_up start_location = string_to_event_location (&arg,
9983                                                                current_language);
9984   parse_breakpoint_sals (start_location.get (), &canonical_start);
9985
9986   if (arg[0] != ',')
9987     error (_("Too few arguments."));
9988   else if (canonical_start.lsals.empty ())
9989     error (_("Could not find location of the beginning of the range."));
9990
9991   const linespec_sals &lsal_start = canonical_start.lsals[0];
9992
9993   if (canonical_start.lsals.size () > 1
9994       || lsal_start.sals.size () != 1)
9995     error (_("Cannot create a ranged breakpoint with multiple locations."));
9996
9997   const symtab_and_line &sal_start = lsal_start.sals[0];
9998   std::string addr_string_start (arg_start, arg - arg_start);
9999
10000   arg++;        /* Skip the comma.  */
10001   arg = skip_spaces (arg);
10002
10003   /* Parse the end location.  */
10004
10005   arg_start = arg;
10006
10007   /* We call decode_line_full directly here instead of using
10008      parse_breakpoint_sals because we need to specify the start location's
10009      symtab and line as the default symtab and line for the end of the
10010      range.  This makes it possible to have ranges like "foo.c:27, +14",
10011      where +14 means 14 lines from the start location.  */
10012   event_location_up end_location = string_to_event_location (&arg,
10013                                                              current_language);
10014   decode_line_full (end_location.get (), DECODE_LINE_FUNFIRSTLINE, NULL,
10015                     sal_start.symtab, sal_start.line,
10016                     &canonical_end, NULL, NULL);
10017
10018   if (canonical_end.lsals.empty ())
10019     error (_("Could not find location of the end of the range."));
10020
10021   const linespec_sals &lsal_end = canonical_end.lsals[0];
10022   if (canonical_end.lsals.size () > 1
10023       || lsal_end.sals.size () != 1)
10024     error (_("Cannot create a ranged breakpoint with multiple locations."));
10025
10026   const symtab_and_line &sal_end = lsal_end.sals[0];
10027
10028   end = find_breakpoint_range_end (sal_end);
10029   if (sal_start.pc > end)
10030     error (_("Invalid address range, end precedes start."));
10031
10032   length = end - sal_start.pc + 1;
10033   if (length < 0)
10034     /* Length overflowed.  */
10035     error (_("Address range too large."));
10036   else if (length == 1)
10037     {
10038       /* This range is simple enough to be handled by
10039          the `hbreak' command.  */
10040       hbreak_command (&addr_string_start[0], 1);
10041
10042       return;
10043     }
10044
10045   /* Now set up the breakpoint.  */
10046   b = set_raw_breakpoint (get_current_arch (), sal_start,
10047                           bp_hardware_breakpoint, &ranged_breakpoint_ops);
10048   set_breakpoint_count (breakpoint_count + 1);
10049   b->number = breakpoint_count;
10050   b->disposition = disp_donttouch;
10051   b->location = std::move (start_location);
10052   b->location_range_end = std::move (end_location);
10053   b->loc->length = length;
10054
10055   mention (b);
10056   observer_notify_breakpoint_created (b);
10057   update_global_location_list (UGLL_MAY_INSERT);
10058 }
10059
10060 /*  Return non-zero if EXP is verified as constant.  Returned zero
10061     means EXP is variable.  Also the constant detection may fail for
10062     some constant expressions and in such case still falsely return
10063     zero.  */
10064
10065 static int
10066 watchpoint_exp_is_const (const struct expression *exp)
10067 {
10068   int i = exp->nelts;
10069
10070   while (i > 0)
10071     {
10072       int oplenp, argsp;
10073
10074       /* We are only interested in the descriptor of each element.  */
10075       operator_length (exp, i, &oplenp, &argsp);
10076       i -= oplenp;
10077
10078       switch (exp->elts[i].opcode)
10079         {
10080         case BINOP_ADD:
10081         case BINOP_SUB:
10082         case BINOP_MUL:
10083         case BINOP_DIV:
10084         case BINOP_REM:
10085         case BINOP_MOD:
10086         case BINOP_LSH:
10087         case BINOP_RSH:
10088         case BINOP_LOGICAL_AND:
10089         case BINOP_LOGICAL_OR:
10090         case BINOP_BITWISE_AND:
10091         case BINOP_BITWISE_IOR:
10092         case BINOP_BITWISE_XOR:
10093         case BINOP_EQUAL:
10094         case BINOP_NOTEQUAL:
10095         case BINOP_LESS:
10096         case BINOP_GTR:
10097         case BINOP_LEQ:
10098         case BINOP_GEQ:
10099         case BINOP_REPEAT:
10100         case BINOP_COMMA:
10101         case BINOP_EXP:
10102         case BINOP_MIN:
10103         case BINOP_MAX:
10104         case BINOP_INTDIV:
10105         case BINOP_CONCAT:
10106         case TERNOP_COND:
10107         case TERNOP_SLICE:
10108
10109         case OP_LONG:
10110         case OP_FLOAT:
10111         case OP_LAST:
10112         case OP_COMPLEX:
10113         case OP_STRING:
10114         case OP_ARRAY:
10115         case OP_TYPE:
10116         case OP_TYPEOF:
10117         case OP_DECLTYPE:
10118         case OP_TYPEID:
10119         case OP_NAME:
10120         case OP_OBJC_NSSTRING:
10121
10122         case UNOP_NEG:
10123         case UNOP_LOGICAL_NOT:
10124         case UNOP_COMPLEMENT:
10125         case UNOP_ADDR:
10126         case UNOP_HIGH:
10127         case UNOP_CAST:
10128
10129         case UNOP_CAST_TYPE:
10130         case UNOP_REINTERPRET_CAST:
10131         case UNOP_DYNAMIC_CAST:
10132           /* Unary, binary and ternary operators: We have to check
10133              their operands.  If they are constant, then so is the
10134              result of that operation.  For instance, if A and B are
10135              determined to be constants, then so is "A + B".
10136
10137              UNOP_IND is one exception to the rule above, because the
10138              value of *ADDR is not necessarily a constant, even when
10139              ADDR is.  */
10140           break;
10141
10142         case OP_VAR_VALUE:
10143           /* Check whether the associated symbol is a constant.
10144
10145              We use SYMBOL_CLASS rather than TYPE_CONST because it's
10146              possible that a buggy compiler could mark a variable as
10147              constant even when it is not, and TYPE_CONST would return
10148              true in this case, while SYMBOL_CLASS wouldn't.
10149
10150              We also have to check for function symbols because they
10151              are always constant.  */
10152           {
10153             struct symbol *s = exp->elts[i + 2].symbol;
10154
10155             if (SYMBOL_CLASS (s) != LOC_BLOCK
10156                 && SYMBOL_CLASS (s) != LOC_CONST
10157                 && SYMBOL_CLASS (s) != LOC_CONST_BYTES)
10158               return 0;
10159             break;
10160           }
10161
10162         /* The default action is to return 0 because we are using
10163            the optimistic approach here: If we don't know something,
10164            then it is not a constant.  */
10165         default:
10166           return 0;
10167         }
10168     }
10169
10170   return 1;
10171 }
10172
10173 /* Watchpoint destructor.  */
10174
10175 watchpoint::~watchpoint ()
10176 {
10177   xfree (this->exp_string);
10178   xfree (this->exp_string_reparse);
10179   value_free (this->val);
10180 }
10181
10182 /* Implement the "re_set" breakpoint_ops method for watchpoints.  */
10183
10184 static void
10185 re_set_watchpoint (struct breakpoint *b)
10186 {
10187   struct watchpoint *w = (struct watchpoint *) b;
10188
10189   /* Watchpoint can be either on expression using entirely global
10190      variables, or it can be on local variables.
10191
10192      Watchpoints of the first kind are never auto-deleted, and even
10193      persist across program restarts.  Since they can use variables
10194      from shared libraries, we need to reparse expression as libraries
10195      are loaded and unloaded.
10196
10197      Watchpoints on local variables can also change meaning as result
10198      of solib event.  For example, if a watchpoint uses both a local
10199      and a global variables in expression, it's a local watchpoint,
10200      but unloading of a shared library will make the expression
10201      invalid.  This is not a very common use case, but we still
10202      re-evaluate expression, to avoid surprises to the user.
10203
10204      Note that for local watchpoints, we re-evaluate it only if
10205      watchpoints frame id is still valid.  If it's not, it means the
10206      watchpoint is out of scope and will be deleted soon.  In fact,
10207      I'm not sure we'll ever be called in this case.
10208
10209      If a local watchpoint's frame id is still valid, then
10210      w->exp_valid_block is likewise valid, and we can safely use it.
10211
10212      Don't do anything about disabled watchpoints, since they will be
10213      reevaluated again when enabled.  */
10214   update_watchpoint (w, 1 /* reparse */);
10215 }
10216
10217 /* Implement the "insert" breakpoint_ops method for hardware watchpoints.  */
10218
10219 static int
10220 insert_watchpoint (struct bp_location *bl)
10221 {
10222   struct watchpoint *w = (struct watchpoint *) bl->owner;
10223   int length = w->exact ? 1 : bl->length;
10224
10225   return target_insert_watchpoint (bl->address, length, bl->watchpoint_type,
10226                                    w->cond_exp.get ());
10227 }
10228
10229 /* Implement the "remove" breakpoint_ops method for hardware watchpoints.  */
10230
10231 static int
10232 remove_watchpoint (struct bp_location *bl, enum remove_bp_reason reason)
10233 {
10234   struct watchpoint *w = (struct watchpoint *) bl->owner;
10235   int length = w->exact ? 1 : bl->length;
10236
10237   return target_remove_watchpoint (bl->address, length, bl->watchpoint_type,
10238                                    w->cond_exp.get ());
10239 }
10240
10241 static int
10242 breakpoint_hit_watchpoint (const struct bp_location *bl,
10243                            const address_space *aspace, CORE_ADDR bp_addr,
10244                            const struct target_waitstatus *ws)
10245 {
10246   struct breakpoint *b = bl->owner;
10247   struct watchpoint *w = (struct watchpoint *) b;
10248
10249   /* Continuable hardware watchpoints are treated as non-existent if the
10250      reason we stopped wasn't a hardware watchpoint (we didn't stop on
10251      some data address).  Otherwise gdb won't stop on a break instruction
10252      in the code (not from a breakpoint) when a hardware watchpoint has
10253      been defined.  Also skip watchpoints which we know did not trigger
10254      (did not match the data address).  */
10255   if (is_hardware_watchpoint (b)
10256       && w->watchpoint_triggered == watch_triggered_no)
10257     return 0;
10258
10259   return 1;
10260 }
10261
10262 static void
10263 check_status_watchpoint (bpstat bs)
10264 {
10265   gdb_assert (is_watchpoint (bs->breakpoint_at));
10266
10267   bpstat_check_watchpoint (bs);
10268 }
10269
10270 /* Implement the "resources_needed" breakpoint_ops method for
10271    hardware watchpoints.  */
10272
10273 static int
10274 resources_needed_watchpoint (const struct bp_location *bl)
10275 {
10276   struct watchpoint *w = (struct watchpoint *) bl->owner;
10277   int length = w->exact? 1 : bl->length;
10278
10279   return target_region_ok_for_hw_watchpoint (bl->address, length);
10280 }
10281
10282 /* Implement the "works_in_software_mode" breakpoint_ops method for
10283    hardware watchpoints.  */
10284
10285 static int
10286 works_in_software_mode_watchpoint (const struct breakpoint *b)
10287 {
10288   /* Read and access watchpoints only work with hardware support.  */
10289   return b->type == bp_watchpoint || b->type == bp_hardware_watchpoint;
10290 }
10291
10292 static enum print_stop_action
10293 print_it_watchpoint (bpstat bs)
10294 {
10295   struct breakpoint *b;
10296   enum print_stop_action result;
10297   struct watchpoint *w;
10298   struct ui_out *uiout = current_uiout;
10299
10300   gdb_assert (bs->bp_location_at != NULL);
10301
10302   b = bs->breakpoint_at;
10303   w = (struct watchpoint *) b;
10304
10305   annotate_watchpoint (b->number);
10306   maybe_print_thread_hit_breakpoint (uiout);
10307
10308   string_file stb;
10309
10310   gdb::optional<ui_out_emit_tuple> tuple_emitter;
10311   switch (b->type)
10312     {
10313     case bp_watchpoint:
10314     case bp_hardware_watchpoint:
10315       if (uiout->is_mi_like_p ())
10316         uiout->field_string
10317           ("reason", async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
10318       mention (b);
10319       tuple_emitter.emplace (uiout, "value");
10320       uiout->text ("\nOld value = ");
10321       watchpoint_value_print (bs->old_val, &stb);
10322       uiout->field_stream ("old", stb);
10323       uiout->text ("\nNew value = ");
10324       watchpoint_value_print (w->val, &stb);
10325       uiout->field_stream ("new", stb);
10326       uiout->text ("\n");
10327       /* More than one watchpoint may have been triggered.  */
10328       result = PRINT_UNKNOWN;
10329       break;
10330
10331     case bp_read_watchpoint:
10332       if (uiout->is_mi_like_p ())
10333         uiout->field_string
10334           ("reason", async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
10335       mention (b);
10336       tuple_emitter.emplace (uiout, "value");
10337       uiout->text ("\nValue = ");
10338       watchpoint_value_print (w->val, &stb);
10339       uiout->field_stream ("value", stb);
10340       uiout->text ("\n");
10341       result = PRINT_UNKNOWN;
10342       break;
10343
10344     case bp_access_watchpoint:
10345       if (bs->old_val != NULL)
10346         {
10347           if (uiout->is_mi_like_p ())
10348             uiout->field_string
10349               ("reason",
10350                async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10351           mention (b);
10352           tuple_emitter.emplace (uiout, "value");
10353           uiout->text ("\nOld value = ");
10354           watchpoint_value_print (bs->old_val, &stb);
10355           uiout->field_stream ("old", stb);
10356           uiout->text ("\nNew value = ");
10357         }
10358       else
10359         {
10360           mention (b);
10361           if (uiout->is_mi_like_p ())
10362             uiout->field_string
10363               ("reason",
10364                async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10365           tuple_emitter.emplace (uiout, "value");
10366           uiout->text ("\nValue = ");
10367         }
10368       watchpoint_value_print (w->val, &stb);
10369       uiout->field_stream ("new", stb);
10370       uiout->text ("\n");
10371       result = PRINT_UNKNOWN;
10372       break;
10373     default:
10374       result = PRINT_UNKNOWN;
10375     }
10376
10377   return result;
10378 }
10379
10380 /* Implement the "print_mention" breakpoint_ops method for hardware
10381    watchpoints.  */
10382
10383 static void
10384 print_mention_watchpoint (struct breakpoint *b)
10385 {
10386   struct watchpoint *w = (struct watchpoint *) b;
10387   struct ui_out *uiout = current_uiout;
10388   const char *tuple_name;
10389
10390   switch (b->type)
10391     {
10392     case bp_watchpoint:
10393       uiout->text ("Watchpoint ");
10394       tuple_name = "wpt";
10395       break;
10396     case bp_hardware_watchpoint:
10397       uiout->text ("Hardware watchpoint ");
10398       tuple_name = "wpt";
10399       break;
10400     case bp_read_watchpoint:
10401       uiout->text ("Hardware read watchpoint ");
10402       tuple_name = "hw-rwpt";
10403       break;
10404     case bp_access_watchpoint:
10405       uiout->text ("Hardware access (read/write) watchpoint ");
10406       tuple_name = "hw-awpt";
10407       break;
10408     default:
10409       internal_error (__FILE__, __LINE__,
10410                       _("Invalid hardware watchpoint type."));
10411     }
10412
10413   ui_out_emit_tuple tuple_emitter (uiout, tuple_name);
10414   uiout->field_int ("number", b->number);
10415   uiout->text (": ");
10416   uiout->field_string ("exp", w->exp_string);
10417 }
10418
10419 /* Implement the "print_recreate" breakpoint_ops method for
10420    watchpoints.  */
10421
10422 static void
10423 print_recreate_watchpoint (struct breakpoint *b, struct ui_file *fp)
10424 {
10425   struct watchpoint *w = (struct watchpoint *) b;
10426
10427   switch (b->type)
10428     {
10429     case bp_watchpoint:
10430     case bp_hardware_watchpoint:
10431       fprintf_unfiltered (fp, "watch");
10432       break;
10433     case bp_read_watchpoint:
10434       fprintf_unfiltered (fp, "rwatch");
10435       break;
10436     case bp_access_watchpoint:
10437       fprintf_unfiltered (fp, "awatch");
10438       break;
10439     default:
10440       internal_error (__FILE__, __LINE__,
10441                       _("Invalid watchpoint type."));
10442     }
10443
10444   fprintf_unfiltered (fp, " %s", w->exp_string);
10445   print_recreate_thread (b, fp);
10446 }
10447
10448 /* Implement the "explains_signal" breakpoint_ops method for
10449    watchpoints.  */
10450
10451 static int
10452 explains_signal_watchpoint (struct breakpoint *b, enum gdb_signal sig)
10453 {
10454   /* A software watchpoint cannot cause a signal other than
10455      GDB_SIGNAL_TRAP.  */
10456   if (b->type == bp_watchpoint && sig != GDB_SIGNAL_TRAP)
10457     return 0;
10458
10459   return 1;
10460 }
10461
10462 /* The breakpoint_ops structure to be used in hardware watchpoints.  */
10463
10464 static struct breakpoint_ops watchpoint_breakpoint_ops;
10465
10466 /* Implement the "insert" breakpoint_ops method for
10467    masked hardware watchpoints.  */
10468
10469 static int
10470 insert_masked_watchpoint (struct bp_location *bl)
10471 {
10472   struct watchpoint *w = (struct watchpoint *) bl->owner;
10473
10474   return target_insert_mask_watchpoint (bl->address, w->hw_wp_mask,
10475                                         bl->watchpoint_type);
10476 }
10477
10478 /* Implement the "remove" breakpoint_ops method for
10479    masked hardware watchpoints.  */
10480
10481 static int
10482 remove_masked_watchpoint (struct bp_location *bl, enum remove_bp_reason reason)
10483 {
10484   struct watchpoint *w = (struct watchpoint *) bl->owner;
10485
10486   return target_remove_mask_watchpoint (bl->address, w->hw_wp_mask,
10487                                         bl->watchpoint_type);
10488 }
10489
10490 /* Implement the "resources_needed" breakpoint_ops method for
10491    masked hardware watchpoints.  */
10492
10493 static int
10494 resources_needed_masked_watchpoint (const struct bp_location *bl)
10495 {
10496   struct watchpoint *w = (struct watchpoint *) bl->owner;
10497
10498   return target_masked_watch_num_registers (bl->address, w->hw_wp_mask);
10499 }
10500
10501 /* Implement the "works_in_software_mode" breakpoint_ops method for
10502    masked hardware watchpoints.  */
10503
10504 static int
10505 works_in_software_mode_masked_watchpoint (const struct breakpoint *b)
10506 {
10507   return 0;
10508 }
10509
10510 /* Implement the "print_it" breakpoint_ops method for
10511    masked hardware watchpoints.  */
10512
10513 static enum print_stop_action
10514 print_it_masked_watchpoint (bpstat bs)
10515 {
10516   struct breakpoint *b = bs->breakpoint_at;
10517   struct ui_out *uiout = current_uiout;
10518
10519   /* Masked watchpoints have only one location.  */
10520   gdb_assert (b->loc && b->loc->next == NULL);
10521
10522   annotate_watchpoint (b->number);
10523   maybe_print_thread_hit_breakpoint (uiout);
10524
10525   switch (b->type)
10526     {
10527     case bp_hardware_watchpoint:
10528       if (uiout->is_mi_like_p ())
10529         uiout->field_string
10530           ("reason", async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
10531       break;
10532
10533     case bp_read_watchpoint:
10534       if (uiout->is_mi_like_p ())
10535         uiout->field_string
10536           ("reason", async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
10537       break;
10538
10539     case bp_access_watchpoint:
10540       if (uiout->is_mi_like_p ())
10541         uiout->field_string
10542           ("reason",
10543            async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10544       break;
10545     default:
10546       internal_error (__FILE__, __LINE__,
10547                       _("Invalid hardware watchpoint type."));
10548     }
10549
10550   mention (b);
10551   uiout->text (_("\n\
10552 Check the underlying instruction at PC for the memory\n\
10553 address and value which triggered this watchpoint.\n"));
10554   uiout->text ("\n");
10555
10556   /* More than one watchpoint may have been triggered.  */
10557   return PRINT_UNKNOWN;
10558 }
10559
10560 /* Implement the "print_one_detail" breakpoint_ops method for
10561    masked hardware watchpoints.  */
10562
10563 static void
10564 print_one_detail_masked_watchpoint (const struct breakpoint *b,
10565                                     struct ui_out *uiout)
10566 {
10567   struct watchpoint *w = (struct watchpoint *) b;
10568
10569   /* Masked watchpoints have only one location.  */
10570   gdb_assert (b->loc && b->loc->next == NULL);
10571
10572   uiout->text ("\tmask ");
10573   uiout->field_core_addr ("mask", b->loc->gdbarch, w->hw_wp_mask);
10574   uiout->text ("\n");
10575 }
10576
10577 /* Implement the "print_mention" breakpoint_ops method for
10578    masked hardware watchpoints.  */
10579
10580 static void
10581 print_mention_masked_watchpoint (struct breakpoint *b)
10582 {
10583   struct watchpoint *w = (struct watchpoint *) b;
10584   struct ui_out *uiout = current_uiout;
10585   const char *tuple_name;
10586
10587   switch (b->type)
10588     {
10589     case bp_hardware_watchpoint:
10590       uiout->text ("Masked hardware watchpoint ");
10591       tuple_name = "wpt";
10592       break;
10593     case bp_read_watchpoint:
10594       uiout->text ("Masked hardware read watchpoint ");
10595       tuple_name = "hw-rwpt";
10596       break;
10597     case bp_access_watchpoint:
10598       uiout->text ("Masked hardware access (read/write) watchpoint ");
10599       tuple_name = "hw-awpt";
10600       break;
10601     default:
10602       internal_error (__FILE__, __LINE__,
10603                       _("Invalid hardware watchpoint type."));
10604     }
10605
10606   ui_out_emit_tuple tuple_emitter (uiout, tuple_name);
10607   uiout->field_int ("number", b->number);
10608   uiout->text (": ");
10609   uiout->field_string ("exp", w->exp_string);
10610 }
10611
10612 /* Implement the "print_recreate" breakpoint_ops method for
10613    masked hardware watchpoints.  */
10614
10615 static void
10616 print_recreate_masked_watchpoint (struct breakpoint *b, struct ui_file *fp)
10617 {
10618   struct watchpoint *w = (struct watchpoint *) b;
10619   char tmp[40];
10620
10621   switch (b->type)
10622     {
10623     case bp_hardware_watchpoint:
10624       fprintf_unfiltered (fp, "watch");
10625       break;
10626     case bp_read_watchpoint:
10627       fprintf_unfiltered (fp, "rwatch");
10628       break;
10629     case bp_access_watchpoint:
10630       fprintf_unfiltered (fp, "awatch");
10631       break;
10632     default:
10633       internal_error (__FILE__, __LINE__,
10634                       _("Invalid hardware watchpoint type."));
10635     }
10636
10637   sprintf_vma (tmp, w->hw_wp_mask);
10638   fprintf_unfiltered (fp, " %s mask 0x%s", w->exp_string, tmp);
10639   print_recreate_thread (b, fp);
10640 }
10641
10642 /* The breakpoint_ops structure to be used in masked hardware watchpoints.  */
10643
10644 static struct breakpoint_ops masked_watchpoint_breakpoint_ops;
10645
10646 /* Tell whether the given watchpoint is a masked hardware watchpoint.  */
10647
10648 static int
10649 is_masked_watchpoint (const struct breakpoint *b)
10650 {
10651   return b->ops == &masked_watchpoint_breakpoint_ops;
10652 }
10653
10654 /* accessflag:  hw_write:  watch write, 
10655                 hw_read:   watch read, 
10656                 hw_access: watch access (read or write) */
10657 static void
10658 watch_command_1 (const char *arg, int accessflag, int from_tty,
10659                  int just_location, int internal)
10660 {
10661   struct breakpoint *scope_breakpoint = NULL;
10662   const struct block *exp_valid_block = NULL, *cond_exp_valid_block = NULL;
10663   struct value *val, *mark, *result;
10664   int saved_bitpos = 0, saved_bitsize = 0;
10665   const char *exp_start = NULL;
10666   const char *exp_end = NULL;
10667   const char *tok, *end_tok;
10668   int toklen = -1;
10669   const char *cond_start = NULL;
10670   const char *cond_end = NULL;
10671   enum bptype bp_type;
10672   int thread = -1;
10673   int pc = 0;
10674   /* Flag to indicate whether we are going to use masks for
10675      the hardware watchpoint.  */
10676   int use_mask = 0;
10677   CORE_ADDR mask = 0;
10678
10679   /* Make sure that we actually have parameters to parse.  */
10680   if (arg != NULL && arg[0] != '\0')
10681     {
10682       const char *value_start;
10683
10684       exp_end = arg + strlen (arg);
10685
10686       /* Look for "parameter value" pairs at the end
10687          of the arguments string.  */
10688       for (tok = exp_end - 1; tok > arg; tok--)
10689         {
10690           /* Skip whitespace at the end of the argument list.  */
10691           while (tok > arg && (*tok == ' ' || *tok == '\t'))
10692             tok--;
10693
10694           /* Find the beginning of the last token.
10695              This is the value of the parameter.  */
10696           while (tok > arg && (*tok != ' ' && *tok != '\t'))
10697             tok--;
10698           value_start = tok + 1;
10699
10700           /* Skip whitespace.  */
10701           while (tok > arg && (*tok == ' ' || *tok == '\t'))
10702             tok--;
10703
10704           end_tok = tok;
10705
10706           /* Find the beginning of the second to last token.
10707              This is the parameter itself.  */
10708           while (tok > arg && (*tok != ' ' && *tok != '\t'))
10709             tok--;
10710           tok++;
10711           toklen = end_tok - tok + 1;
10712
10713           if (toklen == 6 && startswith (tok, "thread"))
10714             {
10715               struct thread_info *thr;
10716               /* At this point we've found a "thread" token, which means
10717                  the user is trying to set a watchpoint that triggers
10718                  only in a specific thread.  */
10719               const char *endp;
10720
10721               if (thread != -1)
10722                 error(_("You can specify only one thread."));
10723
10724               /* Extract the thread ID from the next token.  */
10725               thr = parse_thread_id (value_start, &endp);
10726
10727               /* Check if the user provided a valid thread ID.  */
10728               if (*endp != ' ' && *endp != '\t' && *endp != '\0')
10729                 invalid_thread_id_error (value_start);
10730
10731               thread = thr->global_num;
10732             }
10733           else if (toklen == 4 && startswith (tok, "mask"))
10734             {
10735               /* We've found a "mask" token, which means the user wants to
10736                  create a hardware watchpoint that is going to have the mask
10737                  facility.  */
10738               struct value *mask_value, *mark;
10739
10740               if (use_mask)
10741                 error(_("You can specify only one mask."));
10742
10743               use_mask = just_location = 1;
10744
10745               mark = value_mark ();
10746               mask_value = parse_to_comma_and_eval (&value_start);
10747               mask = value_as_address (mask_value);
10748               value_free_to_mark (mark);
10749             }
10750           else
10751             /* We didn't recognize what we found.  We should stop here.  */
10752             break;
10753
10754           /* Truncate the string and get rid of the "parameter value" pair before
10755              the arguments string is parsed by the parse_exp_1 function.  */
10756           exp_end = tok;
10757         }
10758     }
10759   else
10760     exp_end = arg;
10761
10762   /* Parse the rest of the arguments.  From here on out, everything
10763      is in terms of a newly allocated string instead of the original
10764      ARG.  */
10765   innermost_block = NULL;
10766   std::string expression (arg, exp_end - arg);
10767   exp_start = arg = expression.c_str ();
10768   expression_up exp = parse_exp_1 (&arg, 0, 0, 0);
10769   exp_end = arg;
10770   /* Remove trailing whitespace from the expression before saving it.
10771      This makes the eventual display of the expression string a bit
10772      prettier.  */
10773   while (exp_end > exp_start && (exp_end[-1] == ' ' || exp_end[-1] == '\t'))
10774     --exp_end;
10775
10776   /* Checking if the expression is not constant.  */
10777   if (watchpoint_exp_is_const (exp.get ()))
10778     {
10779       int len;
10780
10781       len = exp_end - exp_start;
10782       while (len > 0 && isspace (exp_start[len - 1]))
10783         len--;
10784       error (_("Cannot watch constant value `%.*s'."), len, exp_start);
10785     }
10786
10787   exp_valid_block = innermost_block;
10788   mark = value_mark ();
10789   fetch_subexp_value (exp.get (), &pc, &val, &result, NULL, just_location);
10790
10791   if (val != NULL && just_location)
10792     {
10793       saved_bitpos = value_bitpos (val);
10794       saved_bitsize = value_bitsize (val);
10795     }
10796
10797   if (just_location)
10798     {
10799       int ret;
10800
10801       exp_valid_block = NULL;
10802       val = value_addr (result);
10803       release_value (val);
10804       value_free_to_mark (mark);
10805
10806       if (use_mask)
10807         {
10808           ret = target_masked_watch_num_registers (value_as_address (val),
10809                                                    mask);
10810           if (ret == -1)
10811             error (_("This target does not support masked watchpoints."));
10812           else if (ret == -2)
10813             error (_("Invalid mask or memory region."));
10814         }
10815     }
10816   else if (val != NULL)
10817     release_value (val);
10818
10819   tok = skip_spaces (arg);
10820   end_tok = skip_to_space (tok);
10821
10822   toklen = end_tok - tok;
10823   if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
10824     {
10825       innermost_block = NULL;
10826       tok = cond_start = end_tok + 1;
10827       parse_exp_1 (&tok, 0, 0, 0);
10828
10829       /* The watchpoint expression may not be local, but the condition
10830          may still be.  E.g.: `watch global if local > 0'.  */
10831       cond_exp_valid_block = innermost_block;
10832
10833       cond_end = tok;
10834     }
10835   if (*tok)
10836     error (_("Junk at end of command."));
10837
10838   frame_info *wp_frame = block_innermost_frame (exp_valid_block);
10839
10840   /* Save this because create_internal_breakpoint below invalidates
10841      'wp_frame'.  */
10842   frame_id watchpoint_frame = get_frame_id (wp_frame);
10843
10844   /* If the expression is "local", then set up a "watchpoint scope"
10845      breakpoint at the point where we've left the scope of the watchpoint
10846      expression.  Create the scope breakpoint before the watchpoint, so
10847      that we will encounter it first in bpstat_stop_status.  */
10848   if (exp_valid_block != NULL && wp_frame != NULL)
10849     {
10850       frame_id caller_frame_id = frame_unwind_caller_id (wp_frame);
10851
10852       if (frame_id_p (caller_frame_id))
10853         {
10854           gdbarch *caller_arch = frame_unwind_caller_arch (wp_frame);
10855           CORE_ADDR caller_pc = frame_unwind_caller_pc (wp_frame);
10856
10857           scope_breakpoint
10858             = create_internal_breakpoint (caller_arch, caller_pc,
10859                                           bp_watchpoint_scope,
10860                                           &momentary_breakpoint_ops);
10861
10862           /* create_internal_breakpoint could invalidate WP_FRAME.  */
10863           wp_frame = NULL;
10864
10865           scope_breakpoint->enable_state = bp_enabled;
10866
10867           /* Automatically delete the breakpoint when it hits.  */
10868           scope_breakpoint->disposition = disp_del;
10869
10870           /* Only break in the proper frame (help with recursion).  */
10871           scope_breakpoint->frame_id = caller_frame_id;
10872
10873           /* Set the address at which we will stop.  */
10874           scope_breakpoint->loc->gdbarch = caller_arch;
10875           scope_breakpoint->loc->requested_address = caller_pc;
10876           scope_breakpoint->loc->address
10877             = adjust_breakpoint_address (scope_breakpoint->loc->gdbarch,
10878                                          scope_breakpoint->loc->requested_address,
10879                                          scope_breakpoint->type);
10880         }
10881     }
10882
10883   /* Now set up the breakpoint.  We create all watchpoints as hardware
10884      watchpoints here even if hardware watchpoints are turned off, a call
10885      to update_watchpoint later in this function will cause the type to
10886      drop back to bp_watchpoint (software watchpoint) if required.  */
10887
10888   if (accessflag == hw_read)
10889     bp_type = bp_read_watchpoint;
10890   else if (accessflag == hw_access)
10891     bp_type = bp_access_watchpoint;
10892   else
10893     bp_type = bp_hardware_watchpoint;
10894
10895   std::unique_ptr<watchpoint> w (new watchpoint ());
10896
10897   if (use_mask)
10898     init_raw_breakpoint_without_location (w.get (), NULL, bp_type,
10899                                           &masked_watchpoint_breakpoint_ops);
10900   else
10901     init_raw_breakpoint_without_location (w.get (), NULL, bp_type,
10902                                           &watchpoint_breakpoint_ops);
10903   w->thread = thread;
10904   w->disposition = disp_donttouch;
10905   w->pspace = current_program_space;
10906   w->exp = std::move (exp);
10907   w->exp_valid_block = exp_valid_block;
10908   w->cond_exp_valid_block = cond_exp_valid_block;
10909   if (just_location)
10910     {
10911       struct type *t = value_type (val);
10912       CORE_ADDR addr = value_as_address (val);
10913
10914       w->exp_string_reparse
10915         = current_language->la_watch_location_expression (t, addr).release ();
10916
10917       w->exp_string = xstrprintf ("-location %.*s",
10918                                   (int) (exp_end - exp_start), exp_start);
10919     }
10920   else
10921     w->exp_string = savestring (exp_start, exp_end - exp_start);
10922
10923   if (use_mask)
10924     {
10925       w->hw_wp_mask = mask;
10926     }
10927   else
10928     {
10929       w->val = val;
10930       w->val_bitpos = saved_bitpos;
10931       w->val_bitsize = saved_bitsize;
10932       w->val_valid = 1;
10933     }
10934
10935   if (cond_start)
10936     w->cond_string = savestring (cond_start, cond_end - cond_start);
10937   else
10938     w->cond_string = 0;
10939
10940   if (frame_id_p (watchpoint_frame))
10941     {
10942       w->watchpoint_frame = watchpoint_frame;
10943       w->watchpoint_thread = inferior_ptid;
10944     }
10945   else
10946     {
10947       w->watchpoint_frame = null_frame_id;
10948       w->watchpoint_thread = null_ptid;
10949     }
10950
10951   if (scope_breakpoint != NULL)
10952     {
10953       /* The scope breakpoint is related to the watchpoint.  We will
10954          need to act on them together.  */
10955       w->related_breakpoint = scope_breakpoint;
10956       scope_breakpoint->related_breakpoint = w.get ();
10957     }
10958
10959   if (!just_location)
10960     value_free_to_mark (mark);
10961
10962   /* Finally update the new watchpoint.  This creates the locations
10963      that should be inserted.  */
10964   update_watchpoint (w.get (), 1);
10965
10966   install_breakpoint (internal, std::move (w), 1);
10967 }
10968
10969 /* Return count of debug registers needed to watch the given expression.
10970    If the watchpoint cannot be handled in hardware return zero.  */
10971
10972 static int
10973 can_use_hardware_watchpoint (struct value *v)
10974 {
10975   int found_memory_cnt = 0;
10976   struct value *head = v;
10977
10978   /* Did the user specifically forbid us to use hardware watchpoints? */
10979   if (!can_use_hw_watchpoints)
10980     return 0;
10981
10982   /* Make sure that the value of the expression depends only upon
10983      memory contents, and values computed from them within GDB.  If we
10984      find any register references or function calls, we can't use a
10985      hardware watchpoint.
10986
10987      The idea here is that evaluating an expression generates a series
10988      of values, one holding the value of every subexpression.  (The
10989      expression a*b+c has five subexpressions: a, b, a*b, c, and
10990      a*b+c.)  GDB's values hold almost enough information to establish
10991      the criteria given above --- they identify memory lvalues,
10992      register lvalues, computed values, etcetera.  So we can evaluate
10993      the expression, and then scan the chain of values that leaves
10994      behind to decide whether we can detect any possible change to the
10995      expression's final value using only hardware watchpoints.
10996
10997      However, I don't think that the values returned by inferior
10998      function calls are special in any way.  So this function may not
10999      notice that an expression involving an inferior function call
11000      can't be watched with hardware watchpoints.  FIXME.  */
11001   for (; v; v = value_next (v))
11002     {
11003       if (VALUE_LVAL (v) == lval_memory)
11004         {
11005           if (v != head && value_lazy (v))
11006             /* A lazy memory lvalue in the chain is one that GDB never
11007                needed to fetch; we either just used its address (e.g.,
11008                `a' in `a.b') or we never needed it at all (e.g., `a'
11009                in `a,b').  This doesn't apply to HEAD; if that is
11010                lazy then it was not readable, but watch it anyway.  */
11011             ;
11012           else
11013             {
11014               /* Ahh, memory we actually used!  Check if we can cover
11015                  it with hardware watchpoints.  */
11016               struct type *vtype = check_typedef (value_type (v));
11017
11018               /* We only watch structs and arrays if user asked for it
11019                  explicitly, never if they just happen to appear in a
11020                  middle of some value chain.  */
11021               if (v == head
11022                   || (TYPE_CODE (vtype) != TYPE_CODE_STRUCT
11023                       && TYPE_CODE (vtype) != TYPE_CODE_ARRAY))
11024                 {
11025                   CORE_ADDR vaddr = value_address (v);
11026                   int len;
11027                   int num_regs;
11028
11029                   len = (target_exact_watchpoints
11030                          && is_scalar_type_recursive (vtype))?
11031                     1 : TYPE_LENGTH (value_type (v));
11032
11033                   num_regs = target_region_ok_for_hw_watchpoint (vaddr, len);
11034                   if (!num_regs)
11035                     return 0;
11036                   else
11037                     found_memory_cnt += num_regs;
11038                 }
11039             }
11040         }
11041       else if (VALUE_LVAL (v) != not_lval
11042                && deprecated_value_modifiable (v) == 0)
11043         return 0;       /* These are values from the history (e.g., $1).  */
11044       else if (VALUE_LVAL (v) == lval_register)
11045         return 0;       /* Cannot watch a register with a HW watchpoint.  */
11046     }
11047
11048   /* The expression itself looks suitable for using a hardware
11049      watchpoint, but give the target machine a chance to reject it.  */
11050   return found_memory_cnt;
11051 }
11052
11053 void
11054 watch_command_wrapper (const char *arg, int from_tty, int internal)
11055 {
11056   watch_command_1 (arg, hw_write, from_tty, 0, internal);
11057 }
11058
11059 /* A helper function that looks for the "-location" argument and then
11060    calls watch_command_1.  */
11061
11062 static void
11063 watch_maybe_just_location (char *arg, int accessflag, int from_tty)
11064 {
11065   int just_location = 0;
11066
11067   if (arg
11068       && (check_for_argument (&arg, "-location", sizeof ("-location") - 1)
11069           || check_for_argument (&arg, "-l", sizeof ("-l") - 1)))
11070     {
11071       arg = skip_spaces (arg);
11072       just_location = 1;
11073     }
11074
11075   watch_command_1 (arg, accessflag, from_tty, just_location, 0);
11076 }
11077
11078 static void
11079 watch_command (char *arg, int from_tty)
11080 {
11081   watch_maybe_just_location (arg, hw_write, from_tty);
11082 }
11083
11084 void
11085 rwatch_command_wrapper (const char *arg, int from_tty, int internal)
11086 {
11087   watch_command_1 (arg, hw_read, from_tty, 0, internal);
11088 }
11089
11090 static void
11091 rwatch_command (char *arg, int from_tty)
11092 {
11093   watch_maybe_just_location (arg, hw_read, from_tty);
11094 }
11095
11096 void
11097 awatch_command_wrapper (const char *arg, int from_tty, int internal)
11098 {
11099   watch_command_1 (arg, hw_access, from_tty, 0, internal);
11100 }
11101
11102 static void
11103 awatch_command (char *arg, int from_tty)
11104 {
11105   watch_maybe_just_location (arg, hw_access, from_tty);
11106 }
11107 \f
11108
11109 /* Data for the FSM that manages the until(location)/advance commands
11110    in infcmd.c.  Here because it uses the mechanisms of
11111    breakpoints.  */
11112
11113 struct until_break_fsm
11114 {
11115   /* The base class.  */
11116   struct thread_fsm thread_fsm;
11117
11118   /* The thread that as current when the command was executed.  */
11119   int thread;
11120
11121   /* The breakpoint set at the destination location.  */
11122   struct breakpoint *location_breakpoint;
11123
11124   /* Breakpoint set at the return address in the caller frame.  May be
11125      NULL.  */
11126   struct breakpoint *caller_breakpoint;
11127 };
11128
11129 static void until_break_fsm_clean_up (struct thread_fsm *self,
11130                                       struct thread_info *thread);
11131 static int until_break_fsm_should_stop (struct thread_fsm *self,
11132                                         struct thread_info *thread);
11133 static enum async_reply_reason
11134   until_break_fsm_async_reply_reason (struct thread_fsm *self);
11135
11136 /* until_break_fsm's vtable.  */
11137
11138 static struct thread_fsm_ops until_break_fsm_ops =
11139 {
11140   NULL, /* dtor */
11141   until_break_fsm_clean_up,
11142   until_break_fsm_should_stop,
11143   NULL, /* return_value */
11144   until_break_fsm_async_reply_reason,
11145 };
11146
11147 /* Allocate a new until_break_command_fsm.  */
11148
11149 static struct until_break_fsm *
11150 new_until_break_fsm (struct interp *cmd_interp, int thread,
11151                      struct breakpoint *location_breakpoint,
11152                      struct breakpoint *caller_breakpoint)
11153 {
11154   struct until_break_fsm *sm;
11155
11156   sm = XCNEW (struct until_break_fsm);
11157   thread_fsm_ctor (&sm->thread_fsm, &until_break_fsm_ops, cmd_interp);
11158
11159   sm->thread = thread;
11160   sm->location_breakpoint = location_breakpoint;
11161   sm->caller_breakpoint = caller_breakpoint;
11162
11163   return sm;
11164 }
11165
11166 /* Implementation of the 'should_stop' FSM method for the
11167    until(location)/advance commands.  */
11168
11169 static int
11170 until_break_fsm_should_stop (struct thread_fsm *self,
11171                              struct thread_info *tp)
11172 {
11173   struct until_break_fsm *sm = (struct until_break_fsm *) self;
11174
11175   if (bpstat_find_breakpoint (tp->control.stop_bpstat,
11176                               sm->location_breakpoint) != NULL
11177       || (sm->caller_breakpoint != NULL
11178           && bpstat_find_breakpoint (tp->control.stop_bpstat,
11179                                      sm->caller_breakpoint) != NULL))
11180     thread_fsm_set_finished (self);
11181
11182   return 1;
11183 }
11184
11185 /* Implementation of the 'clean_up' FSM method for the
11186    until(location)/advance commands.  */
11187
11188 static void
11189 until_break_fsm_clean_up (struct thread_fsm *self,
11190                           struct thread_info *thread)
11191 {
11192   struct until_break_fsm *sm = (struct until_break_fsm *) self;
11193
11194   /* Clean up our temporary breakpoints.  */
11195   if (sm->location_breakpoint != NULL)
11196     {
11197       delete_breakpoint (sm->location_breakpoint);
11198       sm->location_breakpoint = NULL;
11199     }
11200   if (sm->caller_breakpoint != NULL)
11201     {
11202       delete_breakpoint (sm->caller_breakpoint);
11203       sm->caller_breakpoint = NULL;
11204     }
11205   delete_longjmp_breakpoint (sm->thread);
11206 }
11207
11208 /* Implementation of the 'async_reply_reason' FSM method for the
11209    until(location)/advance commands.  */
11210
11211 static enum async_reply_reason
11212 until_break_fsm_async_reply_reason (struct thread_fsm *self)
11213 {
11214   return EXEC_ASYNC_LOCATION_REACHED;
11215 }
11216
11217 void
11218 until_break_command (const char *arg, int from_tty, int anywhere)
11219 {
11220   struct frame_info *frame;
11221   struct gdbarch *frame_gdbarch;
11222   struct frame_id stack_frame_id;
11223   struct frame_id caller_frame_id;
11224   struct breakpoint *location_breakpoint;
11225   struct breakpoint *caller_breakpoint = NULL;
11226   struct cleanup *old_chain;
11227   int thread;
11228   struct thread_info *tp;
11229   struct until_break_fsm *sm;
11230
11231   clear_proceed_status (0);
11232
11233   /* Set a breakpoint where the user wants it and at return from
11234      this function.  */
11235
11236   event_location_up location = string_to_event_location (&arg, current_language);
11237
11238   std::vector<symtab_and_line> sals
11239     = (last_displayed_sal_is_valid ()
11240        ? decode_line_1 (location.get (), DECODE_LINE_FUNFIRSTLINE, NULL,
11241                         get_last_displayed_symtab (),
11242                         get_last_displayed_line ())
11243        : decode_line_1 (location.get (), DECODE_LINE_FUNFIRSTLINE,
11244                         NULL, (struct symtab *) NULL, 0));
11245
11246   if (sals.size () != 1)
11247     error (_("Couldn't get information on specified line."));
11248
11249   symtab_and_line &sal = sals[0];
11250
11251   if (*arg)
11252     error (_("Junk at end of arguments."));
11253
11254   resolve_sal_pc (&sal);
11255
11256   tp = inferior_thread ();
11257   thread = tp->global_num;
11258
11259   old_chain = make_cleanup (null_cleanup, NULL);
11260
11261   /* Note linespec handling above invalidates the frame chain.
11262      Installing a breakpoint also invalidates the frame chain (as it
11263      may need to switch threads), so do any frame handling before
11264      that.  */
11265
11266   frame = get_selected_frame (NULL);
11267   frame_gdbarch = get_frame_arch (frame);
11268   stack_frame_id = get_stack_frame_id (frame);
11269   caller_frame_id = frame_unwind_caller_id (frame);
11270
11271   /* Keep within the current frame, or in frames called by the current
11272      one.  */
11273
11274   if (frame_id_p (caller_frame_id))
11275     {
11276       struct symtab_and_line sal2;
11277       struct gdbarch *caller_gdbarch;
11278
11279       sal2 = find_pc_line (frame_unwind_caller_pc (frame), 0);
11280       sal2.pc = frame_unwind_caller_pc (frame);
11281       caller_gdbarch = frame_unwind_caller_arch (frame);
11282       caller_breakpoint = set_momentary_breakpoint (caller_gdbarch,
11283                                                     sal2,
11284                                                     caller_frame_id,
11285                                                     bp_until);
11286       make_cleanup_delete_breakpoint (caller_breakpoint);
11287
11288       set_longjmp_breakpoint (tp, caller_frame_id);
11289       make_cleanup (delete_longjmp_breakpoint_cleanup, &thread);
11290     }
11291
11292   /* set_momentary_breakpoint could invalidate FRAME.  */
11293   frame = NULL;
11294
11295   if (anywhere)
11296     /* If the user told us to continue until a specified location,
11297        we don't specify a frame at which we need to stop.  */
11298     location_breakpoint = set_momentary_breakpoint (frame_gdbarch, sal,
11299                                                     null_frame_id, bp_until);
11300   else
11301     /* Otherwise, specify the selected frame, because we want to stop
11302        only at the very same frame.  */
11303     location_breakpoint = set_momentary_breakpoint (frame_gdbarch, sal,
11304                                                     stack_frame_id, bp_until);
11305   make_cleanup_delete_breakpoint (location_breakpoint);
11306
11307   sm = new_until_break_fsm (command_interp (), tp->global_num,
11308                             location_breakpoint, caller_breakpoint);
11309   tp->thread_fsm = &sm->thread_fsm;
11310
11311   discard_cleanups (old_chain);
11312
11313   proceed (-1, GDB_SIGNAL_DEFAULT);
11314 }
11315
11316 /* This function attempts to parse an optional "if <cond>" clause
11317    from the arg string.  If one is not found, it returns NULL.
11318
11319    Else, it returns a pointer to the condition string.  (It does not
11320    attempt to evaluate the string against a particular block.)  And,
11321    it updates arg to point to the first character following the parsed
11322    if clause in the arg string.  */
11323
11324 const char *
11325 ep_parse_optional_if_clause (const char **arg)
11326 {
11327   const char *cond_string;
11328
11329   if (((*arg)[0] != 'i') || ((*arg)[1] != 'f') || !isspace ((*arg)[2]))
11330     return NULL;
11331
11332   /* Skip the "if" keyword.  */
11333   (*arg) += 2;
11334
11335   /* Skip any extra leading whitespace, and record the start of the
11336      condition string.  */
11337   *arg = skip_spaces (*arg);
11338   cond_string = *arg;
11339
11340   /* Assume that the condition occupies the remainder of the arg
11341      string.  */
11342   (*arg) += strlen (cond_string);
11343
11344   return cond_string;
11345 }
11346
11347 /* Commands to deal with catching events, such as signals, exceptions,
11348    process start/exit, etc.  */
11349
11350 typedef enum
11351 {
11352   catch_fork_temporary, catch_vfork_temporary,
11353   catch_fork_permanent, catch_vfork_permanent
11354 }
11355 catch_fork_kind;
11356
11357 static void
11358 catch_fork_command_1 (char *arg_entry, int from_tty,
11359                       struct cmd_list_element *command)
11360 {
11361   const char *arg = arg_entry;
11362   struct gdbarch *gdbarch = get_current_arch ();
11363   const char *cond_string = NULL;
11364   catch_fork_kind fork_kind;
11365   int tempflag;
11366
11367   fork_kind = (catch_fork_kind) (uintptr_t) get_cmd_context (command);
11368   tempflag = (fork_kind == catch_fork_temporary
11369               || fork_kind == catch_vfork_temporary);
11370
11371   if (!arg)
11372     arg = "";
11373   arg = skip_spaces (arg);
11374
11375   /* The allowed syntax is:
11376      catch [v]fork
11377      catch [v]fork if <cond>
11378
11379      First, check if there's an if clause.  */
11380   cond_string = ep_parse_optional_if_clause (&arg);
11381
11382   if ((*arg != '\0') && !isspace (*arg))
11383     error (_("Junk at end of arguments."));
11384
11385   /* If this target supports it, create a fork or vfork catchpoint
11386      and enable reporting of such events.  */
11387   switch (fork_kind)
11388     {
11389     case catch_fork_temporary:
11390     case catch_fork_permanent:
11391       create_fork_vfork_event_catchpoint (gdbarch, tempflag, cond_string,
11392                                           &catch_fork_breakpoint_ops);
11393       break;
11394     case catch_vfork_temporary:
11395     case catch_vfork_permanent:
11396       create_fork_vfork_event_catchpoint (gdbarch, tempflag, cond_string,
11397                                           &catch_vfork_breakpoint_ops);
11398       break;
11399     default:
11400       error (_("unsupported or unknown fork kind; cannot catch it"));
11401       break;
11402     }
11403 }
11404
11405 static void
11406 catch_exec_command_1 (char *arg_entry, int from_tty,
11407                       struct cmd_list_element *command)
11408 {
11409   const char *arg = arg_entry;
11410   struct gdbarch *gdbarch = get_current_arch ();
11411   int tempflag;
11412   const char *cond_string = NULL;
11413
11414   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
11415
11416   if (!arg)
11417     arg = "";
11418   arg = skip_spaces (arg);
11419
11420   /* The allowed syntax is:
11421      catch exec
11422      catch exec if <cond>
11423
11424      First, check if there's an if clause.  */
11425   cond_string = ep_parse_optional_if_clause (&arg);
11426
11427   if ((*arg != '\0') && !isspace (*arg))
11428     error (_("Junk at end of arguments."));
11429
11430   std::unique_ptr<exec_catchpoint> c (new exec_catchpoint ());
11431   init_catchpoint (c.get (), gdbarch, tempflag, cond_string,
11432                    &catch_exec_breakpoint_ops);
11433   c->exec_pathname = NULL;
11434
11435   install_breakpoint (0, std::move (c), 1);
11436 }
11437
11438 void
11439 init_ada_exception_breakpoint (struct breakpoint *b,
11440                                struct gdbarch *gdbarch,
11441                                struct symtab_and_line sal,
11442                                const char *addr_string,
11443                                const struct breakpoint_ops *ops,
11444                                int tempflag,
11445                                int enabled,
11446                                int from_tty)
11447 {
11448   if (from_tty)
11449     {
11450       struct gdbarch *loc_gdbarch = get_sal_arch (sal);
11451       if (!loc_gdbarch)
11452         loc_gdbarch = gdbarch;
11453
11454       describe_other_breakpoints (loc_gdbarch,
11455                                   sal.pspace, sal.pc, sal.section, -1);
11456       /* FIXME: brobecker/2006-12-28: Actually, re-implement a special
11457          version for exception catchpoints, because two catchpoints
11458          used for different exception names will use the same address.
11459          In this case, a "breakpoint ... also set at..." warning is
11460          unproductive.  Besides, the warning phrasing is also a bit
11461          inappropriate, we should use the word catchpoint, and tell
11462          the user what type of catchpoint it is.  The above is good
11463          enough for now, though.  */
11464     }
11465
11466   init_raw_breakpoint (b, gdbarch, sal, bp_breakpoint, ops);
11467
11468   b->enable_state = enabled ? bp_enabled : bp_disabled;
11469   b->disposition = tempflag ? disp_del : disp_donttouch;
11470   b->location = string_to_event_location (&addr_string,
11471                                           language_def (language_ada));
11472   b->language = language_ada;
11473 }
11474
11475 static void
11476 catch_command (const char *arg, int from_tty)
11477 {
11478   error (_("Catch requires an event name."));
11479 }
11480 \f
11481
11482 static void
11483 tcatch_command (const char *arg, int from_tty)
11484 {
11485   error (_("Catch requires an event name."));
11486 }
11487
11488 /* Compare two breakpoints and return a strcmp-like result.  */
11489
11490 static int
11491 compare_breakpoints (const breakpoint *a, const breakpoint *b)
11492 {
11493   uintptr_t ua = (uintptr_t) a;
11494   uintptr_t ub = (uintptr_t) b;
11495
11496   if (a->number < b->number)
11497     return -1;
11498   else if (a->number > b->number)
11499     return 1;
11500
11501   /* Now sort by address, in case we see, e..g, two breakpoints with
11502      the number 0.  */
11503   if (ua < ub)
11504     return -1;
11505   return ua > ub ? 1 : 0;
11506 }
11507
11508 /* Delete breakpoints by address or line.  */
11509
11510 static void
11511 clear_command (char *arg, int from_tty)
11512 {
11513   struct breakpoint *b;
11514   int default_match;
11515   int i;
11516
11517   std::vector<symtab_and_line> decoded_sals;
11518   symtab_and_line last_sal;
11519   gdb::array_view<symtab_and_line> sals;
11520   if (arg)
11521     {
11522       decoded_sals
11523         = decode_line_with_current_source (arg,
11524                                            (DECODE_LINE_FUNFIRSTLINE
11525                                             | DECODE_LINE_LIST_MODE));
11526       default_match = 0;
11527       sals = decoded_sals;
11528     }
11529   else
11530     {
11531       /* Set sal's line, symtab, pc, and pspace to the values
11532          corresponding to the last call to print_frame_info.  If the
11533          codepoint is not valid, this will set all the fields to 0.  */
11534       last_sal = get_last_displayed_sal ();
11535       if (last_sal.symtab == 0)
11536         error (_("No source file specified."));
11537
11538       default_match = 1;
11539       sals = last_sal;
11540     }
11541
11542   /* We don't call resolve_sal_pc here.  That's not as bad as it
11543      seems, because all existing breakpoints typically have both
11544      file/line and pc set.  So, if clear is given file/line, we can
11545      match this to existing breakpoint without obtaining pc at all.
11546
11547      We only support clearing given the address explicitly 
11548      present in breakpoint table.  Say, we've set breakpoint 
11549      at file:line.  There were several PC values for that file:line,
11550      due to optimization, all in one block.
11551
11552      We've picked one PC value.  If "clear" is issued with another
11553      PC corresponding to the same file:line, the breakpoint won't
11554      be cleared.  We probably can still clear the breakpoint, but 
11555      since the other PC value is never presented to user, user
11556      can only find it by guessing, and it does not seem important
11557      to support that.  */
11558
11559   /* For each line spec given, delete bps which correspond to it.  Do
11560      it in two passes, solely to preserve the current behavior that
11561      from_tty is forced true if we delete more than one
11562      breakpoint.  */
11563
11564   std::vector<struct breakpoint *> found;
11565   for (const auto &sal : sals)
11566     {
11567       const char *sal_fullname;
11568
11569       /* If exact pc given, clear bpts at that pc.
11570          If line given (pc == 0), clear all bpts on specified line.
11571          If defaulting, clear all bpts on default line
11572          or at default pc.
11573
11574          defaulting    sal.pc != 0    tests to do
11575
11576          0              1             pc
11577          1              1             pc _and_ line
11578          0              0             line
11579          1              0             <can't happen> */
11580
11581       sal_fullname = (sal.symtab == NULL
11582                       ? NULL : symtab_to_fullname (sal.symtab));
11583
11584       /* Find all matching breakpoints and add them to 'found'.  */
11585       ALL_BREAKPOINTS (b)
11586         {
11587           int match = 0;
11588           /* Are we going to delete b?  */
11589           if (b->type != bp_none && !is_watchpoint (b))
11590             {
11591               struct bp_location *loc = b->loc;
11592               for (; loc; loc = loc->next)
11593                 {
11594                   /* If the user specified file:line, don't allow a PC
11595                      match.  This matches historical gdb behavior.  */
11596                   int pc_match = (!sal.explicit_line
11597                                   && sal.pc
11598                                   && (loc->pspace == sal.pspace)
11599                                   && (loc->address == sal.pc)
11600                                   && (!section_is_overlay (loc->section)
11601                                       || loc->section == sal.section));
11602                   int line_match = 0;
11603
11604                   if ((default_match || sal.explicit_line)
11605                       && loc->symtab != NULL
11606                       && sal_fullname != NULL
11607                       && sal.pspace == loc->pspace
11608                       && loc->line_number == sal.line
11609                       && filename_cmp (symtab_to_fullname (loc->symtab),
11610                                        sal_fullname) == 0)
11611                     line_match = 1;
11612
11613                   if (pc_match || line_match)
11614                     {
11615                       match = 1;
11616                       break;
11617                     }
11618                 }
11619             }
11620
11621           if (match)
11622             found.push_back (b);
11623         }
11624     }
11625
11626   /* Now go thru the 'found' chain and delete them.  */
11627   if (found.empty ())
11628     {
11629       if (arg)
11630         error (_("No breakpoint at %s."), arg);
11631       else
11632         error (_("No breakpoint at this line."));
11633     }
11634
11635   /* Remove duplicates from the vec.  */
11636   std::sort (found.begin (), found.end (),
11637              [] (const breakpoint *a, const breakpoint *b)
11638              {
11639                return compare_breakpoints (a, b) < 0;
11640              });
11641   found.erase (std::unique (found.begin (), found.end (),
11642                             [] (const breakpoint *a, const breakpoint *b)
11643                             {
11644                               return compare_breakpoints (a, b) == 0;
11645                             }),
11646                found.end ());
11647
11648   if (found.size () > 1)
11649     from_tty = 1;       /* Always report if deleted more than one.  */
11650   if (from_tty)
11651     {
11652       if (found.size () == 1)
11653         printf_unfiltered (_("Deleted breakpoint "));
11654       else
11655         printf_unfiltered (_("Deleted breakpoints "));
11656     }
11657
11658   for (breakpoint *iter : found)
11659     {
11660       if (from_tty)
11661         printf_unfiltered ("%d ", iter->number);
11662       delete_breakpoint (iter);
11663     }
11664   if (from_tty)
11665     putchar_unfiltered ('\n');
11666 }
11667 \f
11668 /* Delete breakpoint in BS if they are `delete' breakpoints and
11669    all breakpoints that are marked for deletion, whether hit or not.
11670    This is called after any breakpoint is hit, or after errors.  */
11671
11672 void
11673 breakpoint_auto_delete (bpstat bs)
11674 {
11675   struct breakpoint *b, *b_tmp;
11676
11677   for (; bs; bs = bs->next)
11678     if (bs->breakpoint_at
11679         && bs->breakpoint_at->disposition == disp_del
11680         && bs->stop)
11681       delete_breakpoint (bs->breakpoint_at);
11682
11683   ALL_BREAKPOINTS_SAFE (b, b_tmp)
11684   {
11685     if (b->disposition == disp_del_at_next_stop)
11686       delete_breakpoint (b);
11687   }
11688 }
11689
11690 /* A comparison function for bp_location AP and BP being interfaced to
11691    qsort.  Sort elements primarily by their ADDRESS (no matter what
11692    does breakpoint_address_is_meaningful say for its OWNER),
11693    secondarily by ordering first permanent elements and
11694    terciarily just ensuring the array is sorted stable way despite
11695    qsort being an unstable algorithm.  */
11696
11697 static int
11698 bp_locations_compare (const void *ap, const void *bp)
11699 {
11700   const struct bp_location *a = *(const struct bp_location **) ap;
11701   const struct bp_location *b = *(const struct bp_location **) bp;
11702
11703   if (a->address != b->address)
11704     return (a->address > b->address) - (a->address < b->address);
11705
11706   /* Sort locations at the same address by their pspace number, keeping
11707      locations of the same inferior (in a multi-inferior environment)
11708      grouped.  */
11709
11710   if (a->pspace->num != b->pspace->num)
11711     return ((a->pspace->num > b->pspace->num)
11712             - (a->pspace->num < b->pspace->num));
11713
11714   /* Sort permanent breakpoints first.  */
11715   if (a->permanent != b->permanent)
11716     return (a->permanent < b->permanent) - (a->permanent > b->permanent);
11717
11718   /* Make the internal GDB representation stable across GDB runs
11719      where A and B memory inside GDB can differ.  Breakpoint locations of
11720      the same type at the same address can be sorted in arbitrary order.  */
11721
11722   if (a->owner->number != b->owner->number)
11723     return ((a->owner->number > b->owner->number)
11724             - (a->owner->number < b->owner->number));
11725
11726   return (a > b) - (a < b);
11727 }
11728
11729 /* Set bp_locations_placed_address_before_address_max and
11730    bp_locations_shadow_len_after_address_max according to the current
11731    content of the bp_locations array.  */
11732
11733 static void
11734 bp_locations_target_extensions_update (void)
11735 {
11736   struct bp_location *bl, **blp_tmp;
11737
11738   bp_locations_placed_address_before_address_max = 0;
11739   bp_locations_shadow_len_after_address_max = 0;
11740
11741   ALL_BP_LOCATIONS (bl, blp_tmp)
11742     {
11743       CORE_ADDR start, end, addr;
11744
11745       if (!bp_location_has_shadow (bl))
11746         continue;
11747
11748       start = bl->target_info.placed_address;
11749       end = start + bl->target_info.shadow_len;
11750
11751       gdb_assert (bl->address >= start);
11752       addr = bl->address - start;
11753       if (addr > bp_locations_placed_address_before_address_max)
11754         bp_locations_placed_address_before_address_max = addr;
11755
11756       /* Zero SHADOW_LEN would not pass bp_location_has_shadow.  */
11757
11758       gdb_assert (bl->address < end);
11759       addr = end - bl->address;
11760       if (addr > bp_locations_shadow_len_after_address_max)
11761         bp_locations_shadow_len_after_address_max = addr;
11762     }
11763 }
11764
11765 /* Download tracepoint locations if they haven't been.  */
11766
11767 static void
11768 download_tracepoint_locations (void)
11769 {
11770   struct breakpoint *b;
11771   enum tribool can_download_tracepoint = TRIBOOL_UNKNOWN;
11772
11773   scoped_restore_current_pspace_and_thread restore_pspace_thread;
11774
11775   ALL_TRACEPOINTS (b)
11776     {
11777       struct bp_location *bl;
11778       struct tracepoint *t;
11779       int bp_location_downloaded = 0;
11780
11781       if ((b->type == bp_fast_tracepoint
11782            ? !may_insert_fast_tracepoints
11783            : !may_insert_tracepoints))
11784         continue;
11785
11786       if (can_download_tracepoint == TRIBOOL_UNKNOWN)
11787         {
11788           if (target_can_download_tracepoint ())
11789             can_download_tracepoint = TRIBOOL_TRUE;
11790           else
11791             can_download_tracepoint = TRIBOOL_FALSE;
11792         }
11793
11794       if (can_download_tracepoint == TRIBOOL_FALSE)
11795         break;
11796
11797       for (bl = b->loc; bl; bl = bl->next)
11798         {
11799           /* In tracepoint, locations are _never_ duplicated, so
11800              should_be_inserted is equivalent to
11801              unduplicated_should_be_inserted.  */
11802           if (!should_be_inserted (bl) || bl->inserted)
11803             continue;
11804
11805           switch_to_program_space_and_thread (bl->pspace);
11806
11807           target_download_tracepoint (bl);
11808
11809           bl->inserted = 1;
11810           bp_location_downloaded = 1;
11811         }
11812       t = (struct tracepoint *) b;
11813       t->number_on_target = b->number;
11814       if (bp_location_downloaded)
11815         observer_notify_breakpoint_modified (b);
11816     }
11817 }
11818
11819 /* Swap the insertion/duplication state between two locations.  */
11820
11821 static void
11822 swap_insertion (struct bp_location *left, struct bp_location *right)
11823 {
11824   const int left_inserted = left->inserted;
11825   const int left_duplicate = left->duplicate;
11826   const int left_needs_update = left->needs_update;
11827   const struct bp_target_info left_target_info = left->target_info;
11828
11829   /* Locations of tracepoints can never be duplicated.  */
11830   if (is_tracepoint (left->owner))
11831     gdb_assert (!left->duplicate);
11832   if (is_tracepoint (right->owner))
11833     gdb_assert (!right->duplicate);
11834
11835   left->inserted = right->inserted;
11836   left->duplicate = right->duplicate;
11837   left->needs_update = right->needs_update;
11838   left->target_info = right->target_info;
11839   right->inserted = left_inserted;
11840   right->duplicate = left_duplicate;
11841   right->needs_update = left_needs_update;
11842   right->target_info = left_target_info;
11843 }
11844
11845 /* Force the re-insertion of the locations at ADDRESS.  This is called
11846    once a new/deleted/modified duplicate location is found and we are evaluating
11847    conditions on the target's side.  Such conditions need to be updated on
11848    the target.  */
11849
11850 static void
11851 force_breakpoint_reinsertion (struct bp_location *bl)
11852 {
11853   struct bp_location **locp = NULL, **loc2p;
11854   struct bp_location *loc;
11855   CORE_ADDR address = 0;
11856   int pspace_num;
11857
11858   address = bl->address;
11859   pspace_num = bl->pspace->num;
11860
11861   /* This is only meaningful if the target is
11862      evaluating conditions and if the user has
11863      opted for condition evaluation on the target's
11864      side.  */
11865   if (gdb_evaluates_breakpoint_condition_p ()
11866       || !target_supports_evaluation_of_breakpoint_conditions ())
11867     return;
11868
11869   /* Flag all breakpoint locations with this address and
11870      the same program space as the location
11871      as "its condition has changed".  We need to
11872      update the conditions on the target's side.  */
11873   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, address)
11874     {
11875       loc = *loc2p;
11876
11877       if (!is_breakpoint (loc->owner)
11878           || pspace_num != loc->pspace->num)
11879         continue;
11880
11881       /* Flag the location appropriately.  We use a different state to
11882          let everyone know that we already updated the set of locations
11883          with addr bl->address and program space bl->pspace.  This is so
11884          we don't have to keep calling these functions just to mark locations
11885          that have already been marked.  */
11886       loc->condition_changed = condition_updated;
11887
11888       /* Free the agent expression bytecode as well.  We will compute
11889          it later on.  */
11890       loc->cond_bytecode.reset ();
11891     }
11892 }
11893 /* Called whether new breakpoints are created, or existing breakpoints
11894    deleted, to update the global location list and recompute which
11895    locations are duplicate of which.
11896
11897    The INSERT_MODE flag determines whether locations may not, may, or
11898    shall be inserted now.  See 'enum ugll_insert_mode' for more
11899    info.  */
11900
11901 static void
11902 update_global_location_list (enum ugll_insert_mode insert_mode)
11903 {
11904   struct breakpoint *b;
11905   struct bp_location **locp, *loc;
11906   /* Last breakpoint location address that was marked for update.  */
11907   CORE_ADDR last_addr = 0;
11908   /* Last breakpoint location program space that was marked for update.  */
11909   int last_pspace_num = -1;
11910
11911   /* Used in the duplicates detection below.  When iterating over all
11912      bp_locations, points to the first bp_location of a given address.
11913      Breakpoints and watchpoints of different types are never
11914      duplicates of each other.  Keep one pointer for each type of
11915      breakpoint/watchpoint, so we only need to loop over all locations
11916      once.  */
11917   struct bp_location *bp_loc_first;  /* breakpoint */
11918   struct bp_location *wp_loc_first;  /* hardware watchpoint */
11919   struct bp_location *awp_loc_first; /* access watchpoint */
11920   struct bp_location *rwp_loc_first; /* read watchpoint */
11921
11922   /* Saved former bp_locations array which we compare against the newly
11923      built bp_locations from the current state of ALL_BREAKPOINTS.  */
11924   struct bp_location **old_locp;
11925   unsigned old_locations_count;
11926   gdb::unique_xmalloc_ptr<struct bp_location *> old_locations (bp_locations);
11927
11928   old_locations_count = bp_locations_count;
11929   bp_locations = NULL;
11930   bp_locations_count = 0;
11931
11932   ALL_BREAKPOINTS (b)
11933     for (loc = b->loc; loc; loc = loc->next)
11934       bp_locations_count++;
11935
11936   bp_locations = XNEWVEC (struct bp_location *, bp_locations_count);
11937   locp = bp_locations;
11938   ALL_BREAKPOINTS (b)
11939     for (loc = b->loc; loc; loc = loc->next)
11940       *locp++ = loc;
11941   qsort (bp_locations, bp_locations_count, sizeof (*bp_locations),
11942          bp_locations_compare);
11943
11944   bp_locations_target_extensions_update ();
11945
11946   /* Identify bp_location instances that are no longer present in the
11947      new list, and therefore should be freed.  Note that it's not
11948      necessary that those locations should be removed from inferior --
11949      if there's another location at the same address (previously
11950      marked as duplicate), we don't need to remove/insert the
11951      location.
11952      
11953      LOCP is kept in sync with OLD_LOCP, each pointing to the current
11954      and former bp_location array state respectively.  */
11955
11956   locp = bp_locations;
11957   for (old_locp = old_locations.get ();
11958        old_locp < old_locations.get () + old_locations_count;
11959        old_locp++)
11960     {
11961       struct bp_location *old_loc = *old_locp;
11962       struct bp_location **loc2p;
11963
11964       /* Tells if 'old_loc' is found among the new locations.  If
11965          not, we have to free it.  */
11966       int found_object = 0;
11967       /* Tells if the location should remain inserted in the target.  */
11968       int keep_in_target = 0;
11969       int removed = 0;
11970
11971       /* Skip LOCP entries which will definitely never be needed.
11972          Stop either at or being the one matching OLD_LOC.  */
11973       while (locp < bp_locations + bp_locations_count
11974              && (*locp)->address < old_loc->address)
11975         locp++;
11976
11977       for (loc2p = locp;
11978            (loc2p < bp_locations + bp_locations_count
11979             && (*loc2p)->address == old_loc->address);
11980            loc2p++)
11981         {
11982           /* Check if this is a new/duplicated location or a duplicated
11983              location that had its condition modified.  If so, we want to send
11984              its condition to the target if evaluation of conditions is taking
11985              place there.  */
11986           if ((*loc2p)->condition_changed == condition_modified
11987               && (last_addr != old_loc->address
11988                   || last_pspace_num != old_loc->pspace->num))
11989             {
11990               force_breakpoint_reinsertion (*loc2p);
11991               last_pspace_num = old_loc->pspace->num;
11992             }
11993
11994           if (*loc2p == old_loc)
11995             found_object = 1;
11996         }
11997
11998       /* We have already handled this address, update it so that we don't
11999          have to go through updates again.  */
12000       last_addr = old_loc->address;
12001
12002       /* Target-side condition evaluation: Handle deleted locations.  */
12003       if (!found_object)
12004         force_breakpoint_reinsertion (old_loc);
12005
12006       /* If this location is no longer present, and inserted, look if
12007          there's maybe a new location at the same address.  If so,
12008          mark that one inserted, and don't remove this one.  This is
12009          needed so that we don't have a time window where a breakpoint
12010          at certain location is not inserted.  */
12011
12012       if (old_loc->inserted)
12013         {
12014           /* If the location is inserted now, we might have to remove
12015              it.  */
12016
12017           if (found_object && should_be_inserted (old_loc))
12018             {
12019               /* The location is still present in the location list,
12020                  and still should be inserted.  Don't do anything.  */
12021               keep_in_target = 1;
12022             }
12023           else
12024             {
12025               /* This location still exists, but it won't be kept in the
12026                  target since it may have been disabled.  We proceed to
12027                  remove its target-side condition.  */
12028
12029               /* The location is either no longer present, or got
12030                  disabled.  See if there's another location at the
12031                  same address, in which case we don't need to remove
12032                  this one from the target.  */
12033
12034               /* OLD_LOC comes from existing struct breakpoint.  */
12035               if (breakpoint_address_is_meaningful (old_loc->owner))
12036                 {
12037                   for (loc2p = locp;
12038                        (loc2p < bp_locations + bp_locations_count
12039                         && (*loc2p)->address == old_loc->address);
12040                        loc2p++)
12041                     {
12042                       struct bp_location *loc2 = *loc2p;
12043
12044                       if (breakpoint_locations_match (loc2, old_loc))
12045                         {
12046                           /* Read watchpoint locations are switched to
12047                              access watchpoints, if the former are not
12048                              supported, but the latter are.  */
12049                           if (is_hardware_watchpoint (old_loc->owner))
12050                             {
12051                               gdb_assert (is_hardware_watchpoint (loc2->owner));
12052                               loc2->watchpoint_type = old_loc->watchpoint_type;
12053                             }
12054
12055                           /* loc2 is a duplicated location. We need to check
12056                              if it should be inserted in case it will be
12057                              unduplicated.  */
12058                           if (loc2 != old_loc
12059                               && unduplicated_should_be_inserted (loc2))
12060                             {
12061                               swap_insertion (old_loc, loc2);
12062                               keep_in_target = 1;
12063                               break;
12064                             }
12065                         }
12066                     }
12067                 }
12068             }
12069
12070           if (!keep_in_target)
12071             {
12072               if (remove_breakpoint (old_loc))
12073                 {
12074                   /* This is just about all we can do.  We could keep
12075                      this location on the global list, and try to
12076                      remove it next time, but there's no particular
12077                      reason why we will succeed next time.
12078                      
12079                      Note that at this point, old_loc->owner is still
12080                      valid, as delete_breakpoint frees the breakpoint
12081                      only after calling us.  */
12082                   printf_filtered (_("warning: Error removing "
12083                                      "breakpoint %d\n"), 
12084                                    old_loc->owner->number);
12085                 }
12086               removed = 1;
12087             }
12088         }
12089
12090       if (!found_object)
12091         {
12092           if (removed && target_is_non_stop_p ()
12093               && need_moribund_for_location_type (old_loc))
12094             {
12095               /* This location was removed from the target.  In
12096                  non-stop mode, a race condition is possible where
12097                  we've removed a breakpoint, but stop events for that
12098                  breakpoint are already queued and will arrive later.
12099                  We apply an heuristic to be able to distinguish such
12100                  SIGTRAPs from other random SIGTRAPs: we keep this
12101                  breakpoint location for a bit, and will retire it
12102                  after we see some number of events.  The theory here
12103                  is that reporting of events should, "on the average",
12104                  be fair, so after a while we'll see events from all
12105                  threads that have anything of interest, and no longer
12106                  need to keep this breakpoint location around.  We
12107                  don't hold locations forever so to reduce chances of
12108                  mistaking a non-breakpoint SIGTRAP for a breakpoint
12109                  SIGTRAP.
12110
12111                  The heuristic failing can be disastrous on
12112                  decr_pc_after_break targets.
12113
12114                  On decr_pc_after_break targets, like e.g., x86-linux,
12115                  if we fail to recognize a late breakpoint SIGTRAP,
12116                  because events_till_retirement has reached 0 too
12117                  soon, we'll fail to do the PC adjustment, and report
12118                  a random SIGTRAP to the user.  When the user resumes
12119                  the inferior, it will most likely immediately crash
12120                  with SIGILL/SIGBUS/SIGSEGV, or worse, get silently
12121                  corrupted, because of being resumed e.g., in the
12122                  middle of a multi-byte instruction, or skipped a
12123                  one-byte instruction.  This was actually seen happen
12124                  on native x86-linux, and should be less rare on
12125                  targets that do not support new thread events, like
12126                  remote, due to the heuristic depending on
12127                  thread_count.
12128
12129                  Mistaking a random SIGTRAP for a breakpoint trap
12130                  causes similar symptoms (PC adjustment applied when
12131                  it shouldn't), but then again, playing with SIGTRAPs
12132                  behind the debugger's back is asking for trouble.
12133
12134                  Since hardware watchpoint traps are always
12135                  distinguishable from other traps, so we don't need to
12136                  apply keep hardware watchpoint moribund locations
12137                  around.  We simply always ignore hardware watchpoint
12138                  traps we can no longer explain.  */
12139
12140               old_loc->events_till_retirement = 3 * (thread_count () + 1);
12141               old_loc->owner = NULL;
12142
12143               VEC_safe_push (bp_location_p, moribund_locations, old_loc);
12144             }
12145           else
12146             {
12147               old_loc->owner = NULL;
12148               decref_bp_location (&old_loc);
12149             }
12150         }
12151     }
12152
12153   /* Rescan breakpoints at the same address and section, marking the
12154      first one as "first" and any others as "duplicates".  This is so
12155      that the bpt instruction is only inserted once.  If we have a
12156      permanent breakpoint at the same place as BPT, make that one the
12157      official one, and the rest as duplicates.  Permanent breakpoints
12158      are sorted first for the same address.
12159
12160      Do the same for hardware watchpoints, but also considering the
12161      watchpoint's type (regular/access/read) and length.  */
12162
12163   bp_loc_first = NULL;
12164   wp_loc_first = NULL;
12165   awp_loc_first = NULL;
12166   rwp_loc_first = NULL;
12167   ALL_BP_LOCATIONS (loc, locp)
12168     {
12169       /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always
12170          non-NULL.  */
12171       struct bp_location **loc_first_p;
12172       b = loc->owner;
12173
12174       if (!unduplicated_should_be_inserted (loc)
12175           || !breakpoint_address_is_meaningful (b)
12176           /* Don't detect duplicate for tracepoint locations because they are
12177            never duplicated.  See the comments in field `duplicate' of
12178            `struct bp_location'.  */
12179           || is_tracepoint (b))
12180         {
12181           /* Clear the condition modification flag.  */
12182           loc->condition_changed = condition_unchanged;
12183           continue;
12184         }
12185
12186       if (b->type == bp_hardware_watchpoint)
12187         loc_first_p = &wp_loc_first;
12188       else if (b->type == bp_read_watchpoint)
12189         loc_first_p = &rwp_loc_first;
12190       else if (b->type == bp_access_watchpoint)
12191         loc_first_p = &awp_loc_first;
12192       else
12193         loc_first_p = &bp_loc_first;
12194
12195       if (*loc_first_p == NULL
12196           || (overlay_debugging && loc->section != (*loc_first_p)->section)
12197           || !breakpoint_locations_match (loc, *loc_first_p))
12198         {
12199           *loc_first_p = loc;
12200           loc->duplicate = 0;
12201
12202           if (is_breakpoint (loc->owner) && loc->condition_changed)
12203             {
12204               loc->needs_update = 1;
12205               /* Clear the condition modification flag.  */
12206               loc->condition_changed = condition_unchanged;
12207             }
12208           continue;
12209         }
12210
12211
12212       /* This and the above ensure the invariant that the first location
12213          is not duplicated, and is the inserted one.
12214          All following are marked as duplicated, and are not inserted.  */
12215       if (loc->inserted)
12216         swap_insertion (loc, *loc_first_p);
12217       loc->duplicate = 1;
12218
12219       /* Clear the condition modification flag.  */
12220       loc->condition_changed = condition_unchanged;
12221     }
12222
12223   if (insert_mode == UGLL_INSERT || breakpoints_should_be_inserted_now ())
12224     {
12225       if (insert_mode != UGLL_DONT_INSERT)
12226         insert_breakpoint_locations ();
12227       else
12228         {
12229           /* Even though the caller told us to not insert new
12230              locations, we may still need to update conditions on the
12231              target's side of breakpoints that were already inserted
12232              if the target is evaluating breakpoint conditions.  We
12233              only update conditions for locations that are marked
12234              "needs_update".  */
12235           update_inserted_breakpoint_locations ();
12236         }
12237     }
12238
12239   if (insert_mode != UGLL_DONT_INSERT)
12240     download_tracepoint_locations ();
12241 }
12242
12243 void
12244 breakpoint_retire_moribund (void)
12245 {
12246   struct bp_location *loc;
12247   int ix;
12248
12249   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
12250     if (--(loc->events_till_retirement) == 0)
12251       {
12252         decref_bp_location (&loc);
12253         VEC_unordered_remove (bp_location_p, moribund_locations, ix);
12254         --ix;
12255       }
12256 }
12257
12258 static void
12259 update_global_location_list_nothrow (enum ugll_insert_mode insert_mode)
12260 {
12261
12262   TRY
12263     {
12264       update_global_location_list (insert_mode);
12265     }
12266   CATCH (e, RETURN_MASK_ERROR)
12267     {
12268     }
12269   END_CATCH
12270 }
12271
12272 /* Clear BKP from a BPS.  */
12273
12274 static void
12275 bpstat_remove_bp_location (bpstat bps, struct breakpoint *bpt)
12276 {
12277   bpstat bs;
12278
12279   for (bs = bps; bs; bs = bs->next)
12280     if (bs->breakpoint_at == bpt)
12281       {
12282         bs->breakpoint_at = NULL;
12283         bs->old_val = NULL;
12284         /* bs->commands will be freed later.  */
12285       }
12286 }
12287
12288 /* Callback for iterate_over_threads.  */
12289 static int
12290 bpstat_remove_breakpoint_callback (struct thread_info *th, void *data)
12291 {
12292   struct breakpoint *bpt = (struct breakpoint *) data;
12293
12294   bpstat_remove_bp_location (th->control.stop_bpstat, bpt);
12295   return 0;
12296 }
12297
12298 /* Helper for breakpoint and tracepoint breakpoint_ops->mention
12299    callbacks.  */
12300
12301 static void
12302 say_where (struct breakpoint *b)
12303 {
12304   struct value_print_options opts;
12305
12306   get_user_print_options (&opts);
12307
12308   /* i18n: cagney/2005-02-11: Below needs to be merged into a
12309      single string.  */
12310   if (b->loc == NULL)
12311     {
12312       /* For pending locations, the output differs slightly based
12313          on b->extra_string.  If this is non-NULL, it contains either
12314          a condition or dprintf arguments.  */
12315       if (b->extra_string == NULL)
12316         {
12317           printf_filtered (_(" (%s) pending."),
12318                            event_location_to_string (b->location.get ()));
12319         }
12320       else if (b->type == bp_dprintf)
12321         {
12322           printf_filtered (_(" (%s,%s) pending."),
12323                            event_location_to_string (b->location.get ()),
12324                            b->extra_string);
12325         }
12326       else
12327         {
12328           printf_filtered (_(" (%s %s) pending."),
12329                            event_location_to_string (b->location.get ()),
12330                            b->extra_string);
12331         }
12332     }
12333   else
12334     {
12335       if (opts.addressprint || b->loc->symtab == NULL)
12336         {
12337           printf_filtered (" at ");
12338           fputs_filtered (paddress (b->loc->gdbarch, b->loc->address),
12339                           gdb_stdout);
12340         }
12341       if (b->loc->symtab != NULL)
12342         {
12343           /* If there is a single location, we can print the location
12344              more nicely.  */
12345           if (b->loc->next == NULL)
12346             printf_filtered (": file %s, line %d.",
12347                              symtab_to_filename_for_display (b->loc->symtab),
12348                              b->loc->line_number);
12349           else
12350             /* This is not ideal, but each location may have a
12351                different file name, and this at least reflects the
12352                real situation somewhat.  */
12353             printf_filtered (": %s.",
12354                              event_location_to_string (b->location.get ()));
12355         }
12356
12357       if (b->loc->next)
12358         {
12359           struct bp_location *loc = b->loc;
12360           int n = 0;
12361           for (; loc; loc = loc->next)
12362             ++n;
12363           printf_filtered (" (%d locations)", n);
12364         }
12365     }
12366 }
12367
12368 /* Default bp_location_ops methods.  */
12369
12370 static void
12371 bp_location_dtor (struct bp_location *self)
12372 {
12373   xfree (self->function_name);
12374 }
12375
12376 static const struct bp_location_ops bp_location_ops =
12377 {
12378   bp_location_dtor
12379 };
12380
12381 /* Destructor for the breakpoint base class.  */
12382
12383 breakpoint::~breakpoint ()
12384 {
12385   xfree (this->cond_string);
12386   xfree (this->extra_string);
12387   xfree (this->filter);
12388 }
12389
12390 static struct bp_location *
12391 base_breakpoint_allocate_location (struct breakpoint *self)
12392 {
12393   return new bp_location (&bp_location_ops, self);
12394 }
12395
12396 static void
12397 base_breakpoint_re_set (struct breakpoint *b)
12398 {
12399   /* Nothing to re-set. */
12400 }
12401
12402 #define internal_error_pure_virtual_called() \
12403   gdb_assert_not_reached ("pure virtual function called")
12404
12405 static int
12406 base_breakpoint_insert_location (struct bp_location *bl)
12407 {
12408   internal_error_pure_virtual_called ();
12409 }
12410
12411 static int
12412 base_breakpoint_remove_location (struct bp_location *bl,
12413                                  enum remove_bp_reason reason)
12414 {
12415   internal_error_pure_virtual_called ();
12416 }
12417
12418 static int
12419 base_breakpoint_breakpoint_hit (const struct bp_location *bl,
12420                                 const address_space *aspace,
12421                                 CORE_ADDR bp_addr,
12422                                 const struct target_waitstatus *ws)
12423 {
12424   internal_error_pure_virtual_called ();
12425 }
12426
12427 static void
12428 base_breakpoint_check_status (bpstat bs)
12429 {
12430   /* Always stop.   */
12431 }
12432
12433 /* A "works_in_software_mode" breakpoint_ops method that just internal
12434    errors.  */
12435
12436 static int
12437 base_breakpoint_works_in_software_mode (const struct breakpoint *b)
12438 {
12439   internal_error_pure_virtual_called ();
12440 }
12441
12442 /* A "resources_needed" breakpoint_ops method that just internal
12443    errors.  */
12444
12445 static int
12446 base_breakpoint_resources_needed (const struct bp_location *bl)
12447 {
12448   internal_error_pure_virtual_called ();
12449 }
12450
12451 static enum print_stop_action
12452 base_breakpoint_print_it (bpstat bs)
12453 {
12454   internal_error_pure_virtual_called ();
12455 }
12456
12457 static void
12458 base_breakpoint_print_one_detail (const struct breakpoint *self,
12459                                   struct ui_out *uiout)
12460 {
12461   /* nothing */
12462 }
12463
12464 static void
12465 base_breakpoint_print_mention (struct breakpoint *b)
12466 {
12467   internal_error_pure_virtual_called ();
12468 }
12469
12470 static void
12471 base_breakpoint_print_recreate (struct breakpoint *b, struct ui_file *fp)
12472 {
12473   internal_error_pure_virtual_called ();
12474 }
12475
12476 static void
12477 base_breakpoint_create_sals_from_location
12478   (const struct event_location *location,
12479    struct linespec_result *canonical,
12480    enum bptype type_wanted)
12481 {
12482   internal_error_pure_virtual_called ();
12483 }
12484
12485 static void
12486 base_breakpoint_create_breakpoints_sal (struct gdbarch *gdbarch,
12487                                         struct linespec_result *c,
12488                                         gdb::unique_xmalloc_ptr<char> cond_string,
12489                                         gdb::unique_xmalloc_ptr<char> extra_string,
12490                                         enum bptype type_wanted,
12491                                         enum bpdisp disposition,
12492                                         int thread,
12493                                         int task, int ignore_count,
12494                                         const struct breakpoint_ops *o,
12495                                         int from_tty, int enabled,
12496                                         int internal, unsigned flags)
12497 {
12498   internal_error_pure_virtual_called ();
12499 }
12500
12501 static std::vector<symtab_and_line>
12502 base_breakpoint_decode_location (struct breakpoint *b,
12503                                  const struct event_location *location,
12504                                  struct program_space *search_pspace)
12505 {
12506   internal_error_pure_virtual_called ();
12507 }
12508
12509 /* The default 'explains_signal' method.  */
12510
12511 static int
12512 base_breakpoint_explains_signal (struct breakpoint *b, enum gdb_signal sig)
12513 {
12514   return 1;
12515 }
12516
12517 /* The default "after_condition_true" method.  */
12518
12519 static void
12520 base_breakpoint_after_condition_true (struct bpstats *bs)
12521 {
12522   /* Nothing to do.   */
12523 }
12524
12525 struct breakpoint_ops base_breakpoint_ops =
12526 {
12527   base_breakpoint_allocate_location,
12528   base_breakpoint_re_set,
12529   base_breakpoint_insert_location,
12530   base_breakpoint_remove_location,
12531   base_breakpoint_breakpoint_hit,
12532   base_breakpoint_check_status,
12533   base_breakpoint_resources_needed,
12534   base_breakpoint_works_in_software_mode,
12535   base_breakpoint_print_it,
12536   NULL,
12537   base_breakpoint_print_one_detail,
12538   base_breakpoint_print_mention,
12539   base_breakpoint_print_recreate,
12540   base_breakpoint_create_sals_from_location,
12541   base_breakpoint_create_breakpoints_sal,
12542   base_breakpoint_decode_location,
12543   base_breakpoint_explains_signal,
12544   base_breakpoint_after_condition_true,
12545 };
12546
12547 /* Default breakpoint_ops methods.  */
12548
12549 static void
12550 bkpt_re_set (struct breakpoint *b)
12551 {
12552   /* FIXME: is this still reachable?  */
12553   if (breakpoint_event_location_empty_p (b))
12554     {
12555       /* Anything without a location can't be re-set.  */
12556       delete_breakpoint (b);
12557       return;
12558     }
12559
12560   breakpoint_re_set_default (b);
12561 }
12562
12563 static int
12564 bkpt_insert_location (struct bp_location *bl)
12565 {
12566   CORE_ADDR addr = bl->target_info.reqstd_address;
12567
12568   bl->target_info.kind = breakpoint_kind (bl, &addr);
12569   bl->target_info.placed_address = addr;
12570
12571   if (bl->loc_type == bp_loc_hardware_breakpoint)
12572     return target_insert_hw_breakpoint (bl->gdbarch, &bl->target_info);
12573   else
12574     return target_insert_breakpoint (bl->gdbarch, &bl->target_info);
12575 }
12576
12577 static int
12578 bkpt_remove_location (struct bp_location *bl, enum remove_bp_reason reason)
12579 {
12580   if (bl->loc_type == bp_loc_hardware_breakpoint)
12581     return target_remove_hw_breakpoint (bl->gdbarch, &bl->target_info);
12582   else
12583     return target_remove_breakpoint (bl->gdbarch, &bl->target_info, reason);
12584 }
12585
12586 static int
12587 bkpt_breakpoint_hit (const struct bp_location *bl,
12588                      const address_space *aspace, CORE_ADDR bp_addr,
12589                      const struct target_waitstatus *ws)
12590 {
12591   if (ws->kind != TARGET_WAITKIND_STOPPED
12592       || ws->value.sig != GDB_SIGNAL_TRAP)
12593     return 0;
12594
12595   if (!breakpoint_address_match (bl->pspace->aspace, bl->address,
12596                                  aspace, bp_addr))
12597     return 0;
12598
12599   if (overlay_debugging         /* unmapped overlay section */
12600       && section_is_overlay (bl->section)
12601       && !section_is_mapped (bl->section))
12602     return 0;
12603
12604   return 1;
12605 }
12606
12607 static int
12608 dprintf_breakpoint_hit (const struct bp_location *bl,
12609                         const address_space *aspace, CORE_ADDR bp_addr,
12610                         const struct target_waitstatus *ws)
12611 {
12612   if (dprintf_style == dprintf_style_agent
12613       && target_can_run_breakpoint_commands ())
12614     {
12615       /* An agent-style dprintf never causes a stop.  If we see a trap
12616          for this address it must be for a breakpoint that happens to
12617          be set at the same address.  */
12618       return 0;
12619     }
12620
12621   return bkpt_breakpoint_hit (bl, aspace, bp_addr, ws);
12622 }
12623
12624 static int
12625 bkpt_resources_needed (const struct bp_location *bl)
12626 {
12627   gdb_assert (bl->owner->type == bp_hardware_breakpoint);
12628
12629   return 1;
12630 }
12631
12632 static enum print_stop_action
12633 bkpt_print_it (bpstat bs)
12634 {
12635   struct breakpoint *b;
12636   const struct bp_location *bl;
12637   int bp_temp;
12638   struct ui_out *uiout = current_uiout;
12639
12640   gdb_assert (bs->bp_location_at != NULL);
12641
12642   bl = bs->bp_location_at;
12643   b = bs->breakpoint_at;
12644
12645   bp_temp = b->disposition == disp_del;
12646   if (bl->address != bl->requested_address)
12647     breakpoint_adjustment_warning (bl->requested_address,
12648                                    bl->address,
12649                                    b->number, 1);
12650   annotate_breakpoint (b->number);
12651   maybe_print_thread_hit_breakpoint (uiout);
12652
12653   if (bp_temp)
12654     uiout->text ("Temporary breakpoint ");
12655   else
12656     uiout->text ("Breakpoint ");
12657   if (uiout->is_mi_like_p ())
12658     {
12659       uiout->field_string ("reason",
12660                            async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
12661       uiout->field_string ("disp", bpdisp_text (b->disposition));
12662     }
12663   uiout->field_int ("bkptno", b->number);
12664   uiout->text (", ");
12665
12666   return PRINT_SRC_AND_LOC;
12667 }
12668
12669 static void
12670 bkpt_print_mention (struct breakpoint *b)
12671 {
12672   if (current_uiout->is_mi_like_p ())
12673     return;
12674
12675   switch (b->type)
12676     {
12677     case bp_breakpoint:
12678     case bp_gnu_ifunc_resolver:
12679       if (b->disposition == disp_del)
12680         printf_filtered (_("Temporary breakpoint"));
12681       else
12682         printf_filtered (_("Breakpoint"));
12683       printf_filtered (_(" %d"), b->number);
12684       if (b->type == bp_gnu_ifunc_resolver)
12685         printf_filtered (_(" at gnu-indirect-function resolver"));
12686       break;
12687     case bp_hardware_breakpoint:
12688       printf_filtered (_("Hardware assisted breakpoint %d"), b->number);
12689       break;
12690     case bp_dprintf:
12691       printf_filtered (_("Dprintf %d"), b->number);
12692       break;
12693     }
12694
12695   say_where (b);
12696 }
12697
12698 static void
12699 bkpt_print_recreate (struct breakpoint *tp, struct ui_file *fp)
12700 {
12701   if (tp->type == bp_breakpoint && tp->disposition == disp_del)
12702     fprintf_unfiltered (fp, "tbreak");
12703   else if (tp->type == bp_breakpoint)
12704     fprintf_unfiltered (fp, "break");
12705   else if (tp->type == bp_hardware_breakpoint
12706            && tp->disposition == disp_del)
12707     fprintf_unfiltered (fp, "thbreak");
12708   else if (tp->type == bp_hardware_breakpoint)
12709     fprintf_unfiltered (fp, "hbreak");
12710   else
12711     internal_error (__FILE__, __LINE__,
12712                     _("unhandled breakpoint type %d"), (int) tp->type);
12713
12714   fprintf_unfiltered (fp, " %s",
12715                       event_location_to_string (tp->location.get ()));
12716
12717   /* Print out extra_string if this breakpoint is pending.  It might
12718      contain, for example, conditions that were set by the user.  */
12719   if (tp->loc == NULL && tp->extra_string != NULL)
12720     fprintf_unfiltered (fp, " %s", tp->extra_string);
12721
12722   print_recreate_thread (tp, fp);
12723 }
12724
12725 static void
12726 bkpt_create_sals_from_location (const struct event_location *location,
12727                                 struct linespec_result *canonical,
12728                                 enum bptype type_wanted)
12729 {
12730   create_sals_from_location_default (location, canonical, type_wanted);
12731 }
12732
12733 static void
12734 bkpt_create_breakpoints_sal (struct gdbarch *gdbarch,
12735                              struct linespec_result *canonical,
12736                              gdb::unique_xmalloc_ptr<char> cond_string,
12737                              gdb::unique_xmalloc_ptr<char> extra_string,
12738                              enum bptype type_wanted,
12739                              enum bpdisp disposition,
12740                              int thread,
12741                              int task, int ignore_count,
12742                              const struct breakpoint_ops *ops,
12743                              int from_tty, int enabled,
12744                              int internal, unsigned flags)
12745 {
12746   create_breakpoints_sal_default (gdbarch, canonical,
12747                                   std::move (cond_string),
12748                                   std::move (extra_string),
12749                                   type_wanted,
12750                                   disposition, thread, task,
12751                                   ignore_count, ops, from_tty,
12752                                   enabled, internal, flags);
12753 }
12754
12755 static std::vector<symtab_and_line>
12756 bkpt_decode_location (struct breakpoint *b,
12757                       const struct event_location *location,
12758                       struct program_space *search_pspace)
12759 {
12760   return decode_location_default (b, location, search_pspace);
12761 }
12762
12763 /* Virtual table for internal breakpoints.  */
12764
12765 static void
12766 internal_bkpt_re_set (struct breakpoint *b)
12767 {
12768   switch (b->type)
12769     {
12770       /* Delete overlay event and longjmp master breakpoints; they
12771          will be reset later by breakpoint_re_set.  */
12772     case bp_overlay_event:
12773     case bp_longjmp_master:
12774     case bp_std_terminate_master:
12775     case bp_exception_master:
12776       delete_breakpoint (b);
12777       break;
12778
12779       /* This breakpoint is special, it's set up when the inferior
12780          starts and we really don't want to touch it.  */
12781     case bp_shlib_event:
12782
12783       /* Like bp_shlib_event, this breakpoint type is special.  Once
12784          it is set up, we do not want to touch it.  */
12785     case bp_thread_event:
12786       break;
12787     }
12788 }
12789
12790 static void
12791 internal_bkpt_check_status (bpstat bs)
12792 {
12793   if (bs->breakpoint_at->type == bp_shlib_event)
12794     {
12795       /* If requested, stop when the dynamic linker notifies GDB of
12796          events.  This allows the user to get control and place
12797          breakpoints in initializer routines for dynamically loaded
12798          objects (among other things).  */
12799       bs->stop = stop_on_solib_events;
12800       bs->print = stop_on_solib_events;
12801     }
12802   else
12803     bs->stop = 0;
12804 }
12805
12806 static enum print_stop_action
12807 internal_bkpt_print_it (bpstat bs)
12808 {
12809   struct breakpoint *b;
12810
12811   b = bs->breakpoint_at;
12812
12813   switch (b->type)
12814     {
12815     case bp_shlib_event:
12816       /* Did we stop because the user set the stop_on_solib_events
12817          variable?  (If so, we report this as a generic, "Stopped due
12818          to shlib event" message.) */
12819       print_solib_event (0);
12820       break;
12821
12822     case bp_thread_event:
12823       /* Not sure how we will get here.
12824          GDB should not stop for these breakpoints.  */
12825       printf_filtered (_("Thread Event Breakpoint: gdb should not stop!\n"));
12826       break;
12827
12828     case bp_overlay_event:
12829       /* By analogy with the thread event, GDB should not stop for these.  */
12830       printf_filtered (_("Overlay Event Breakpoint: gdb should not stop!\n"));
12831       break;
12832
12833     case bp_longjmp_master:
12834       /* These should never be enabled.  */
12835       printf_filtered (_("Longjmp Master Breakpoint: gdb should not stop!\n"));
12836       break;
12837
12838     case bp_std_terminate_master:
12839       /* These should never be enabled.  */
12840       printf_filtered (_("std::terminate Master Breakpoint: "
12841                          "gdb should not stop!\n"));
12842       break;
12843
12844     case bp_exception_master:
12845       /* These should never be enabled.  */
12846       printf_filtered (_("Exception Master Breakpoint: "
12847                          "gdb should not stop!\n"));
12848       break;
12849     }
12850
12851   return PRINT_NOTHING;
12852 }
12853
12854 static void
12855 internal_bkpt_print_mention (struct breakpoint *b)
12856 {
12857   /* Nothing to mention.  These breakpoints are internal.  */
12858 }
12859
12860 /* Virtual table for momentary breakpoints  */
12861
12862 static void
12863 momentary_bkpt_re_set (struct breakpoint *b)
12864 {
12865   /* Keep temporary breakpoints, which can be encountered when we step
12866      over a dlopen call and solib_add is resetting the breakpoints.
12867      Otherwise these should have been blown away via the cleanup chain
12868      or by breakpoint_init_inferior when we rerun the executable.  */
12869 }
12870
12871 static void
12872 momentary_bkpt_check_status (bpstat bs)
12873 {
12874   /* Nothing.  The point of these breakpoints is causing a stop.  */
12875 }
12876
12877 static enum print_stop_action
12878 momentary_bkpt_print_it (bpstat bs)
12879 {
12880   return PRINT_UNKNOWN;
12881 }
12882
12883 static void
12884 momentary_bkpt_print_mention (struct breakpoint *b)
12885 {
12886   /* Nothing to mention.  These breakpoints are internal.  */
12887 }
12888
12889 /* Ensure INITIATING_FRAME is cleared when no such breakpoint exists.
12890
12891    It gets cleared already on the removal of the first one of such placed
12892    breakpoints.  This is OK as they get all removed altogether.  */
12893
12894 longjmp_breakpoint::~longjmp_breakpoint ()
12895 {
12896   thread_info *tp = find_thread_global_id (this->thread);
12897
12898   if (tp != NULL)
12899     tp->initiating_frame = null_frame_id;
12900 }
12901
12902 /* Specific methods for probe breakpoints.  */
12903
12904 static int
12905 bkpt_probe_insert_location (struct bp_location *bl)
12906 {
12907   int v = bkpt_insert_location (bl);
12908
12909   if (v == 0)
12910     {
12911       /* The insertion was successful, now let's set the probe's semaphore
12912          if needed.  */
12913       if (bl->probe.probe->pops->set_semaphore != NULL)
12914         bl->probe.probe->pops->set_semaphore (bl->probe.probe,
12915                                               bl->probe.objfile,
12916                                               bl->gdbarch);
12917     }
12918
12919   return v;
12920 }
12921
12922 static int
12923 bkpt_probe_remove_location (struct bp_location *bl,
12924                             enum remove_bp_reason reason)
12925 {
12926   /* Let's clear the semaphore before removing the location.  */
12927   if (bl->probe.probe->pops->clear_semaphore != NULL)
12928     bl->probe.probe->pops->clear_semaphore (bl->probe.probe,
12929                                             bl->probe.objfile,
12930                                             bl->gdbarch);
12931
12932   return bkpt_remove_location (bl, reason);
12933 }
12934
12935 static void
12936 bkpt_probe_create_sals_from_location (const struct event_location *location,
12937                                       struct linespec_result *canonical,
12938                                       enum bptype type_wanted)
12939 {
12940   struct linespec_sals lsal;
12941
12942   lsal.sals = parse_probes (location, NULL, canonical);
12943   lsal.canonical
12944     = xstrdup (event_location_to_string (canonical->location.get ()));
12945   canonical->lsals.push_back (std::move (lsal));
12946 }
12947
12948 static std::vector<symtab_and_line>
12949 bkpt_probe_decode_location (struct breakpoint *b,
12950                             const struct event_location *location,
12951                             struct program_space *search_pspace)
12952 {
12953   std::vector<symtab_and_line> sals = parse_probes (location, search_pspace, NULL);
12954   if (sals.empty ())
12955     error (_("probe not found"));
12956   return sals;
12957 }
12958
12959 /* The breakpoint_ops structure to be used in tracepoints.  */
12960
12961 static void
12962 tracepoint_re_set (struct breakpoint *b)
12963 {
12964   breakpoint_re_set_default (b);
12965 }
12966
12967 static int
12968 tracepoint_breakpoint_hit (const struct bp_location *bl,
12969                            const address_space *aspace, CORE_ADDR bp_addr,
12970                            const struct target_waitstatus *ws)
12971 {
12972   /* By definition, the inferior does not report stops at
12973      tracepoints.  */
12974   return 0;
12975 }
12976
12977 static void
12978 tracepoint_print_one_detail (const struct breakpoint *self,
12979                              struct ui_out *uiout)
12980 {
12981   struct tracepoint *tp = (struct tracepoint *) self;
12982   if (tp->static_trace_marker_id)
12983     {
12984       gdb_assert (self->type == bp_static_tracepoint);
12985
12986       uiout->text ("\tmarker id is ");
12987       uiout->field_string ("static-tracepoint-marker-string-id",
12988                            tp->static_trace_marker_id);
12989       uiout->text ("\n");
12990     }
12991 }
12992
12993 static void
12994 tracepoint_print_mention (struct breakpoint *b)
12995 {
12996   if (current_uiout->is_mi_like_p ())
12997     return;
12998
12999   switch (b->type)
13000     {
13001     case bp_tracepoint:
13002       printf_filtered (_("Tracepoint"));
13003       printf_filtered (_(" %d"), b->number);
13004       break;
13005     case bp_fast_tracepoint:
13006       printf_filtered (_("Fast tracepoint"));
13007       printf_filtered (_(" %d"), b->number);
13008       break;
13009     case bp_static_tracepoint:
13010       printf_filtered (_("Static tracepoint"));
13011       printf_filtered (_(" %d"), b->number);
13012       break;
13013     default:
13014       internal_error (__FILE__, __LINE__,
13015                       _("unhandled tracepoint type %d"), (int) b->type);
13016     }
13017
13018   say_where (b);
13019 }
13020
13021 static void
13022 tracepoint_print_recreate (struct breakpoint *self, struct ui_file *fp)
13023 {
13024   struct tracepoint *tp = (struct tracepoint *) self;
13025
13026   if (self->type == bp_fast_tracepoint)
13027     fprintf_unfiltered (fp, "ftrace");
13028   else if (self->type == bp_static_tracepoint)
13029     fprintf_unfiltered (fp, "strace");
13030   else if (self->type == bp_tracepoint)
13031     fprintf_unfiltered (fp, "trace");
13032   else
13033     internal_error (__FILE__, __LINE__,
13034                     _("unhandled tracepoint type %d"), (int) self->type);
13035
13036   fprintf_unfiltered (fp, " %s",
13037                       event_location_to_string (self->location.get ()));
13038   print_recreate_thread (self, fp);
13039
13040   if (tp->pass_count)
13041     fprintf_unfiltered (fp, "  passcount %d\n", tp->pass_count);
13042 }
13043
13044 static void
13045 tracepoint_create_sals_from_location (const struct event_location *location,
13046                                       struct linespec_result *canonical,
13047                                       enum bptype type_wanted)
13048 {
13049   create_sals_from_location_default (location, canonical, type_wanted);
13050 }
13051
13052 static void
13053 tracepoint_create_breakpoints_sal (struct gdbarch *gdbarch,
13054                                    struct linespec_result *canonical,
13055                                    gdb::unique_xmalloc_ptr<char> cond_string,
13056                                    gdb::unique_xmalloc_ptr<char> extra_string,
13057                                    enum bptype type_wanted,
13058                                    enum bpdisp disposition,
13059                                    int thread,
13060                                    int task, int ignore_count,
13061                                    const struct breakpoint_ops *ops,
13062                                    int from_tty, int enabled,
13063                                    int internal, unsigned flags)
13064 {
13065   create_breakpoints_sal_default (gdbarch, canonical,
13066                                   std::move (cond_string),
13067                                   std::move (extra_string),
13068                                   type_wanted,
13069                                   disposition, thread, task,
13070                                   ignore_count, ops, from_tty,
13071                                   enabled, internal, flags);
13072 }
13073
13074 static std::vector<symtab_and_line>
13075 tracepoint_decode_location (struct breakpoint *b,
13076                             const struct event_location *location,
13077                             struct program_space *search_pspace)
13078 {
13079   return decode_location_default (b, location, search_pspace);
13080 }
13081
13082 struct breakpoint_ops tracepoint_breakpoint_ops;
13083
13084 /* The breakpoint_ops structure to be use on tracepoints placed in a
13085    static probe.  */
13086
13087 static void
13088 tracepoint_probe_create_sals_from_location
13089   (const struct event_location *location,
13090    struct linespec_result *canonical,
13091    enum bptype type_wanted)
13092 {
13093   /* We use the same method for breakpoint on probes.  */
13094   bkpt_probe_create_sals_from_location (location, canonical, type_wanted);
13095 }
13096
13097 static std::vector<symtab_and_line>
13098 tracepoint_probe_decode_location (struct breakpoint *b,
13099                                   const struct event_location *location,
13100                                   struct program_space *search_pspace)
13101 {
13102   /* We use the same method for breakpoint on probes.  */
13103   return bkpt_probe_decode_location (b, location, search_pspace);
13104 }
13105
13106 static struct breakpoint_ops tracepoint_probe_breakpoint_ops;
13107
13108 /* Dprintf breakpoint_ops methods.  */
13109
13110 static void
13111 dprintf_re_set (struct breakpoint *b)
13112 {
13113   breakpoint_re_set_default (b);
13114
13115   /* extra_string should never be non-NULL for dprintf.  */
13116   gdb_assert (b->extra_string != NULL);
13117
13118   /* 1 - connect to target 1, that can run breakpoint commands.
13119      2 - create a dprintf, which resolves fine.
13120      3 - disconnect from target 1
13121      4 - connect to target 2, that can NOT run breakpoint commands.
13122
13123      After steps #3/#4, you'll want the dprintf command list to
13124      be updated, because target 1 and 2 may well return different
13125      answers for target_can_run_breakpoint_commands().
13126      Given absence of finer grained resetting, we get to do
13127      it all the time.  */
13128   if (b->extra_string != NULL)
13129     update_dprintf_command_list (b);
13130 }
13131
13132 /* Implement the "print_recreate" breakpoint_ops method for dprintf.  */
13133
13134 static void
13135 dprintf_print_recreate (struct breakpoint *tp, struct ui_file *fp)
13136 {
13137   fprintf_unfiltered (fp, "dprintf %s,%s",
13138                       event_location_to_string (tp->location.get ()),
13139                       tp->extra_string);
13140   print_recreate_thread (tp, fp);
13141 }
13142
13143 /* Implement the "after_condition_true" breakpoint_ops method for
13144    dprintf.
13145
13146    dprintf's are implemented with regular commands in their command
13147    list, but we run the commands here instead of before presenting the
13148    stop to the user, as dprintf's don't actually cause a stop.  This
13149    also makes it so that the commands of multiple dprintfs at the same
13150    address are all handled.  */
13151
13152 static void
13153 dprintf_after_condition_true (struct bpstats *bs)
13154 {
13155   struct bpstats tmp_bs;
13156   struct bpstats *tmp_bs_p = &tmp_bs;
13157
13158   /* dprintf's never cause a stop.  This wasn't set in the
13159      check_status hook instead because that would make the dprintf's
13160      condition not be evaluated.  */
13161   bs->stop = 0;
13162
13163   /* Run the command list here.  Take ownership of it instead of
13164      copying.  We never want these commands to run later in
13165      bpstat_do_actions, if a breakpoint that causes a stop happens to
13166      be set at same address as this dprintf, or even if running the
13167      commands here throws.  */
13168   tmp_bs.commands = bs->commands;
13169   bs->commands = NULL;
13170
13171   bpstat_do_actions_1 (&tmp_bs_p);
13172
13173   /* 'tmp_bs.commands' will usually be NULL by now, but
13174      bpstat_do_actions_1 may return early without processing the whole
13175      list.  */
13176 }
13177
13178 /* The breakpoint_ops structure to be used on static tracepoints with
13179    markers (`-m').  */
13180
13181 static void
13182 strace_marker_create_sals_from_location (const struct event_location *location,
13183                                          struct linespec_result *canonical,
13184                                          enum bptype type_wanted)
13185 {
13186   struct linespec_sals lsal;
13187   const char *arg_start, *arg;
13188
13189   arg = arg_start = get_linespec_location (location);
13190   lsal.sals = decode_static_tracepoint_spec (&arg);
13191
13192   std::string str (arg_start, arg - arg_start);
13193   const char *ptr = str.c_str ();
13194   canonical->location = new_linespec_location (&ptr);
13195
13196   lsal.canonical
13197     = xstrdup (event_location_to_string (canonical->location.get ()));
13198   canonical->lsals.push_back (std::move (lsal));
13199 }
13200
13201 static void
13202 strace_marker_create_breakpoints_sal (struct gdbarch *gdbarch,
13203                                       struct linespec_result *canonical,
13204                                       gdb::unique_xmalloc_ptr<char> cond_string,
13205                                       gdb::unique_xmalloc_ptr<char> extra_string,
13206                                       enum bptype type_wanted,
13207                                       enum bpdisp disposition,
13208                                       int thread,
13209                                       int task, int ignore_count,
13210                                       const struct breakpoint_ops *ops,
13211                                       int from_tty, int enabled,
13212                                       int internal, unsigned flags)
13213 {
13214   const linespec_sals &lsal = canonical->lsals[0];
13215
13216   /* If the user is creating a static tracepoint by marker id
13217      (strace -m MARKER_ID), then store the sals index, so that
13218      breakpoint_re_set can try to match up which of the newly
13219      found markers corresponds to this one, and, don't try to
13220      expand multiple locations for each sal, given than SALS
13221      already should contain all sals for MARKER_ID.  */
13222
13223   for (size_t i = 0; i < lsal.sals.size (); i++)
13224     {
13225       event_location_up location
13226         = copy_event_location (canonical->location.get ());
13227
13228       std::unique_ptr<tracepoint> tp (new tracepoint ());
13229       init_breakpoint_sal (tp.get (), gdbarch, lsal.sals[i],
13230                            std::move (location), NULL,
13231                            std::move (cond_string),
13232                            std::move (extra_string),
13233                            type_wanted, disposition,
13234                            thread, task, ignore_count, ops,
13235                            from_tty, enabled, internal, flags,
13236                            canonical->special_display);
13237       /* Given that its possible to have multiple markers with
13238          the same string id, if the user is creating a static
13239          tracepoint by marker id ("strace -m MARKER_ID"), then
13240          store the sals index, so that breakpoint_re_set can
13241          try to match up which of the newly found markers
13242          corresponds to this one  */
13243       tp->static_trace_marker_id_idx = i;
13244
13245       install_breakpoint (internal, std::move (tp), 0);
13246     }
13247 }
13248
13249 static std::vector<symtab_and_line>
13250 strace_marker_decode_location (struct breakpoint *b,
13251                                const struct event_location *location,
13252                                struct program_space *search_pspace)
13253 {
13254   struct tracepoint *tp = (struct tracepoint *) b;
13255   const char *s = get_linespec_location (location);
13256
13257   std::vector<symtab_and_line> sals = decode_static_tracepoint_spec (&s);
13258   if (sals.size () > tp->static_trace_marker_id_idx)
13259     {
13260       sals[0] = sals[tp->static_trace_marker_id_idx];
13261       sals.resize (1);
13262       return sals;
13263     }
13264   else
13265     error (_("marker %s not found"), tp->static_trace_marker_id);
13266 }
13267
13268 static struct breakpoint_ops strace_marker_breakpoint_ops;
13269
13270 static int
13271 strace_marker_p (struct breakpoint *b)
13272 {
13273   return b->ops == &strace_marker_breakpoint_ops;
13274 }
13275
13276 /* Delete a breakpoint and clean up all traces of it in the data
13277    structures.  */
13278
13279 void
13280 delete_breakpoint (struct breakpoint *bpt)
13281 {
13282   struct breakpoint *b;
13283
13284   gdb_assert (bpt != NULL);
13285
13286   /* Has this bp already been deleted?  This can happen because
13287      multiple lists can hold pointers to bp's.  bpstat lists are
13288      especial culprits.
13289
13290      One example of this happening is a watchpoint's scope bp.  When
13291      the scope bp triggers, we notice that the watchpoint is out of
13292      scope, and delete it.  We also delete its scope bp.  But the
13293      scope bp is marked "auto-deleting", and is already on a bpstat.
13294      That bpstat is then checked for auto-deleting bp's, which are
13295      deleted.
13296
13297      A real solution to this problem might involve reference counts in
13298      bp's, and/or giving them pointers back to their referencing
13299      bpstat's, and teaching delete_breakpoint to only free a bp's
13300      storage when no more references were extent.  A cheaper bandaid
13301      was chosen.  */
13302   if (bpt->type == bp_none)
13303     return;
13304
13305   /* At least avoid this stale reference until the reference counting
13306      of breakpoints gets resolved.  */
13307   if (bpt->related_breakpoint != bpt)
13308     {
13309       struct breakpoint *related;
13310       struct watchpoint *w;
13311
13312       if (bpt->type == bp_watchpoint_scope)
13313         w = (struct watchpoint *) bpt->related_breakpoint;
13314       else if (bpt->related_breakpoint->type == bp_watchpoint_scope)
13315         w = (struct watchpoint *) bpt;
13316       else
13317         w = NULL;
13318       if (w != NULL)
13319         watchpoint_del_at_next_stop (w);
13320
13321       /* Unlink bpt from the bpt->related_breakpoint ring.  */
13322       for (related = bpt; related->related_breakpoint != bpt;
13323            related = related->related_breakpoint);
13324       related->related_breakpoint = bpt->related_breakpoint;
13325       bpt->related_breakpoint = bpt;
13326     }
13327
13328   /* watch_command_1 creates a watchpoint but only sets its number if
13329      update_watchpoint succeeds in creating its bp_locations.  If there's
13330      a problem in that process, we'll be asked to delete the half-created
13331      watchpoint.  In that case, don't announce the deletion.  */
13332   if (bpt->number)
13333     observer_notify_breakpoint_deleted (bpt);
13334
13335   if (breakpoint_chain == bpt)
13336     breakpoint_chain = bpt->next;
13337
13338   ALL_BREAKPOINTS (b)
13339     if (b->next == bpt)
13340     {
13341       b->next = bpt->next;
13342       break;
13343     }
13344
13345   /* Be sure no bpstat's are pointing at the breakpoint after it's
13346      been freed.  */
13347   /* FIXME, how can we find all bpstat's?  We just check stop_bpstat
13348      in all threads for now.  Note that we cannot just remove bpstats
13349      pointing at bpt from the stop_bpstat list entirely, as breakpoint
13350      commands are associated with the bpstat; if we remove it here,
13351      then the later call to bpstat_do_actions (&stop_bpstat); in
13352      event-top.c won't do anything, and temporary breakpoints with
13353      commands won't work.  */
13354
13355   iterate_over_threads (bpstat_remove_breakpoint_callback, bpt);
13356
13357   /* Now that breakpoint is removed from breakpoint list, update the
13358      global location list.  This will remove locations that used to
13359      belong to this breakpoint.  Do this before freeing the breakpoint
13360      itself, since remove_breakpoint looks at location's owner.  It
13361      might be better design to have location completely
13362      self-contained, but it's not the case now.  */
13363   update_global_location_list (UGLL_DONT_INSERT);
13364
13365   /* On the chance that someone will soon try again to delete this
13366      same bp, we mark it as deleted before freeing its storage.  */
13367   bpt->type = bp_none;
13368   delete bpt;
13369 }
13370
13371 static void
13372 do_delete_breakpoint_cleanup (void *b)
13373 {
13374   delete_breakpoint ((struct breakpoint *) b);
13375 }
13376
13377 struct cleanup *
13378 make_cleanup_delete_breakpoint (struct breakpoint *b)
13379 {
13380   return make_cleanup (do_delete_breakpoint_cleanup, b);
13381 }
13382
13383 /* Iterator function to call a user-provided callback function once
13384    for each of B and its related breakpoints.  */
13385
13386 static void
13387 iterate_over_related_breakpoints (struct breakpoint *b,
13388                                   gdb::function_view<void (breakpoint *)> function)
13389 {
13390   struct breakpoint *related;
13391
13392   related = b;
13393   do
13394     {
13395       struct breakpoint *next;
13396
13397       /* FUNCTION may delete RELATED.  */
13398       next = related->related_breakpoint;
13399
13400       if (next == related)
13401         {
13402           /* RELATED is the last ring entry.  */
13403           function (related);
13404
13405           /* FUNCTION may have deleted it, so we'd never reach back to
13406              B.  There's nothing left to do anyway, so just break
13407              out.  */
13408           break;
13409         }
13410       else
13411         function (related);
13412
13413       related = next;
13414     }
13415   while (related != b);
13416 }
13417
13418 static void
13419 delete_command (const char *arg, int from_tty)
13420 {
13421   struct breakpoint *b, *b_tmp;
13422
13423   dont_repeat ();
13424
13425   if (arg == 0)
13426     {
13427       int breaks_to_delete = 0;
13428
13429       /* Delete all breakpoints if no argument.  Do not delete
13430          internal breakpoints, these have to be deleted with an
13431          explicit breakpoint number argument.  */
13432       ALL_BREAKPOINTS (b)
13433         if (user_breakpoint_p (b))
13434           {
13435             breaks_to_delete = 1;
13436             break;
13437           }
13438
13439       /* Ask user only if there are some breakpoints to delete.  */
13440       if (!from_tty
13441           || (breaks_to_delete && query (_("Delete all breakpoints? "))))
13442         {
13443           ALL_BREAKPOINTS_SAFE (b, b_tmp)
13444             if (user_breakpoint_p (b))
13445               delete_breakpoint (b);
13446         }
13447     }
13448   else
13449     map_breakpoint_numbers
13450       (arg, [&] (breakpoint *b)
13451        {
13452          iterate_over_related_breakpoints (b, delete_breakpoint);
13453        });
13454 }
13455
13456 /* Return true if all locations of B bound to PSPACE are pending.  If
13457    PSPACE is NULL, all locations of all program spaces are
13458    considered.  */
13459
13460 static int
13461 all_locations_are_pending (struct breakpoint *b, struct program_space *pspace)
13462 {
13463   struct bp_location *loc;
13464
13465   for (loc = b->loc; loc != NULL; loc = loc->next)
13466     if ((pspace == NULL
13467          || loc->pspace == pspace)
13468         && !loc->shlib_disabled
13469         && !loc->pspace->executing_startup)
13470       return 0;
13471   return 1;
13472 }
13473
13474 /* Subroutine of update_breakpoint_locations to simplify it.
13475    Return non-zero if multiple fns in list LOC have the same name.
13476    Null names are ignored.  */
13477
13478 static int
13479 ambiguous_names_p (struct bp_location *loc)
13480 {
13481   struct bp_location *l;
13482   htab_t htab = htab_create_alloc (13, htab_hash_string,
13483                                    (int (*) (const void *, 
13484                                              const void *)) streq,
13485                                    NULL, xcalloc, xfree);
13486
13487   for (l = loc; l != NULL; l = l->next)
13488     {
13489       const char **slot;
13490       const char *name = l->function_name;
13491
13492       /* Allow for some names to be NULL, ignore them.  */
13493       if (name == NULL)
13494         continue;
13495
13496       slot = (const char **) htab_find_slot (htab, (const void *) name,
13497                                              INSERT);
13498       /* NOTE: We can assume slot != NULL here because xcalloc never
13499          returns NULL.  */
13500       if (*slot != NULL)
13501         {
13502           htab_delete (htab);
13503           return 1;
13504         }
13505       *slot = name;
13506     }
13507
13508   htab_delete (htab);
13509   return 0;
13510 }
13511
13512 /* When symbols change, it probably means the sources changed as well,
13513    and it might mean the static tracepoint markers are no longer at
13514    the same address or line numbers they used to be at last we
13515    checked.  Losing your static tracepoints whenever you rebuild is
13516    undesirable.  This function tries to resync/rematch gdb static
13517    tracepoints with the markers on the target, for static tracepoints
13518    that have not been set by marker id.  Static tracepoint that have
13519    been set by marker id are reset by marker id in breakpoint_re_set.
13520    The heuristic is:
13521
13522    1) For a tracepoint set at a specific address, look for a marker at
13523    the old PC.  If one is found there, assume to be the same marker.
13524    If the name / string id of the marker found is different from the
13525    previous known name, assume that means the user renamed the marker
13526    in the sources, and output a warning.
13527
13528    2) For a tracepoint set at a given line number, look for a marker
13529    at the new address of the old line number.  If one is found there,
13530    assume to be the same marker.  If the name / string id of the
13531    marker found is different from the previous known name, assume that
13532    means the user renamed the marker in the sources, and output a
13533    warning.
13534
13535    3) If a marker is no longer found at the same address or line, it
13536    may mean the marker no longer exists.  But it may also just mean
13537    the code changed a bit.  Maybe the user added a few lines of code
13538    that made the marker move up or down (in line number terms).  Ask
13539    the target for info about the marker with the string id as we knew
13540    it.  If found, update line number and address in the matching
13541    static tracepoint.  This will get confused if there's more than one
13542    marker with the same ID (possible in UST, although unadvised
13543    precisely because it confuses tools).  */
13544
13545 static struct symtab_and_line
13546 update_static_tracepoint (struct breakpoint *b, struct symtab_and_line sal)
13547 {
13548   struct tracepoint *tp = (struct tracepoint *) b;
13549   struct static_tracepoint_marker marker;
13550   CORE_ADDR pc;
13551
13552   pc = sal.pc;
13553   if (sal.line)
13554     find_line_pc (sal.symtab, sal.line, &pc);
13555
13556   if (target_static_tracepoint_marker_at (pc, &marker))
13557     {
13558       if (strcmp (tp->static_trace_marker_id, marker.str_id) != 0)
13559         warning (_("static tracepoint %d changed probed marker from %s to %s"),
13560                  b->number,
13561                  tp->static_trace_marker_id, marker.str_id);
13562
13563       xfree (tp->static_trace_marker_id);
13564       tp->static_trace_marker_id = xstrdup (marker.str_id);
13565       release_static_tracepoint_marker (&marker);
13566
13567       return sal;
13568     }
13569
13570   /* Old marker wasn't found on target at lineno.  Try looking it up
13571      by string ID.  */
13572   if (!sal.explicit_pc
13573       && sal.line != 0
13574       && sal.symtab != NULL
13575       && tp->static_trace_marker_id != NULL)
13576     {
13577       VEC(static_tracepoint_marker_p) *markers;
13578
13579       markers
13580         = target_static_tracepoint_markers_by_strid (tp->static_trace_marker_id);
13581
13582       if (!VEC_empty(static_tracepoint_marker_p, markers))
13583         {
13584           struct symbol *sym;
13585           struct static_tracepoint_marker *tpmarker;
13586           struct ui_out *uiout = current_uiout;
13587           struct explicit_location explicit_loc;
13588
13589           tpmarker = VEC_index (static_tracepoint_marker_p, markers, 0);
13590
13591           xfree (tp->static_trace_marker_id);
13592           tp->static_trace_marker_id = xstrdup (tpmarker->str_id);
13593
13594           warning (_("marker for static tracepoint %d (%s) not "
13595                      "found at previous line number"),
13596                    b->number, tp->static_trace_marker_id);
13597
13598           symtab_and_line sal2 = find_pc_line (tpmarker->address, 0);
13599           sym = find_pc_sect_function (tpmarker->address, NULL);
13600           uiout->text ("Now in ");
13601           if (sym)
13602             {
13603               uiout->field_string ("func", SYMBOL_PRINT_NAME (sym));
13604               uiout->text (" at ");
13605             }
13606           uiout->field_string ("file",
13607                                symtab_to_filename_for_display (sal2.symtab));
13608           uiout->text (":");
13609
13610           if (uiout->is_mi_like_p ())
13611             {
13612               const char *fullname = symtab_to_fullname (sal2.symtab);
13613
13614               uiout->field_string ("fullname", fullname);
13615             }
13616
13617           uiout->field_int ("line", sal2.line);
13618           uiout->text ("\n");
13619
13620           b->loc->line_number = sal2.line;
13621           b->loc->symtab = sym != NULL ? sal2.symtab : NULL;
13622
13623           b->location.reset (NULL);
13624           initialize_explicit_location (&explicit_loc);
13625           explicit_loc.source_filename
13626             = ASTRDUP (symtab_to_filename_for_display (sal2.symtab));
13627           explicit_loc.line_offset.offset = b->loc->line_number;
13628           explicit_loc.line_offset.sign = LINE_OFFSET_NONE;
13629           b->location = new_explicit_location (&explicit_loc);
13630
13631           /* Might be nice to check if function changed, and warn if
13632              so.  */
13633
13634           release_static_tracepoint_marker (tpmarker);
13635         }
13636     }
13637   return sal;
13638 }
13639
13640 /* Returns 1 iff locations A and B are sufficiently same that
13641    we don't need to report breakpoint as changed.  */
13642
13643 static int
13644 locations_are_equal (struct bp_location *a, struct bp_location *b)
13645 {
13646   while (a && b)
13647     {
13648       if (a->address != b->address)
13649         return 0;
13650
13651       if (a->shlib_disabled != b->shlib_disabled)
13652         return 0;
13653
13654       if (a->enabled != b->enabled)
13655         return 0;
13656
13657       a = a->next;
13658       b = b->next;
13659     }
13660
13661   if ((a == NULL) != (b == NULL))
13662     return 0;
13663
13664   return 1;
13665 }
13666
13667 /* Split all locations of B that are bound to PSPACE out of B's
13668    location list to a separate list and return that list's head.  If
13669    PSPACE is NULL, hoist out all locations of B.  */
13670
13671 static struct bp_location *
13672 hoist_existing_locations (struct breakpoint *b, struct program_space *pspace)
13673 {
13674   struct bp_location head;
13675   struct bp_location *i = b->loc;
13676   struct bp_location **i_link = &b->loc;
13677   struct bp_location *hoisted = &head;
13678
13679   if (pspace == NULL)
13680     {
13681       i = b->loc;
13682       b->loc = NULL;
13683       return i;
13684     }
13685
13686   head.next = NULL;
13687
13688   while (i != NULL)
13689     {
13690       if (i->pspace == pspace)
13691         {
13692           *i_link = i->next;
13693           i->next = NULL;
13694           hoisted->next = i;
13695           hoisted = i;
13696         }
13697       else
13698         i_link = &i->next;
13699       i = *i_link;
13700     }
13701
13702   return head.next;
13703 }
13704
13705 /* Create new breakpoint locations for B (a hardware or software
13706    breakpoint) based on SALS and SALS_END.  If SALS_END.NELTS is not
13707    zero, then B is a ranged breakpoint.  Only recreates locations for
13708    FILTER_PSPACE.  Locations of other program spaces are left
13709    untouched.  */
13710
13711 void
13712 update_breakpoint_locations (struct breakpoint *b,
13713                              struct program_space *filter_pspace,
13714                              gdb::array_view<const symtab_and_line> sals,
13715                              gdb::array_view<const symtab_and_line> sals_end)
13716 {
13717   int i;
13718   struct bp_location *existing_locations;
13719
13720   if (!sals_end.empty () && (sals.size () != 1 || sals_end.size () != 1))
13721     {
13722       /* Ranged breakpoints have only one start location and one end
13723          location.  */
13724       b->enable_state = bp_disabled;
13725       printf_unfiltered (_("Could not reset ranged breakpoint %d: "
13726                            "multiple locations found\n"),
13727                          b->number);
13728       return;
13729     }
13730
13731   /* If there's no new locations, and all existing locations are
13732      pending, don't do anything.  This optimizes the common case where
13733      all locations are in the same shared library, that was unloaded.
13734      We'd like to retain the location, so that when the library is
13735      loaded again, we don't loose the enabled/disabled status of the
13736      individual locations.  */
13737   if (all_locations_are_pending (b, filter_pspace) && sals.empty ())
13738     return;
13739
13740   existing_locations = hoist_existing_locations (b, filter_pspace);
13741
13742   for (const auto &sal : sals)
13743     {
13744       struct bp_location *new_loc;
13745
13746       switch_to_program_space_and_thread (sal.pspace);
13747
13748       new_loc = add_location_to_breakpoint (b, &sal);
13749
13750       /* Reparse conditions, they might contain references to the
13751          old symtab.  */
13752       if (b->cond_string != NULL)
13753         {
13754           const char *s;
13755
13756           s = b->cond_string;
13757           TRY
13758             {
13759               new_loc->cond = parse_exp_1 (&s, sal.pc,
13760                                            block_for_pc (sal.pc),
13761                                            0);
13762             }
13763           CATCH (e, RETURN_MASK_ERROR)
13764             {
13765               warning (_("failed to reevaluate condition "
13766                          "for breakpoint %d: %s"), 
13767                        b->number, e.message);
13768               new_loc->enabled = 0;
13769             }
13770           END_CATCH
13771         }
13772
13773       if (!sals_end.empty ())
13774         {
13775           CORE_ADDR end = find_breakpoint_range_end (sals_end[0]);
13776
13777           new_loc->length = end - sals[0].pc + 1;
13778         }
13779     }
13780
13781   /* If possible, carry over 'disable' status from existing
13782      breakpoints.  */
13783   {
13784     struct bp_location *e = existing_locations;
13785     /* If there are multiple breakpoints with the same function name,
13786        e.g. for inline functions, comparing function names won't work.
13787        Instead compare pc addresses; this is just a heuristic as things
13788        may have moved, but in practice it gives the correct answer
13789        often enough until a better solution is found.  */
13790     int have_ambiguous_names = ambiguous_names_p (b->loc);
13791
13792     for (; e; e = e->next)
13793       {
13794         if (!e->enabled && e->function_name)
13795           {
13796             struct bp_location *l = b->loc;
13797             if (have_ambiguous_names)
13798               {
13799                 for (; l; l = l->next)
13800                   if (breakpoint_locations_match (e, l))
13801                     {
13802                       l->enabled = 0;
13803                       break;
13804                     }
13805               }
13806             else
13807               {
13808                 for (; l; l = l->next)
13809                   if (l->function_name
13810                       && strcmp (e->function_name, l->function_name) == 0)
13811                     {
13812                       l->enabled = 0;
13813                       break;
13814                     }
13815               }
13816           }
13817       }
13818   }
13819
13820   if (!locations_are_equal (existing_locations, b->loc))
13821     observer_notify_breakpoint_modified (b);
13822 }
13823
13824 /* Find the SaL locations corresponding to the given LOCATION.
13825    On return, FOUND will be 1 if any SaL was found, zero otherwise.  */
13826
13827 static std::vector<symtab_and_line>
13828 location_to_sals (struct breakpoint *b, struct event_location *location,
13829                   struct program_space *search_pspace, int *found)
13830 {
13831   struct gdb_exception exception = exception_none;
13832
13833   gdb_assert (b->ops != NULL);
13834
13835   std::vector<symtab_and_line> sals;
13836
13837   TRY
13838     {
13839       sals = b->ops->decode_location (b, location, search_pspace);
13840     }
13841   CATCH (e, RETURN_MASK_ERROR)
13842     {
13843       int not_found_and_ok = 0;
13844
13845       exception = e;
13846
13847       /* For pending breakpoints, it's expected that parsing will
13848          fail until the right shared library is loaded.  User has
13849          already told to create pending breakpoints and don't need
13850          extra messages.  If breakpoint is in bp_shlib_disabled
13851          state, then user already saw the message about that
13852          breakpoint being disabled, and don't want to see more
13853          errors.  */
13854       if (e.error == NOT_FOUND_ERROR
13855           && (b->condition_not_parsed
13856               || (b->loc != NULL
13857                   && search_pspace != NULL
13858                   && b->loc->pspace != search_pspace)
13859               || (b->loc && b->loc->shlib_disabled)
13860               || (b->loc && b->loc->pspace->executing_startup)
13861               || b->enable_state == bp_disabled))
13862         not_found_and_ok = 1;
13863
13864       if (!not_found_and_ok)
13865         {
13866           /* We surely don't want to warn about the same breakpoint
13867              10 times.  One solution, implemented here, is disable
13868              the breakpoint on error.  Another solution would be to
13869              have separate 'warning emitted' flag.  Since this
13870              happens only when a binary has changed, I don't know
13871              which approach is better.  */
13872           b->enable_state = bp_disabled;
13873           throw_exception (e);
13874         }
13875     }
13876   END_CATCH
13877
13878   if (exception.reason == 0 || exception.error != NOT_FOUND_ERROR)
13879     {
13880       for (auto &sal : sals)
13881         resolve_sal_pc (&sal);
13882       if (b->condition_not_parsed && b->extra_string != NULL)
13883         {
13884           char *cond_string, *extra_string;
13885           int thread, task;
13886
13887           find_condition_and_thread (b->extra_string, sals[0].pc,
13888                                      &cond_string, &thread, &task,
13889                                      &extra_string);
13890           gdb_assert (b->cond_string == NULL);
13891           if (cond_string)
13892             b->cond_string = cond_string;
13893           b->thread = thread;
13894           b->task = task;
13895           if (extra_string)
13896             {
13897               xfree (b->extra_string);
13898               b->extra_string = extra_string;
13899             }
13900           b->condition_not_parsed = 0;
13901         }
13902
13903       if (b->type == bp_static_tracepoint && !strace_marker_p (b))
13904         sals[0] = update_static_tracepoint (b, sals[0]);
13905
13906       *found = 1;
13907     }
13908   else
13909     *found = 0;
13910
13911   return sals;
13912 }
13913
13914 /* The default re_set method, for typical hardware or software
13915    breakpoints.  Reevaluate the breakpoint and recreate its
13916    locations.  */
13917
13918 static void
13919 breakpoint_re_set_default (struct breakpoint *b)
13920 {
13921   struct program_space *filter_pspace = current_program_space;
13922   std::vector<symtab_and_line> expanded, expanded_end;
13923
13924   int found;
13925   std::vector<symtab_and_line> sals = location_to_sals (b, b->location.get (),
13926                                                         filter_pspace, &found);
13927   if (found)
13928     expanded = std::move (sals);
13929
13930   if (b->location_range_end != NULL)
13931     {
13932       std::vector<symtab_and_line> sals_end
13933         = location_to_sals (b, b->location_range_end.get (),
13934                             filter_pspace, &found);
13935       if (found)
13936         expanded_end = std::move (sals_end);
13937     }
13938
13939   update_breakpoint_locations (b, filter_pspace, expanded, expanded_end);
13940 }
13941
13942 /* Default method for creating SALs from an address string.  It basically
13943    calls parse_breakpoint_sals.  Return 1 for success, zero for failure.  */
13944
13945 static void
13946 create_sals_from_location_default (const struct event_location *location,
13947                                    struct linespec_result *canonical,
13948                                    enum bptype type_wanted)
13949 {
13950   parse_breakpoint_sals (location, canonical);
13951 }
13952
13953 /* Call create_breakpoints_sal for the given arguments.  This is the default
13954    function for the `create_breakpoints_sal' method of
13955    breakpoint_ops.  */
13956
13957 static void
13958 create_breakpoints_sal_default (struct gdbarch *gdbarch,
13959                                 struct linespec_result *canonical,
13960                                 gdb::unique_xmalloc_ptr<char> cond_string,
13961                                 gdb::unique_xmalloc_ptr<char> extra_string,
13962                                 enum bptype type_wanted,
13963                                 enum bpdisp disposition,
13964                                 int thread,
13965                                 int task, int ignore_count,
13966                                 const struct breakpoint_ops *ops,
13967                                 int from_tty, int enabled,
13968                                 int internal, unsigned flags)
13969 {
13970   create_breakpoints_sal (gdbarch, canonical,
13971                           std::move (cond_string),
13972                           std::move (extra_string),
13973                           type_wanted, disposition,
13974                           thread, task, ignore_count, ops, from_tty,
13975                           enabled, internal, flags);
13976 }
13977
13978 /* Decode the line represented by S by calling decode_line_full.  This is the
13979    default function for the `decode_location' method of breakpoint_ops.  */
13980
13981 static std::vector<symtab_and_line>
13982 decode_location_default (struct breakpoint *b,
13983                          const struct event_location *location,
13984                          struct program_space *search_pspace)
13985 {
13986   struct linespec_result canonical;
13987
13988   decode_line_full (location, DECODE_LINE_FUNFIRSTLINE, search_pspace,
13989                     (struct symtab *) NULL, 0,
13990                     &canonical, multiple_symbols_all,
13991                     b->filter);
13992
13993   /* We should get 0 or 1 resulting SALs.  */
13994   gdb_assert (canonical.lsals.size () < 2);
13995
13996   if (!canonical.lsals.empty ())
13997     {
13998       const linespec_sals &lsal = canonical.lsals[0];
13999       return std::move (lsal.sals);
14000     }
14001   return {};
14002 }
14003
14004 /* Reset a breakpoint.  */
14005
14006 static void
14007 breakpoint_re_set_one (breakpoint *b)
14008 {
14009   input_radix = b->input_radix;
14010   set_language (b->language);
14011
14012   b->ops->re_set (b);
14013 }
14014
14015 /* Re-set breakpoint locations for the current program space.
14016    Locations bound to other program spaces are left untouched.  */
14017
14018 void
14019 breakpoint_re_set (void)
14020 {
14021   struct breakpoint *b, *b_tmp;
14022
14023   {
14024     scoped_restore_current_language save_language;
14025     scoped_restore save_input_radix = make_scoped_restore (&input_radix);
14026     scoped_restore_current_pspace_and_thread restore_pspace_thread;
14027
14028     /* Note: we must not try to insert locations until after all
14029        breakpoints have been re-set.  Otherwise, e.g., when re-setting
14030        breakpoint 1, we'd insert the locations of breakpoint 2, which
14031        hadn't been re-set yet, and thus may have stale locations.  */
14032
14033     ALL_BREAKPOINTS_SAFE (b, b_tmp)
14034       {
14035         TRY
14036           {
14037             breakpoint_re_set_one (b);
14038           }
14039         CATCH (ex, RETURN_MASK_ALL)
14040           {
14041             exception_fprintf (gdb_stderr, ex,
14042                                "Error in re-setting breakpoint %d: ",
14043                                b->number);
14044           }
14045         END_CATCH
14046       }
14047
14048     jit_breakpoint_re_set ();
14049   }
14050
14051   create_overlay_event_breakpoint ();
14052   create_longjmp_master_breakpoint ();
14053   create_std_terminate_master_breakpoint ();
14054   create_exception_master_breakpoint ();
14055
14056   /* Now we can insert.  */
14057   update_global_location_list (UGLL_MAY_INSERT);
14058 }
14059 \f
14060 /* Reset the thread number of this breakpoint:
14061
14062    - If the breakpoint is for all threads, leave it as-is.
14063    - Else, reset it to the current thread for inferior_ptid.  */
14064 void
14065 breakpoint_re_set_thread (struct breakpoint *b)
14066 {
14067   if (b->thread != -1)
14068     {
14069       if (in_thread_list (inferior_ptid))
14070         b->thread = ptid_to_global_thread_id (inferior_ptid);
14071
14072       /* We're being called after following a fork.  The new fork is
14073          selected as current, and unless this was a vfork will have a
14074          different program space from the original thread.  Reset that
14075          as well.  */
14076       b->loc->pspace = current_program_space;
14077     }
14078 }
14079
14080 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
14081    If from_tty is nonzero, it prints a message to that effect,
14082    which ends with a period (no newline).  */
14083
14084 void
14085 set_ignore_count (int bptnum, int count, int from_tty)
14086 {
14087   struct breakpoint *b;
14088
14089   if (count < 0)
14090     count = 0;
14091
14092   ALL_BREAKPOINTS (b)
14093     if (b->number == bptnum)
14094     {
14095       if (is_tracepoint (b))
14096         {
14097           if (from_tty && count != 0)
14098             printf_filtered (_("Ignore count ignored for tracepoint %d."),
14099                              bptnum);
14100           return;
14101         }
14102       
14103       b->ignore_count = count;
14104       if (from_tty)
14105         {
14106           if (count == 0)
14107             printf_filtered (_("Will stop next time "
14108                                "breakpoint %d is reached."),
14109                              bptnum);
14110           else if (count == 1)
14111             printf_filtered (_("Will ignore next crossing of breakpoint %d."),
14112                              bptnum);
14113           else
14114             printf_filtered (_("Will ignore next %d "
14115                                "crossings of breakpoint %d."),
14116                              count, bptnum);
14117         }
14118       observer_notify_breakpoint_modified (b);
14119       return;
14120     }
14121
14122   error (_("No breakpoint number %d."), bptnum);
14123 }
14124
14125 /* Command to set ignore-count of breakpoint N to COUNT.  */
14126
14127 static void
14128 ignore_command (char *args, int from_tty)
14129 {
14130   char *p = args;
14131   int num;
14132
14133   if (p == 0)
14134     error_no_arg (_("a breakpoint number"));
14135
14136   num = get_number (&p);
14137   if (num == 0)
14138     error (_("bad breakpoint number: '%s'"), args);
14139   if (*p == 0)
14140     error (_("Second argument (specified ignore-count) is missing."));
14141
14142   set_ignore_count (num,
14143                     longest_to_int (value_as_long (parse_and_eval (p))),
14144                     from_tty);
14145   if (from_tty)
14146     printf_filtered ("\n");
14147 }
14148 \f
14149 /* Call FUNCTION on each of the breakpoints
14150    whose numbers are given in ARGS.  */
14151
14152 static void
14153 map_breakpoint_numbers (const char *args,
14154                         gdb::function_view<void (breakpoint *)> function)
14155 {
14156   int num;
14157   struct breakpoint *b, *tmp;
14158
14159   if (args == 0 || *args == '\0')
14160     error_no_arg (_("one or more breakpoint numbers"));
14161
14162   number_or_range_parser parser (args);
14163
14164   while (!parser.finished ())
14165     {
14166       const char *p = parser.cur_tok ();
14167       bool match = false;
14168
14169       num = parser.get_number ();
14170       if (num == 0)
14171         {
14172           warning (_("bad breakpoint number at or near '%s'"), p);
14173         }
14174       else
14175         {
14176           ALL_BREAKPOINTS_SAFE (b, tmp)
14177             if (b->number == num)
14178               {
14179                 match = true;
14180                 function (b);
14181                 break;
14182               }
14183           if (!match)
14184             printf_unfiltered (_("No breakpoint number %d.\n"), num);
14185         }
14186     }
14187 }
14188
14189 static struct bp_location *
14190 find_location_by_number (const char *number)
14191 {
14192   const char *p1;
14193   int bp_num;
14194   int loc_num;
14195   struct breakpoint *b;
14196   struct bp_location *loc;  
14197
14198   p1 = number;
14199   bp_num = get_number_trailer (&p1, '.');
14200   if (bp_num == 0 || p1[0] != '.')
14201     error (_("Bad breakpoint number '%s'"), number);
14202
14203   ALL_BREAKPOINTS (b)
14204     if (b->number == bp_num)
14205       {
14206         break;
14207       }
14208
14209   if (!b || b->number != bp_num)
14210     error (_("Bad breakpoint number '%s'"), number);
14211   
14212   /* Skip the dot.  */
14213   ++p1;
14214   const char *save = p1;
14215   loc_num = get_number (&p1);
14216   if (loc_num == 0)
14217     error (_("Bad breakpoint location number '%s'"), number);
14218
14219   --loc_num;
14220   loc = b->loc;
14221   for (;loc_num && loc; --loc_num, loc = loc->next)
14222     ;
14223   if (!loc)
14224     error (_("Bad breakpoint location number '%s'"), save);
14225     
14226   return loc;  
14227 }
14228
14229
14230 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
14231    If from_tty is nonzero, it prints a message to that effect,
14232    which ends with a period (no newline).  */
14233
14234 void
14235 disable_breakpoint (struct breakpoint *bpt)
14236 {
14237   /* Never disable a watchpoint scope breakpoint; we want to
14238      hit them when we leave scope so we can delete both the
14239      watchpoint and its scope breakpoint at that time.  */
14240   if (bpt->type == bp_watchpoint_scope)
14241     return;
14242
14243   bpt->enable_state = bp_disabled;
14244
14245   /* Mark breakpoint locations modified.  */
14246   mark_breakpoint_modified (bpt);
14247
14248   if (target_supports_enable_disable_tracepoint ()
14249       && current_trace_status ()->running && is_tracepoint (bpt))
14250     {
14251       struct bp_location *location;
14252      
14253       for (location = bpt->loc; location; location = location->next)
14254         target_disable_tracepoint (location);
14255     }
14256
14257   update_global_location_list (UGLL_DONT_INSERT);
14258
14259   observer_notify_breakpoint_modified (bpt);
14260 }
14261
14262 static void
14263 disable_command (const char *args, int from_tty)
14264 {
14265   if (args == 0)
14266     {
14267       struct breakpoint *bpt;
14268
14269       ALL_BREAKPOINTS (bpt)
14270         if (user_breakpoint_p (bpt))
14271           disable_breakpoint (bpt);
14272     }
14273   else
14274     {
14275       std::string num = extract_arg (&args);
14276
14277       while (!num.empty ())
14278         {
14279           if (num.find ('.') != std::string::npos)
14280             {
14281               struct bp_location *loc = find_location_by_number (num.c_str ());
14282
14283               if (loc)
14284                 {
14285                   if (loc->enabled)
14286                     {
14287                       loc->enabled = 0;
14288                       mark_breakpoint_location_modified (loc);
14289                     }
14290                   if (target_supports_enable_disable_tracepoint ()
14291                       && current_trace_status ()->running && loc->owner
14292                       && is_tracepoint (loc->owner))
14293                     target_disable_tracepoint (loc);
14294                 }
14295               update_global_location_list (UGLL_DONT_INSERT);
14296             }
14297           else
14298             map_breakpoint_numbers
14299               (num.c_str (), [&] (breakpoint *b)
14300                {
14301                  iterate_over_related_breakpoints (b, disable_breakpoint);
14302                });
14303           num = extract_arg (&args);
14304         }
14305     }
14306 }
14307
14308 static void
14309 enable_breakpoint_disp (struct breakpoint *bpt, enum bpdisp disposition,
14310                         int count)
14311 {
14312   int target_resources_ok;
14313
14314   if (bpt->type == bp_hardware_breakpoint)
14315     {
14316       int i;
14317       i = hw_breakpoint_used_count ();
14318       target_resources_ok = 
14319         target_can_use_hardware_watchpoint (bp_hardware_breakpoint, 
14320                                             i + 1, 0);
14321       if (target_resources_ok == 0)
14322         error (_("No hardware breakpoint support in the target."));
14323       else if (target_resources_ok < 0)
14324         error (_("Hardware breakpoints used exceeds limit."));
14325     }
14326
14327   if (is_watchpoint (bpt))
14328     {
14329       /* Initialize it just to avoid a GCC false warning.  */
14330       enum enable_state orig_enable_state = bp_disabled;
14331
14332       TRY
14333         {
14334           struct watchpoint *w = (struct watchpoint *) bpt;
14335
14336           orig_enable_state = bpt->enable_state;
14337           bpt->enable_state = bp_enabled;
14338           update_watchpoint (w, 1 /* reparse */);
14339         }
14340       CATCH (e, RETURN_MASK_ALL)
14341         {
14342           bpt->enable_state = orig_enable_state;
14343           exception_fprintf (gdb_stderr, e, _("Cannot enable watchpoint %d: "),
14344                              bpt->number);
14345           return;
14346         }
14347       END_CATCH
14348     }
14349
14350   bpt->enable_state = bp_enabled;
14351
14352   /* Mark breakpoint locations modified.  */
14353   mark_breakpoint_modified (bpt);
14354
14355   if (target_supports_enable_disable_tracepoint ()
14356       && current_trace_status ()->running && is_tracepoint (bpt))
14357     {
14358       struct bp_location *location;
14359
14360       for (location = bpt->loc; location; location = location->next)
14361         target_enable_tracepoint (location);
14362     }
14363
14364   bpt->disposition = disposition;
14365   bpt->enable_count = count;
14366   update_global_location_list (UGLL_MAY_INSERT);
14367
14368   observer_notify_breakpoint_modified (bpt);
14369 }
14370
14371
14372 void
14373 enable_breakpoint (struct breakpoint *bpt)
14374 {
14375   enable_breakpoint_disp (bpt, bpt->disposition, 0);
14376 }
14377
14378 /* The enable command enables the specified breakpoints (or all defined
14379    breakpoints) so they once again become (or continue to be) effective
14380    in stopping the inferior.  */
14381
14382 static void
14383 enable_command (const char *args, int from_tty)
14384 {
14385   if (args == 0)
14386     {
14387       struct breakpoint *bpt;
14388
14389       ALL_BREAKPOINTS (bpt)
14390         if (user_breakpoint_p (bpt))
14391           enable_breakpoint (bpt);
14392     }
14393   else
14394     {
14395       std::string num = extract_arg (&args);
14396
14397       while (!num.empty ())
14398         {
14399           if (num.find ('.') != std::string::npos)
14400             {
14401               struct bp_location *loc = find_location_by_number (num.c_str ());
14402
14403               if (loc)
14404                 {
14405                   if (!loc->enabled)
14406                     {
14407                       loc->enabled = 1;
14408                       mark_breakpoint_location_modified (loc);
14409                     }
14410                   if (target_supports_enable_disable_tracepoint ()
14411                       && current_trace_status ()->running && loc->owner
14412                       && is_tracepoint (loc->owner))
14413                     target_enable_tracepoint (loc);
14414                 }
14415               update_global_location_list (UGLL_MAY_INSERT);
14416             }
14417           else
14418             map_breakpoint_numbers
14419               (num.c_str (), [&] (breakpoint *b)
14420                {
14421                  iterate_over_related_breakpoints (b, enable_breakpoint);
14422                });
14423           num = extract_arg (&args);
14424         }
14425     }
14426 }
14427
14428 static void
14429 enable_once_command (const char *args, int from_tty)
14430 {
14431   map_breakpoint_numbers
14432     (args, [&] (breakpoint *b)
14433      {
14434        iterate_over_related_breakpoints
14435          (b, [&] (breakpoint *bpt)
14436           {
14437             enable_breakpoint_disp (bpt, disp_disable, 1);
14438           });
14439      });
14440 }
14441
14442 static void
14443 enable_count_command (const char *args, int from_tty)
14444 {
14445   int count;
14446
14447   if (args == NULL)
14448     error_no_arg (_("hit count"));
14449
14450   count = get_number (&args);
14451
14452   map_breakpoint_numbers
14453     (args, [&] (breakpoint *b)
14454      {
14455        iterate_over_related_breakpoints
14456          (b, [&] (breakpoint *bpt)
14457           {
14458             enable_breakpoint_disp (bpt, disp_disable, count);
14459           });
14460      });
14461 }
14462
14463 static void
14464 enable_delete_command (const char *args, int from_tty)
14465 {
14466   map_breakpoint_numbers
14467     (args, [&] (breakpoint *b)
14468      {
14469        iterate_over_related_breakpoints
14470          (b, [&] (breakpoint *bpt)
14471           {
14472             enable_breakpoint_disp (bpt, disp_del, 1);
14473           });
14474      });
14475 }
14476 \f
14477 static void
14478 set_breakpoint_cmd (const char *args, int from_tty)
14479 {
14480 }
14481
14482 static void
14483 show_breakpoint_cmd (const char *args, int from_tty)
14484 {
14485 }
14486
14487 /* Invalidate last known value of any hardware watchpoint if
14488    the memory which that value represents has been written to by
14489    GDB itself.  */
14490
14491 static void
14492 invalidate_bp_value_on_memory_change (struct inferior *inferior,
14493                                       CORE_ADDR addr, ssize_t len,
14494                                       const bfd_byte *data)
14495 {
14496   struct breakpoint *bp;
14497
14498   ALL_BREAKPOINTS (bp)
14499     if (bp->enable_state == bp_enabled
14500         && bp->type == bp_hardware_watchpoint)
14501       {
14502         struct watchpoint *wp = (struct watchpoint *) bp;
14503
14504         if (wp->val_valid && wp->val)
14505           {
14506             struct bp_location *loc;
14507
14508             for (loc = bp->loc; loc != NULL; loc = loc->next)
14509               if (loc->loc_type == bp_loc_hardware_watchpoint
14510                   && loc->address + loc->length > addr
14511                   && addr + len > loc->address)
14512                 {
14513                   value_free (wp->val);
14514                   wp->val = NULL;
14515                   wp->val_valid = 0;
14516                 }
14517           }
14518       }
14519 }
14520
14521 /* Create and insert a breakpoint for software single step.  */
14522
14523 void
14524 insert_single_step_breakpoint (struct gdbarch *gdbarch,
14525                                const address_space *aspace,
14526                                CORE_ADDR next_pc)
14527 {
14528   struct thread_info *tp = inferior_thread ();
14529   struct symtab_and_line sal;
14530   CORE_ADDR pc = next_pc;
14531
14532   if (tp->control.single_step_breakpoints == NULL)
14533     {
14534       tp->control.single_step_breakpoints
14535         = new_single_step_breakpoint (tp->global_num, gdbarch);
14536     }
14537
14538   sal = find_pc_line (pc, 0);
14539   sal.pc = pc;
14540   sal.section = find_pc_overlay (pc);
14541   sal.explicit_pc = 1;
14542   add_location_to_breakpoint (tp->control.single_step_breakpoints, &sal);
14543
14544   update_global_location_list (UGLL_INSERT);
14545 }
14546
14547 /* Insert single step breakpoints according to the current state.  */
14548
14549 int
14550 insert_single_step_breakpoints (struct gdbarch *gdbarch)
14551 {
14552   struct regcache *regcache = get_current_regcache ();
14553   std::vector<CORE_ADDR> next_pcs;
14554
14555   next_pcs = gdbarch_software_single_step (gdbarch, regcache);
14556
14557   if (!next_pcs.empty ())
14558     {
14559       struct frame_info *frame = get_current_frame ();
14560       struct address_space *aspace = get_frame_address_space (frame);
14561
14562       for (CORE_ADDR pc : next_pcs)
14563         insert_single_step_breakpoint (gdbarch, aspace, pc);
14564
14565       return 1;
14566     }
14567   else
14568     return 0;
14569 }
14570
14571 /* See breakpoint.h.  */
14572
14573 int
14574 breakpoint_has_location_inserted_here (struct breakpoint *bp,
14575                                        const address_space *aspace,
14576                                        CORE_ADDR pc)
14577 {
14578   struct bp_location *loc;
14579
14580   for (loc = bp->loc; loc != NULL; loc = loc->next)
14581     if (loc->inserted
14582         && breakpoint_location_address_match (loc, aspace, pc))
14583       return 1;
14584
14585   return 0;
14586 }
14587
14588 /* Check whether a software single-step breakpoint is inserted at
14589    PC.  */
14590
14591 int
14592 single_step_breakpoint_inserted_here_p (const address_space *aspace,
14593                                         CORE_ADDR pc)
14594 {
14595   struct breakpoint *bpt;
14596
14597   ALL_BREAKPOINTS (bpt)
14598     {
14599       if (bpt->type == bp_single_step
14600           && breakpoint_has_location_inserted_here (bpt, aspace, pc))
14601         return 1;
14602     }
14603   return 0;
14604 }
14605
14606 /* Tracepoint-specific operations.  */
14607
14608 /* Set tracepoint count to NUM.  */
14609 static void
14610 set_tracepoint_count (int num)
14611 {
14612   tracepoint_count = num;
14613   set_internalvar_integer (lookup_internalvar ("tpnum"), num);
14614 }
14615
14616 static void
14617 trace_command (char *arg_in, int from_tty)
14618 {
14619   const char *arg = arg_in;
14620   struct breakpoint_ops *ops;
14621
14622   event_location_up location = string_to_event_location (&arg,
14623                                                          current_language);
14624   if (location != NULL
14625       && event_location_type (location.get ()) == PROBE_LOCATION)
14626     ops = &tracepoint_probe_breakpoint_ops;
14627   else
14628     ops = &tracepoint_breakpoint_ops;
14629
14630   create_breakpoint (get_current_arch (),
14631                      location.get (),
14632                      NULL, 0, arg, 1 /* parse arg */,
14633                      0 /* tempflag */,
14634                      bp_tracepoint /* type_wanted */,
14635                      0 /* Ignore count */,
14636                      pending_break_support,
14637                      ops,
14638                      from_tty,
14639                      1 /* enabled */,
14640                      0 /* internal */, 0);
14641 }
14642
14643 static void
14644 ftrace_command (char *arg_in, int from_tty)
14645 {
14646   const char *arg = arg_in;
14647   event_location_up location = string_to_event_location (&arg,
14648                                                          current_language);
14649   create_breakpoint (get_current_arch (),
14650                      location.get (),
14651                      NULL, 0, arg, 1 /* parse arg */,
14652                      0 /* tempflag */,
14653                      bp_fast_tracepoint /* type_wanted */,
14654                      0 /* Ignore count */,
14655                      pending_break_support,
14656                      &tracepoint_breakpoint_ops,
14657                      from_tty,
14658                      1 /* enabled */,
14659                      0 /* internal */, 0);
14660 }
14661
14662 /* strace command implementation.  Creates a static tracepoint.  */
14663
14664 static void
14665 strace_command (char *arg_in, int from_tty)
14666 {
14667   const char *arg = arg_in;
14668   struct breakpoint_ops *ops;
14669   event_location_up location;
14670
14671   /* Decide if we are dealing with a static tracepoint marker (`-m'),
14672      or with a normal static tracepoint.  */
14673   if (arg && startswith (arg, "-m") && isspace (arg[2]))
14674     {
14675       ops = &strace_marker_breakpoint_ops;
14676       location = new_linespec_location (&arg);
14677     }
14678   else
14679     {
14680       ops = &tracepoint_breakpoint_ops;
14681       location = string_to_event_location (&arg, current_language);
14682     }
14683
14684   create_breakpoint (get_current_arch (),
14685                      location.get (),
14686                      NULL, 0, arg, 1 /* parse arg */,
14687                      0 /* tempflag */,
14688                      bp_static_tracepoint /* type_wanted */,
14689                      0 /* Ignore count */,
14690                      pending_break_support,
14691                      ops,
14692                      from_tty,
14693                      1 /* enabled */,
14694                      0 /* internal */, 0);
14695 }
14696
14697 /* Set up a fake reader function that gets command lines from a linked
14698    list that was acquired during tracepoint uploading.  */
14699
14700 static struct uploaded_tp *this_utp;
14701 static int next_cmd;
14702
14703 static char *
14704 read_uploaded_action (void)
14705 {
14706   char *rslt;
14707
14708   VEC_iterate (char_ptr, this_utp->cmd_strings, next_cmd, rslt);
14709
14710   next_cmd++;
14711
14712   return rslt;
14713 }
14714
14715 /* Given information about a tracepoint as recorded on a target (which
14716    can be either a live system or a trace file), attempt to create an
14717    equivalent GDB tracepoint.  This is not a reliable process, since
14718    the target does not necessarily have all the information used when
14719    the tracepoint was originally defined.  */
14720   
14721 struct tracepoint *
14722 create_tracepoint_from_upload (struct uploaded_tp *utp)
14723 {
14724   const char *addr_str;
14725   char small_buf[100];
14726   struct tracepoint *tp;
14727
14728   if (utp->at_string)
14729     addr_str = utp->at_string;
14730   else
14731     {
14732       /* In the absence of a source location, fall back to raw
14733          address.  Since there is no way to confirm that the address
14734          means the same thing as when the trace was started, warn the
14735          user.  */
14736       warning (_("Uploaded tracepoint %d has no "
14737                  "source location, using raw address"),
14738                utp->number);
14739       xsnprintf (small_buf, sizeof (small_buf), "*%s", hex_string (utp->addr));
14740       addr_str = small_buf;
14741     }
14742
14743   /* There's not much we can do with a sequence of bytecodes.  */
14744   if (utp->cond && !utp->cond_string)
14745     warning (_("Uploaded tracepoint %d condition "
14746                "has no source form, ignoring it"),
14747              utp->number);
14748
14749   event_location_up location = string_to_event_location (&addr_str,
14750                                                          current_language);
14751   if (!create_breakpoint (get_current_arch (),
14752                           location.get (),
14753                           utp->cond_string, -1, addr_str,
14754                           0 /* parse cond/thread */,
14755                           0 /* tempflag */,
14756                           utp->type /* type_wanted */,
14757                           0 /* Ignore count */,
14758                           pending_break_support,
14759                           &tracepoint_breakpoint_ops,
14760                           0 /* from_tty */,
14761                           utp->enabled /* enabled */,
14762                           0 /* internal */,
14763                           CREATE_BREAKPOINT_FLAGS_INSERTED))
14764     return NULL;
14765
14766   /* Get the tracepoint we just created.  */
14767   tp = get_tracepoint (tracepoint_count);
14768   gdb_assert (tp != NULL);
14769
14770   if (utp->pass > 0)
14771     {
14772       xsnprintf (small_buf, sizeof (small_buf), "%d %d", utp->pass,
14773                  tp->number);
14774
14775       trace_pass_command (small_buf, 0);
14776     }
14777
14778   /* If we have uploaded versions of the original commands, set up a
14779      special-purpose "reader" function and call the usual command line
14780      reader, then pass the result to the breakpoint command-setting
14781      function.  */
14782   if (!VEC_empty (char_ptr, utp->cmd_strings))
14783     {
14784       command_line_up cmd_list;
14785
14786       this_utp = utp;
14787       next_cmd = 0;
14788
14789       cmd_list = read_command_lines_1 (read_uploaded_action, 1, NULL, NULL);
14790
14791       breakpoint_set_commands (tp, std::move (cmd_list));
14792     }
14793   else if (!VEC_empty (char_ptr, utp->actions)
14794            || !VEC_empty (char_ptr, utp->step_actions))
14795     warning (_("Uploaded tracepoint %d actions "
14796                "have no source form, ignoring them"),
14797              utp->number);
14798
14799   /* Copy any status information that might be available.  */
14800   tp->hit_count = utp->hit_count;
14801   tp->traceframe_usage = utp->traceframe_usage;
14802
14803   return tp;
14804 }
14805   
14806 /* Print information on tracepoint number TPNUM_EXP, or all if
14807    omitted.  */
14808
14809 static void
14810 info_tracepoints_command (char *args, int from_tty)
14811 {
14812   struct ui_out *uiout = current_uiout;
14813   int num_printed;
14814
14815   num_printed = breakpoint_1 (args, 0, is_tracepoint);
14816
14817   if (num_printed == 0)
14818     {
14819       if (args == NULL || *args == '\0')
14820         uiout->message ("No tracepoints.\n");
14821       else
14822         uiout->message ("No tracepoint matching '%s'.\n", args);
14823     }
14824
14825   default_collect_info ();
14826 }
14827
14828 /* The 'enable trace' command enables tracepoints.
14829    Not supported by all targets.  */
14830 static void
14831 enable_trace_command (char *args, int from_tty)
14832 {
14833   enable_command (args, from_tty);
14834 }
14835
14836 /* The 'disable trace' command disables tracepoints.
14837    Not supported by all targets.  */
14838 static void
14839 disable_trace_command (char *args, int from_tty)
14840 {
14841   disable_command (args, from_tty);
14842 }
14843
14844 /* Remove a tracepoint (or all if no argument).  */
14845 static void
14846 delete_trace_command (const char *arg, int from_tty)
14847 {
14848   struct breakpoint *b, *b_tmp;
14849
14850   dont_repeat ();
14851
14852   if (arg == 0)
14853     {
14854       int breaks_to_delete = 0;
14855
14856       /* Delete all breakpoints if no argument.
14857          Do not delete internal or call-dummy breakpoints, these
14858          have to be deleted with an explicit breakpoint number 
14859          argument.  */
14860       ALL_TRACEPOINTS (b)
14861         if (is_tracepoint (b) && user_breakpoint_p (b))
14862           {
14863             breaks_to_delete = 1;
14864             break;
14865           }
14866
14867       /* Ask user only if there are some breakpoints to delete.  */
14868       if (!from_tty
14869           || (breaks_to_delete && query (_("Delete all tracepoints? "))))
14870         {
14871           ALL_BREAKPOINTS_SAFE (b, b_tmp)
14872             if (is_tracepoint (b) && user_breakpoint_p (b))
14873               delete_breakpoint (b);
14874         }
14875     }
14876   else
14877     map_breakpoint_numbers
14878       (arg, [&] (breakpoint *b)
14879        {
14880          iterate_over_related_breakpoints (b, delete_breakpoint);
14881        });
14882 }
14883
14884 /* Helper function for trace_pass_command.  */
14885
14886 static void
14887 trace_pass_set_count (struct tracepoint *tp, int count, int from_tty)
14888 {
14889   tp->pass_count = count;
14890   observer_notify_breakpoint_modified (tp);
14891   if (from_tty)
14892     printf_filtered (_("Setting tracepoint %d's passcount to %d\n"),
14893                      tp->number, count);
14894 }
14895
14896 /* Set passcount for tracepoint.
14897
14898    First command argument is passcount, second is tracepoint number.
14899    If tracepoint number omitted, apply to most recently defined.
14900    Also accepts special argument "all".  */
14901
14902 static void
14903 trace_pass_command (char *args, int from_tty)
14904 {
14905   struct tracepoint *t1;
14906   unsigned int count;
14907
14908   if (args == 0 || *args == 0)
14909     error (_("passcount command requires an "
14910              "argument (count + optional TP num)"));
14911
14912   count = strtoul (args, &args, 10);    /* Count comes first, then TP num.  */
14913
14914   args = skip_spaces (args);
14915   if (*args && strncasecmp (args, "all", 3) == 0)
14916     {
14917       struct breakpoint *b;
14918
14919       args += 3;                        /* Skip special argument "all".  */
14920       if (*args)
14921         error (_("Junk at end of arguments."));
14922
14923       ALL_TRACEPOINTS (b)
14924       {
14925         t1 = (struct tracepoint *) b;
14926         trace_pass_set_count (t1, count, from_tty);
14927       }
14928     }
14929   else if (*args == '\0')
14930     {
14931       t1 = get_tracepoint_by_number (&args, NULL);
14932       if (t1)
14933         trace_pass_set_count (t1, count, from_tty);
14934     }
14935   else
14936     {
14937       number_or_range_parser parser (args);
14938       while (!parser.finished ())
14939         {
14940           t1 = get_tracepoint_by_number (&args, &parser);
14941           if (t1)
14942             trace_pass_set_count (t1, count, from_tty);
14943         }
14944     }
14945 }
14946
14947 struct tracepoint *
14948 get_tracepoint (int num)
14949 {
14950   struct breakpoint *t;
14951
14952   ALL_TRACEPOINTS (t)
14953     if (t->number == num)
14954       return (struct tracepoint *) t;
14955
14956   return NULL;
14957 }
14958
14959 /* Find the tracepoint with the given target-side number (which may be
14960    different from the tracepoint number after disconnecting and
14961    reconnecting).  */
14962
14963 struct tracepoint *
14964 get_tracepoint_by_number_on_target (int num)
14965 {
14966   struct breakpoint *b;
14967
14968   ALL_TRACEPOINTS (b)
14969     {
14970       struct tracepoint *t = (struct tracepoint *) b;
14971
14972       if (t->number_on_target == num)
14973         return t;
14974     }
14975
14976   return NULL;
14977 }
14978
14979 /* Utility: parse a tracepoint number and look it up in the list.
14980    If STATE is not NULL, use, get_number_or_range_state and ignore ARG.
14981    If the argument is missing, the most recent tracepoint
14982    (tracepoint_count) is returned.  */
14983
14984 struct tracepoint *
14985 get_tracepoint_by_number (char **arg,
14986                           number_or_range_parser *parser)
14987 {
14988   struct breakpoint *t;
14989   int tpnum;
14990   char *instring = arg == NULL ? NULL : *arg;
14991
14992   if (parser != NULL)
14993     {
14994       gdb_assert (!parser->finished ());
14995       tpnum = parser->get_number ();
14996     }
14997   else if (arg == NULL || *arg == NULL || ! **arg)
14998     tpnum = tracepoint_count;
14999   else
15000     tpnum = get_number (arg);
15001
15002   if (tpnum <= 0)
15003     {
15004       if (instring && *instring)
15005         printf_filtered (_("bad tracepoint number at or near '%s'\n"), 
15006                          instring);
15007       else
15008         printf_filtered (_("No previous tracepoint\n"));
15009       return NULL;
15010     }
15011
15012   ALL_TRACEPOINTS (t)
15013     if (t->number == tpnum)
15014     {
15015       return (struct tracepoint *) t;
15016     }
15017
15018   printf_unfiltered ("No tracepoint number %d.\n", tpnum);
15019   return NULL;
15020 }
15021
15022 void
15023 print_recreate_thread (struct breakpoint *b, struct ui_file *fp)
15024 {
15025   if (b->thread != -1)
15026     fprintf_unfiltered (fp, " thread %d", b->thread);
15027
15028   if (b->task != 0)
15029     fprintf_unfiltered (fp, " task %d", b->task);
15030
15031   fprintf_unfiltered (fp, "\n");
15032 }
15033
15034 /* Save information on user settable breakpoints (watchpoints, etc) to
15035    a new script file named FILENAME.  If FILTER is non-NULL, call it
15036    on each breakpoint and only include the ones for which it returns
15037    non-zero.  */
15038
15039 static void
15040 save_breakpoints (const char *filename, int from_tty,
15041                   int (*filter) (const struct breakpoint *))
15042 {
15043   struct breakpoint *tp;
15044   int any = 0;
15045   int extra_trace_bits = 0;
15046
15047   if (filename == 0 || *filename == 0)
15048     error (_("Argument required (file name in which to save)"));
15049
15050   /* See if we have anything to save.  */
15051   ALL_BREAKPOINTS (tp)
15052   {
15053     /* Skip internal and momentary breakpoints.  */
15054     if (!user_breakpoint_p (tp))
15055       continue;
15056
15057     /* If we have a filter, only save the breakpoints it accepts.  */
15058     if (filter && !filter (tp))
15059       continue;
15060
15061     any = 1;
15062
15063     if (is_tracepoint (tp))
15064       {
15065         extra_trace_bits = 1;
15066
15067         /* We can stop searching.  */
15068         break;
15069       }
15070   }
15071
15072   if (!any)
15073     {
15074       warning (_("Nothing to save."));
15075       return;
15076     }
15077
15078   gdb::unique_xmalloc_ptr<char> expanded_filename (tilde_expand (filename));
15079
15080   stdio_file fp;
15081
15082   if (!fp.open (expanded_filename.get (), "w"))
15083     error (_("Unable to open file '%s' for saving (%s)"),
15084            expanded_filename.get (), safe_strerror (errno));
15085
15086   if (extra_trace_bits)
15087     save_trace_state_variables (&fp);
15088
15089   ALL_BREAKPOINTS (tp)
15090   {
15091     /* Skip internal and momentary breakpoints.  */
15092     if (!user_breakpoint_p (tp))
15093       continue;
15094
15095     /* If we have a filter, only save the breakpoints it accepts.  */
15096     if (filter && !filter (tp))
15097       continue;
15098
15099     tp->ops->print_recreate (tp, &fp);
15100
15101     /* Note, we can't rely on tp->number for anything, as we can't
15102        assume the recreated breakpoint numbers will match.  Use $bpnum
15103        instead.  */
15104
15105     if (tp->cond_string)
15106       fp.printf ("  condition $bpnum %s\n", tp->cond_string);
15107
15108     if (tp->ignore_count)
15109       fp.printf ("  ignore $bpnum %d\n", tp->ignore_count);
15110
15111     if (tp->type != bp_dprintf && tp->commands)
15112       {
15113         fp.puts ("  commands\n");
15114         
15115         current_uiout->redirect (&fp);
15116         TRY
15117           {
15118             print_command_lines (current_uiout, tp->commands.get (), 2);
15119           }
15120         CATCH (ex, RETURN_MASK_ALL)
15121           {
15122           current_uiout->redirect (NULL);
15123             throw_exception (ex);
15124           }
15125         END_CATCH
15126
15127         current_uiout->redirect (NULL);
15128         fp.puts ("  end\n");
15129       }
15130
15131     if (tp->enable_state == bp_disabled)
15132       fp.puts ("disable $bpnum\n");
15133
15134     /* If this is a multi-location breakpoint, check if the locations
15135        should be individually disabled.  Watchpoint locations are
15136        special, and not user visible.  */
15137     if (!is_watchpoint (tp) && tp->loc && tp->loc->next)
15138       {
15139         struct bp_location *loc;
15140         int n = 1;
15141
15142         for (loc = tp->loc; loc != NULL; loc = loc->next, n++)
15143           if (!loc->enabled)
15144             fp.printf ("disable $bpnum.%d\n", n);
15145       }
15146   }
15147
15148   if (extra_trace_bits && *default_collect)
15149     fp.printf ("set default-collect %s\n", default_collect);
15150
15151   if (from_tty)
15152     printf_filtered (_("Saved to file '%s'.\n"), expanded_filename.get ());
15153 }
15154
15155 /* The `save breakpoints' command.  */
15156
15157 static void
15158 save_breakpoints_command (const char *args, int from_tty)
15159 {
15160   save_breakpoints (args, from_tty, NULL);
15161 }
15162
15163 /* The `save tracepoints' command.  */
15164
15165 static void
15166 save_tracepoints_command (const char *args, int from_tty)
15167 {
15168   save_breakpoints (args, from_tty, is_tracepoint);
15169 }
15170
15171 /* Create a vector of all tracepoints.  */
15172
15173 VEC(breakpoint_p) *
15174 all_tracepoints (void)
15175 {
15176   VEC(breakpoint_p) *tp_vec = 0;
15177   struct breakpoint *tp;
15178
15179   ALL_TRACEPOINTS (tp)
15180   {
15181     VEC_safe_push (breakpoint_p, tp_vec, tp);
15182   }
15183
15184   return tp_vec;
15185 }
15186
15187 \f
15188 /* This help string is used to consolidate all the help string for specifying
15189    locations used by several commands.  */
15190
15191 #define LOCATION_HELP_STRING \
15192 "Linespecs are colon-separated lists of location parameters, such as\n\
15193 source filename, function name, label name, and line number.\n\
15194 Example: To specify the start of a label named \"the_top\" in the\n\
15195 function \"fact\" in the file \"factorial.c\", use\n\
15196 \"factorial.c:fact:the_top\".\n\
15197 \n\
15198 Address locations begin with \"*\" and specify an exact address in the\n\
15199 program.  Example: To specify the fourth byte past the start function\n\
15200 \"main\", use \"*main + 4\".\n\
15201 \n\
15202 Explicit locations are similar to linespecs but use an option/argument\n\
15203 syntax to specify location parameters.\n\
15204 Example: To specify the start of the label named \"the_top\" in the\n\
15205 function \"fact\" in the file \"factorial.c\", use \"-source factorial.c\n\
15206 -function fact -label the_top\".\n"
15207
15208 /* This help string is used for the break, hbreak, tbreak and thbreak
15209    commands.  It is defined as a macro to prevent duplication.
15210    COMMAND should be a string constant containing the name of the
15211    command.  */
15212
15213 #define BREAK_ARGS_HELP(command) \
15214 command" [PROBE_MODIFIER] [LOCATION] [thread THREADNUM] [if CONDITION]\n\
15215 PROBE_MODIFIER shall be present if the command is to be placed in a\n\
15216 probe point.  Accepted values are `-probe' (for a generic, automatically\n\
15217 guessed probe type), `-probe-stap' (for a SystemTap probe) or \n\
15218 `-probe-dtrace' (for a DTrace probe).\n\
15219 LOCATION may be a linespec, address, or explicit location as described\n\
15220 below.\n\
15221 \n\
15222 With no LOCATION, uses current execution address of the selected\n\
15223 stack frame.  This is useful for breaking on return to a stack frame.\n\
15224 \n\
15225 THREADNUM is the number from \"info threads\".\n\
15226 CONDITION is a boolean expression.\n\
15227 \n" LOCATION_HELP_STRING "\n\
15228 Multiple breakpoints at one place are permitted, and useful if their\n\
15229 conditions are different.\n\
15230 \n\
15231 Do \"help breakpoints\" for info on other commands dealing with breakpoints."
15232
15233 /* List of subcommands for "catch".  */
15234 static struct cmd_list_element *catch_cmdlist;
15235
15236 /* List of subcommands for "tcatch".  */
15237 static struct cmd_list_element *tcatch_cmdlist;
15238
15239 void
15240 add_catch_command (const char *name, const char *docstring,
15241                    cmd_sfunc_ftype *sfunc,
15242                    completer_ftype *completer,
15243                    void *user_data_catch,
15244                    void *user_data_tcatch)
15245 {
15246   struct cmd_list_element *command;
15247
15248   command = add_cmd (name, class_breakpoint, docstring,
15249                      &catch_cmdlist);
15250   set_cmd_sfunc (command, sfunc);
15251   set_cmd_context (command, user_data_catch);
15252   set_cmd_completer (command, completer);
15253
15254   command = add_cmd (name, class_breakpoint, docstring,
15255                      &tcatch_cmdlist);
15256   set_cmd_sfunc (command, sfunc);
15257   set_cmd_context (command, user_data_tcatch);
15258   set_cmd_completer (command, completer);
15259 }
15260
15261 static void
15262 save_command (const char *arg, int from_tty)
15263 {
15264   printf_unfiltered (_("\"save\" must be followed by "
15265                        "the name of a save subcommand.\n"));
15266   help_list (save_cmdlist, "save ", all_commands, gdb_stdout);
15267 }
15268
15269 struct breakpoint *
15270 iterate_over_breakpoints (int (*callback) (struct breakpoint *, void *),
15271                           void *data)
15272 {
15273   struct breakpoint *b, *b_tmp;
15274
15275   ALL_BREAKPOINTS_SAFE (b, b_tmp)
15276     {
15277       if ((*callback) (b, data))
15278         return b;
15279     }
15280
15281   return NULL;
15282 }
15283
15284 /* Zero if any of the breakpoint's locations could be a location where
15285    functions have been inlined, nonzero otherwise.  */
15286
15287 static int
15288 is_non_inline_function (struct breakpoint *b)
15289 {
15290   /* The shared library event breakpoint is set on the address of a
15291      non-inline function.  */
15292   if (b->type == bp_shlib_event)
15293     return 1;
15294
15295   return 0;
15296 }
15297
15298 /* Nonzero if the specified PC cannot be a location where functions
15299    have been inlined.  */
15300
15301 int
15302 pc_at_non_inline_function (const address_space *aspace, CORE_ADDR pc,
15303                            const struct target_waitstatus *ws)
15304 {
15305   struct breakpoint *b;
15306   struct bp_location *bl;
15307
15308   ALL_BREAKPOINTS (b)
15309     {
15310       if (!is_non_inline_function (b))
15311         continue;
15312
15313       for (bl = b->loc; bl != NULL; bl = bl->next)
15314         {
15315           if (!bl->shlib_disabled
15316               && bpstat_check_location (bl, aspace, pc, ws))
15317             return 1;
15318         }
15319     }
15320
15321   return 0;
15322 }
15323
15324 /* Remove any references to OBJFILE which is going to be freed.  */
15325
15326 void
15327 breakpoint_free_objfile (struct objfile *objfile)
15328 {
15329   struct bp_location **locp, *loc;
15330
15331   ALL_BP_LOCATIONS (loc, locp)
15332     if (loc->symtab != NULL && SYMTAB_OBJFILE (loc->symtab) == objfile)
15333       loc->symtab = NULL;
15334 }
15335
15336 void
15337 initialize_breakpoint_ops (void)
15338 {
15339   static int initialized = 0;
15340
15341   struct breakpoint_ops *ops;
15342
15343   if (initialized)
15344     return;
15345   initialized = 1;
15346
15347   /* The breakpoint_ops structure to be inherit by all kinds of
15348      breakpoints (real breakpoints, i.e., user "break" breakpoints,
15349      internal and momentary breakpoints, etc.).  */
15350   ops = &bkpt_base_breakpoint_ops;
15351   *ops = base_breakpoint_ops;
15352   ops->re_set = bkpt_re_set;
15353   ops->insert_location = bkpt_insert_location;
15354   ops->remove_location = bkpt_remove_location;
15355   ops->breakpoint_hit = bkpt_breakpoint_hit;
15356   ops->create_sals_from_location = bkpt_create_sals_from_location;
15357   ops->create_breakpoints_sal = bkpt_create_breakpoints_sal;
15358   ops->decode_location = bkpt_decode_location;
15359
15360   /* The breakpoint_ops structure to be used in regular breakpoints.  */
15361   ops = &bkpt_breakpoint_ops;
15362   *ops = bkpt_base_breakpoint_ops;
15363   ops->re_set = bkpt_re_set;
15364   ops->resources_needed = bkpt_resources_needed;
15365   ops->print_it = bkpt_print_it;
15366   ops->print_mention = bkpt_print_mention;
15367   ops->print_recreate = bkpt_print_recreate;
15368
15369   /* Ranged breakpoints.  */
15370   ops = &ranged_breakpoint_ops;
15371   *ops = bkpt_breakpoint_ops;
15372   ops->breakpoint_hit = breakpoint_hit_ranged_breakpoint;
15373   ops->resources_needed = resources_needed_ranged_breakpoint;
15374   ops->print_it = print_it_ranged_breakpoint;
15375   ops->print_one = print_one_ranged_breakpoint;
15376   ops->print_one_detail = print_one_detail_ranged_breakpoint;
15377   ops->print_mention = print_mention_ranged_breakpoint;
15378   ops->print_recreate = print_recreate_ranged_breakpoint;
15379
15380   /* Internal breakpoints.  */
15381   ops = &internal_breakpoint_ops;
15382   *ops = bkpt_base_breakpoint_ops;
15383   ops->re_set = internal_bkpt_re_set;
15384   ops->check_status = internal_bkpt_check_status;
15385   ops->print_it = internal_bkpt_print_it;
15386   ops->print_mention = internal_bkpt_print_mention;
15387
15388   /* Momentary breakpoints.  */
15389   ops = &momentary_breakpoint_ops;
15390   *ops = bkpt_base_breakpoint_ops;
15391   ops->re_set = momentary_bkpt_re_set;
15392   ops->check_status = momentary_bkpt_check_status;
15393   ops->print_it = momentary_bkpt_print_it;
15394   ops->print_mention = momentary_bkpt_print_mention;
15395
15396   /* Probe breakpoints.  */
15397   ops = &bkpt_probe_breakpoint_ops;
15398   *ops = bkpt_breakpoint_ops;
15399   ops->insert_location = bkpt_probe_insert_location;
15400   ops->remove_location = bkpt_probe_remove_location;
15401   ops->create_sals_from_location = bkpt_probe_create_sals_from_location;
15402   ops->decode_location = bkpt_probe_decode_location;
15403
15404   /* Watchpoints.  */
15405   ops = &watchpoint_breakpoint_ops;
15406   *ops = base_breakpoint_ops;
15407   ops->re_set = re_set_watchpoint;
15408   ops->insert_location = insert_watchpoint;
15409   ops->remove_location = remove_watchpoint;
15410   ops->breakpoint_hit = breakpoint_hit_watchpoint;
15411   ops->check_status = check_status_watchpoint;
15412   ops->resources_needed = resources_needed_watchpoint;
15413   ops->works_in_software_mode = works_in_software_mode_watchpoint;
15414   ops->print_it = print_it_watchpoint;
15415   ops->print_mention = print_mention_watchpoint;
15416   ops->print_recreate = print_recreate_watchpoint;
15417   ops->explains_signal = explains_signal_watchpoint;
15418
15419   /* Masked watchpoints.  */
15420   ops = &masked_watchpoint_breakpoint_ops;
15421   *ops = watchpoint_breakpoint_ops;
15422   ops->insert_location = insert_masked_watchpoint;
15423   ops->remove_location = remove_masked_watchpoint;
15424   ops->resources_needed = resources_needed_masked_watchpoint;
15425   ops->works_in_software_mode = works_in_software_mode_masked_watchpoint;
15426   ops->print_it = print_it_masked_watchpoint;
15427   ops->print_one_detail = print_one_detail_masked_watchpoint;
15428   ops->print_mention = print_mention_masked_watchpoint;
15429   ops->print_recreate = print_recreate_masked_watchpoint;
15430
15431   /* Tracepoints.  */
15432   ops = &tracepoint_breakpoint_ops;
15433   *ops = base_breakpoint_ops;
15434   ops->re_set = tracepoint_re_set;
15435   ops->breakpoint_hit = tracepoint_breakpoint_hit;
15436   ops->print_one_detail = tracepoint_print_one_detail;
15437   ops->print_mention = tracepoint_print_mention;
15438   ops->print_recreate = tracepoint_print_recreate;
15439   ops->create_sals_from_location = tracepoint_create_sals_from_location;
15440   ops->create_breakpoints_sal = tracepoint_create_breakpoints_sal;
15441   ops->decode_location = tracepoint_decode_location;
15442
15443   /* Probe tracepoints.  */
15444   ops = &tracepoint_probe_breakpoint_ops;
15445   *ops = tracepoint_breakpoint_ops;
15446   ops->create_sals_from_location = tracepoint_probe_create_sals_from_location;
15447   ops->decode_location = tracepoint_probe_decode_location;
15448
15449   /* Static tracepoints with marker (`-m').  */
15450   ops = &strace_marker_breakpoint_ops;
15451   *ops = tracepoint_breakpoint_ops;
15452   ops->create_sals_from_location = strace_marker_create_sals_from_location;
15453   ops->create_breakpoints_sal = strace_marker_create_breakpoints_sal;
15454   ops->decode_location = strace_marker_decode_location;
15455
15456   /* Fork catchpoints.  */
15457   ops = &catch_fork_breakpoint_ops;
15458   *ops = base_breakpoint_ops;
15459   ops->insert_location = insert_catch_fork;
15460   ops->remove_location = remove_catch_fork;
15461   ops->breakpoint_hit = breakpoint_hit_catch_fork;
15462   ops->print_it = print_it_catch_fork;
15463   ops->print_one = print_one_catch_fork;
15464   ops->print_mention = print_mention_catch_fork;
15465   ops->print_recreate = print_recreate_catch_fork;
15466
15467   /* Vfork catchpoints.  */
15468   ops = &catch_vfork_breakpoint_ops;
15469   *ops = base_breakpoint_ops;
15470   ops->insert_location = insert_catch_vfork;
15471   ops->remove_location = remove_catch_vfork;
15472   ops->breakpoint_hit = breakpoint_hit_catch_vfork;
15473   ops->print_it = print_it_catch_vfork;
15474   ops->print_one = print_one_catch_vfork;
15475   ops->print_mention = print_mention_catch_vfork;
15476   ops->print_recreate = print_recreate_catch_vfork;
15477
15478   /* Exec catchpoints.  */
15479   ops = &catch_exec_breakpoint_ops;
15480   *ops = base_breakpoint_ops;
15481   ops->insert_location = insert_catch_exec;
15482   ops->remove_location = remove_catch_exec;
15483   ops->breakpoint_hit = breakpoint_hit_catch_exec;
15484   ops->print_it = print_it_catch_exec;
15485   ops->print_one = print_one_catch_exec;
15486   ops->print_mention = print_mention_catch_exec;
15487   ops->print_recreate = print_recreate_catch_exec;
15488
15489   /* Solib-related catchpoints.  */
15490   ops = &catch_solib_breakpoint_ops;
15491   *ops = base_breakpoint_ops;
15492   ops->insert_location = insert_catch_solib;
15493   ops->remove_location = remove_catch_solib;
15494   ops->breakpoint_hit = breakpoint_hit_catch_solib;
15495   ops->check_status = check_status_catch_solib;
15496   ops->print_it = print_it_catch_solib;
15497   ops->print_one = print_one_catch_solib;
15498   ops->print_mention = print_mention_catch_solib;
15499   ops->print_recreate = print_recreate_catch_solib;
15500
15501   ops = &dprintf_breakpoint_ops;
15502   *ops = bkpt_base_breakpoint_ops;
15503   ops->re_set = dprintf_re_set;
15504   ops->resources_needed = bkpt_resources_needed;
15505   ops->print_it = bkpt_print_it;
15506   ops->print_mention = bkpt_print_mention;
15507   ops->print_recreate = dprintf_print_recreate;
15508   ops->after_condition_true = dprintf_after_condition_true;
15509   ops->breakpoint_hit = dprintf_breakpoint_hit;
15510 }
15511
15512 /* Chain containing all defined "enable breakpoint" subcommands.  */
15513
15514 static struct cmd_list_element *enablebreaklist = NULL;
15515
15516 void
15517 _initialize_breakpoint (void)
15518 {
15519   struct cmd_list_element *c;
15520
15521   initialize_breakpoint_ops ();
15522
15523   observer_attach_solib_unloaded (disable_breakpoints_in_unloaded_shlib);
15524   observer_attach_free_objfile (disable_breakpoints_in_freed_objfile);
15525   observer_attach_memory_changed (invalidate_bp_value_on_memory_change);
15526
15527   breakpoint_objfile_key
15528     = register_objfile_data_with_cleanup (NULL, free_breakpoint_objfile_data);
15529
15530   breakpoint_chain = 0;
15531   /* Don't bother to call set_breakpoint_count.  $bpnum isn't useful
15532      before a breakpoint is set.  */
15533   breakpoint_count = 0;
15534
15535   tracepoint_count = 0;
15536
15537   add_com ("ignore", class_breakpoint, ignore_command, _("\
15538 Set ignore-count of breakpoint number N to COUNT.\n\
15539 Usage is `ignore N COUNT'."));
15540
15541   add_com ("commands", class_breakpoint, commands_command, _("\
15542 Set commands to be executed when the given breakpoints are hit.\n\
15543 Give a space-separated breakpoint list as argument after \"commands\".\n\
15544 A list element can be a breakpoint number (e.g. `5') or a range of numbers\n\
15545 (e.g. `5-7').\n\
15546 With no argument, the targeted breakpoint is the last one set.\n\
15547 The commands themselves follow starting on the next line.\n\
15548 Type a line containing \"end\" to indicate the end of them.\n\
15549 Give \"silent\" as the first line to make the breakpoint silent;\n\
15550 then no output is printed when it is hit, except what the commands print."));
15551
15552   c = add_com ("condition", class_breakpoint, condition_command, _("\
15553 Specify breakpoint number N to break only if COND is true.\n\
15554 Usage is `condition N COND', where N is an integer and COND is an\n\
15555 expression to be evaluated whenever breakpoint N is reached."));
15556   set_cmd_completer (c, condition_completer);
15557
15558   c = add_com ("tbreak", class_breakpoint, tbreak_command, _("\
15559 Set a temporary breakpoint.\n\
15560 Like \"break\" except the breakpoint is only temporary,\n\
15561 so it will be deleted when hit.  Equivalent to \"break\" followed\n\
15562 by using \"enable delete\" on the breakpoint number.\n\
15563 \n"
15564 BREAK_ARGS_HELP ("tbreak")));
15565   set_cmd_completer (c, location_completer);
15566
15567   c = add_com ("hbreak", class_breakpoint, hbreak_command, _("\
15568 Set a hardware assisted breakpoint.\n\
15569 Like \"break\" except the breakpoint requires hardware support,\n\
15570 some target hardware may not have this support.\n\
15571 \n"
15572 BREAK_ARGS_HELP ("hbreak")));
15573   set_cmd_completer (c, location_completer);
15574
15575   c = add_com ("thbreak", class_breakpoint, thbreak_command, _("\
15576 Set a temporary hardware assisted breakpoint.\n\
15577 Like \"hbreak\" except the breakpoint is only temporary,\n\
15578 so it will be deleted when hit.\n\
15579 \n"
15580 BREAK_ARGS_HELP ("thbreak")));
15581   set_cmd_completer (c, location_completer);
15582
15583   add_prefix_cmd ("enable", class_breakpoint, enable_command, _("\
15584 Enable some breakpoints.\n\
15585 Give breakpoint numbers (separated by spaces) as arguments.\n\
15586 With no subcommand, breakpoints are enabled until you command otherwise.\n\
15587 This is used to cancel the effect of the \"disable\" command.\n\
15588 With a subcommand you can enable temporarily."),
15589                   &enablelist, "enable ", 1, &cmdlist);
15590
15591   add_com_alias ("en", "enable", class_breakpoint, 1);
15592
15593   add_prefix_cmd ("breakpoints", class_breakpoint, enable_command, _("\
15594 Enable some breakpoints.\n\
15595 Give breakpoint numbers (separated by spaces) as arguments.\n\
15596 This is used to cancel the effect of the \"disable\" command.\n\
15597 May be abbreviated to simply \"enable\".\n"),
15598                    &enablebreaklist, "enable breakpoints ", 1, &enablelist);
15599
15600   add_cmd ("once", no_class, enable_once_command, _("\
15601 Enable breakpoints for one hit.  Give breakpoint numbers.\n\
15602 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
15603            &enablebreaklist);
15604
15605   add_cmd ("delete", no_class, enable_delete_command, _("\
15606 Enable breakpoints and delete when hit.  Give breakpoint numbers.\n\
15607 If a breakpoint is hit while enabled in this fashion, it is deleted."),
15608            &enablebreaklist);
15609
15610   add_cmd ("count", no_class, enable_count_command, _("\
15611 Enable breakpoints for COUNT hits.  Give count and then breakpoint numbers.\n\
15612 If a breakpoint is hit while enabled in this fashion,\n\
15613 the count is decremented; when it reaches zero, the breakpoint is disabled."),
15614            &enablebreaklist);
15615
15616   add_cmd ("delete", no_class, enable_delete_command, _("\
15617 Enable breakpoints and delete when hit.  Give breakpoint numbers.\n\
15618 If a breakpoint is hit while enabled in this fashion, it is deleted."),
15619            &enablelist);
15620
15621   add_cmd ("once", no_class, enable_once_command, _("\
15622 Enable breakpoints for one hit.  Give breakpoint numbers.\n\
15623 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
15624            &enablelist);
15625
15626   add_cmd ("count", no_class, enable_count_command, _("\
15627 Enable breakpoints for COUNT hits.  Give count and then breakpoint numbers.\n\
15628 If a breakpoint is hit while enabled in this fashion,\n\
15629 the count is decremented; when it reaches zero, the breakpoint is disabled."),
15630            &enablelist);
15631
15632   add_prefix_cmd ("disable", class_breakpoint, disable_command, _("\
15633 Disable some breakpoints.\n\
15634 Arguments are breakpoint numbers with spaces in between.\n\
15635 To disable all breakpoints, give no argument.\n\
15636 A disabled breakpoint is not forgotten, but has no effect until re-enabled."),
15637                   &disablelist, "disable ", 1, &cmdlist);
15638   add_com_alias ("dis", "disable", class_breakpoint, 1);
15639   add_com_alias ("disa", "disable", class_breakpoint, 1);
15640
15641   add_cmd ("breakpoints", class_alias, disable_command, _("\
15642 Disable some breakpoints.\n\
15643 Arguments are breakpoint numbers with spaces in between.\n\
15644 To disable all breakpoints, give no argument.\n\
15645 A disabled breakpoint is not forgotten, but has no effect until re-enabled.\n\
15646 This command may be abbreviated \"disable\"."),
15647            &disablelist);
15648
15649   add_prefix_cmd ("delete", class_breakpoint, delete_command, _("\
15650 Delete some breakpoints or auto-display expressions.\n\
15651 Arguments are breakpoint numbers with spaces in between.\n\
15652 To delete all breakpoints, give no argument.\n\
15653 \n\
15654 Also a prefix command for deletion of other GDB objects.\n\
15655 The \"unset\" command is also an alias for \"delete\"."),
15656                   &deletelist, "delete ", 1, &cmdlist);
15657   add_com_alias ("d", "delete", class_breakpoint, 1);
15658   add_com_alias ("del", "delete", class_breakpoint, 1);
15659
15660   add_cmd ("breakpoints", class_alias, delete_command, _("\
15661 Delete some breakpoints or auto-display expressions.\n\
15662 Arguments are breakpoint numbers with spaces in between.\n\
15663 To delete all breakpoints, give no argument.\n\
15664 This command may be abbreviated \"delete\"."),
15665            &deletelist);
15666
15667   add_com ("clear", class_breakpoint, clear_command, _("\
15668 Clear breakpoint at specified location.\n\
15669 Argument may be a linespec, explicit, or address location as described below.\n\
15670 \n\
15671 With no argument, clears all breakpoints in the line that the selected frame\n\
15672 is executing in.\n"
15673 "\n" LOCATION_HELP_STRING "\n\
15674 See also the \"delete\" command which clears breakpoints by number."));
15675   add_com_alias ("cl", "clear", class_breakpoint, 1);
15676
15677   c = add_com ("break", class_breakpoint, break_command, _("\
15678 Set breakpoint at specified location.\n"
15679 BREAK_ARGS_HELP ("break")));
15680   set_cmd_completer (c, location_completer);
15681
15682   add_com_alias ("b", "break", class_run, 1);
15683   add_com_alias ("br", "break", class_run, 1);
15684   add_com_alias ("bre", "break", class_run, 1);
15685   add_com_alias ("brea", "break", class_run, 1);
15686
15687   if (dbx_commands)
15688     {
15689       add_abbrev_prefix_cmd ("stop", class_breakpoint, stop_command, _("\
15690 Break in function/address or break at a line in the current file."),
15691                              &stoplist, "stop ", 1, &cmdlist);
15692       add_cmd ("in", class_breakpoint, stopin_command,
15693                _("Break in function or address."), &stoplist);
15694       add_cmd ("at", class_breakpoint, stopat_command,
15695                _("Break at a line in the current file."), &stoplist);
15696       add_com ("status", class_info, info_breakpoints_command, _("\
15697 Status of user-settable breakpoints, or breakpoint number NUMBER.\n\
15698 The \"Type\" column indicates one of:\n\
15699 \tbreakpoint     - normal breakpoint\n\
15700 \twatchpoint     - watchpoint\n\
15701 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
15702 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
15703 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
15704 address and file/line number respectively.\n\
15705 \n\
15706 Convenience variable \"$_\" and default examine address for \"x\"\n\
15707 are set to the address of the last breakpoint listed unless the command\n\
15708 is prefixed with \"server \".\n\n\
15709 Convenience variable \"$bpnum\" contains the number of the last\n\
15710 breakpoint set."));
15711     }
15712
15713   add_info ("breakpoints", info_breakpoints_command, _("\
15714 Status of specified breakpoints (all user-settable breakpoints if no argument).\n\
15715 The \"Type\" column indicates one of:\n\
15716 \tbreakpoint     - normal breakpoint\n\
15717 \twatchpoint     - watchpoint\n\
15718 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
15719 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
15720 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
15721 address and file/line number respectively.\n\
15722 \n\
15723 Convenience variable \"$_\" and default examine address for \"x\"\n\
15724 are set to the address of the last breakpoint listed unless the command\n\
15725 is prefixed with \"server \".\n\n\
15726 Convenience variable \"$bpnum\" contains the number of the last\n\
15727 breakpoint set."));
15728
15729   add_info_alias ("b", "breakpoints", 1);
15730
15731   add_cmd ("breakpoints", class_maintenance, maintenance_info_breakpoints, _("\
15732 Status of all breakpoints, or breakpoint number NUMBER.\n\
15733 The \"Type\" column indicates one of:\n\
15734 \tbreakpoint     - normal breakpoint\n\
15735 \twatchpoint     - watchpoint\n\
15736 \tlongjmp        - internal breakpoint used to step through longjmp()\n\
15737 \tlongjmp resume - internal breakpoint at the target of longjmp()\n\
15738 \tuntil          - internal breakpoint used by the \"until\" command\n\
15739 \tfinish         - internal breakpoint used by the \"finish\" command\n\
15740 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
15741 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
15742 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
15743 address and file/line number respectively.\n\
15744 \n\
15745 Convenience variable \"$_\" and default examine address for \"x\"\n\
15746 are set to the address of the last breakpoint listed unless the command\n\
15747 is prefixed with \"server \".\n\n\
15748 Convenience variable \"$bpnum\" contains the number of the last\n\
15749 breakpoint set."),
15750            &maintenanceinfolist);
15751
15752   add_prefix_cmd ("catch", class_breakpoint, catch_command, _("\
15753 Set catchpoints to catch events."),
15754                   &catch_cmdlist, "catch ",
15755                   0/*allow-unknown*/, &cmdlist);
15756
15757   add_prefix_cmd ("tcatch", class_breakpoint, tcatch_command, _("\
15758 Set temporary catchpoints to catch events."),
15759                   &tcatch_cmdlist, "tcatch ",
15760                   0/*allow-unknown*/, &cmdlist);
15761
15762   add_catch_command ("fork", _("Catch calls to fork."),
15763                      catch_fork_command_1,
15764                      NULL,
15765                      (void *) (uintptr_t) catch_fork_permanent,
15766                      (void *) (uintptr_t) catch_fork_temporary);
15767   add_catch_command ("vfork", _("Catch calls to vfork."),
15768                      catch_fork_command_1,
15769                      NULL,
15770                      (void *) (uintptr_t) catch_vfork_permanent,
15771                      (void *) (uintptr_t) catch_vfork_temporary);
15772   add_catch_command ("exec", _("Catch calls to exec."),
15773                      catch_exec_command_1,
15774                      NULL,
15775                      CATCH_PERMANENT,
15776                      CATCH_TEMPORARY);
15777   add_catch_command ("load", _("Catch loads of shared libraries.\n\
15778 Usage: catch load [REGEX]\n\
15779 If REGEX is given, only stop for libraries matching the regular expression."),
15780                      catch_load_command_1,
15781                      NULL,
15782                      CATCH_PERMANENT,
15783                      CATCH_TEMPORARY);
15784   add_catch_command ("unload", _("Catch unloads of shared libraries.\n\
15785 Usage: catch unload [REGEX]\n\
15786 If REGEX is given, only stop for libraries matching the regular expression."),
15787                      catch_unload_command_1,
15788                      NULL,
15789                      CATCH_PERMANENT,
15790                      CATCH_TEMPORARY);
15791
15792   c = add_com ("watch", class_breakpoint, watch_command, _("\
15793 Set a watchpoint for an expression.\n\
15794 Usage: watch [-l|-location] EXPRESSION\n\
15795 A watchpoint stops execution of your program whenever the value of\n\
15796 an expression changes.\n\
15797 If -l or -location is given, this evaluates EXPRESSION and watches\n\
15798 the memory to which it refers."));
15799   set_cmd_completer (c, expression_completer);
15800
15801   c = add_com ("rwatch", class_breakpoint, rwatch_command, _("\
15802 Set a read watchpoint for an expression.\n\
15803 Usage: rwatch [-l|-location] EXPRESSION\n\
15804 A watchpoint stops execution of your program whenever the value of\n\
15805 an expression is read.\n\
15806 If -l or -location is given, this evaluates EXPRESSION and watches\n\
15807 the memory to which it refers."));
15808   set_cmd_completer (c, expression_completer);
15809
15810   c = add_com ("awatch", class_breakpoint, awatch_command, _("\
15811 Set a watchpoint for an expression.\n\
15812 Usage: awatch [-l|-location] EXPRESSION\n\
15813 A watchpoint stops execution of your program whenever the value of\n\
15814 an expression is either read or written.\n\
15815 If -l or -location is given, this evaluates EXPRESSION and watches\n\
15816 the memory to which it refers."));
15817   set_cmd_completer (c, expression_completer);
15818
15819   add_info ("watchpoints", info_watchpoints_command, _("\
15820 Status of specified watchpoints (all watchpoints if no argument)."));
15821
15822   /* XXX: cagney/2005-02-23: This should be a boolean, and should
15823      respond to changes - contrary to the description.  */
15824   add_setshow_zinteger_cmd ("can-use-hw-watchpoints", class_support,
15825                             &can_use_hw_watchpoints, _("\
15826 Set debugger's willingness to use watchpoint hardware."), _("\
15827 Show debugger's willingness to use watchpoint hardware."), _("\
15828 If zero, gdb will not use hardware for new watchpoints, even if\n\
15829 such is available.  (However, any hardware watchpoints that were\n\
15830 created before setting this to nonzero, will continue to use watchpoint\n\
15831 hardware.)"),
15832                             NULL,
15833                             show_can_use_hw_watchpoints,
15834                             &setlist, &showlist);
15835
15836   can_use_hw_watchpoints = 1;
15837
15838   /* Tracepoint manipulation commands.  */
15839
15840   c = add_com ("trace", class_breakpoint, trace_command, _("\
15841 Set a tracepoint at specified location.\n\
15842 \n"
15843 BREAK_ARGS_HELP ("trace") "\n\
15844 Do \"help tracepoints\" for info on other tracepoint commands."));
15845   set_cmd_completer (c, location_completer);
15846
15847   add_com_alias ("tp", "trace", class_alias, 0);
15848   add_com_alias ("tr", "trace", class_alias, 1);
15849   add_com_alias ("tra", "trace", class_alias, 1);
15850   add_com_alias ("trac", "trace", class_alias, 1);
15851
15852   c = add_com ("ftrace", class_breakpoint, ftrace_command, _("\
15853 Set a fast tracepoint at specified location.\n\
15854 \n"
15855 BREAK_ARGS_HELP ("ftrace") "\n\
15856 Do \"help tracepoints\" for info on other tracepoint commands."));
15857   set_cmd_completer (c, location_completer);
15858
15859   c = add_com ("strace", class_breakpoint, strace_command, _("\
15860 Set a static tracepoint at location or marker.\n\
15861 \n\
15862 strace [LOCATION] [if CONDITION]\n\
15863 LOCATION may be a linespec, explicit, or address location (described below) \n\
15864 or -m MARKER_ID.\n\n\
15865 If a marker id is specified, probe the marker with that name.  With\n\
15866 no LOCATION, uses current execution address of the selected stack frame.\n\
15867 Static tracepoints accept an extra collect action -- ``collect $_sdata''.\n\
15868 This collects arbitrary user data passed in the probe point call to the\n\
15869 tracing library.  You can inspect it when analyzing the trace buffer,\n\
15870 by printing the $_sdata variable like any other convenience variable.\n\
15871 \n\
15872 CONDITION is a boolean expression.\n\
15873 \n" LOCATION_HELP_STRING "\n\
15874 Multiple tracepoints at one place are permitted, and useful if their\n\
15875 conditions are different.\n\
15876 \n\
15877 Do \"help breakpoints\" for info on other commands dealing with breakpoints.\n\
15878 Do \"help tracepoints\" for info on other tracepoint commands."));
15879   set_cmd_completer (c, location_completer);
15880
15881   add_info ("tracepoints", info_tracepoints_command, _("\
15882 Status of specified tracepoints (all tracepoints if no argument).\n\
15883 Convenience variable \"$tpnum\" contains the number of the\n\
15884 last tracepoint set."));
15885
15886   add_info_alias ("tp", "tracepoints", 1);
15887
15888   add_cmd ("tracepoints", class_trace, delete_trace_command, _("\
15889 Delete specified tracepoints.\n\
15890 Arguments are tracepoint numbers, separated by spaces.\n\
15891 No argument means delete all tracepoints."),
15892            &deletelist);
15893   add_alias_cmd ("tr", "tracepoints", class_trace, 1, &deletelist);
15894
15895   c = add_cmd ("tracepoints", class_trace, disable_trace_command, _("\
15896 Disable specified tracepoints.\n\
15897 Arguments are tracepoint numbers, separated by spaces.\n\
15898 No argument means disable all tracepoints."),
15899            &disablelist);
15900   deprecate_cmd (c, "disable");
15901
15902   c = add_cmd ("tracepoints", class_trace, enable_trace_command, _("\
15903 Enable specified tracepoints.\n\
15904 Arguments are tracepoint numbers, separated by spaces.\n\
15905 No argument means enable all tracepoints."),
15906            &enablelist);
15907   deprecate_cmd (c, "enable");
15908
15909   add_com ("passcount", class_trace, trace_pass_command, _("\
15910 Set the passcount for a tracepoint.\n\
15911 The trace will end when the tracepoint has been passed 'count' times.\n\
15912 Usage: passcount COUNT TPNUM, where TPNUM may also be \"all\";\n\
15913 if TPNUM is omitted, passcount refers to the last tracepoint defined."));
15914
15915   add_prefix_cmd ("save", class_breakpoint, save_command,
15916                   _("Save breakpoint definitions as a script."),
15917                   &save_cmdlist, "save ",
15918                   0/*allow-unknown*/, &cmdlist);
15919
15920   c = add_cmd ("breakpoints", class_breakpoint, save_breakpoints_command, _("\
15921 Save current breakpoint definitions as a script.\n\
15922 This includes all types of breakpoints (breakpoints, watchpoints,\n\
15923 catchpoints, tracepoints).  Use the 'source' command in another debug\n\
15924 session to restore them."),
15925                &save_cmdlist);
15926   set_cmd_completer (c, filename_completer);
15927
15928   c = add_cmd ("tracepoints", class_trace, save_tracepoints_command, _("\
15929 Save current tracepoint definitions as a script.\n\
15930 Use the 'source' command in another debug session to restore them."),
15931                &save_cmdlist);
15932   set_cmd_completer (c, filename_completer);
15933
15934   c = add_com_alias ("save-tracepoints", "save tracepoints", class_trace, 0);
15935   deprecate_cmd (c, "save tracepoints");
15936
15937   add_prefix_cmd ("breakpoint", class_maintenance, set_breakpoint_cmd, _("\
15938 Breakpoint specific settings\n\
15939 Configure various breakpoint-specific variables such as\n\
15940 pending breakpoint behavior"),
15941                   &breakpoint_set_cmdlist, "set breakpoint ",
15942                   0/*allow-unknown*/, &setlist);
15943   add_prefix_cmd ("breakpoint", class_maintenance, show_breakpoint_cmd, _("\
15944 Breakpoint specific settings\n\
15945 Configure various breakpoint-specific variables such as\n\
15946 pending breakpoint behavior"),
15947                   &breakpoint_show_cmdlist, "show breakpoint ",
15948                   0/*allow-unknown*/, &showlist);
15949
15950   add_setshow_auto_boolean_cmd ("pending", no_class,
15951                                 &pending_break_support, _("\
15952 Set debugger's behavior regarding pending breakpoints."), _("\
15953 Show debugger's behavior regarding pending breakpoints."), _("\
15954 If on, an unrecognized breakpoint location will cause gdb to create a\n\
15955 pending breakpoint.  If off, an unrecognized breakpoint location results in\n\
15956 an error.  If auto, an unrecognized breakpoint location results in a\n\
15957 user-query to see if a pending breakpoint should be created."),
15958                                 NULL,
15959                                 show_pending_break_support,
15960                                 &breakpoint_set_cmdlist,
15961                                 &breakpoint_show_cmdlist);
15962
15963   pending_break_support = AUTO_BOOLEAN_AUTO;
15964
15965   add_setshow_boolean_cmd ("auto-hw", no_class,
15966                            &automatic_hardware_breakpoints, _("\
15967 Set automatic usage of hardware breakpoints."), _("\
15968 Show automatic usage of hardware breakpoints."), _("\
15969 If set, the debugger will automatically use hardware breakpoints for\n\
15970 breakpoints set with \"break\" but falling in read-only memory.  If not set,\n\
15971 a warning will be emitted for such breakpoints."),
15972                            NULL,
15973                            show_automatic_hardware_breakpoints,
15974                            &breakpoint_set_cmdlist,
15975                            &breakpoint_show_cmdlist);
15976
15977   add_setshow_boolean_cmd ("always-inserted", class_support,
15978                            &always_inserted_mode, _("\
15979 Set mode for inserting breakpoints."), _("\
15980 Show mode for inserting breakpoints."), _("\
15981 When this mode is on, breakpoints are inserted immediately as soon as\n\
15982 they're created, kept inserted even when execution stops, and removed\n\
15983 only when the user deletes them.  When this mode is off (the default),\n\
15984 breakpoints are inserted only when execution continues, and removed\n\
15985 when execution stops."),
15986                                 NULL,
15987                                 &show_always_inserted_mode,
15988                                 &breakpoint_set_cmdlist,
15989                                 &breakpoint_show_cmdlist);
15990
15991   add_setshow_enum_cmd ("condition-evaluation", class_breakpoint,
15992                         condition_evaluation_enums,
15993                         &condition_evaluation_mode_1, _("\
15994 Set mode of breakpoint condition evaluation."), _("\
15995 Show mode of breakpoint condition evaluation."), _("\
15996 When this is set to \"host\", breakpoint conditions will be\n\
15997 evaluated on the host's side by GDB.  When it is set to \"target\",\n\
15998 breakpoint conditions will be downloaded to the target (if the target\n\
15999 supports such feature) and conditions will be evaluated on the target's side.\n\
16000 If this is set to \"auto\" (default), this will be automatically set to\n\
16001 \"target\" if it supports condition evaluation, otherwise it will\n\
16002 be set to \"gdb\""),
16003                            &set_condition_evaluation_mode,
16004                            &show_condition_evaluation_mode,
16005                            &breakpoint_set_cmdlist,
16006                            &breakpoint_show_cmdlist);
16007
16008   add_com ("break-range", class_breakpoint, break_range_command, _("\
16009 Set a breakpoint for an address range.\n\
16010 break-range START-LOCATION, END-LOCATION\n\
16011 where START-LOCATION and END-LOCATION can be one of the following:\n\
16012   LINENUM, for that line in the current file,\n\
16013   FILE:LINENUM, for that line in that file,\n\
16014   +OFFSET, for that number of lines after the current line\n\
16015            or the start of the range\n\
16016   FUNCTION, for the first line in that function,\n\
16017   FILE:FUNCTION, to distinguish among like-named static functions.\n\
16018   *ADDRESS, for the instruction at that address.\n\
16019 \n\
16020 The breakpoint will stop execution of the inferior whenever it executes\n\
16021 an instruction at any address within the [START-LOCATION, END-LOCATION]\n\
16022 range (including START-LOCATION and END-LOCATION)."));
16023
16024   c = add_com ("dprintf", class_breakpoint, dprintf_command, _("\
16025 Set a dynamic printf at specified location.\n\
16026 dprintf location,format string,arg1,arg2,...\n\
16027 location may be a linespec, explicit, or address location.\n"
16028 "\n" LOCATION_HELP_STRING));
16029   set_cmd_completer (c, location_completer);
16030
16031   add_setshow_enum_cmd ("dprintf-style", class_support,
16032                         dprintf_style_enums, &dprintf_style, _("\
16033 Set the style of usage for dynamic printf."), _("\
16034 Show the style of usage for dynamic printf."), _("\
16035 This setting chooses how GDB will do a dynamic printf.\n\
16036 If the value is \"gdb\", then the printing is done by GDB to its own\n\
16037 console, as with the \"printf\" command.\n\
16038 If the value is \"call\", the print is done by calling a function in your\n\
16039 program; by default printf(), but you can choose a different function or\n\
16040 output stream by setting dprintf-function and dprintf-channel."),
16041                         update_dprintf_commands, NULL,
16042                         &setlist, &showlist);
16043
16044   dprintf_function = xstrdup ("printf");
16045   add_setshow_string_cmd ("dprintf-function", class_support,
16046                           &dprintf_function, _("\
16047 Set the function to use for dynamic printf"), _("\
16048 Show the function to use for dynamic printf"), NULL,
16049                           update_dprintf_commands, NULL,
16050                           &setlist, &showlist);
16051
16052   dprintf_channel = xstrdup ("");
16053   add_setshow_string_cmd ("dprintf-channel", class_support,
16054                           &dprintf_channel, _("\
16055 Set the channel to use for dynamic printf"), _("\
16056 Show the channel to use for dynamic printf"), NULL,
16057                           update_dprintf_commands, NULL,
16058                           &setlist, &showlist);
16059
16060   add_setshow_boolean_cmd ("disconnected-dprintf", no_class,
16061                            &disconnected_dprintf, _("\
16062 Set whether dprintf continues after GDB disconnects."), _("\
16063 Show whether dprintf continues after GDB disconnects."), _("\
16064 Use this to let dprintf commands continue to hit and produce output\n\
16065 even if GDB disconnects or detaches from the target."),
16066                            NULL,
16067                            NULL,
16068                            &setlist, &showlist);
16069
16070   add_com ("agent-printf", class_vars, agent_printf_command, _("\
16071 agent-printf \"printf format string\", arg1, arg2, arg3, ..., argn\n\
16072 (target agent only) This is useful for formatted output in user-defined commands."));
16073
16074   automatic_hardware_breakpoints = 1;
16075
16076   observer_attach_about_to_proceed (breakpoint_about_to_proceed);
16077   observer_attach_thread_exit (remove_threaded_breakpoints);
16078 }