Constify add_com
[external/binutils.git] / gdb / breakpoint.c
1 /* Everything about breakpoints, for GDB.
2
3    Copyright (C) 1986-2017 Free Software Foundation, Inc.
4
5    This file is part of GDB.
6
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
19
20 #include "defs.h"
21 #include "arch-utils.h"
22 #include <ctype.h>
23 #include "hashtab.h"
24 #include "symtab.h"
25 #include "frame.h"
26 #include "breakpoint.h"
27 #include "tracepoint.h"
28 #include "gdbtypes.h"
29 #include "expression.h"
30 #include "gdbcore.h"
31 #include "gdbcmd.h"
32 #include "value.h"
33 #include "command.h"
34 #include "inferior.h"
35 #include "infrun.h"
36 #include "gdbthread.h"
37 #include "target.h"
38 #include "language.h"
39 #include "gdb-demangle.h"
40 #include "filenames.h"
41 #include "annotate.h"
42 #include "symfile.h"
43 #include "objfiles.h"
44 #include "source.h"
45 #include "linespec.h"
46 #include "completer.h"
47 #include "ui-out.h"
48 #include "cli/cli-script.h"
49 #include "block.h"
50 #include "solib.h"
51 #include "solist.h"
52 #include "observer.h"
53 #include "memattr.h"
54 #include "ada-lang.h"
55 #include "top.h"
56 #include "valprint.h"
57 #include "jit.h"
58 #include "parser-defs.h"
59 #include "gdb_regex.h"
60 #include "probe.h"
61 #include "cli/cli-utils.h"
62 #include "continuations.h"
63 #include "stack.h"
64 #include "skip.h"
65 #include "ax-gdb.h"
66 #include "dummy-frame.h"
67 #include "interps.h"
68 #include "format.h"
69 #include "thread-fsm.h"
70 #include "tid-parse.h"
71
72 /* readline include files */
73 #include "readline/readline.h"
74 #include "readline/history.h"
75
76 /* readline defines this.  */
77 #undef savestring
78
79 #include "mi/mi-common.h"
80 #include "extension.h"
81 #include <algorithm>
82 #include "progspace-and-thread.h"
83 #include "common/array-view.h"
84 #include "common/gdb_optional.h"
85
86 /* Enums for exception-handling support.  */
87 enum exception_event_kind
88 {
89   EX_EVENT_THROW,
90   EX_EVENT_RETHROW,
91   EX_EVENT_CATCH
92 };
93
94 /* Prototypes for local functions.  */
95
96 static void map_breakpoint_numbers (const char *,
97                                     gdb::function_view<void (breakpoint *)>);
98
99 static void breakpoint_re_set_default (struct breakpoint *);
100
101 static void
102   create_sals_from_location_default (const struct event_location *location,
103                                      struct linespec_result *canonical,
104                                      enum bptype type_wanted);
105
106 static void create_breakpoints_sal_default (struct gdbarch *,
107                                             struct linespec_result *,
108                                             gdb::unique_xmalloc_ptr<char>,
109                                             gdb::unique_xmalloc_ptr<char>,
110                                             enum bptype,
111                                             enum bpdisp, int, int,
112                                             int,
113                                             const struct breakpoint_ops *,
114                                             int, int, int, unsigned);
115
116 static std::vector<symtab_and_line> decode_location_default
117   (struct breakpoint *b, const struct event_location *location,
118    struct program_space *search_pspace);
119
120 static int can_use_hardware_watchpoint (struct value *);
121
122 static void mention (struct breakpoint *);
123
124 static struct breakpoint *set_raw_breakpoint_without_location (struct gdbarch *,
125                                                                enum bptype,
126                                                                const struct breakpoint_ops *);
127 static struct bp_location *add_location_to_breakpoint (struct breakpoint *,
128                                                        const struct symtab_and_line *);
129
130 /* This function is used in gdbtk sources and thus can not be made
131    static.  */
132 struct breakpoint *set_raw_breakpoint (struct gdbarch *gdbarch,
133                                        struct symtab_and_line,
134                                        enum bptype,
135                                        const struct breakpoint_ops *);
136
137 static struct breakpoint *
138   momentary_breakpoint_from_master (struct breakpoint *orig,
139                                     enum bptype type,
140                                     const struct breakpoint_ops *ops,
141                                     int loc_enabled);
142
143 static void breakpoint_adjustment_warning (CORE_ADDR, CORE_ADDR, int, int);
144
145 static CORE_ADDR adjust_breakpoint_address (struct gdbarch *gdbarch,
146                                             CORE_ADDR bpaddr,
147                                             enum bptype bptype);
148
149 static void describe_other_breakpoints (struct gdbarch *,
150                                         struct program_space *, CORE_ADDR,
151                                         struct obj_section *, int);
152
153 static int watchpoint_locations_match (struct bp_location *loc1,
154                                        struct bp_location *loc2);
155
156 static int breakpoint_location_address_match (struct bp_location *bl,
157                                               const struct address_space *aspace,
158                                               CORE_ADDR addr);
159
160 static int breakpoint_location_address_range_overlap (struct bp_location *,
161                                                       const address_space *,
162                                                       CORE_ADDR, int);
163
164 static void info_watchpoints_command (char *, int);
165
166 static int remove_breakpoint (struct bp_location *);
167 static int remove_breakpoint_1 (struct bp_location *, enum remove_bp_reason);
168
169 static enum print_stop_action print_bp_stop_message (bpstat bs);
170
171 static int hw_breakpoint_used_count (void);
172
173 static int hw_watchpoint_use_count (struct breakpoint *);
174
175 static int hw_watchpoint_used_count_others (struct breakpoint *except,
176                                             enum bptype type,
177                                             int *other_type_used);
178
179 static void enable_breakpoint_disp (struct breakpoint *, enum bpdisp,
180                                     int count);
181
182 static void free_bp_location (struct bp_location *loc);
183 static void incref_bp_location (struct bp_location *loc);
184 static void decref_bp_location (struct bp_location **loc);
185
186 static struct bp_location *allocate_bp_location (struct breakpoint *bpt);
187
188 /* update_global_location_list's modes of operation wrt to whether to
189    insert locations now.  */
190 enum ugll_insert_mode
191 {
192   /* Don't insert any breakpoint locations into the inferior, only
193      remove already-inserted locations that no longer should be
194      inserted.  Functions that delete a breakpoint or breakpoints
195      should specify this mode, so that deleting a breakpoint doesn't
196      have the side effect of inserting the locations of other
197      breakpoints that are marked not-inserted, but should_be_inserted
198      returns true on them.
199
200      This behavior is useful is situations close to tear-down -- e.g.,
201      after an exec, while the target still has execution, but
202      breakpoint shadows of the previous executable image should *NOT*
203      be restored to the new image; or before detaching, where the
204      target still has execution and wants to delete breakpoints from
205      GDB's lists, and all breakpoints had already been removed from
206      the inferior.  */
207   UGLL_DONT_INSERT,
208
209   /* May insert breakpoints iff breakpoints_should_be_inserted_now
210      claims breakpoints should be inserted now.  */
211   UGLL_MAY_INSERT,
212
213   /* Insert locations now, irrespective of
214      breakpoints_should_be_inserted_now.  E.g., say all threads are
215      stopped right now, and the user did "continue".  We need to
216      insert breakpoints _before_ resuming the target, but
217      UGLL_MAY_INSERT wouldn't insert them, because
218      breakpoints_should_be_inserted_now returns false at that point,
219      as no thread is running yet.  */
220   UGLL_INSERT
221 };
222
223 static void update_global_location_list (enum ugll_insert_mode);
224
225 static void update_global_location_list_nothrow (enum ugll_insert_mode);
226
227 static int is_hardware_watchpoint (const struct breakpoint *bpt);
228
229 static void insert_breakpoint_locations (void);
230
231 static void info_tracepoints_command (char *, int);
232
233 static void enable_trace_command (char *, int);
234
235 static void disable_trace_command (char *, int);
236
237 static void trace_pass_command (const char *, int);
238
239 static void set_tracepoint_count (int num);
240
241 static int is_masked_watchpoint (const struct breakpoint *b);
242
243 static struct bp_location **get_first_locp_gte_addr (CORE_ADDR address);
244
245 /* Return 1 if B refers to a static tracepoint set by marker ("-m"), zero
246    otherwise.  */
247
248 static int strace_marker_p (struct breakpoint *b);
249
250 /* The breakpoint_ops structure to be inherited by all breakpoint_ops
251    that are implemented on top of software or hardware breakpoints
252    (user breakpoints, internal and momentary breakpoints, etc.).  */
253 static struct breakpoint_ops bkpt_base_breakpoint_ops;
254
255 /* Internal breakpoints class type.  */
256 static struct breakpoint_ops internal_breakpoint_ops;
257
258 /* Momentary breakpoints class type.  */
259 static struct breakpoint_ops momentary_breakpoint_ops;
260
261 /* The breakpoint_ops structure to be used in regular user created
262    breakpoints.  */
263 struct breakpoint_ops bkpt_breakpoint_ops;
264
265 /* Breakpoints set on probes.  */
266 static struct breakpoint_ops bkpt_probe_breakpoint_ops;
267
268 /* Dynamic printf class type.  */
269 struct breakpoint_ops dprintf_breakpoint_ops;
270
271 /* The style in which to perform a dynamic printf.  This is a user
272    option because different output options have different tradeoffs;
273    if GDB does the printing, there is better error handling if there
274    is a problem with any of the arguments, but using an inferior
275    function lets you have special-purpose printers and sending of
276    output to the same place as compiled-in print functions.  */
277
278 static const char dprintf_style_gdb[] = "gdb";
279 static const char dprintf_style_call[] = "call";
280 static const char dprintf_style_agent[] = "agent";
281 static const char *const dprintf_style_enums[] = {
282   dprintf_style_gdb,
283   dprintf_style_call,
284   dprintf_style_agent,
285   NULL
286 };
287 static const char *dprintf_style = dprintf_style_gdb;
288
289 /* The function to use for dynamic printf if the preferred style is to
290    call into the inferior.  The value is simply a string that is
291    copied into the command, so it can be anything that GDB can
292    evaluate to a callable address, not necessarily a function name.  */
293
294 static char *dprintf_function;
295
296 /* The channel to use for dynamic printf if the preferred style is to
297    call into the inferior; if a nonempty string, it will be passed to
298    the call as the first argument, with the format string as the
299    second.  As with the dprintf function, this can be anything that
300    GDB knows how to evaluate, so in addition to common choices like
301    "stderr", this could be an app-specific expression like
302    "mystreams[curlogger]".  */
303
304 static char *dprintf_channel;
305
306 /* True if dprintf commands should continue to operate even if GDB
307    has disconnected.  */
308 static int disconnected_dprintf = 1;
309
310 struct command_line *
311 breakpoint_commands (struct breakpoint *b)
312 {
313   return b->commands ? b->commands.get () : NULL;
314 }
315
316 /* Flag indicating that a command has proceeded the inferior past the
317    current breakpoint.  */
318
319 static int breakpoint_proceeded;
320
321 const char *
322 bpdisp_text (enum bpdisp disp)
323 {
324   /* NOTE: the following values are a part of MI protocol and
325      represent values of 'disp' field returned when inferior stops at
326      a breakpoint.  */
327   static const char * const bpdisps[] = {"del", "dstp", "dis", "keep"};
328
329   return bpdisps[(int) disp];
330 }
331
332 /* Prototypes for exported functions.  */
333 /* If FALSE, gdb will not use hardware support for watchpoints, even
334    if such is available.  */
335 static int can_use_hw_watchpoints;
336
337 static void
338 show_can_use_hw_watchpoints (struct ui_file *file, int from_tty,
339                              struct cmd_list_element *c,
340                              const char *value)
341 {
342   fprintf_filtered (file,
343                     _("Debugger's willingness to use "
344                       "watchpoint hardware is %s.\n"),
345                     value);
346 }
347
348 /* If AUTO_BOOLEAN_FALSE, gdb will not attempt to create pending breakpoints.
349    If AUTO_BOOLEAN_TRUE, gdb will automatically create pending breakpoints
350    for unrecognized breakpoint locations.
351    If AUTO_BOOLEAN_AUTO, gdb will query when breakpoints are unrecognized.  */
352 static enum auto_boolean pending_break_support;
353 static void
354 show_pending_break_support (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 behavior regarding "
360                       "pending breakpoints is %s.\n"),
361                     value);
362 }
363
364 /* If 1, gdb will automatically use hardware breakpoints for breakpoints
365    set with "break" but falling in read-only memory.
366    If 0, gdb will warn about such breakpoints, but won't automatically
367    use hardware breakpoints.  */
368 static int automatic_hardware_breakpoints;
369 static void
370 show_automatic_hardware_breakpoints (struct ui_file *file, int from_tty,
371                                      struct cmd_list_element *c,
372                                      const char *value)
373 {
374   fprintf_filtered (file,
375                     _("Automatic usage of hardware breakpoints is %s.\n"),
376                     value);
377 }
378
379 /* If on, GDB keeps breakpoints inserted even if the inferior is
380    stopped, and immediately inserts any new breakpoints as soon as
381    they're created.  If off (default), GDB keeps breakpoints off of
382    the target as long as possible.  That is, it delays inserting
383    breakpoints until the next resume, and removes them again when the
384    target fully stops.  This is a bit safer in case GDB crashes while
385    processing user input.  */
386 static int always_inserted_mode = 0;
387
388 static void
389 show_always_inserted_mode (struct ui_file *file, int from_tty,
390                      struct cmd_list_element *c, const char *value)
391 {
392   fprintf_filtered (file, _("Always inserted breakpoint mode is %s.\n"),
393                     value);
394 }
395
396 /* See breakpoint.h.  */
397
398 int
399 breakpoints_should_be_inserted_now (void)
400 {
401   if (gdbarch_has_global_breakpoints (target_gdbarch ()))
402     {
403       /* If breakpoints are global, they should be inserted even if no
404          thread under gdb's control is running, or even if there are
405          no threads under GDB's control yet.  */
406       return 1;
407     }
408   else if (target_has_execution)
409     {
410       struct thread_info *tp;
411
412       if (always_inserted_mode)
413         {
414           /* The user wants breakpoints inserted even if all threads
415              are stopped.  */
416           return 1;
417         }
418
419       if (threads_are_executing ())
420         return 1;
421
422       /* Don't remove breakpoints yet if, even though all threads are
423          stopped, we still have events to process.  */
424       ALL_NON_EXITED_THREADS (tp)
425         if (tp->resumed
426             && tp->suspend.waitstatus_pending_p)
427           return 1;
428     }
429   return 0;
430 }
431
432 static const char condition_evaluation_both[] = "host or target";
433
434 /* Modes for breakpoint condition evaluation.  */
435 static const char condition_evaluation_auto[] = "auto";
436 static const char condition_evaluation_host[] = "host";
437 static const char condition_evaluation_target[] = "target";
438 static const char *const condition_evaluation_enums[] = {
439   condition_evaluation_auto,
440   condition_evaluation_host,
441   condition_evaluation_target,
442   NULL
443 };
444
445 /* Global that holds the current mode for breakpoint condition evaluation.  */
446 static const char *condition_evaluation_mode_1 = condition_evaluation_auto;
447
448 /* Global that we use to display information to the user (gets its value from
449    condition_evaluation_mode_1.  */
450 static const char *condition_evaluation_mode = condition_evaluation_auto;
451
452 /* Translate a condition evaluation mode MODE into either "host"
453    or "target".  This is used mostly to translate from "auto" to the
454    real setting that is being used.  It returns the translated
455    evaluation mode.  */
456
457 static const char *
458 translate_condition_evaluation_mode (const char *mode)
459 {
460   if (mode == condition_evaluation_auto)
461     {
462       if (target_supports_evaluation_of_breakpoint_conditions ())
463         return condition_evaluation_target;
464       else
465         return condition_evaluation_host;
466     }
467   else
468     return mode;
469 }
470
471 /* Discovers what condition_evaluation_auto translates to.  */
472
473 static const char *
474 breakpoint_condition_evaluation_mode (void)
475 {
476   return translate_condition_evaluation_mode (condition_evaluation_mode);
477 }
478
479 /* Return true if GDB should evaluate breakpoint conditions or false
480    otherwise.  */
481
482 static int
483 gdb_evaluates_breakpoint_condition_p (void)
484 {
485   const char *mode = breakpoint_condition_evaluation_mode ();
486
487   return (mode == condition_evaluation_host);
488 }
489
490 /* Are we executing breakpoint commands?  */
491 static int executing_breakpoint_commands;
492
493 /* Are overlay event breakpoints enabled? */
494 static int overlay_events_enabled;
495
496 /* See description in breakpoint.h. */
497 int target_exact_watchpoints = 0;
498
499 /* Walk the following statement or block through all breakpoints.
500    ALL_BREAKPOINTS_SAFE does so even if the statement deletes the
501    current breakpoint.  */
502
503 #define ALL_BREAKPOINTS(B)  for (B = breakpoint_chain; B; B = B->next)
504
505 #define ALL_BREAKPOINTS_SAFE(B,TMP)     \
506         for (B = breakpoint_chain;      \
507              B ? (TMP=B->next, 1): 0;   \
508              B = TMP)
509
510 /* Similar iterator for the low-level breakpoints.  SAFE variant is
511    not provided so update_global_location_list must not be called
512    while executing the block of ALL_BP_LOCATIONS.  */
513
514 #define ALL_BP_LOCATIONS(B,BP_TMP)                                      \
515         for (BP_TMP = bp_locations;                                     \
516              BP_TMP < bp_locations + bp_locations_count && (B = *BP_TMP);\
517              BP_TMP++)
518
519 /* Iterates through locations with address ADDRESS for the currently selected
520    program space.  BP_LOCP_TMP points to each object.  BP_LOCP_START points
521    to where the loop should start from.
522    If BP_LOCP_START is a NULL pointer, the macro automatically seeks the
523    appropriate location to start with.  */
524
525 #define ALL_BP_LOCATIONS_AT_ADDR(BP_LOCP_TMP, BP_LOCP_START, ADDRESS)   \
526         for (BP_LOCP_START = BP_LOCP_START == NULL ? get_first_locp_gte_addr (ADDRESS) : BP_LOCP_START, \
527              BP_LOCP_TMP = BP_LOCP_START;                               \
528              BP_LOCP_START                                              \
529              && (BP_LOCP_TMP < bp_locations + bp_locations_count        \
530              && (*BP_LOCP_TMP)->address == ADDRESS);                    \
531              BP_LOCP_TMP++)
532
533 /* Iterator for tracepoints only.  */
534
535 #define ALL_TRACEPOINTS(B)  \
536   for (B = breakpoint_chain; B; B = B->next)  \
537     if (is_tracepoint (B))
538
539 /* Chains of all breakpoints defined.  */
540
541 struct breakpoint *breakpoint_chain;
542
543 /* Array is sorted by bp_locations_compare - primarily by the ADDRESS.  */
544
545 static struct bp_location **bp_locations;
546
547 /* Number of elements of BP_LOCATIONS.  */
548
549 static unsigned bp_locations_count;
550
551 /* Maximum alignment offset between bp_target_info.PLACED_ADDRESS and
552    ADDRESS for the current elements of BP_LOCATIONS which get a valid
553    result from bp_location_has_shadow.  You can use it for roughly
554    limiting the subrange of BP_LOCATIONS to scan for shadow bytes for
555    an address you need to read.  */
556
557 static CORE_ADDR bp_locations_placed_address_before_address_max;
558
559 /* Maximum offset plus alignment between bp_target_info.PLACED_ADDRESS
560    + bp_target_info.SHADOW_LEN and ADDRESS for the current elements of
561    BP_LOCATIONS which get a valid result from bp_location_has_shadow.
562    You can use it for roughly limiting the subrange of BP_LOCATIONS to
563    scan for shadow bytes for an address you need to read.  */
564
565 static CORE_ADDR bp_locations_shadow_len_after_address_max;
566
567 /* The locations that no longer correspond to any breakpoint, unlinked
568    from the bp_locations array, but for which a hit may still be
569    reported by a target.  */
570 VEC(bp_location_p) *moribund_locations = NULL;
571
572 /* Number of last breakpoint made.  */
573
574 static int breakpoint_count;
575
576 /* The value of `breakpoint_count' before the last command that
577    created breakpoints.  If the last (break-like) command created more
578    than one breakpoint, then the difference between BREAKPOINT_COUNT
579    and PREV_BREAKPOINT_COUNT is more than one.  */
580 static int prev_breakpoint_count;
581
582 /* Number of last tracepoint made.  */
583
584 static int tracepoint_count;
585
586 static struct cmd_list_element *breakpoint_set_cmdlist;
587 static struct cmd_list_element *breakpoint_show_cmdlist;
588 struct cmd_list_element *save_cmdlist;
589
590 /* See declaration at breakpoint.h.  */
591
592 struct breakpoint *
593 breakpoint_find_if (int (*func) (struct breakpoint *b, void *d),
594                     void *user_data)
595 {
596   struct breakpoint *b = NULL;
597
598   ALL_BREAKPOINTS (b)
599     {
600       if (func (b, user_data) != 0)
601         break;
602     }
603
604   return b;
605 }
606
607 /* Return whether a breakpoint is an active enabled breakpoint.  */
608 static int
609 breakpoint_enabled (struct breakpoint *b)
610 {
611   return (b->enable_state == bp_enabled);
612 }
613
614 /* Set breakpoint count to NUM.  */
615
616 static void
617 set_breakpoint_count (int num)
618 {
619   prev_breakpoint_count = breakpoint_count;
620   breakpoint_count = num;
621   set_internalvar_integer (lookup_internalvar ("bpnum"), num);
622 }
623
624 /* Used by `start_rbreak_breakpoints' below, to record the current
625    breakpoint count before "rbreak" creates any breakpoint.  */
626 static int rbreak_start_breakpoint_count;
627
628 /* Called at the start an "rbreak" command to record the first
629    breakpoint made.  */
630
631 scoped_rbreak_breakpoints::scoped_rbreak_breakpoints ()
632 {
633   rbreak_start_breakpoint_count = breakpoint_count;
634 }
635
636 /* Called at the end of an "rbreak" command to record the last
637    breakpoint made.  */
638
639 scoped_rbreak_breakpoints::~scoped_rbreak_breakpoints ()
640 {
641   prev_breakpoint_count = rbreak_start_breakpoint_count;
642 }
643
644 /* Used in run_command to zero the hit count when a new run starts.  */
645
646 void
647 clear_breakpoint_hit_counts (void)
648 {
649   struct breakpoint *b;
650
651   ALL_BREAKPOINTS (b)
652     b->hit_count = 0;
653 }
654
655 \f
656 /* Return the breakpoint with the specified number, or NULL
657    if the number does not refer to an existing breakpoint.  */
658
659 struct breakpoint *
660 get_breakpoint (int num)
661 {
662   struct breakpoint *b;
663
664   ALL_BREAKPOINTS (b)
665     if (b->number == num)
666       return b;
667   
668   return NULL;
669 }
670
671 \f
672
673 /* Mark locations as "conditions have changed" in case the target supports
674    evaluating conditions on its side.  */
675
676 static void
677 mark_breakpoint_modified (struct breakpoint *b)
678 {
679   struct bp_location *loc;
680
681   /* This is only meaningful if the target is
682      evaluating conditions and if the user has
683      opted for condition evaluation on the target's
684      side.  */
685   if (gdb_evaluates_breakpoint_condition_p ()
686       || !target_supports_evaluation_of_breakpoint_conditions ())
687     return;
688
689   if (!is_breakpoint (b))
690     return;
691
692   for (loc = b->loc; loc; loc = loc->next)
693     loc->condition_changed = condition_modified;
694 }
695
696 /* Mark location as "conditions have changed" in case the target supports
697    evaluating conditions on its side.  */
698
699 static void
700 mark_breakpoint_location_modified (struct bp_location *loc)
701 {
702   /* This is only meaningful if the target is
703      evaluating conditions and if the user has
704      opted for condition evaluation on the target's
705      side.  */
706   if (gdb_evaluates_breakpoint_condition_p ()
707       || !target_supports_evaluation_of_breakpoint_conditions ())
708
709     return;
710
711   if (!is_breakpoint (loc->owner))
712     return;
713
714   loc->condition_changed = condition_modified;
715 }
716
717 /* Sets the condition-evaluation mode using the static global
718    condition_evaluation_mode.  */
719
720 static void
721 set_condition_evaluation_mode (char *args, int from_tty,
722                                struct cmd_list_element *c)
723 {
724   const char *old_mode, *new_mode;
725
726   if ((condition_evaluation_mode_1 == condition_evaluation_target)
727       && !target_supports_evaluation_of_breakpoint_conditions ())
728     {
729       condition_evaluation_mode_1 = condition_evaluation_mode;
730       warning (_("Target does not support breakpoint condition evaluation.\n"
731                  "Using host evaluation mode instead."));
732       return;
733     }
734
735   new_mode = translate_condition_evaluation_mode (condition_evaluation_mode_1);
736   old_mode = translate_condition_evaluation_mode (condition_evaluation_mode);
737
738   /* Flip the switch.  Flip it even if OLD_MODE == NEW_MODE as one of the
739      settings was "auto".  */
740   condition_evaluation_mode = condition_evaluation_mode_1;
741
742   /* Only update the mode if the user picked a different one.  */
743   if (new_mode != old_mode)
744     {
745       struct bp_location *loc, **loc_tmp;
746       /* If the user switched to a different evaluation mode, we
747          need to synch the changes with the target as follows:
748
749          "host" -> "target": Send all (valid) conditions to the target.
750          "target" -> "host": Remove all the conditions from the target.
751       */
752
753       if (new_mode == condition_evaluation_target)
754         {
755           /* Mark everything modified and synch conditions with the
756              target.  */
757           ALL_BP_LOCATIONS (loc, loc_tmp)
758             mark_breakpoint_location_modified (loc);
759         }
760       else
761         {
762           /* Manually mark non-duplicate locations to synch conditions
763              with the target.  We do this to remove all the conditions the
764              target knows about.  */
765           ALL_BP_LOCATIONS (loc, loc_tmp)
766             if (is_breakpoint (loc->owner) && loc->inserted)
767               loc->needs_update = 1;
768         }
769
770       /* Do the update.  */
771       update_global_location_list (UGLL_MAY_INSERT);
772     }
773
774   return;
775 }
776
777 /* Shows the current mode of breakpoint condition evaluation.  Explicitly shows
778    what "auto" is translating to.  */
779
780 static void
781 show_condition_evaluation_mode (struct ui_file *file, int from_tty,
782                                 struct cmd_list_element *c, const char *value)
783 {
784   if (condition_evaluation_mode == condition_evaluation_auto)
785     fprintf_filtered (file,
786                       _("Breakpoint condition evaluation "
787                         "mode is %s (currently %s).\n"),
788                       value,
789                       breakpoint_condition_evaluation_mode ());
790   else
791     fprintf_filtered (file, _("Breakpoint condition evaluation mode is %s.\n"),
792                       value);
793 }
794
795 /* A comparison function for bp_location AP and BP that is used by
796    bsearch.  This comparison function only cares about addresses, unlike
797    the more general bp_locations_compare function.  */
798
799 static int
800 bp_locations_compare_addrs (const void *ap, const void *bp)
801 {
802   const struct bp_location *a = *(const struct bp_location **) ap;
803   const struct bp_location *b = *(const struct bp_location **) bp;
804
805   if (a->address == b->address)
806     return 0;
807   else
808     return ((a->address > b->address) - (a->address < b->address));
809 }
810
811 /* Helper function to skip all bp_locations with addresses
812    less than ADDRESS.  It returns the first bp_location that
813    is greater than or equal to ADDRESS.  If none is found, just
814    return NULL.  */
815
816 static struct bp_location **
817 get_first_locp_gte_addr (CORE_ADDR address)
818 {
819   struct bp_location dummy_loc;
820   struct bp_location *dummy_locp = &dummy_loc;
821   struct bp_location **locp_found = NULL;
822
823   /* Initialize the dummy location's address field.  */
824   dummy_loc.address = address;
825
826   /* Find a close match to the first location at ADDRESS.  */
827   locp_found = ((struct bp_location **)
828                 bsearch (&dummy_locp, bp_locations, bp_locations_count,
829                          sizeof (struct bp_location **),
830                          bp_locations_compare_addrs));
831
832   /* Nothing was found, nothing left to do.  */
833   if (locp_found == NULL)
834     return NULL;
835
836   /* We may have found a location that is at ADDRESS but is not the first in the
837      location's list.  Go backwards (if possible) and locate the first one.  */
838   while ((locp_found - 1) >= bp_locations
839          && (*(locp_found - 1))->address == address)
840     locp_found--;
841
842   return locp_found;
843 }
844
845 void
846 set_breakpoint_condition (struct breakpoint *b, const char *exp,
847                           int from_tty)
848 {
849   xfree (b->cond_string);
850   b->cond_string = NULL;
851
852   if (is_watchpoint (b))
853     {
854       struct watchpoint *w = (struct watchpoint *) b;
855
856       w->cond_exp.reset ();
857     }
858   else
859     {
860       struct bp_location *loc;
861
862       for (loc = b->loc; loc; loc = loc->next)
863         {
864           loc->cond.reset ();
865
866           /* No need to free the condition agent expression
867              bytecode (if we have one).  We will handle this
868              when we go through update_global_location_list.  */
869         }
870     }
871
872   if (*exp == 0)
873     {
874       if (from_tty)
875         printf_filtered (_("Breakpoint %d now unconditional.\n"), b->number);
876     }
877   else
878     {
879       const char *arg = exp;
880
881       /* I don't know if it matters whether this is the string the user
882          typed in or the decompiled expression.  */
883       b->cond_string = xstrdup (arg);
884       b->condition_not_parsed = 0;
885
886       if (is_watchpoint (b))
887         {
888           struct watchpoint *w = (struct watchpoint *) b;
889
890           innermost_block = NULL;
891           arg = exp;
892           w->cond_exp = parse_exp_1 (&arg, 0, 0, 0);
893           if (*arg)
894             error (_("Junk at end of expression"));
895           w->cond_exp_valid_block = innermost_block;
896         }
897       else
898         {
899           struct bp_location *loc;
900
901           for (loc = b->loc; loc; loc = loc->next)
902             {
903               arg = exp;
904               loc->cond =
905                 parse_exp_1 (&arg, loc->address,
906                              block_for_pc (loc->address), 0);
907               if (*arg)
908                 error (_("Junk at end of expression"));
909             }
910         }
911     }
912   mark_breakpoint_modified (b);
913
914   observer_notify_breakpoint_modified (b);
915 }
916
917 /* Completion for the "condition" command.  */
918
919 static void
920 condition_completer (struct cmd_list_element *cmd,
921                      completion_tracker &tracker,
922                      const char *text, const char *word)
923 {
924   const char *space;
925
926   text = skip_spaces (text);
927   space = skip_to_space (text);
928   if (*space == '\0')
929     {
930       int len;
931       struct breakpoint *b;
932       VEC (char_ptr) *result = NULL;
933
934       if (text[0] == '$')
935         {
936           /* We don't support completion of history indices.  */
937           if (!isdigit (text[1]))
938             complete_internalvar (tracker, &text[1]);
939           return;
940         }
941
942       /* We're completing the breakpoint number.  */
943       len = strlen (text);
944
945       ALL_BREAKPOINTS (b)
946         {
947           char number[50];
948
949           xsnprintf (number, sizeof (number), "%d", b->number);
950
951           if (strncmp (number, text, len) == 0)
952             {
953               gdb::unique_xmalloc_ptr<char> copy (xstrdup (number));
954               tracker.add_completion (std::move (copy));
955             }
956         }
957
958       return;
959     }
960
961   /* We're completing the expression part.  */
962   text = skip_spaces (space);
963   expression_completer (cmd, tracker, text, word);
964 }
965
966 /* condition N EXP -- set break condition of breakpoint N to EXP.  */
967
968 static void
969 condition_command (const char *arg, int from_tty)
970 {
971   struct breakpoint *b;
972   const char *p;
973   int bnum;
974
975   if (arg == 0)
976     error_no_arg (_("breakpoint number"));
977
978   p = arg;
979   bnum = get_number (&p);
980   if (bnum == 0)
981     error (_("Bad breakpoint argument: '%s'"), arg);
982
983   ALL_BREAKPOINTS (b)
984     if (b->number == bnum)
985       {
986         /* Check if this breakpoint has a "stop" method implemented in an
987            extension language.  This method and conditions entered into GDB
988            from the CLI are mutually exclusive.  */
989         const struct extension_language_defn *extlang
990           = get_breakpoint_cond_ext_lang (b, EXT_LANG_NONE);
991
992         if (extlang != NULL)
993           {
994             error (_("Only one stop condition allowed.  There is currently"
995                      " a %s stop condition defined for this breakpoint."),
996                    ext_lang_capitalized_name (extlang));
997           }
998         set_breakpoint_condition (b, p, from_tty);
999
1000         if (is_breakpoint (b))
1001           update_global_location_list (UGLL_MAY_INSERT);
1002
1003         return;
1004       }
1005
1006   error (_("No breakpoint number %d."), bnum);
1007 }
1008
1009 /* Check that COMMAND do not contain commands that are suitable
1010    only for tracepoints and not suitable for ordinary breakpoints.
1011    Throw if any such commands is found.  */
1012
1013 static void
1014 check_no_tracepoint_commands (struct command_line *commands)
1015 {
1016   struct command_line *c;
1017
1018   for (c = commands; c; c = c->next)
1019     {
1020       int i;
1021
1022       if (c->control_type == while_stepping_control)
1023         error (_("The 'while-stepping' command can "
1024                  "only be used for tracepoints"));
1025
1026       for (i = 0; i < c->body_count; ++i)
1027         check_no_tracepoint_commands ((c->body_list)[i]);
1028
1029       /* Not that command parsing removes leading whitespace and comment
1030          lines and also empty lines.  So, we only need to check for
1031          command directly.  */
1032       if (strstr (c->line, "collect ") == c->line)
1033         error (_("The 'collect' command can only be used for tracepoints"));
1034
1035       if (strstr (c->line, "teval ") == c->line)
1036         error (_("The 'teval' command can only be used for tracepoints"));
1037     }
1038 }
1039
1040 struct longjmp_breakpoint : public breakpoint
1041 {
1042   ~longjmp_breakpoint () override;
1043 };
1044
1045 /* Encapsulate tests for different types of tracepoints.  */
1046
1047 static bool
1048 is_tracepoint_type (bptype type)
1049 {
1050   return (type == bp_tracepoint
1051           || type == bp_fast_tracepoint
1052           || type == bp_static_tracepoint);
1053 }
1054
1055 static bool
1056 is_longjmp_type (bptype type)
1057 {
1058   return type == bp_longjmp || type == bp_exception;
1059 }
1060
1061 int
1062 is_tracepoint (const struct breakpoint *b)
1063 {
1064   return is_tracepoint_type (b->type);
1065 }
1066
1067 /* Factory function to create an appropriate instance of breakpoint given
1068    TYPE.  */
1069
1070 static std::unique_ptr<breakpoint>
1071 new_breakpoint_from_type (bptype type)
1072 {
1073   breakpoint *b;
1074
1075   if (is_tracepoint_type (type))
1076     b = new tracepoint ();
1077   else if (is_longjmp_type (type))
1078     b = new longjmp_breakpoint ();
1079   else
1080     b = new breakpoint ();
1081
1082   return std::unique_ptr<breakpoint> (b);
1083 }
1084
1085 /* A helper function that validates that COMMANDS are valid for a
1086    breakpoint.  This function will throw an exception if a problem is
1087    found.  */
1088
1089 static void
1090 validate_commands_for_breakpoint (struct breakpoint *b,
1091                                   struct command_line *commands)
1092 {
1093   if (is_tracepoint (b))
1094     {
1095       struct tracepoint *t = (struct tracepoint *) b;
1096       struct command_line *c;
1097       struct command_line *while_stepping = 0;
1098
1099       /* Reset the while-stepping step count.  The previous commands
1100          might have included a while-stepping action, while the new
1101          ones might not.  */
1102       t->step_count = 0;
1103
1104       /* We need to verify that each top-level element of commands is
1105          valid for tracepoints, that there's at most one
1106          while-stepping element, and that the while-stepping's body
1107          has valid tracing commands excluding nested while-stepping.
1108          We also need to validate the tracepoint action line in the
1109          context of the tracepoint --- validate_actionline actually
1110          has side effects, like setting the tracepoint's
1111          while-stepping STEP_COUNT, in addition to checking if the
1112          collect/teval actions parse and make sense in the
1113          tracepoint's context.  */
1114       for (c = commands; c; c = c->next)
1115         {
1116           if (c->control_type == while_stepping_control)
1117             {
1118               if (b->type == bp_fast_tracepoint)
1119                 error (_("The 'while-stepping' command "
1120                          "cannot be used for fast tracepoint"));
1121               else if (b->type == bp_static_tracepoint)
1122                 error (_("The 'while-stepping' command "
1123                          "cannot be used for static tracepoint"));
1124
1125               if (while_stepping)
1126                 error (_("The 'while-stepping' command "
1127                          "can be used only once"));
1128               else
1129                 while_stepping = c;
1130             }
1131
1132           validate_actionline (c->line, b);
1133         }
1134       if (while_stepping)
1135         {
1136           struct command_line *c2;
1137
1138           gdb_assert (while_stepping->body_count == 1);
1139           c2 = while_stepping->body_list[0];
1140           for (; c2; c2 = c2->next)
1141             {
1142               if (c2->control_type == while_stepping_control)
1143                 error (_("The 'while-stepping' command cannot be nested"));
1144             }
1145         }
1146     }
1147   else
1148     {
1149       check_no_tracepoint_commands (commands);
1150     }
1151 }
1152
1153 /* Return a vector of all the static tracepoints set at ADDR.  The
1154    caller is responsible for releasing the vector.  */
1155
1156 VEC(breakpoint_p) *
1157 static_tracepoints_here (CORE_ADDR addr)
1158 {
1159   struct breakpoint *b;
1160   VEC(breakpoint_p) *found = 0;
1161   struct bp_location *loc;
1162
1163   ALL_BREAKPOINTS (b)
1164     if (b->type == bp_static_tracepoint)
1165       {
1166         for (loc = b->loc; loc; loc = loc->next)
1167           if (loc->address == addr)
1168             VEC_safe_push(breakpoint_p, found, b);
1169       }
1170
1171   return found;
1172 }
1173
1174 /* Set the command list of B to COMMANDS.  If breakpoint is tracepoint,
1175    validate that only allowed commands are included.  */
1176
1177 void
1178 breakpoint_set_commands (struct breakpoint *b, 
1179                          command_line_up &&commands)
1180 {
1181   validate_commands_for_breakpoint (b, commands.get ());
1182
1183   b->commands = std::move (commands);
1184   observer_notify_breakpoint_modified (b);
1185 }
1186
1187 /* Set the internal `silent' flag on the breakpoint.  Note that this
1188    is not the same as the "silent" that may appear in the breakpoint's
1189    commands.  */
1190
1191 void
1192 breakpoint_set_silent (struct breakpoint *b, int silent)
1193 {
1194   int old_silent = b->silent;
1195
1196   b->silent = silent;
1197   if (old_silent != silent)
1198     observer_notify_breakpoint_modified (b);
1199 }
1200
1201 /* Set the thread for this breakpoint.  If THREAD is -1, make the
1202    breakpoint work for any thread.  */
1203
1204 void
1205 breakpoint_set_thread (struct breakpoint *b, int thread)
1206 {
1207   int old_thread = b->thread;
1208
1209   b->thread = thread;
1210   if (old_thread != thread)
1211     observer_notify_breakpoint_modified (b);
1212 }
1213
1214 /* Set the task for this breakpoint.  If TASK is 0, make the
1215    breakpoint work for any task.  */
1216
1217 void
1218 breakpoint_set_task (struct breakpoint *b, int task)
1219 {
1220   int old_task = b->task;
1221
1222   b->task = task;
1223   if (old_task != task)
1224     observer_notify_breakpoint_modified (b);
1225 }
1226
1227 void
1228 check_tracepoint_command (char *line, void *closure)
1229 {
1230   struct breakpoint *b = (struct breakpoint *) closure;
1231
1232   validate_actionline (line, b);
1233 }
1234
1235 static void
1236 commands_command_1 (const char *arg, int from_tty,
1237                     struct command_line *control)
1238 {
1239   counted_command_line cmd;
1240
1241   std::string new_arg;
1242
1243   if (arg == NULL || !*arg)
1244     {
1245       if (breakpoint_count - prev_breakpoint_count > 1)
1246         new_arg = string_printf ("%d-%d", prev_breakpoint_count + 1,
1247                                  breakpoint_count);
1248       else if (breakpoint_count > 0)
1249         new_arg = string_printf ("%d", breakpoint_count);
1250       arg = new_arg.c_str ();
1251     }
1252
1253   map_breakpoint_numbers
1254     (arg, [&] (breakpoint *b)
1255      {
1256        if (cmd == NULL)
1257          {
1258            if (control != NULL)
1259              cmd = copy_command_lines (control->body_list[0]);
1260            else
1261              {
1262                std::string str
1263                  = string_printf (_("Type commands for breakpoint(s) "
1264                                     "%s, one per line."),
1265                                   arg);
1266
1267                cmd = read_command_lines (&str[0],
1268                                          from_tty, 1,
1269                                          (is_tracepoint (b)
1270                                           ? check_tracepoint_command : 0),
1271                                          b);
1272              }
1273          }
1274
1275        /* If a breakpoint was on the list more than once, we don't need to
1276           do anything.  */
1277        if (b->commands != cmd)
1278          {
1279            validate_commands_for_breakpoint (b, cmd.get ());
1280            b->commands = cmd;
1281            observer_notify_breakpoint_modified (b);
1282          }
1283      });
1284
1285   if (cmd == NULL)
1286     error (_("No breakpoints specified."));
1287 }
1288
1289 static void
1290 commands_command (const char *arg, int from_tty)
1291 {
1292   commands_command_1 (arg, from_tty, NULL);
1293 }
1294
1295 /* Like commands_command, but instead of reading the commands from
1296    input stream, takes them from an already parsed command structure.
1297
1298    This is used by cli-script.c to DTRT with breakpoint commands
1299    that are part of if and while bodies.  */
1300 enum command_control_type
1301 commands_from_control_command (const char *arg, struct command_line *cmd)
1302 {
1303   commands_command_1 (arg, 0, cmd);
1304   return simple_control;
1305 }
1306
1307 /* Return non-zero if BL->TARGET_INFO contains valid information.  */
1308
1309 static int
1310 bp_location_has_shadow (struct bp_location *bl)
1311 {
1312   if (bl->loc_type != bp_loc_software_breakpoint)
1313     return 0;
1314   if (!bl->inserted)
1315     return 0;
1316   if (bl->target_info.shadow_len == 0)
1317     /* BL isn't valid, or doesn't shadow memory.  */
1318     return 0;
1319   return 1;
1320 }
1321
1322 /* Update BUF, which is LEN bytes read from the target address
1323    MEMADDR, by replacing a memory breakpoint with its shadowed
1324    contents.
1325
1326    If READBUF is not NULL, this buffer must not overlap with the of
1327    the breakpoint location's shadow_contents buffer.  Otherwise, a
1328    failed assertion internal error will be raised.  */
1329
1330 static void
1331 one_breakpoint_xfer_memory (gdb_byte *readbuf, gdb_byte *writebuf,
1332                             const gdb_byte *writebuf_org,
1333                             ULONGEST memaddr, LONGEST len,
1334                             struct bp_target_info *target_info,
1335                             struct gdbarch *gdbarch)
1336 {
1337   /* Now do full processing of the found relevant range of elements.  */
1338   CORE_ADDR bp_addr = 0;
1339   int bp_size = 0;
1340   int bptoffset = 0;
1341
1342   if (!breakpoint_address_match (target_info->placed_address_space, 0,
1343                                  current_program_space->aspace, 0))
1344     {
1345       /* The breakpoint is inserted in a different address space.  */
1346       return;
1347     }
1348
1349   /* Addresses and length of the part of the breakpoint that
1350      we need to copy.  */
1351   bp_addr = target_info->placed_address;
1352   bp_size = target_info->shadow_len;
1353
1354   if (bp_addr + bp_size <= memaddr)
1355     {
1356       /* The breakpoint is entirely before the chunk of memory we are
1357          reading.  */
1358       return;
1359     }
1360
1361   if (bp_addr >= memaddr + len)
1362     {
1363       /* The breakpoint is entirely after the chunk of memory we are
1364          reading.  */
1365       return;
1366     }
1367
1368   /* Offset within shadow_contents.  */
1369   if (bp_addr < memaddr)
1370     {
1371       /* Only copy the second part of the breakpoint.  */
1372       bp_size -= memaddr - bp_addr;
1373       bptoffset = memaddr - bp_addr;
1374       bp_addr = memaddr;
1375     }
1376
1377   if (bp_addr + bp_size > memaddr + len)
1378     {
1379       /* Only copy the first part of the breakpoint.  */
1380       bp_size -= (bp_addr + bp_size) - (memaddr + len);
1381     }
1382
1383   if (readbuf != NULL)
1384     {
1385       /* Verify that the readbuf buffer does not overlap with the
1386          shadow_contents buffer.  */
1387       gdb_assert (target_info->shadow_contents >= readbuf + len
1388                   || readbuf >= (target_info->shadow_contents
1389                                  + target_info->shadow_len));
1390
1391       /* Update the read buffer with this inserted breakpoint's
1392          shadow.  */
1393       memcpy (readbuf + bp_addr - memaddr,
1394               target_info->shadow_contents + bptoffset, bp_size);
1395     }
1396   else
1397     {
1398       const unsigned char *bp;
1399       CORE_ADDR addr = target_info->reqstd_address;
1400       int placed_size;
1401
1402       /* Update the shadow with what we want to write to memory.  */
1403       memcpy (target_info->shadow_contents + bptoffset,
1404               writebuf_org + bp_addr - memaddr, bp_size);
1405
1406       /* Determine appropriate breakpoint contents and size for this
1407          address.  */
1408       bp = gdbarch_breakpoint_from_pc (gdbarch, &addr, &placed_size);
1409
1410       /* Update the final write buffer with this inserted
1411          breakpoint's INSN.  */
1412       memcpy (writebuf + bp_addr - memaddr, bp + bptoffset, bp_size);
1413     }
1414 }
1415
1416 /* Update BUF, which is LEN bytes read from the target address MEMADDR,
1417    by replacing any memory breakpoints with their shadowed contents.
1418
1419    If READBUF is not NULL, this buffer must not overlap with any of
1420    the breakpoint location's shadow_contents buffers.  Otherwise,
1421    a failed assertion internal error will be raised.
1422
1423    The range of shadowed area by each bp_location is:
1424      bl->address - bp_locations_placed_address_before_address_max
1425      up to bl->address + bp_locations_shadow_len_after_address_max
1426    The range we were requested to resolve shadows for is:
1427      memaddr ... memaddr + len
1428    Thus the safe cutoff boundaries for performance optimization are
1429      memaddr + len <= (bl->address
1430                        - bp_locations_placed_address_before_address_max)
1431    and:
1432      bl->address + bp_locations_shadow_len_after_address_max <= memaddr  */
1433
1434 void
1435 breakpoint_xfer_memory (gdb_byte *readbuf, gdb_byte *writebuf,
1436                         const gdb_byte *writebuf_org,
1437                         ULONGEST memaddr, LONGEST len)
1438 {
1439   /* Left boundary, right boundary and median element of our binary
1440      search.  */
1441   unsigned bc_l, bc_r, bc;
1442
1443   /* Find BC_L which is a leftmost element which may affect BUF
1444      content.  It is safe to report lower value but a failure to
1445      report higher one.  */
1446
1447   bc_l = 0;
1448   bc_r = bp_locations_count;
1449   while (bc_l + 1 < bc_r)
1450     {
1451       struct bp_location *bl;
1452
1453       bc = (bc_l + bc_r) / 2;
1454       bl = bp_locations[bc];
1455
1456       /* Check first BL->ADDRESS will not overflow due to the added
1457          constant.  Then advance the left boundary only if we are sure
1458          the BC element can in no way affect the BUF content (MEMADDR
1459          to MEMADDR + LEN range).
1460
1461          Use the BP_LOCATIONS_SHADOW_LEN_AFTER_ADDRESS_MAX safety
1462          offset so that we cannot miss a breakpoint with its shadow
1463          range tail still reaching MEMADDR.  */
1464
1465       if ((bl->address + bp_locations_shadow_len_after_address_max
1466            >= bl->address)
1467           && (bl->address + bp_locations_shadow_len_after_address_max
1468               <= memaddr))
1469         bc_l = bc;
1470       else
1471         bc_r = bc;
1472     }
1473
1474   /* Due to the binary search above, we need to make sure we pick the
1475      first location that's at BC_L's address.  E.g., if there are
1476      multiple locations at the same address, BC_L may end up pointing
1477      at a duplicate location, and miss the "master"/"inserted"
1478      location.  Say, given locations L1, L2 and L3 at addresses A and
1479      B:
1480
1481       L1@A, L2@A, L3@B, ...
1482
1483      BC_L could end up pointing at location L2, while the "master"
1484      location could be L1.  Since the `loc->inserted' flag is only set
1485      on "master" locations, we'd forget to restore the shadow of L1
1486      and L2.  */
1487   while (bc_l > 0
1488          && bp_locations[bc_l]->address == bp_locations[bc_l - 1]->address)
1489     bc_l--;
1490
1491   /* Now do full processing of the found relevant range of elements.  */
1492
1493   for (bc = bc_l; bc < bp_locations_count; bc++)
1494   {
1495     struct bp_location *bl = bp_locations[bc];
1496
1497     /* bp_location array has BL->OWNER always non-NULL.  */
1498     if (bl->owner->type == bp_none)
1499       warning (_("reading through apparently deleted breakpoint #%d?"),
1500                bl->owner->number);
1501
1502     /* Performance optimization: any further element can no longer affect BUF
1503        content.  */
1504
1505     if (bl->address >= bp_locations_placed_address_before_address_max
1506         && memaddr + len <= (bl->address
1507                              - bp_locations_placed_address_before_address_max))
1508       break;
1509
1510     if (!bp_location_has_shadow (bl))
1511       continue;
1512
1513     one_breakpoint_xfer_memory (readbuf, writebuf, writebuf_org,
1514                                 memaddr, len, &bl->target_info, bl->gdbarch);
1515   }
1516 }
1517
1518 \f
1519
1520 /* Return true if BPT is either a software breakpoint or a hardware
1521    breakpoint.  */
1522
1523 int
1524 is_breakpoint (const struct breakpoint *bpt)
1525 {
1526   return (bpt->type == bp_breakpoint
1527           || bpt->type == bp_hardware_breakpoint
1528           || bpt->type == bp_dprintf);
1529 }
1530
1531 /* Return true if BPT is of any hardware watchpoint kind.  */
1532
1533 static int
1534 is_hardware_watchpoint (const struct breakpoint *bpt)
1535 {
1536   return (bpt->type == bp_hardware_watchpoint
1537           || bpt->type == bp_read_watchpoint
1538           || bpt->type == bp_access_watchpoint);
1539 }
1540
1541 /* Return true if BPT is of any watchpoint kind, hardware or
1542    software.  */
1543
1544 int
1545 is_watchpoint (const struct breakpoint *bpt)
1546 {
1547   return (is_hardware_watchpoint (bpt)
1548           || bpt->type == bp_watchpoint);
1549 }
1550
1551 /* Returns true if the current thread and its running state are safe
1552    to evaluate or update watchpoint B.  Watchpoints on local
1553    expressions need to be evaluated in the context of the thread that
1554    was current when the watchpoint was created, and, that thread needs
1555    to be stopped to be able to select the correct frame context.
1556    Watchpoints on global expressions can be evaluated on any thread,
1557    and in any state.  It is presently left to the target allowing
1558    memory accesses when threads are running.  */
1559
1560 static int
1561 watchpoint_in_thread_scope (struct watchpoint *b)
1562 {
1563   return (b->pspace == current_program_space
1564           && (ptid_equal (b->watchpoint_thread, null_ptid)
1565               || (ptid_equal (inferior_ptid, b->watchpoint_thread)
1566                   && !is_executing (inferior_ptid))));
1567 }
1568
1569 /* Set watchpoint B to disp_del_at_next_stop, even including its possible
1570    associated bp_watchpoint_scope breakpoint.  */
1571
1572 static void
1573 watchpoint_del_at_next_stop (struct watchpoint *w)
1574 {
1575   if (w->related_breakpoint != w)
1576     {
1577       gdb_assert (w->related_breakpoint->type == bp_watchpoint_scope);
1578       gdb_assert (w->related_breakpoint->related_breakpoint == w);
1579       w->related_breakpoint->disposition = disp_del_at_next_stop;
1580       w->related_breakpoint->related_breakpoint = w->related_breakpoint;
1581       w->related_breakpoint = w;
1582     }
1583   w->disposition = disp_del_at_next_stop;
1584 }
1585
1586 /* Extract a bitfield value from value VAL using the bit parameters contained in
1587    watchpoint W.  */
1588
1589 static struct value *
1590 extract_bitfield_from_watchpoint_value (struct watchpoint *w, struct value *val)
1591 {
1592   struct value *bit_val;
1593
1594   if (val == NULL)
1595     return NULL;
1596
1597   bit_val = allocate_value (value_type (val));
1598
1599   unpack_value_bitfield (bit_val,
1600                          w->val_bitpos,
1601                          w->val_bitsize,
1602                          value_contents_for_printing (val),
1603                          value_offset (val),
1604                          val);
1605
1606   return bit_val;
1607 }
1608
1609 /* Allocate a dummy location and add it to B, which must be a software
1610    watchpoint.  This is required because even if a software watchpoint
1611    is not watching any memory, bpstat_stop_status requires a location
1612    to be able to report stops.  */
1613
1614 static void
1615 software_watchpoint_add_no_memory_location (struct breakpoint *b,
1616                                             struct program_space *pspace)
1617 {
1618   gdb_assert (b->type == bp_watchpoint && b->loc == NULL);
1619
1620   b->loc = allocate_bp_location (b);
1621   b->loc->pspace = pspace;
1622   b->loc->address = -1;
1623   b->loc->length = -1;
1624 }
1625
1626 /* Returns true if B is a software watchpoint that is not watching any
1627    memory (e.g., "watch $pc").  */
1628
1629 static int
1630 is_no_memory_software_watchpoint (struct breakpoint *b)
1631 {
1632   return (b->type == bp_watchpoint
1633           && b->loc != NULL
1634           && b->loc->next == NULL
1635           && b->loc->address == -1
1636           && b->loc->length == -1);
1637 }
1638
1639 /* Assuming that B is a watchpoint:
1640    - Reparse watchpoint expression, if REPARSE is non-zero
1641    - Evaluate expression and store the result in B->val
1642    - Evaluate the condition if there is one, and store the result
1643      in b->loc->cond.
1644    - Update the list of values that must be watched in B->loc.
1645
1646    If the watchpoint disposition is disp_del_at_next_stop, then do
1647    nothing.  If this is local watchpoint that is out of scope, delete
1648    it.
1649
1650    Even with `set breakpoint always-inserted on' the watchpoints are
1651    removed + inserted on each stop here.  Normal breakpoints must
1652    never be removed because they might be missed by a running thread
1653    when debugging in non-stop mode.  On the other hand, hardware
1654    watchpoints (is_hardware_watchpoint; processed here) are specific
1655    to each LWP since they are stored in each LWP's hardware debug
1656    registers.  Therefore, such LWP must be stopped first in order to
1657    be able to modify its hardware watchpoints.
1658
1659    Hardware watchpoints must be reset exactly once after being
1660    presented to the user.  It cannot be done sooner, because it would
1661    reset the data used to present the watchpoint hit to the user.  And
1662    it must not be done later because it could display the same single
1663    watchpoint hit during multiple GDB stops.  Note that the latter is
1664    relevant only to the hardware watchpoint types bp_read_watchpoint
1665    and bp_access_watchpoint.  False hit by bp_hardware_watchpoint is
1666    not user-visible - its hit is suppressed if the memory content has
1667    not changed.
1668
1669    The following constraints influence the location where we can reset
1670    hardware watchpoints:
1671
1672    * target_stopped_by_watchpoint and target_stopped_data_address are
1673      called several times when GDB stops.
1674
1675    [linux] 
1676    * Multiple hardware watchpoints can be hit at the same time,
1677      causing GDB to stop.  GDB only presents one hardware watchpoint
1678      hit at a time as the reason for stopping, and all the other hits
1679      are presented later, one after the other, each time the user
1680      requests the execution to be resumed.  Execution is not resumed
1681      for the threads still having pending hit event stored in
1682      LWP_INFO->STATUS.  While the watchpoint is already removed from
1683      the inferior on the first stop the thread hit event is kept being
1684      reported from its cached value by linux_nat_stopped_data_address
1685      until the real thread resume happens after the watchpoint gets
1686      presented and thus its LWP_INFO->STATUS gets reset.
1687
1688    Therefore the hardware watchpoint hit can get safely reset on the
1689    watchpoint removal from inferior.  */
1690
1691 static void
1692 update_watchpoint (struct watchpoint *b, int reparse)
1693 {
1694   int within_current_scope;
1695   struct frame_id saved_frame_id;
1696   int frame_saved;
1697
1698   /* If this is a local watchpoint, we only want to check if the
1699      watchpoint frame is in scope if the current thread is the thread
1700      that was used to create the watchpoint.  */
1701   if (!watchpoint_in_thread_scope (b))
1702     return;
1703
1704   if (b->disposition == disp_del_at_next_stop)
1705     return;
1706  
1707   frame_saved = 0;
1708
1709   /* Determine if the watchpoint is within scope.  */
1710   if (b->exp_valid_block == NULL)
1711     within_current_scope = 1;
1712   else
1713     {
1714       struct frame_info *fi = get_current_frame ();
1715       struct gdbarch *frame_arch = get_frame_arch (fi);
1716       CORE_ADDR frame_pc = get_frame_pc (fi);
1717
1718       /* If we're at a point where the stack has been destroyed
1719          (e.g. in a function epilogue), unwinding may not work
1720          properly. Do not attempt to recreate locations at this
1721          point.  See similar comments in watchpoint_check.  */
1722       if (gdbarch_stack_frame_destroyed_p (frame_arch, frame_pc))
1723         return;
1724
1725       /* Save the current frame's ID so we can restore it after
1726          evaluating the watchpoint expression on its own frame.  */
1727       /* FIXME drow/2003-09-09: It would be nice if evaluate_expression
1728          took a frame parameter, so that we didn't have to change the
1729          selected frame.  */
1730       frame_saved = 1;
1731       saved_frame_id = get_frame_id (get_selected_frame (NULL));
1732
1733       fi = frame_find_by_id (b->watchpoint_frame);
1734       within_current_scope = (fi != NULL);
1735       if (within_current_scope)
1736         select_frame (fi);
1737     }
1738
1739   /* We don't free locations.  They are stored in the bp_location array
1740      and update_global_location_list will eventually delete them and
1741      remove breakpoints if needed.  */
1742   b->loc = NULL;
1743
1744   if (within_current_scope && reparse)
1745     {
1746       const char *s;
1747
1748       b->exp.reset ();
1749       s = b->exp_string_reparse ? b->exp_string_reparse : b->exp_string;
1750       b->exp = parse_exp_1 (&s, 0, b->exp_valid_block, 0);
1751       /* If the meaning of expression itself changed, the old value is
1752          no longer relevant.  We don't want to report a watchpoint hit
1753          to the user when the old value and the new value may actually
1754          be completely different objects.  */
1755       value_free (b->val);
1756       b->val = NULL;
1757       b->val_valid = 0;
1758
1759       /* Note that unlike with breakpoints, the watchpoint's condition
1760          expression is stored in the breakpoint object, not in the
1761          locations (re)created below.  */
1762       if (b->cond_string != NULL)
1763         {
1764           b->cond_exp.reset ();
1765
1766           s = b->cond_string;
1767           b->cond_exp = parse_exp_1 (&s, 0, b->cond_exp_valid_block, 0);
1768         }
1769     }
1770
1771   /* If we failed to parse the expression, for example because
1772      it refers to a global variable in a not-yet-loaded shared library,
1773      don't try to insert watchpoint.  We don't automatically delete
1774      such watchpoint, though, since failure to parse expression
1775      is different from out-of-scope watchpoint.  */
1776   if (!target_has_execution)
1777     {
1778       /* Without execution, memory can't change.  No use to try and
1779          set watchpoint locations.  The watchpoint will be reset when
1780          the target gains execution, through breakpoint_re_set.  */
1781       if (!can_use_hw_watchpoints)
1782         {
1783           if (b->ops->works_in_software_mode (b))
1784             b->type = bp_watchpoint;
1785           else
1786             error (_("Can't set read/access watchpoint when "
1787                      "hardware watchpoints are disabled."));
1788         }
1789     }
1790   else if (within_current_scope && b->exp)
1791     {
1792       int pc = 0;
1793       struct value *val_chain, *v, *result, *next;
1794       struct program_space *frame_pspace;
1795
1796       fetch_subexp_value (b->exp.get (), &pc, &v, &result, &val_chain, 0);
1797
1798       /* Avoid setting b->val if it's already set.  The meaning of
1799          b->val is 'the last value' user saw, and we should update
1800          it only if we reported that last value to user.  As it
1801          happens, the code that reports it updates b->val directly.
1802          We don't keep track of the memory value for masked
1803          watchpoints.  */
1804       if (!b->val_valid && !is_masked_watchpoint (b))
1805         {
1806           if (b->val_bitsize != 0)
1807             {
1808               v = extract_bitfield_from_watchpoint_value (b, v);
1809               if (v != NULL)
1810                 release_value (v);
1811             }
1812           b->val = v;
1813           b->val_valid = 1;
1814         }
1815
1816       frame_pspace = get_frame_program_space (get_selected_frame (NULL));
1817
1818       /* Look at each value on the value chain.  */
1819       for (v = val_chain; v; v = value_next (v))
1820         {
1821           /* If it's a memory location, and GDB actually needed
1822              its contents to evaluate the expression, then we
1823              must watch it.  If the first value returned is
1824              still lazy, that means an error occurred reading it;
1825              watch it anyway in case it becomes readable.  */
1826           if (VALUE_LVAL (v) == lval_memory
1827               && (v == val_chain || ! value_lazy (v)))
1828             {
1829               struct type *vtype = check_typedef (value_type (v));
1830
1831               /* We only watch structs and arrays if user asked
1832                  for it explicitly, never if they just happen to
1833                  appear in the middle of some value chain.  */
1834               if (v == result
1835                   || (TYPE_CODE (vtype) != TYPE_CODE_STRUCT
1836                       && TYPE_CODE (vtype) != TYPE_CODE_ARRAY))
1837                 {
1838                   CORE_ADDR addr;
1839                   enum target_hw_bp_type type;
1840                   struct bp_location *loc, **tmp;
1841                   int bitpos = 0, bitsize = 0;
1842
1843                   if (value_bitsize (v) != 0)
1844                     {
1845                       /* Extract the bit parameters out from the bitfield
1846                          sub-expression.  */
1847                       bitpos = value_bitpos (v);
1848                       bitsize = value_bitsize (v);
1849                     }
1850                   else if (v == result && b->val_bitsize != 0)
1851                     {
1852                      /* If VAL_BITSIZE != 0 then RESULT is actually a bitfield
1853                         lvalue whose bit parameters are saved in the fields
1854                         VAL_BITPOS and VAL_BITSIZE.  */
1855                       bitpos = b->val_bitpos;
1856                       bitsize = b->val_bitsize;
1857                     }
1858
1859                   addr = value_address (v);
1860                   if (bitsize != 0)
1861                     {
1862                       /* Skip the bytes that don't contain the bitfield.  */
1863                       addr += bitpos / 8;
1864                     }
1865
1866                   type = hw_write;
1867                   if (b->type == bp_read_watchpoint)
1868                     type = hw_read;
1869                   else if (b->type == bp_access_watchpoint)
1870                     type = hw_access;
1871
1872                   loc = allocate_bp_location (b);
1873                   for (tmp = &(b->loc); *tmp != NULL; tmp = &((*tmp)->next))
1874                     ;
1875                   *tmp = loc;
1876                   loc->gdbarch = get_type_arch (value_type (v));
1877
1878                   loc->pspace = frame_pspace;
1879                   loc->address = addr;
1880
1881                   if (bitsize != 0)
1882                     {
1883                       /* Just cover the bytes that make up the bitfield.  */
1884                       loc->length = ((bitpos % 8) + bitsize + 7) / 8;
1885                     }
1886                   else
1887                     loc->length = TYPE_LENGTH (value_type (v));
1888
1889                   loc->watchpoint_type = type;
1890                 }
1891             }
1892         }
1893
1894       /* Change the type of breakpoint between hardware assisted or
1895          an ordinary watchpoint depending on the hardware support
1896          and free hardware slots.  REPARSE is set when the inferior
1897          is started.  */
1898       if (reparse)
1899         {
1900           int reg_cnt;
1901           enum bp_loc_type loc_type;
1902           struct bp_location *bl;
1903
1904           reg_cnt = can_use_hardware_watchpoint (val_chain);
1905
1906           if (reg_cnt)
1907             {
1908               int i, target_resources_ok, other_type_used;
1909               enum bptype type;
1910
1911               /* Use an exact watchpoint when there's only one memory region to be
1912                  watched, and only one debug register is needed to watch it.  */
1913               b->exact = target_exact_watchpoints && reg_cnt == 1;
1914
1915               /* We need to determine how many resources are already
1916                  used for all other hardware watchpoints plus this one
1917                  to see if we still have enough resources to also fit
1918                  this watchpoint in as well.  */
1919
1920               /* If this is a software watchpoint, we try to turn it
1921                  to a hardware one -- count resources as if B was of
1922                  hardware watchpoint type.  */
1923               type = b->type;
1924               if (type == bp_watchpoint)
1925                 type = bp_hardware_watchpoint;
1926
1927               /* This watchpoint may or may not have been placed on
1928                  the list yet at this point (it won't be in the list
1929                  if we're trying to create it for the first time,
1930                  through watch_command), so always account for it
1931                  manually.  */
1932
1933               /* Count resources used by all watchpoints except B.  */
1934               i = hw_watchpoint_used_count_others (b, type, &other_type_used);
1935
1936               /* Add in the resources needed for B.  */
1937               i += hw_watchpoint_use_count (b);
1938
1939               target_resources_ok
1940                 = target_can_use_hardware_watchpoint (type, i, other_type_used);
1941               if (target_resources_ok <= 0)
1942                 {
1943                   int sw_mode = b->ops->works_in_software_mode (b);
1944
1945                   if (target_resources_ok == 0 && !sw_mode)
1946                     error (_("Target does not support this type of "
1947                              "hardware watchpoint."));
1948                   else if (target_resources_ok < 0 && !sw_mode)
1949                     error (_("There are not enough available hardware "
1950                              "resources for this watchpoint."));
1951
1952                   /* Downgrade to software watchpoint.  */
1953                   b->type = bp_watchpoint;
1954                 }
1955               else
1956                 {
1957                   /* If this was a software watchpoint, we've just
1958                      found we have enough resources to turn it to a
1959                      hardware watchpoint.  Otherwise, this is a
1960                      nop.  */
1961                   b->type = type;
1962                 }
1963             }
1964           else if (!b->ops->works_in_software_mode (b))
1965             {
1966               if (!can_use_hw_watchpoints)
1967                 error (_("Can't set read/access watchpoint when "
1968                          "hardware watchpoints are disabled."));
1969               else
1970                 error (_("Expression cannot be implemented with "
1971                          "read/access watchpoint."));
1972             }
1973           else
1974             b->type = bp_watchpoint;
1975
1976           loc_type = (b->type == bp_watchpoint? bp_loc_other
1977                       : bp_loc_hardware_watchpoint);
1978           for (bl = b->loc; bl; bl = bl->next)
1979             bl->loc_type = loc_type;
1980         }
1981
1982       for (v = val_chain; v; v = next)
1983         {
1984           next = value_next (v);
1985           if (v != b->val)
1986             value_free (v);
1987         }
1988
1989       /* If a software watchpoint is not watching any memory, then the
1990          above left it without any location set up.  But,
1991          bpstat_stop_status requires a location to be able to report
1992          stops, so make sure there's at least a dummy one.  */
1993       if (b->type == bp_watchpoint && b->loc == NULL)
1994         software_watchpoint_add_no_memory_location (b, frame_pspace);
1995     }
1996   else if (!within_current_scope)
1997     {
1998       printf_filtered (_("\
1999 Watchpoint %d deleted because the program has left the block\n\
2000 in which its expression is valid.\n"),
2001                        b->number);
2002       watchpoint_del_at_next_stop (b);
2003     }
2004
2005   /* Restore the selected frame.  */
2006   if (frame_saved)
2007     select_frame (frame_find_by_id (saved_frame_id));
2008 }
2009
2010
2011 /* Returns 1 iff breakpoint location should be
2012    inserted in the inferior.  We don't differentiate the type of BL's owner
2013    (breakpoint vs. tracepoint), although insert_location in tracepoint's
2014    breakpoint_ops is not defined, because in insert_bp_location,
2015    tracepoint's insert_location will not be called.  */
2016 static int
2017 should_be_inserted (struct bp_location *bl)
2018 {
2019   if (bl->owner == NULL || !breakpoint_enabled (bl->owner))
2020     return 0;
2021
2022   if (bl->owner->disposition == disp_del_at_next_stop)
2023     return 0;
2024
2025   if (!bl->enabled || bl->shlib_disabled || bl->duplicate)
2026     return 0;
2027
2028   if (user_breakpoint_p (bl->owner) && bl->pspace->executing_startup)
2029     return 0;
2030
2031   /* This is set for example, when we're attached to the parent of a
2032      vfork, and have detached from the child.  The child is running
2033      free, and we expect it to do an exec or exit, at which point the
2034      OS makes the parent schedulable again (and the target reports
2035      that the vfork is done).  Until the child is done with the shared
2036      memory region, do not insert breakpoints in the parent, otherwise
2037      the child could still trip on the parent's breakpoints.  Since
2038      the parent is blocked anyway, it won't miss any breakpoint.  */
2039   if (bl->pspace->breakpoints_not_allowed)
2040     return 0;
2041
2042   /* Don't insert a breakpoint if we're trying to step past its
2043      location, except if the breakpoint is a single-step breakpoint,
2044      and the breakpoint's thread is the thread which is stepping past
2045      a breakpoint.  */
2046   if ((bl->loc_type == bp_loc_software_breakpoint
2047        || bl->loc_type == bp_loc_hardware_breakpoint)
2048       && stepping_past_instruction_at (bl->pspace->aspace,
2049                                        bl->address)
2050       /* The single-step breakpoint may be inserted at the location
2051          we're trying to step if the instruction branches to itself.
2052          However, the instruction won't be executed at all and it may
2053          break the semantics of the instruction, for example, the
2054          instruction is a conditional branch or updates some flags.
2055          We can't fix it unless GDB is able to emulate the instruction
2056          or switch to displaced stepping.  */
2057       && !(bl->owner->type == bp_single_step
2058            && thread_is_stepping_over_breakpoint (bl->owner->thread)))
2059     {
2060       if (debug_infrun)
2061         {
2062           fprintf_unfiltered (gdb_stdlog,
2063                               "infrun: skipping breakpoint: "
2064                               "stepping past insn at: %s\n",
2065                               paddress (bl->gdbarch, bl->address));
2066         }
2067       return 0;
2068     }
2069
2070   /* Don't insert watchpoints if we're trying to step past the
2071      instruction that triggered one.  */
2072   if ((bl->loc_type == bp_loc_hardware_watchpoint)
2073       && stepping_past_nonsteppable_watchpoint ())
2074     {
2075       if (debug_infrun)
2076         {
2077           fprintf_unfiltered (gdb_stdlog,
2078                               "infrun: stepping past non-steppable watchpoint. "
2079                               "skipping watchpoint at %s:%d\n",
2080                               paddress (bl->gdbarch, bl->address),
2081                               bl->length);
2082         }
2083       return 0;
2084     }
2085
2086   return 1;
2087 }
2088
2089 /* Same as should_be_inserted but does the check assuming
2090    that the location is not duplicated.  */
2091
2092 static int
2093 unduplicated_should_be_inserted (struct bp_location *bl)
2094 {
2095   int result;
2096   const int save_duplicate = bl->duplicate;
2097
2098   bl->duplicate = 0;
2099   result = should_be_inserted (bl);
2100   bl->duplicate = save_duplicate;
2101   return result;
2102 }
2103
2104 /* Parses a conditional described by an expression COND into an
2105    agent expression bytecode suitable for evaluation
2106    by the bytecode interpreter.  Return NULL if there was
2107    any error during parsing.  */
2108
2109 static agent_expr_up
2110 parse_cond_to_aexpr (CORE_ADDR scope, struct expression *cond)
2111 {
2112   if (cond == NULL)
2113     return NULL;
2114
2115   agent_expr_up aexpr;
2116
2117   /* We don't want to stop processing, so catch any errors
2118      that may show up.  */
2119   TRY
2120     {
2121       aexpr = gen_eval_for_expr (scope, cond);
2122     }
2123
2124   CATCH (ex, RETURN_MASK_ERROR)
2125     {
2126       /* If we got here, it means the condition could not be parsed to a valid
2127          bytecode expression and thus can't be evaluated on the target's side.
2128          It's no use iterating through the conditions.  */
2129     }
2130   END_CATCH
2131
2132   /* We have a valid agent expression.  */
2133   return aexpr;
2134 }
2135
2136 /* Based on location BL, create a list of breakpoint conditions to be
2137    passed on to the target.  If we have duplicated locations with different
2138    conditions, we will add such conditions to the list.  The idea is that the
2139    target will evaluate the list of conditions and will only notify GDB when
2140    one of them is true.  */
2141
2142 static void
2143 build_target_condition_list (struct bp_location *bl)
2144 {
2145   struct bp_location **locp = NULL, **loc2p;
2146   int null_condition_or_parse_error = 0;
2147   int modified = bl->needs_update;
2148   struct bp_location *loc;
2149
2150   /* Release conditions left over from a previous insert.  */
2151   bl->target_info.conditions.clear ();
2152
2153   /* This is only meaningful if the target is
2154      evaluating conditions and if the user has
2155      opted for condition evaluation on the target's
2156      side.  */
2157   if (gdb_evaluates_breakpoint_condition_p ()
2158       || !target_supports_evaluation_of_breakpoint_conditions ())
2159     return;
2160
2161   /* Do a first pass to check for locations with no assigned
2162      conditions or conditions that fail to parse to a valid agent expression
2163      bytecode.  If any of these happen, then it's no use to send conditions
2164      to the target since this location will always trigger and generate a
2165      response back to GDB.  */
2166   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2167     {
2168       loc = (*loc2p);
2169       if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2170         {
2171           if (modified)
2172             {
2173               /* Re-parse the conditions since something changed.  In that
2174                  case we already freed the condition bytecodes (see
2175                  force_breakpoint_reinsertion).  We just
2176                  need to parse the condition to bytecodes again.  */
2177               loc->cond_bytecode = parse_cond_to_aexpr (bl->address,
2178                                                         loc->cond.get ());
2179             }
2180
2181           /* If we have a NULL bytecode expression, it means something
2182              went wrong or we have a null condition expression.  */
2183           if (!loc->cond_bytecode)
2184             {
2185               null_condition_or_parse_error = 1;
2186               break;
2187             }
2188         }
2189     }
2190
2191   /* If any of these happened, it means we will have to evaluate the conditions
2192      for the location's address on gdb's side.  It is no use keeping bytecodes
2193      for all the other duplicate locations, thus we free all of them here.
2194
2195      This is so we have a finer control over which locations' conditions are
2196      being evaluated by GDB or the remote stub.  */
2197   if (null_condition_or_parse_error)
2198     {
2199       ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2200         {
2201           loc = (*loc2p);
2202           if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2203             {
2204               /* Only go as far as the first NULL bytecode is
2205                  located.  */
2206               if (!loc->cond_bytecode)
2207                 return;
2208
2209               loc->cond_bytecode.reset ();
2210             }
2211         }
2212     }
2213
2214   /* No NULL conditions or failed bytecode generation.  Build a condition list
2215      for this location's address.  */
2216   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2217     {
2218       loc = (*loc2p);
2219       if (loc->cond
2220           && is_breakpoint (loc->owner)
2221           && loc->pspace->num == bl->pspace->num
2222           && loc->owner->enable_state == bp_enabled
2223           && loc->enabled)
2224         {
2225           /* Add the condition to the vector.  This will be used later
2226              to send the conditions to the target.  */
2227           bl->target_info.conditions.push_back (loc->cond_bytecode.get ());
2228         }
2229     }
2230
2231   return;
2232 }
2233
2234 /* Parses a command described by string CMD into an agent expression
2235    bytecode suitable for evaluation by the bytecode interpreter.
2236    Return NULL if there was any error during parsing.  */
2237
2238 static agent_expr_up
2239 parse_cmd_to_aexpr (CORE_ADDR scope, char *cmd)
2240 {
2241   struct cleanup *old_cleanups = 0;
2242   struct expression **argvec;
2243   const char *cmdrest;
2244   const char *format_start, *format_end;
2245   struct format_piece *fpieces;
2246   int nargs;
2247   struct gdbarch *gdbarch = get_current_arch ();
2248
2249   if (cmd == NULL)
2250     return NULL;
2251
2252   cmdrest = cmd;
2253
2254   if (*cmdrest == ',')
2255     ++cmdrest;
2256   cmdrest = skip_spaces (cmdrest);
2257
2258   if (*cmdrest++ != '"')
2259     error (_("No format string following the location"));
2260
2261   format_start = cmdrest;
2262
2263   fpieces = parse_format_string (&cmdrest);
2264
2265   old_cleanups = make_cleanup (free_format_pieces_cleanup, &fpieces);
2266
2267   format_end = cmdrest;
2268
2269   if (*cmdrest++ != '"')
2270     error (_("Bad format string, non-terminated '\"'."));
2271   
2272   cmdrest = skip_spaces (cmdrest);
2273
2274   if (!(*cmdrest == ',' || *cmdrest == '\0'))
2275     error (_("Invalid argument syntax"));
2276
2277   if (*cmdrest == ',')
2278     cmdrest++;
2279   cmdrest = skip_spaces (cmdrest);
2280
2281   /* For each argument, make an expression.  */
2282
2283   argvec = (struct expression **) alloca (strlen (cmd)
2284                                          * sizeof (struct expression *));
2285
2286   nargs = 0;
2287   while (*cmdrest != '\0')
2288     {
2289       const char *cmd1;
2290
2291       cmd1 = cmdrest;
2292       expression_up expr = parse_exp_1 (&cmd1, scope, block_for_pc (scope), 1);
2293       argvec[nargs++] = expr.release ();
2294       cmdrest = cmd1;
2295       if (*cmdrest == ',')
2296         ++cmdrest;
2297     }
2298
2299   agent_expr_up aexpr;
2300
2301   /* We don't want to stop processing, so catch any errors
2302      that may show up.  */
2303   TRY
2304     {
2305       aexpr = gen_printf (scope, gdbarch, 0, 0,
2306                           format_start, format_end - format_start,
2307                           fpieces, nargs, argvec);
2308     }
2309   CATCH (ex, RETURN_MASK_ERROR)
2310     {
2311       /* If we got here, it means the command could not be parsed to a valid
2312          bytecode expression and thus can't be evaluated on the target's side.
2313          It's no use iterating through the other commands.  */
2314     }
2315   END_CATCH
2316
2317   do_cleanups (old_cleanups);
2318
2319   /* We have a valid agent expression, return it.  */
2320   return aexpr;
2321 }
2322
2323 /* Based on location BL, create a list of breakpoint commands to be
2324    passed on to the target.  If we have duplicated locations with
2325    different commands, we will add any such to the list.  */
2326
2327 static void
2328 build_target_command_list (struct bp_location *bl)
2329 {
2330   struct bp_location **locp = NULL, **loc2p;
2331   int null_command_or_parse_error = 0;
2332   int modified = bl->needs_update;
2333   struct bp_location *loc;
2334
2335   /* Clear commands left over from a previous insert.  */
2336   bl->target_info.tcommands.clear ();
2337
2338   if (!target_can_run_breakpoint_commands ())
2339     return;
2340
2341   /* For now, limit to agent-style dprintf breakpoints.  */
2342   if (dprintf_style != dprintf_style_agent)
2343     return;
2344
2345   /* For now, if we have any duplicate location that isn't a dprintf,
2346      don't install the target-side commands, as that would make the
2347      breakpoint not be reported to the core, and we'd lose
2348      control.  */
2349   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2350     {
2351       loc = (*loc2p);
2352       if (is_breakpoint (loc->owner)
2353           && loc->pspace->num == bl->pspace->num
2354           && loc->owner->type != bp_dprintf)
2355         return;
2356     }
2357
2358   /* Do a first pass to check for locations with no assigned
2359      conditions or conditions that fail to parse to a valid agent expression
2360      bytecode.  If any of these happen, then it's no use to send conditions
2361      to the target since this location will always trigger and generate a
2362      response back to GDB.  */
2363   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2364     {
2365       loc = (*loc2p);
2366       if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2367         {
2368           if (modified)
2369             {
2370               /* Re-parse the commands since something changed.  In that
2371                  case we already freed the command bytecodes (see
2372                  force_breakpoint_reinsertion).  We just
2373                  need to parse the command to bytecodes again.  */
2374               loc->cmd_bytecode
2375                 = parse_cmd_to_aexpr (bl->address,
2376                                       loc->owner->extra_string);
2377             }
2378
2379           /* If we have a NULL bytecode expression, it means something
2380              went wrong or we have a null command expression.  */
2381           if (!loc->cmd_bytecode)
2382             {
2383               null_command_or_parse_error = 1;
2384               break;
2385             }
2386         }
2387     }
2388
2389   /* If anything failed, then we're not doing target-side commands,
2390      and so clean up.  */
2391   if (null_command_or_parse_error)
2392     {
2393       ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2394         {
2395           loc = (*loc2p);
2396           if (is_breakpoint (loc->owner)
2397               && loc->pspace->num == bl->pspace->num)
2398             {
2399               /* Only go as far as the first NULL bytecode is
2400                  located.  */
2401               if (loc->cmd_bytecode == NULL)
2402                 return;
2403
2404               loc->cmd_bytecode.reset ();
2405             }
2406         }
2407     }
2408
2409   /* No NULL commands or failed bytecode generation.  Build a command list
2410      for this location's address.  */
2411   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2412     {
2413       loc = (*loc2p);
2414       if (loc->owner->extra_string
2415           && is_breakpoint (loc->owner)
2416           && loc->pspace->num == bl->pspace->num
2417           && loc->owner->enable_state == bp_enabled
2418           && loc->enabled)
2419         {
2420           /* Add the command to the vector.  This will be used later
2421              to send the commands to the target.  */
2422           bl->target_info.tcommands.push_back (loc->cmd_bytecode.get ());
2423         }
2424     }
2425
2426   bl->target_info.persist = 0;
2427   /* Maybe flag this location as persistent.  */
2428   if (bl->owner->type == bp_dprintf && disconnected_dprintf)
2429     bl->target_info.persist = 1;
2430 }
2431
2432 /* Return the kind of breakpoint on address *ADDR.  Get the kind
2433    of breakpoint according to ADDR except single-step breakpoint.
2434    Get the kind of single-step breakpoint according to the current
2435    registers state.  */
2436
2437 static int
2438 breakpoint_kind (struct bp_location *bl, CORE_ADDR *addr)
2439 {
2440   if (bl->owner->type == bp_single_step)
2441     {
2442       struct thread_info *thr = find_thread_global_id (bl->owner->thread);
2443       struct regcache *regcache;
2444
2445       regcache = get_thread_regcache (thr->ptid);
2446
2447       return gdbarch_breakpoint_kind_from_current_state (bl->gdbarch,
2448                                                          regcache, addr);
2449     }
2450   else
2451     return gdbarch_breakpoint_kind_from_pc (bl->gdbarch, addr);
2452 }
2453
2454 /* Insert a low-level "breakpoint" of some type.  BL is the breakpoint
2455    location.  Any error messages are printed to TMP_ERROR_STREAM; and
2456    DISABLED_BREAKS, and HW_BREAKPOINT_ERROR are used to report problems.
2457    Returns 0 for success, 1 if the bp_location type is not supported or
2458    -1 for failure.
2459
2460    NOTE drow/2003-09-09: This routine could be broken down to an
2461    object-style method for each breakpoint or catchpoint type.  */
2462 static int
2463 insert_bp_location (struct bp_location *bl,
2464                     struct ui_file *tmp_error_stream,
2465                     int *disabled_breaks,
2466                     int *hw_breakpoint_error,
2467                     int *hw_bp_error_explained_already)
2468 {
2469   enum errors bp_err = GDB_NO_ERROR;
2470   const char *bp_err_message = NULL;
2471
2472   if (!should_be_inserted (bl) || (bl->inserted && !bl->needs_update))
2473     return 0;
2474
2475   /* Note we don't initialize bl->target_info, as that wipes out
2476      the breakpoint location's shadow_contents if the breakpoint
2477      is still inserted at that location.  This in turn breaks
2478      target_read_memory which depends on these buffers when
2479      a memory read is requested at the breakpoint location:
2480      Once the target_info has been wiped, we fail to see that
2481      we have a breakpoint inserted at that address and thus
2482      read the breakpoint instead of returning the data saved in
2483      the breakpoint location's shadow contents.  */
2484   bl->target_info.reqstd_address = bl->address;
2485   bl->target_info.placed_address_space = bl->pspace->aspace;
2486   bl->target_info.length = bl->length;
2487
2488   /* When working with target-side conditions, we must pass all the conditions
2489      for the same breakpoint address down to the target since GDB will not
2490      insert those locations.  With a list of breakpoint conditions, the target
2491      can decide when to stop and notify GDB.  */
2492
2493   if (is_breakpoint (bl->owner))
2494     {
2495       build_target_condition_list (bl);
2496       build_target_command_list (bl);
2497       /* Reset the modification marker.  */
2498       bl->needs_update = 0;
2499     }
2500
2501   if (bl->loc_type == bp_loc_software_breakpoint
2502       || bl->loc_type == bp_loc_hardware_breakpoint)
2503     {
2504       if (bl->owner->type != bp_hardware_breakpoint)
2505         {
2506           /* If the explicitly specified breakpoint type
2507              is not hardware breakpoint, check the memory map to see
2508              if the breakpoint address is in read only memory or not.
2509
2510              Two important cases are:
2511              - location type is not hardware breakpoint, memory
2512              is readonly.  We change the type of the location to
2513              hardware breakpoint.
2514              - location type is hardware breakpoint, memory is
2515              read-write.  This means we've previously made the
2516              location hardware one, but then the memory map changed,
2517              so we undo.
2518              
2519              When breakpoints are removed, remove_breakpoints will use
2520              location types we've just set here, the only possible
2521              problem is that memory map has changed during running
2522              program, but it's not going to work anyway with current
2523              gdb.  */
2524           struct mem_region *mr 
2525             = lookup_mem_region (bl->target_info.reqstd_address);
2526           
2527           if (mr)
2528             {
2529               if (automatic_hardware_breakpoints)
2530                 {
2531                   enum bp_loc_type new_type;
2532                   
2533                   if (mr->attrib.mode != MEM_RW)
2534                     new_type = bp_loc_hardware_breakpoint;
2535                   else 
2536                     new_type = bp_loc_software_breakpoint;
2537                   
2538                   if (new_type != bl->loc_type)
2539                     {
2540                       static int said = 0;
2541
2542                       bl->loc_type = new_type;
2543                       if (!said)
2544                         {
2545                           fprintf_filtered (gdb_stdout,
2546                                             _("Note: automatically using "
2547                                               "hardware breakpoints for "
2548                                               "read-only addresses.\n"));
2549                           said = 1;
2550                         }
2551                     }
2552                 }
2553               else if (bl->loc_type == bp_loc_software_breakpoint
2554                        && mr->attrib.mode != MEM_RW)
2555                 {
2556                   fprintf_unfiltered (tmp_error_stream,
2557                                       _("Cannot insert breakpoint %d.\n"
2558                                         "Cannot set software breakpoint "
2559                                         "at read-only address %s\n"),
2560                                       bl->owner->number,
2561                                       paddress (bl->gdbarch, bl->address));
2562                   return 1;
2563                 }
2564             }
2565         }
2566         
2567       /* First check to see if we have to handle an overlay.  */
2568       if (overlay_debugging == ovly_off
2569           || bl->section == NULL
2570           || !(section_is_overlay (bl->section)))
2571         {
2572           /* No overlay handling: just set the breakpoint.  */
2573           TRY
2574             {
2575               int val;
2576
2577               val = bl->owner->ops->insert_location (bl);
2578               if (val)
2579                 bp_err = GENERIC_ERROR;
2580             }
2581           CATCH (e, RETURN_MASK_ALL)
2582             {
2583               bp_err = e.error;
2584               bp_err_message = e.message;
2585             }
2586           END_CATCH
2587         }
2588       else
2589         {
2590           /* This breakpoint is in an overlay section.
2591              Shall we set a breakpoint at the LMA?  */
2592           if (!overlay_events_enabled)
2593             {
2594               /* Yes -- overlay event support is not active, 
2595                  so we must try to set a breakpoint at the LMA.
2596                  This will not work for a hardware breakpoint.  */
2597               if (bl->loc_type == bp_loc_hardware_breakpoint)
2598                 warning (_("hardware breakpoint %d not supported in overlay!"),
2599                          bl->owner->number);
2600               else
2601                 {
2602                   CORE_ADDR addr = overlay_unmapped_address (bl->address,
2603                                                              bl->section);
2604                   /* Set a software (trap) breakpoint at the LMA.  */
2605                   bl->overlay_target_info = bl->target_info;
2606                   bl->overlay_target_info.reqstd_address = addr;
2607
2608                   /* No overlay handling: just set the breakpoint.  */
2609                   TRY
2610                     {
2611                       int val;
2612
2613                       bl->overlay_target_info.kind
2614                         = breakpoint_kind (bl, &addr);
2615                       bl->overlay_target_info.placed_address = addr;
2616                       val = target_insert_breakpoint (bl->gdbarch,
2617                                                       &bl->overlay_target_info);
2618                       if (val)
2619                         bp_err = GENERIC_ERROR;
2620                     }
2621                   CATCH (e, RETURN_MASK_ALL)
2622                     {
2623                       bp_err = e.error;
2624                       bp_err_message = e.message;
2625                     }
2626                   END_CATCH
2627
2628                   if (bp_err != GDB_NO_ERROR)
2629                     fprintf_unfiltered (tmp_error_stream,
2630                                         "Overlay breakpoint %d "
2631                                         "failed: in ROM?\n",
2632                                         bl->owner->number);
2633                 }
2634             }
2635           /* Shall we set a breakpoint at the VMA? */
2636           if (section_is_mapped (bl->section))
2637             {
2638               /* Yes.  This overlay section is mapped into memory.  */
2639               TRY
2640                 {
2641                   int val;
2642
2643                   val = bl->owner->ops->insert_location (bl);
2644                   if (val)
2645                     bp_err = GENERIC_ERROR;
2646                 }
2647               CATCH (e, RETURN_MASK_ALL)
2648                 {
2649                   bp_err = e.error;
2650                   bp_err_message = e.message;
2651                 }
2652               END_CATCH
2653             }
2654           else
2655             {
2656               /* No.  This breakpoint will not be inserted.  
2657                  No error, but do not mark the bp as 'inserted'.  */
2658               return 0;
2659             }
2660         }
2661
2662       if (bp_err != GDB_NO_ERROR)
2663         {
2664           /* Can't set the breakpoint.  */
2665
2666           /* In some cases, we might not be able to insert a
2667              breakpoint in a shared library that has already been
2668              removed, but we have not yet processed the shlib unload
2669              event.  Unfortunately, some targets that implement
2670              breakpoint insertion themselves can't tell why the
2671              breakpoint insertion failed (e.g., the remote target
2672              doesn't define error codes), so we must treat generic
2673              errors as memory errors.  */
2674           if ((bp_err == GENERIC_ERROR || bp_err == MEMORY_ERROR)
2675               && bl->loc_type == bp_loc_software_breakpoint
2676               && (solib_name_from_address (bl->pspace, bl->address)
2677                   || shared_objfile_contains_address_p (bl->pspace,
2678                                                         bl->address)))
2679             {
2680               /* See also: disable_breakpoints_in_shlibs.  */
2681               bl->shlib_disabled = 1;
2682               observer_notify_breakpoint_modified (bl->owner);
2683               if (!*disabled_breaks)
2684                 {
2685                   fprintf_unfiltered (tmp_error_stream, 
2686                                       "Cannot insert breakpoint %d.\n", 
2687                                       bl->owner->number);
2688                   fprintf_unfiltered (tmp_error_stream, 
2689                                       "Temporarily disabling shared "
2690                                       "library breakpoints:\n");
2691                 }
2692               *disabled_breaks = 1;
2693               fprintf_unfiltered (tmp_error_stream,
2694                                   "breakpoint #%d\n", bl->owner->number);
2695               return 0;
2696             }
2697           else
2698             {
2699               if (bl->loc_type == bp_loc_hardware_breakpoint)
2700                 {
2701                   *hw_breakpoint_error = 1;
2702                   *hw_bp_error_explained_already = bp_err_message != NULL;
2703                   fprintf_unfiltered (tmp_error_stream,
2704                                       "Cannot insert hardware breakpoint %d%s",
2705                                       bl->owner->number, bp_err_message ? ":" : ".\n");
2706                   if (bp_err_message != NULL)
2707                     fprintf_unfiltered (tmp_error_stream, "%s.\n", bp_err_message);
2708                 }
2709               else
2710                 {
2711                   if (bp_err_message == NULL)
2712                     {
2713                       std::string message
2714                         = memory_error_message (TARGET_XFER_E_IO,
2715                                                 bl->gdbarch, bl->address);
2716
2717                       fprintf_unfiltered (tmp_error_stream,
2718                                           "Cannot insert breakpoint %d.\n"
2719                                           "%s\n",
2720                                           bl->owner->number, message.c_str ());
2721                     }
2722                   else
2723                     {
2724                       fprintf_unfiltered (tmp_error_stream,
2725                                           "Cannot insert breakpoint %d: %s\n",
2726                                           bl->owner->number,
2727                                           bp_err_message);
2728                     }
2729                 }
2730               return 1;
2731
2732             }
2733         }
2734       else
2735         bl->inserted = 1;
2736
2737       return 0;
2738     }
2739
2740   else if (bl->loc_type == bp_loc_hardware_watchpoint
2741            /* NOTE drow/2003-09-08: This state only exists for removing
2742               watchpoints.  It's not clear that it's necessary...  */
2743            && bl->owner->disposition != disp_del_at_next_stop)
2744     {
2745       int val;
2746
2747       gdb_assert (bl->owner->ops != NULL
2748                   && bl->owner->ops->insert_location != NULL);
2749
2750       val = bl->owner->ops->insert_location (bl);
2751
2752       /* If trying to set a read-watchpoint, and it turns out it's not
2753          supported, try emulating one with an access watchpoint.  */
2754       if (val == 1 && bl->watchpoint_type == hw_read)
2755         {
2756           struct bp_location *loc, **loc_temp;
2757
2758           /* But don't try to insert it, if there's already another
2759              hw_access location that would be considered a duplicate
2760              of this one.  */
2761           ALL_BP_LOCATIONS (loc, loc_temp)
2762             if (loc != bl
2763                 && loc->watchpoint_type == hw_access
2764                 && watchpoint_locations_match (bl, loc))
2765               {
2766                 bl->duplicate = 1;
2767                 bl->inserted = 1;
2768                 bl->target_info = loc->target_info;
2769                 bl->watchpoint_type = hw_access;
2770                 val = 0;
2771                 break;
2772               }
2773
2774           if (val == 1)
2775             {
2776               bl->watchpoint_type = hw_access;
2777               val = bl->owner->ops->insert_location (bl);
2778
2779               if (val)
2780                 /* Back to the original value.  */
2781                 bl->watchpoint_type = hw_read;
2782             }
2783         }
2784
2785       bl->inserted = (val == 0);
2786     }
2787
2788   else if (bl->owner->type == bp_catchpoint)
2789     {
2790       int val;
2791
2792       gdb_assert (bl->owner->ops != NULL
2793                   && bl->owner->ops->insert_location != NULL);
2794
2795       val = bl->owner->ops->insert_location (bl);
2796       if (val)
2797         {
2798           bl->owner->enable_state = bp_disabled;
2799
2800           if (val == 1)
2801             warning (_("\
2802 Error inserting catchpoint %d: Your system does not support this type\n\
2803 of catchpoint."), bl->owner->number);
2804           else
2805             warning (_("Error inserting catchpoint %d."), bl->owner->number);
2806         }
2807
2808       bl->inserted = (val == 0);
2809
2810       /* We've already printed an error message if there was a problem
2811          inserting this catchpoint, and we've disabled the catchpoint,
2812          so just return success.  */
2813       return 0;
2814     }
2815
2816   return 0;
2817 }
2818
2819 /* This function is called when program space PSPACE is about to be
2820    deleted.  It takes care of updating breakpoints to not reference
2821    PSPACE anymore.  */
2822
2823 void
2824 breakpoint_program_space_exit (struct program_space *pspace)
2825 {
2826   struct breakpoint *b, *b_temp;
2827   struct bp_location *loc, **loc_temp;
2828
2829   /* Remove any breakpoint that was set through this program space.  */
2830   ALL_BREAKPOINTS_SAFE (b, b_temp)
2831     {
2832       if (b->pspace == pspace)
2833         delete_breakpoint (b);
2834     }
2835
2836   /* Breakpoints set through other program spaces could have locations
2837      bound to PSPACE as well.  Remove those.  */
2838   ALL_BP_LOCATIONS (loc, loc_temp)
2839     {
2840       struct bp_location *tmp;
2841
2842       if (loc->pspace == pspace)
2843         {
2844           /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
2845           if (loc->owner->loc == loc)
2846             loc->owner->loc = loc->next;
2847           else
2848             for (tmp = loc->owner->loc; tmp->next != NULL; tmp = tmp->next)
2849               if (tmp->next == loc)
2850                 {
2851                   tmp->next = loc->next;
2852                   break;
2853                 }
2854         }
2855     }
2856
2857   /* Now update the global location list to permanently delete the
2858      removed locations above.  */
2859   update_global_location_list (UGLL_DONT_INSERT);
2860 }
2861
2862 /* Make sure all breakpoints are inserted in inferior.
2863    Throws exception on any error.
2864    A breakpoint that is already inserted won't be inserted
2865    again, so calling this function twice is safe.  */
2866 void
2867 insert_breakpoints (void)
2868 {
2869   struct breakpoint *bpt;
2870
2871   ALL_BREAKPOINTS (bpt)
2872     if (is_hardware_watchpoint (bpt))
2873       {
2874         struct watchpoint *w = (struct watchpoint *) bpt;
2875
2876         update_watchpoint (w, 0 /* don't reparse.  */);
2877       }
2878
2879   /* Updating watchpoints creates new locations, so update the global
2880      location list.  Explicitly tell ugll to insert locations and
2881      ignore breakpoints_always_inserted_mode.  */
2882   update_global_location_list (UGLL_INSERT);
2883 }
2884
2885 /* Invoke CALLBACK for each of bp_location.  */
2886
2887 void
2888 iterate_over_bp_locations (walk_bp_location_callback callback)
2889 {
2890   struct bp_location *loc, **loc_tmp;
2891
2892   ALL_BP_LOCATIONS (loc, loc_tmp)
2893     {
2894       callback (loc, NULL);
2895     }
2896 }
2897
2898 /* This is used when we need to synch breakpoint conditions between GDB and the
2899    target.  It is the case with deleting and disabling of breakpoints when using
2900    always-inserted mode.  */
2901
2902 static void
2903 update_inserted_breakpoint_locations (void)
2904 {
2905   struct bp_location *bl, **blp_tmp;
2906   int error_flag = 0;
2907   int val = 0;
2908   int disabled_breaks = 0;
2909   int hw_breakpoint_error = 0;
2910   int hw_bp_details_reported = 0;
2911
2912   string_file tmp_error_stream;
2913
2914   /* Explicitly mark the warning -- this will only be printed if
2915      there was an error.  */
2916   tmp_error_stream.puts ("Warning:\n");
2917
2918   scoped_restore_current_pspace_and_thread restore_pspace_thread;
2919
2920   ALL_BP_LOCATIONS (bl, blp_tmp)
2921     {
2922       /* We only want to update software breakpoints and hardware
2923          breakpoints.  */
2924       if (!is_breakpoint (bl->owner))
2925         continue;
2926
2927       /* We only want to update locations that are already inserted
2928          and need updating.  This is to avoid unwanted insertion during
2929          deletion of breakpoints.  */
2930       if (!bl->inserted || (bl->inserted && !bl->needs_update))
2931         continue;
2932
2933       switch_to_program_space_and_thread (bl->pspace);
2934
2935       /* For targets that support global breakpoints, there's no need
2936          to select an inferior to insert breakpoint to.  In fact, even
2937          if we aren't attached to any process yet, we should still
2938          insert breakpoints.  */
2939       if (!gdbarch_has_global_breakpoints (target_gdbarch ())
2940           && ptid_equal (inferior_ptid, null_ptid))
2941         continue;
2942
2943       val = insert_bp_location (bl, &tmp_error_stream, &disabled_breaks,
2944                                     &hw_breakpoint_error, &hw_bp_details_reported);
2945       if (val)
2946         error_flag = val;
2947     }
2948
2949   if (error_flag)
2950     {
2951       target_terminal::ours_for_output ();
2952       error_stream (tmp_error_stream);
2953     }
2954 }
2955
2956 /* Used when starting or continuing the program.  */
2957
2958 static void
2959 insert_breakpoint_locations (void)
2960 {
2961   struct breakpoint *bpt;
2962   struct bp_location *bl, **blp_tmp;
2963   int error_flag = 0;
2964   int val = 0;
2965   int disabled_breaks = 0;
2966   int hw_breakpoint_error = 0;
2967   int hw_bp_error_explained_already = 0;
2968
2969   string_file tmp_error_stream;
2970
2971   /* Explicitly mark the warning -- this will only be printed if
2972      there was an error.  */
2973   tmp_error_stream.puts ("Warning:\n");
2974
2975   scoped_restore_current_pspace_and_thread restore_pspace_thread;
2976
2977   ALL_BP_LOCATIONS (bl, blp_tmp)
2978     {
2979       if (!should_be_inserted (bl) || (bl->inserted && !bl->needs_update))
2980         continue;
2981
2982       /* There is no point inserting thread-specific breakpoints if
2983          the thread no longer exists.  ALL_BP_LOCATIONS bp_location
2984          has BL->OWNER always non-NULL.  */
2985       if (bl->owner->thread != -1
2986           && !valid_global_thread_id (bl->owner->thread))
2987         continue;
2988
2989       switch_to_program_space_and_thread (bl->pspace);
2990
2991       /* For targets that support global breakpoints, there's no need
2992          to select an inferior to insert breakpoint to.  In fact, even
2993          if we aren't attached to any process yet, we should still
2994          insert breakpoints.  */
2995       if (!gdbarch_has_global_breakpoints (target_gdbarch ())
2996           && ptid_equal (inferior_ptid, null_ptid))
2997         continue;
2998
2999       val = insert_bp_location (bl, &tmp_error_stream, &disabled_breaks,
3000                                     &hw_breakpoint_error, &hw_bp_error_explained_already);
3001       if (val)
3002         error_flag = val;
3003     }
3004
3005   /* If we failed to insert all locations of a watchpoint, remove
3006      them, as half-inserted watchpoint is of limited use.  */
3007   ALL_BREAKPOINTS (bpt)  
3008     {
3009       int some_failed = 0;
3010       struct bp_location *loc;
3011
3012       if (!is_hardware_watchpoint (bpt))
3013         continue;
3014
3015       if (!breakpoint_enabled (bpt))
3016         continue;
3017
3018       if (bpt->disposition == disp_del_at_next_stop)
3019         continue;
3020       
3021       for (loc = bpt->loc; loc; loc = loc->next)
3022         if (!loc->inserted && should_be_inserted (loc))
3023           {
3024             some_failed = 1;
3025             break;
3026           }
3027       if (some_failed)
3028         {
3029           for (loc = bpt->loc; loc; loc = loc->next)
3030             if (loc->inserted)
3031               remove_breakpoint (loc);
3032
3033           hw_breakpoint_error = 1;
3034           tmp_error_stream.printf ("Could not insert "
3035                                    "hardware watchpoint %d.\n",
3036                                    bpt->number);
3037           error_flag = -1;
3038         }
3039     }
3040
3041   if (error_flag)
3042     {
3043       /* If a hardware breakpoint or watchpoint was inserted, add a
3044          message about possibly exhausted resources.  */
3045       if (hw_breakpoint_error && !hw_bp_error_explained_already)
3046         {
3047           tmp_error_stream.printf ("Could not insert hardware breakpoints:\n\
3048 You may have requested too many hardware breakpoints/watchpoints.\n");
3049         }
3050       target_terminal::ours_for_output ();
3051       error_stream (tmp_error_stream);
3052     }
3053 }
3054
3055 /* Used when the program stops.
3056    Returns zero if successful, or non-zero if there was a problem
3057    removing a breakpoint location.  */
3058
3059 int
3060 remove_breakpoints (void)
3061 {
3062   struct bp_location *bl, **blp_tmp;
3063   int val = 0;
3064
3065   ALL_BP_LOCATIONS (bl, blp_tmp)
3066   {
3067     if (bl->inserted && !is_tracepoint (bl->owner))
3068       val |= remove_breakpoint (bl);
3069   }
3070   return val;
3071 }
3072
3073 /* When a thread exits, remove breakpoints that are related to
3074    that thread.  */
3075
3076 static void
3077 remove_threaded_breakpoints (struct thread_info *tp, int silent)
3078 {
3079   struct breakpoint *b, *b_tmp;
3080
3081   ALL_BREAKPOINTS_SAFE (b, b_tmp)
3082     {
3083       if (b->thread == tp->global_num && user_breakpoint_p (b))
3084         {
3085           b->disposition = disp_del_at_next_stop;
3086
3087           printf_filtered (_("\
3088 Thread-specific breakpoint %d deleted - thread %s no longer in the thread list.\n"),
3089                            b->number, print_thread_id (tp));
3090
3091           /* Hide it from the user.  */
3092           b->number = 0;
3093        }
3094     }
3095 }
3096
3097 /* Remove breakpoints of process PID.  */
3098
3099 int
3100 remove_breakpoints_pid (int pid)
3101 {
3102   struct bp_location *bl, **blp_tmp;
3103   int val;
3104   struct inferior *inf = find_inferior_pid (pid);
3105
3106   ALL_BP_LOCATIONS (bl, blp_tmp)
3107   {
3108     if (bl->pspace != inf->pspace)
3109       continue;
3110
3111     if (bl->inserted && !bl->target_info.persist)
3112       {
3113         val = remove_breakpoint (bl);
3114         if (val != 0)
3115           return val;
3116       }
3117   }
3118   return 0;
3119 }
3120
3121 static int internal_breakpoint_number = -1;
3122
3123 /* Set the breakpoint number of B, depending on the value of INTERNAL.
3124    If INTERNAL is non-zero, the breakpoint number will be populated
3125    from internal_breakpoint_number and that variable decremented.
3126    Otherwise the breakpoint number will be populated from
3127    breakpoint_count and that value incremented.  Internal breakpoints
3128    do not set the internal var bpnum.  */
3129 static void
3130 set_breakpoint_number (int internal, struct breakpoint *b)
3131 {
3132   if (internal)
3133     b->number = internal_breakpoint_number--;
3134   else
3135     {
3136       set_breakpoint_count (breakpoint_count + 1);
3137       b->number = breakpoint_count;
3138     }
3139 }
3140
3141 static struct breakpoint *
3142 create_internal_breakpoint (struct gdbarch *gdbarch,
3143                             CORE_ADDR address, enum bptype type,
3144                             const struct breakpoint_ops *ops)
3145 {
3146   symtab_and_line sal;
3147   sal.pc = address;
3148   sal.section = find_pc_overlay (sal.pc);
3149   sal.pspace = current_program_space;
3150
3151   breakpoint *b = set_raw_breakpoint (gdbarch, sal, type, ops);
3152   b->number = internal_breakpoint_number--;
3153   b->disposition = disp_donttouch;
3154
3155   return b;
3156 }
3157
3158 static const char *const longjmp_names[] =
3159   {
3160     "longjmp", "_longjmp", "siglongjmp", "_siglongjmp"
3161   };
3162 #define NUM_LONGJMP_NAMES ARRAY_SIZE(longjmp_names)
3163
3164 /* Per-objfile data private to breakpoint.c.  */
3165 struct breakpoint_objfile_data
3166 {
3167   /* Minimal symbol for "_ovly_debug_event" (if any).  */
3168   struct bound_minimal_symbol overlay_msym {};
3169
3170   /* Minimal symbol(s) for "longjmp", "siglongjmp", etc. (if any).  */
3171   struct bound_minimal_symbol longjmp_msym[NUM_LONGJMP_NAMES] {};
3172
3173   /* True if we have looked for longjmp probes.  */
3174   int longjmp_searched = 0;
3175
3176   /* SystemTap probe points for longjmp (if any).  These are non-owning
3177      references.  */
3178   std::vector<probe *> longjmp_probes;
3179
3180   /* Minimal symbol for "std::terminate()" (if any).  */
3181   struct bound_minimal_symbol terminate_msym {};
3182
3183   /* Minimal symbol for "_Unwind_DebugHook" (if any).  */
3184   struct bound_minimal_symbol exception_msym {};
3185
3186   /* True if we have looked for exception probes.  */
3187   int exception_searched = 0;
3188
3189   /* SystemTap probe points for unwinding (if any).  These are non-owning
3190      references.  */
3191   std::vector<probe *> exception_probes;
3192 };
3193
3194 static const struct objfile_data *breakpoint_objfile_key;
3195
3196 /* Minimal symbol not found sentinel.  */
3197 static struct minimal_symbol msym_not_found;
3198
3199 /* Returns TRUE if MSYM point to the "not found" sentinel.  */
3200
3201 static int
3202 msym_not_found_p (const struct minimal_symbol *msym)
3203 {
3204   return msym == &msym_not_found;
3205 }
3206
3207 /* Return per-objfile data needed by breakpoint.c.
3208    Allocate the data if necessary.  */
3209
3210 static struct breakpoint_objfile_data *
3211 get_breakpoint_objfile_data (struct objfile *objfile)
3212 {
3213   struct breakpoint_objfile_data *bp_objfile_data;
3214
3215   bp_objfile_data = ((struct breakpoint_objfile_data *)
3216                      objfile_data (objfile, breakpoint_objfile_key));
3217   if (bp_objfile_data == NULL)
3218     {
3219       bp_objfile_data = new breakpoint_objfile_data ();
3220       set_objfile_data (objfile, breakpoint_objfile_key, bp_objfile_data);
3221     }
3222   return bp_objfile_data;
3223 }
3224
3225 static void
3226 free_breakpoint_objfile_data (struct objfile *obj, void *data)
3227 {
3228   struct breakpoint_objfile_data *bp_objfile_data
3229     = (struct breakpoint_objfile_data *) data;
3230
3231   delete bp_objfile_data;
3232 }
3233
3234 static void
3235 create_overlay_event_breakpoint (void)
3236 {
3237   struct objfile *objfile;
3238   const char *const func_name = "_ovly_debug_event";
3239
3240   ALL_OBJFILES (objfile)
3241     {
3242       struct breakpoint *b;
3243       struct breakpoint_objfile_data *bp_objfile_data;
3244       CORE_ADDR addr;
3245       struct explicit_location explicit_loc;
3246
3247       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3248
3249       if (msym_not_found_p (bp_objfile_data->overlay_msym.minsym))
3250         continue;
3251
3252       if (bp_objfile_data->overlay_msym.minsym == NULL)
3253         {
3254           struct bound_minimal_symbol m;
3255
3256           m = lookup_minimal_symbol_text (func_name, objfile);
3257           if (m.minsym == NULL)
3258             {
3259               /* Avoid future lookups in this objfile.  */
3260               bp_objfile_data->overlay_msym.minsym = &msym_not_found;
3261               continue;
3262             }
3263           bp_objfile_data->overlay_msym = m;
3264         }
3265
3266       addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->overlay_msym);
3267       b = create_internal_breakpoint (get_objfile_arch (objfile), addr,
3268                                       bp_overlay_event,
3269                                       &internal_breakpoint_ops);
3270       initialize_explicit_location (&explicit_loc);
3271       explicit_loc.function_name = ASTRDUP (func_name);
3272       b->location = new_explicit_location (&explicit_loc);
3273
3274       if (overlay_debugging == ovly_auto)
3275         {
3276           b->enable_state = bp_enabled;
3277           overlay_events_enabled = 1;
3278         }
3279       else
3280        {
3281          b->enable_state = bp_disabled;
3282          overlay_events_enabled = 0;
3283        }
3284     }
3285 }
3286
3287 static void
3288 create_longjmp_master_breakpoint (void)
3289 {
3290   struct program_space *pspace;
3291
3292   scoped_restore_current_program_space restore_pspace;
3293
3294   ALL_PSPACES (pspace)
3295   {
3296     struct objfile *objfile;
3297
3298     set_current_program_space (pspace);
3299
3300     ALL_OBJFILES (objfile)
3301     {
3302       int i;
3303       struct gdbarch *gdbarch;
3304       struct breakpoint_objfile_data *bp_objfile_data;
3305
3306       gdbarch = get_objfile_arch (objfile);
3307
3308       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3309
3310       if (!bp_objfile_data->longjmp_searched)
3311         {
3312           std::vector<probe *> ret
3313             = find_probes_in_objfile (objfile, "libc", "longjmp");
3314
3315           if (!ret.empty ())
3316             {
3317               /* We are only interested in checking one element.  */
3318               probe *p = ret[0];
3319
3320               if (!can_evaluate_probe_arguments (p))
3321                 {
3322                   /* We cannot use the probe interface here, because it does
3323                      not know how to evaluate arguments.  */
3324                   ret.clear ();
3325                 }
3326             }
3327           bp_objfile_data->longjmp_probes = ret;
3328           bp_objfile_data->longjmp_searched = 1;
3329         }
3330
3331       if (!bp_objfile_data->longjmp_probes.empty ())
3332         {
3333           struct gdbarch *gdbarch = get_objfile_arch (objfile);
3334
3335           for (probe *p : bp_objfile_data->longjmp_probes)
3336             {
3337               struct breakpoint *b;
3338
3339               b = create_internal_breakpoint (gdbarch,
3340                                               get_probe_address (p, objfile),
3341                                               bp_longjmp_master,
3342                                               &internal_breakpoint_ops);
3343               b->location = new_probe_location ("-probe-stap libc:longjmp");
3344               b->enable_state = bp_disabled;
3345             }
3346
3347           continue;
3348         }
3349
3350       if (!gdbarch_get_longjmp_target_p (gdbarch))
3351         continue;
3352
3353       for (i = 0; i < NUM_LONGJMP_NAMES; i++)
3354         {
3355           struct breakpoint *b;
3356           const char *func_name;
3357           CORE_ADDR addr;
3358           struct explicit_location explicit_loc;
3359
3360           if (msym_not_found_p (bp_objfile_data->longjmp_msym[i].minsym))
3361             continue;
3362
3363           func_name = longjmp_names[i];
3364           if (bp_objfile_data->longjmp_msym[i].minsym == NULL)
3365             {
3366               struct bound_minimal_symbol m;
3367
3368               m = lookup_minimal_symbol_text (func_name, objfile);
3369               if (m.minsym == NULL)
3370                 {
3371                   /* Prevent future lookups in this objfile.  */
3372                   bp_objfile_data->longjmp_msym[i].minsym = &msym_not_found;
3373                   continue;
3374                 }
3375               bp_objfile_data->longjmp_msym[i] = m;
3376             }
3377
3378           addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->longjmp_msym[i]);
3379           b = create_internal_breakpoint (gdbarch, addr, bp_longjmp_master,
3380                                           &internal_breakpoint_ops);
3381           initialize_explicit_location (&explicit_loc);
3382           explicit_loc.function_name = ASTRDUP (func_name);
3383           b->location = new_explicit_location (&explicit_loc);
3384           b->enable_state = bp_disabled;
3385         }
3386     }
3387   }
3388 }
3389
3390 /* Create a master std::terminate breakpoint.  */
3391 static void
3392 create_std_terminate_master_breakpoint (void)
3393 {
3394   struct program_space *pspace;
3395   const char *const func_name = "std::terminate()";
3396
3397   scoped_restore_current_program_space restore_pspace;
3398
3399   ALL_PSPACES (pspace)
3400   {
3401     struct objfile *objfile;
3402     CORE_ADDR addr;
3403
3404     set_current_program_space (pspace);
3405
3406     ALL_OBJFILES (objfile)
3407     {
3408       struct breakpoint *b;
3409       struct breakpoint_objfile_data *bp_objfile_data;
3410       struct explicit_location explicit_loc;
3411
3412       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3413
3414       if (msym_not_found_p (bp_objfile_data->terminate_msym.minsym))
3415         continue;
3416
3417       if (bp_objfile_data->terminate_msym.minsym == NULL)
3418         {
3419           struct bound_minimal_symbol m;
3420
3421           m = lookup_minimal_symbol (func_name, NULL, objfile);
3422           if (m.minsym == NULL || (MSYMBOL_TYPE (m.minsym) != mst_text
3423                                    && MSYMBOL_TYPE (m.minsym) != mst_file_text))
3424             {
3425               /* Prevent future lookups in this objfile.  */
3426               bp_objfile_data->terminate_msym.minsym = &msym_not_found;
3427               continue;
3428             }
3429           bp_objfile_data->terminate_msym = m;
3430         }
3431
3432       addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->terminate_msym);
3433       b = create_internal_breakpoint (get_objfile_arch (objfile), addr,
3434                                       bp_std_terminate_master,
3435                                       &internal_breakpoint_ops);
3436       initialize_explicit_location (&explicit_loc);
3437       explicit_loc.function_name = ASTRDUP (func_name);
3438       b->location = new_explicit_location (&explicit_loc);
3439       b->enable_state = bp_disabled;
3440     }
3441   }
3442 }
3443
3444 /* Install a master breakpoint on the unwinder's debug hook.  */
3445
3446 static void
3447 create_exception_master_breakpoint (void)
3448 {
3449   struct objfile *objfile;
3450   const char *const func_name = "_Unwind_DebugHook";
3451
3452   ALL_OBJFILES (objfile)
3453     {
3454       struct breakpoint *b;
3455       struct gdbarch *gdbarch;
3456       struct breakpoint_objfile_data *bp_objfile_data;
3457       CORE_ADDR addr;
3458       struct explicit_location explicit_loc;
3459
3460       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3461
3462       /* We prefer the SystemTap probe point if it exists.  */
3463       if (!bp_objfile_data->exception_searched)
3464         {
3465           std::vector<probe *> ret
3466             = find_probes_in_objfile (objfile, "libgcc", "unwind");
3467
3468           if (!ret.empty ())
3469             {
3470               /* We are only interested in checking one element.  */
3471               probe *p = ret[0];
3472
3473               if (!can_evaluate_probe_arguments (p))
3474                 {
3475                   /* We cannot use the probe interface here, because it does
3476                      not know how to evaluate arguments.  */
3477                   ret.clear ();
3478                 }
3479             }
3480           bp_objfile_data->exception_probes = ret;
3481           bp_objfile_data->exception_searched = 1;
3482         }
3483
3484       if (!bp_objfile_data->exception_probes.empty ())
3485         {
3486           struct gdbarch *gdbarch = get_objfile_arch (objfile);
3487
3488           for (probe *p : bp_objfile_data->exception_probes)
3489             {
3490               struct breakpoint *b;
3491
3492               b = create_internal_breakpoint (gdbarch,
3493                                               get_probe_address (p, objfile),
3494                                               bp_exception_master,
3495                                               &internal_breakpoint_ops);
3496               b->location = new_probe_location ("-probe-stap libgcc:unwind");
3497               b->enable_state = bp_disabled;
3498             }
3499
3500           continue;
3501         }
3502
3503       /* Otherwise, try the hook function.  */
3504
3505       if (msym_not_found_p (bp_objfile_data->exception_msym.minsym))
3506         continue;
3507
3508       gdbarch = get_objfile_arch (objfile);
3509
3510       if (bp_objfile_data->exception_msym.minsym == NULL)
3511         {
3512           struct bound_minimal_symbol debug_hook;
3513
3514           debug_hook = lookup_minimal_symbol (func_name, NULL, objfile);
3515           if (debug_hook.minsym == NULL)
3516             {
3517               bp_objfile_data->exception_msym.minsym = &msym_not_found;
3518               continue;
3519             }
3520
3521           bp_objfile_data->exception_msym = debug_hook;
3522         }
3523
3524       addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->exception_msym);
3525       addr = gdbarch_convert_from_func_ptr_addr (gdbarch, addr,
3526                                                  &current_target);
3527       b = create_internal_breakpoint (gdbarch, addr, bp_exception_master,
3528                                       &internal_breakpoint_ops);
3529       initialize_explicit_location (&explicit_loc);
3530       explicit_loc.function_name = ASTRDUP (func_name);
3531       b->location = new_explicit_location (&explicit_loc);
3532       b->enable_state = bp_disabled;
3533     }
3534 }
3535
3536 /* Does B have a location spec?  */
3537
3538 static int
3539 breakpoint_event_location_empty_p (const struct breakpoint *b)
3540 {
3541   return b->location != NULL && event_location_empty_p (b->location.get ());
3542 }
3543
3544 void
3545 update_breakpoints_after_exec (void)
3546 {
3547   struct breakpoint *b, *b_tmp;
3548   struct bp_location *bploc, **bplocp_tmp;
3549
3550   /* We're about to delete breakpoints from GDB's lists.  If the
3551      INSERTED flag is true, GDB will try to lift the breakpoints by
3552      writing the breakpoints' "shadow contents" back into memory.  The
3553      "shadow contents" are NOT valid after an exec, so GDB should not
3554      do that.  Instead, the target is responsible from marking
3555      breakpoints out as soon as it detects an exec.  We don't do that
3556      here instead, because there may be other attempts to delete
3557      breakpoints after detecting an exec and before reaching here.  */
3558   ALL_BP_LOCATIONS (bploc, bplocp_tmp)
3559     if (bploc->pspace == current_program_space)
3560       gdb_assert (!bploc->inserted);
3561
3562   ALL_BREAKPOINTS_SAFE (b, b_tmp)
3563   {
3564     if (b->pspace != current_program_space)
3565       continue;
3566
3567     /* Solib breakpoints must be explicitly reset after an exec().  */
3568     if (b->type == bp_shlib_event)
3569       {
3570         delete_breakpoint (b);
3571         continue;
3572       }
3573
3574     /* JIT breakpoints must be explicitly reset after an exec().  */
3575     if (b->type == bp_jit_event)
3576       {
3577         delete_breakpoint (b);
3578         continue;
3579       }
3580
3581     /* Thread event breakpoints must be set anew after an exec(),
3582        as must overlay event and longjmp master breakpoints.  */
3583     if (b->type == bp_thread_event || b->type == bp_overlay_event
3584         || b->type == bp_longjmp_master || b->type == bp_std_terminate_master
3585         || b->type == bp_exception_master)
3586       {
3587         delete_breakpoint (b);
3588         continue;
3589       }
3590
3591     /* Step-resume breakpoints are meaningless after an exec().  */
3592     if (b->type == bp_step_resume || b->type == bp_hp_step_resume)
3593       {
3594         delete_breakpoint (b);
3595         continue;
3596       }
3597
3598     /* Just like single-step breakpoints.  */
3599     if (b->type == bp_single_step)
3600       {
3601         delete_breakpoint (b);
3602         continue;
3603       }
3604
3605     /* Longjmp and longjmp-resume breakpoints are also meaningless
3606        after an exec.  */
3607     if (b->type == bp_longjmp || b->type == bp_longjmp_resume
3608         || b->type == bp_longjmp_call_dummy
3609         || b->type == bp_exception || b->type == bp_exception_resume)
3610       {
3611         delete_breakpoint (b);
3612         continue;
3613       }
3614
3615     if (b->type == bp_catchpoint)
3616       {
3617         /* For now, none of the bp_catchpoint breakpoints need to
3618            do anything at this point.  In the future, if some of
3619            the catchpoints need to something, we will need to add
3620            a new method, and call this method from here.  */
3621         continue;
3622       }
3623
3624     /* bp_finish is a special case.  The only way we ought to be able
3625        to see one of these when an exec() has happened, is if the user
3626        caught a vfork, and then said "finish".  Ordinarily a finish just
3627        carries them to the call-site of the current callee, by setting
3628        a temporary bp there and resuming.  But in this case, the finish
3629        will carry them entirely through the vfork & exec.
3630
3631        We don't want to allow a bp_finish to remain inserted now.  But
3632        we can't safely delete it, 'cause finish_command has a handle to
3633        the bp on a bpstat, and will later want to delete it.  There's a
3634        chance (and I've seen it happen) that if we delete the bp_finish
3635        here, that its storage will get reused by the time finish_command
3636        gets 'round to deleting the "use to be a bp_finish" breakpoint.
3637        We really must allow finish_command to delete a bp_finish.
3638
3639        In the absence of a general solution for the "how do we know
3640        it's safe to delete something others may have handles to?"
3641        problem, what we'll do here is just uninsert the bp_finish, and
3642        let finish_command delete it.
3643
3644        (We know the bp_finish is "doomed" in the sense that it's
3645        momentary, and will be deleted as soon as finish_command sees
3646        the inferior stopped.  So it doesn't matter that the bp's
3647        address is probably bogus in the new a.out, unlike e.g., the
3648        solib breakpoints.)  */
3649
3650     if (b->type == bp_finish)
3651       {
3652         continue;
3653       }
3654
3655     /* Without a symbolic address, we have little hope of the
3656        pre-exec() address meaning the same thing in the post-exec()
3657        a.out.  */
3658     if (breakpoint_event_location_empty_p (b))
3659       {
3660         delete_breakpoint (b);
3661         continue;
3662       }
3663   }
3664 }
3665
3666 int
3667 detach_breakpoints (ptid_t ptid)
3668 {
3669   struct bp_location *bl, **blp_tmp;
3670   int val = 0;
3671   scoped_restore save_inferior_ptid = make_scoped_restore (&inferior_ptid);
3672   struct inferior *inf = current_inferior ();
3673
3674   if (ptid_get_pid (ptid) == ptid_get_pid (inferior_ptid))
3675     error (_("Cannot detach breakpoints of inferior_ptid"));
3676
3677   /* Set inferior_ptid; remove_breakpoint_1 uses this global.  */
3678   inferior_ptid = ptid;
3679   ALL_BP_LOCATIONS (bl, blp_tmp)
3680   {
3681     if (bl->pspace != inf->pspace)
3682       continue;
3683
3684     /* This function must physically remove breakpoints locations
3685        from the specified ptid, without modifying the breakpoint
3686        package's state.  Locations of type bp_loc_other are only
3687        maintained at GDB side.  So, there is no need to remove
3688        these bp_loc_other locations.  Moreover, removing these
3689        would modify the breakpoint package's state.  */
3690     if (bl->loc_type == bp_loc_other)
3691       continue;
3692
3693     if (bl->inserted)
3694       val |= remove_breakpoint_1 (bl, DETACH_BREAKPOINT);
3695   }
3696
3697   return val;
3698 }
3699
3700 /* Remove the breakpoint location BL from the current address space.
3701    Note that this is used to detach breakpoints from a child fork.
3702    When we get here, the child isn't in the inferior list, and neither
3703    do we have objects to represent its address space --- we should
3704    *not* look at bl->pspace->aspace here.  */
3705
3706 static int
3707 remove_breakpoint_1 (struct bp_location *bl, enum remove_bp_reason reason)
3708 {
3709   int val;
3710
3711   /* BL is never in moribund_locations by our callers.  */
3712   gdb_assert (bl->owner != NULL);
3713
3714   /* The type of none suggests that owner is actually deleted.
3715      This should not ever happen.  */
3716   gdb_assert (bl->owner->type != bp_none);
3717
3718   if (bl->loc_type == bp_loc_software_breakpoint
3719       || bl->loc_type == bp_loc_hardware_breakpoint)
3720     {
3721       /* "Normal" instruction breakpoint: either the standard
3722          trap-instruction bp (bp_breakpoint), or a
3723          bp_hardware_breakpoint.  */
3724
3725       /* First check to see if we have to handle an overlay.  */
3726       if (overlay_debugging == ovly_off
3727           || bl->section == NULL
3728           || !(section_is_overlay (bl->section)))
3729         {
3730           /* No overlay handling: just remove the breakpoint.  */
3731
3732           /* If we're trying to uninsert a memory breakpoint that we
3733              know is set in a dynamic object that is marked
3734              shlib_disabled, then either the dynamic object was
3735              removed with "remove-symbol-file" or with
3736              "nosharedlibrary".  In the former case, we don't know
3737              whether another dynamic object might have loaded over the
3738              breakpoint's address -- the user might well let us know
3739              about it next with add-symbol-file (the whole point of
3740              add-symbol-file is letting the user manually maintain a
3741              list of dynamically loaded objects).  If we have the
3742              breakpoint's shadow memory, that is, this is a software
3743              breakpoint managed by GDB, check whether the breakpoint
3744              is still inserted in memory, to avoid overwriting wrong
3745              code with stale saved shadow contents.  Note that HW
3746              breakpoints don't have shadow memory, as they're
3747              implemented using a mechanism that is not dependent on
3748              being able to modify the target's memory, and as such
3749              they should always be removed.  */
3750           if (bl->shlib_disabled
3751               && bl->target_info.shadow_len != 0
3752               && !memory_validate_breakpoint (bl->gdbarch, &bl->target_info))
3753             val = 0;
3754           else
3755             val = bl->owner->ops->remove_location (bl, reason);
3756         }
3757       else
3758         {
3759           /* This breakpoint is in an overlay section.
3760              Did we set a breakpoint at the LMA?  */
3761           if (!overlay_events_enabled)
3762               {
3763                 /* Yes -- overlay event support is not active, so we
3764                    should have set a breakpoint at the LMA.  Remove it.  
3765                 */
3766                 /* Ignore any failures: if the LMA is in ROM, we will
3767                    have already warned when we failed to insert it.  */
3768                 if (bl->loc_type == bp_loc_hardware_breakpoint)
3769                   target_remove_hw_breakpoint (bl->gdbarch,
3770                                                &bl->overlay_target_info);
3771                 else
3772                   target_remove_breakpoint (bl->gdbarch,
3773                                             &bl->overlay_target_info,
3774                                             reason);
3775               }
3776           /* Did we set a breakpoint at the VMA? 
3777              If so, we will have marked the breakpoint 'inserted'.  */
3778           if (bl->inserted)
3779             {
3780               /* Yes -- remove it.  Previously we did not bother to
3781                  remove the breakpoint if the section had been
3782                  unmapped, but let's not rely on that being safe.  We
3783                  don't know what the overlay manager might do.  */
3784
3785               /* However, we should remove *software* breakpoints only
3786                  if the section is still mapped, or else we overwrite
3787                  wrong code with the saved shadow contents.  */
3788               if (bl->loc_type == bp_loc_hardware_breakpoint
3789                   || section_is_mapped (bl->section))
3790                 val = bl->owner->ops->remove_location (bl, reason);
3791               else
3792                 val = 0;
3793             }
3794           else
3795             {
3796               /* No -- not inserted, so no need to remove.  No error.  */
3797               val = 0;
3798             }
3799         }
3800
3801       /* In some cases, we might not be able to remove a breakpoint in
3802          a shared library that has already been removed, but we have
3803          not yet processed the shlib unload event.  Similarly for an
3804          unloaded add-symbol-file object - the user might not yet have
3805          had the chance to remove-symbol-file it.  shlib_disabled will
3806          be set if the library/object has already been removed, but
3807          the breakpoint hasn't been uninserted yet, e.g., after
3808          "nosharedlibrary" or "remove-symbol-file" with breakpoints
3809          always-inserted mode.  */
3810       if (val
3811           && (bl->loc_type == bp_loc_software_breakpoint
3812               && (bl->shlib_disabled
3813                   || solib_name_from_address (bl->pspace, bl->address)
3814                   || shared_objfile_contains_address_p (bl->pspace,
3815                                                         bl->address))))
3816         val = 0;
3817
3818       if (val)
3819         return val;
3820       bl->inserted = (reason == DETACH_BREAKPOINT);
3821     }
3822   else if (bl->loc_type == bp_loc_hardware_watchpoint)
3823     {
3824       gdb_assert (bl->owner->ops != NULL
3825                   && bl->owner->ops->remove_location != NULL);
3826
3827       bl->inserted = (reason == DETACH_BREAKPOINT);
3828       bl->owner->ops->remove_location (bl, reason);
3829
3830       /* Failure to remove any of the hardware watchpoints comes here.  */
3831       if (reason == REMOVE_BREAKPOINT && bl->inserted)
3832         warning (_("Could not remove hardware watchpoint %d."),
3833                  bl->owner->number);
3834     }
3835   else if (bl->owner->type == bp_catchpoint
3836            && breakpoint_enabled (bl->owner)
3837            && !bl->duplicate)
3838     {
3839       gdb_assert (bl->owner->ops != NULL
3840                   && bl->owner->ops->remove_location != NULL);
3841
3842       val = bl->owner->ops->remove_location (bl, reason);
3843       if (val)
3844         return val;
3845
3846       bl->inserted = (reason == DETACH_BREAKPOINT);
3847     }
3848
3849   return 0;
3850 }
3851
3852 static int
3853 remove_breakpoint (struct bp_location *bl)
3854 {
3855   /* BL is never in moribund_locations by our callers.  */
3856   gdb_assert (bl->owner != NULL);
3857
3858   /* The type of none suggests that owner is actually deleted.
3859      This should not ever happen.  */
3860   gdb_assert (bl->owner->type != bp_none);
3861
3862   scoped_restore_current_pspace_and_thread restore_pspace_thread;
3863
3864   switch_to_program_space_and_thread (bl->pspace);
3865
3866   return remove_breakpoint_1 (bl, REMOVE_BREAKPOINT);
3867 }
3868
3869 /* Clear the "inserted" flag in all breakpoints.  */
3870
3871 void
3872 mark_breakpoints_out (void)
3873 {
3874   struct bp_location *bl, **blp_tmp;
3875
3876   ALL_BP_LOCATIONS (bl, blp_tmp)
3877     if (bl->pspace == current_program_space)
3878       bl->inserted = 0;
3879 }
3880
3881 /* Clear the "inserted" flag in all breakpoints and delete any
3882    breakpoints which should go away between runs of the program.
3883
3884    Plus other such housekeeping that has to be done for breakpoints
3885    between runs.
3886
3887    Note: this function gets called at the end of a run (by
3888    generic_mourn_inferior) and when a run begins (by
3889    init_wait_for_inferior).  */
3890
3891
3892
3893 void
3894 breakpoint_init_inferior (enum inf_context context)
3895 {
3896   struct breakpoint *b, *b_tmp;
3897   struct bp_location *bl;
3898   int ix;
3899   struct program_space *pspace = current_program_space;
3900
3901   /* If breakpoint locations are shared across processes, then there's
3902      nothing to do.  */
3903   if (gdbarch_has_global_breakpoints (target_gdbarch ()))
3904     return;
3905
3906   mark_breakpoints_out ();
3907
3908   ALL_BREAKPOINTS_SAFE (b, b_tmp)
3909   {
3910     if (b->loc && b->loc->pspace != pspace)
3911       continue;
3912
3913     switch (b->type)
3914       {
3915       case bp_call_dummy:
3916       case bp_longjmp_call_dummy:
3917
3918         /* If the call dummy breakpoint is at the entry point it will
3919            cause problems when the inferior is rerun, so we better get
3920            rid of it.  */
3921
3922       case bp_watchpoint_scope:
3923
3924         /* Also get rid of scope breakpoints.  */
3925
3926       case bp_shlib_event:
3927
3928         /* Also remove solib event breakpoints.  Their addresses may
3929            have changed since the last time we ran the program.
3930            Actually we may now be debugging against different target;
3931            and so the solib backend that installed this breakpoint may
3932            not be used in by the target.  E.g.,
3933
3934            (gdb) file prog-linux
3935            (gdb) run               # native linux target
3936            ...
3937            (gdb) kill
3938            (gdb) file prog-win.exe
3939            (gdb) tar rem :9999     # remote Windows gdbserver.
3940         */
3941
3942       case bp_step_resume:
3943
3944         /* Also remove step-resume breakpoints.  */
3945
3946       case bp_single_step:
3947
3948         /* Also remove single-step breakpoints.  */
3949
3950         delete_breakpoint (b);
3951         break;
3952
3953       case bp_watchpoint:
3954       case bp_hardware_watchpoint:
3955       case bp_read_watchpoint:
3956       case bp_access_watchpoint:
3957         {
3958           struct watchpoint *w = (struct watchpoint *) b;
3959
3960           /* Likewise for watchpoints on local expressions.  */
3961           if (w->exp_valid_block != NULL)
3962             delete_breakpoint (b);
3963           else
3964             {
3965               /* Get rid of existing locations, which are no longer
3966                  valid.  New ones will be created in
3967                  update_watchpoint, when the inferior is restarted.
3968                  The next update_global_location_list call will
3969                  garbage collect them.  */
3970               b->loc = NULL;
3971
3972               if (context == inf_starting)
3973                 {
3974                   /* Reset val field to force reread of starting value in
3975                      insert_breakpoints.  */
3976                   if (w->val)
3977                     value_free (w->val);
3978                   w->val = NULL;
3979                   w->val_valid = 0;
3980                 }
3981             }
3982         }
3983         break;
3984       default:
3985         break;
3986       }
3987   }
3988
3989   /* Get rid of the moribund locations.  */
3990   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, bl); ++ix)
3991     decref_bp_location (&bl);
3992   VEC_free (bp_location_p, moribund_locations);
3993 }
3994
3995 /* These functions concern about actual breakpoints inserted in the
3996    target --- to e.g. check if we need to do decr_pc adjustment or if
3997    we need to hop over the bkpt --- so we check for address space
3998    match, not program space.  */
3999
4000 /* breakpoint_here_p (PC) returns non-zero if an enabled breakpoint
4001    exists at PC.  It returns ordinary_breakpoint_here if it's an
4002    ordinary breakpoint, or permanent_breakpoint_here if it's a
4003    permanent breakpoint.
4004    - When continuing from a location with an ordinary breakpoint, we
4005      actually single step once before calling insert_breakpoints.
4006    - When continuing from a location with a permanent breakpoint, we
4007      need to use the `SKIP_PERMANENT_BREAKPOINT' macro, provided by
4008      the target, to advance the PC past the breakpoint.  */
4009
4010 enum breakpoint_here
4011 breakpoint_here_p (const address_space *aspace, CORE_ADDR pc)
4012 {
4013   struct bp_location *bl, **blp_tmp;
4014   int any_breakpoint_here = 0;
4015
4016   ALL_BP_LOCATIONS (bl, blp_tmp)
4017     {
4018       if (bl->loc_type != bp_loc_software_breakpoint
4019           && bl->loc_type != bp_loc_hardware_breakpoint)
4020         continue;
4021
4022       /* ALL_BP_LOCATIONS bp_location has BL->OWNER always non-NULL.  */
4023       if ((breakpoint_enabled (bl->owner)
4024            || bl->permanent)
4025           && breakpoint_location_address_match (bl, aspace, pc))
4026         {
4027           if (overlay_debugging 
4028               && section_is_overlay (bl->section)
4029               && !section_is_mapped (bl->section))
4030             continue;           /* unmapped overlay -- can't be a match */
4031           else if (bl->permanent)
4032             return permanent_breakpoint_here;
4033           else
4034             any_breakpoint_here = 1;
4035         }
4036     }
4037
4038   return any_breakpoint_here ? ordinary_breakpoint_here : no_breakpoint_here;
4039 }
4040
4041 /* See breakpoint.h.  */
4042
4043 int
4044 breakpoint_in_range_p (const address_space *aspace,
4045                        CORE_ADDR addr, ULONGEST len)
4046 {
4047   struct bp_location *bl, **blp_tmp;
4048
4049   ALL_BP_LOCATIONS (bl, blp_tmp)
4050     {
4051       if (bl->loc_type != bp_loc_software_breakpoint
4052           && bl->loc_type != bp_loc_hardware_breakpoint)
4053         continue;
4054
4055       if ((breakpoint_enabled (bl->owner)
4056            || bl->permanent)
4057           && breakpoint_location_address_range_overlap (bl, aspace,
4058                                                         addr, len))
4059         {
4060           if (overlay_debugging
4061               && section_is_overlay (bl->section)
4062               && !section_is_mapped (bl->section))
4063             {
4064               /* Unmapped overlay -- can't be a match.  */
4065               continue;
4066             }
4067
4068           return 1;
4069         }
4070     }
4071
4072   return 0;
4073 }
4074
4075 /* Return true if there's a moribund breakpoint at PC.  */
4076
4077 int
4078 moribund_breakpoint_here_p (const address_space *aspace, CORE_ADDR pc)
4079 {
4080   struct bp_location *loc;
4081   int ix;
4082
4083   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
4084     if (breakpoint_location_address_match (loc, aspace, pc))
4085       return 1;
4086
4087   return 0;
4088 }
4089
4090 /* Returns non-zero iff BL is inserted at PC, in address space
4091    ASPACE.  */
4092
4093 static int
4094 bp_location_inserted_here_p (struct bp_location *bl,
4095                              const address_space *aspace, CORE_ADDR pc)
4096 {
4097   if (bl->inserted
4098       && breakpoint_address_match (bl->pspace->aspace, bl->address,
4099                                    aspace, pc))
4100     {
4101       if (overlay_debugging
4102           && section_is_overlay (bl->section)
4103           && !section_is_mapped (bl->section))
4104         return 0;               /* unmapped overlay -- can't be a match */
4105       else
4106         return 1;
4107     }
4108   return 0;
4109 }
4110
4111 /* Returns non-zero iff there's a breakpoint inserted at PC.  */
4112
4113 int
4114 breakpoint_inserted_here_p (const address_space *aspace, CORE_ADDR pc)
4115 {
4116   struct bp_location **blp, **blp_tmp = NULL;
4117
4118   ALL_BP_LOCATIONS_AT_ADDR (blp, blp_tmp, pc)
4119     {
4120       struct bp_location *bl = *blp;
4121
4122       if (bl->loc_type != bp_loc_software_breakpoint
4123           && bl->loc_type != bp_loc_hardware_breakpoint)
4124         continue;
4125
4126       if (bp_location_inserted_here_p (bl, aspace, pc))
4127         return 1;
4128     }
4129   return 0;
4130 }
4131
4132 /* This function returns non-zero iff there is a software breakpoint
4133    inserted at PC.  */
4134
4135 int
4136 software_breakpoint_inserted_here_p (const address_space *aspace,
4137                                      CORE_ADDR pc)
4138 {
4139   struct bp_location **blp, **blp_tmp = NULL;
4140
4141   ALL_BP_LOCATIONS_AT_ADDR (blp, blp_tmp, pc)
4142     {
4143       struct bp_location *bl = *blp;
4144
4145       if (bl->loc_type != bp_loc_software_breakpoint)
4146         continue;
4147
4148       if (bp_location_inserted_here_p (bl, aspace, pc))
4149         return 1;
4150     }
4151
4152   return 0;
4153 }
4154
4155 /* See breakpoint.h.  */
4156
4157 int
4158 hardware_breakpoint_inserted_here_p (const address_space *aspace,
4159                                      CORE_ADDR pc)
4160 {
4161   struct bp_location **blp, **blp_tmp = NULL;
4162
4163   ALL_BP_LOCATIONS_AT_ADDR (blp, blp_tmp, pc)
4164     {
4165       struct bp_location *bl = *blp;
4166
4167       if (bl->loc_type != bp_loc_hardware_breakpoint)
4168         continue;
4169
4170       if (bp_location_inserted_here_p (bl, aspace, pc))
4171         return 1;
4172     }
4173
4174   return 0;
4175 }
4176
4177 int
4178 hardware_watchpoint_inserted_in_range (const address_space *aspace,
4179                                        CORE_ADDR addr, ULONGEST len)
4180 {
4181   struct breakpoint *bpt;
4182
4183   ALL_BREAKPOINTS (bpt)
4184     {
4185       struct bp_location *loc;
4186
4187       if (bpt->type != bp_hardware_watchpoint
4188           && bpt->type != bp_access_watchpoint)
4189         continue;
4190
4191       if (!breakpoint_enabled (bpt))
4192         continue;
4193
4194       for (loc = bpt->loc; loc; loc = loc->next)
4195         if (loc->pspace->aspace == aspace && loc->inserted)
4196           {
4197             CORE_ADDR l, h;
4198
4199             /* Check for intersection.  */
4200             l = std::max<CORE_ADDR> (loc->address, addr);
4201             h = std::min<CORE_ADDR> (loc->address + loc->length, addr + len);
4202             if (l < h)
4203               return 1;
4204           }
4205     }
4206   return 0;
4207 }
4208 \f
4209
4210 /* bpstat stuff.  External routines' interfaces are documented
4211    in breakpoint.h.  */
4212
4213 int
4214 is_catchpoint (struct breakpoint *ep)
4215 {
4216   return (ep->type == bp_catchpoint);
4217 }
4218
4219 /* Frees any storage that is part of a bpstat.  Does not walk the
4220    'next' chain.  */
4221
4222 bpstats::~bpstats ()
4223 {
4224   if (old_val != NULL)
4225     value_free (old_val);
4226   if (bp_location_at != NULL)
4227     decref_bp_location (&bp_location_at);
4228 }
4229
4230 /* Clear a bpstat so that it says we are not at any breakpoint.
4231    Also free any storage that is part of a bpstat.  */
4232
4233 void
4234 bpstat_clear (bpstat *bsp)
4235 {
4236   bpstat p;
4237   bpstat q;
4238
4239   if (bsp == 0)
4240     return;
4241   p = *bsp;
4242   while (p != NULL)
4243     {
4244       q = p->next;
4245       delete p;
4246       p = q;
4247     }
4248   *bsp = NULL;
4249 }
4250
4251 bpstats::bpstats (const bpstats &other)
4252   : next (NULL),
4253     bp_location_at (other.bp_location_at),
4254     breakpoint_at (other.breakpoint_at),
4255     commands (other.commands),
4256     old_val (other.old_val),
4257     print (other.print),
4258     stop (other.stop),
4259     print_it (other.print_it)
4260 {
4261   if (old_val != NULL)
4262     {
4263       old_val = value_copy (old_val);
4264       release_value (old_val);
4265     }
4266   incref_bp_location (bp_location_at);
4267 }
4268
4269 /* Return a copy of a bpstat.  Like "bs1 = bs2" but all storage that
4270    is part of the bpstat is copied as well.  */
4271
4272 bpstat
4273 bpstat_copy (bpstat bs)
4274 {
4275   bpstat p = NULL;
4276   bpstat tmp;
4277   bpstat retval = NULL;
4278
4279   if (bs == NULL)
4280     return bs;
4281
4282   for (; bs != NULL; bs = bs->next)
4283     {
4284       tmp = new bpstats (*bs);
4285
4286       if (p == NULL)
4287         /* This is the first thing in the chain.  */
4288         retval = tmp;
4289       else
4290         p->next = tmp;
4291       p = tmp;
4292     }
4293   p->next = NULL;
4294   return retval;
4295 }
4296
4297 /* Find the bpstat associated with this breakpoint.  */
4298
4299 bpstat
4300 bpstat_find_breakpoint (bpstat bsp, struct breakpoint *breakpoint)
4301 {
4302   if (bsp == NULL)
4303     return NULL;
4304
4305   for (; bsp != NULL; bsp = bsp->next)
4306     {
4307       if (bsp->breakpoint_at == breakpoint)
4308         return bsp;
4309     }
4310   return NULL;
4311 }
4312
4313 /* See breakpoint.h.  */
4314
4315 int
4316 bpstat_explains_signal (bpstat bsp, enum gdb_signal sig)
4317 {
4318   for (; bsp != NULL; bsp = bsp->next)
4319     {
4320       if (bsp->breakpoint_at == NULL)
4321         {
4322           /* A moribund location can never explain a signal other than
4323              GDB_SIGNAL_TRAP.  */
4324           if (sig == GDB_SIGNAL_TRAP)
4325             return 1;
4326         }
4327       else
4328         {
4329           if (bsp->breakpoint_at->ops->explains_signal (bsp->breakpoint_at,
4330                                                         sig))
4331             return 1;
4332         }
4333     }
4334
4335   return 0;
4336 }
4337
4338 /* Put in *NUM the breakpoint number of the first breakpoint we are
4339    stopped at.  *BSP upon return is a bpstat which points to the
4340    remaining breakpoints stopped at (but which is not guaranteed to be
4341    good for anything but further calls to bpstat_num).
4342
4343    Return 0 if passed a bpstat which does not indicate any breakpoints.
4344    Return -1 if stopped at a breakpoint that has been deleted since
4345    we set it.
4346    Return 1 otherwise.  */
4347
4348 int
4349 bpstat_num (bpstat *bsp, int *num)
4350 {
4351   struct breakpoint *b;
4352
4353   if ((*bsp) == NULL)
4354     return 0;                   /* No more breakpoint values */
4355
4356   /* We assume we'll never have several bpstats that correspond to a
4357      single breakpoint -- otherwise, this function might return the
4358      same number more than once and this will look ugly.  */
4359   b = (*bsp)->breakpoint_at;
4360   *bsp = (*bsp)->next;
4361   if (b == NULL)
4362     return -1;                  /* breakpoint that's been deleted since */
4363
4364   *num = b->number;             /* We have its number */
4365   return 1;
4366 }
4367
4368 /* See breakpoint.h.  */
4369
4370 void
4371 bpstat_clear_actions (void)
4372 {
4373   struct thread_info *tp;
4374   bpstat bs;
4375
4376   if (ptid_equal (inferior_ptid, null_ptid))
4377     return;
4378
4379   tp = find_thread_ptid (inferior_ptid);
4380   if (tp == NULL)
4381     return;
4382
4383   for (bs = tp->control.stop_bpstat; bs != NULL; bs = bs->next)
4384     {
4385       bs->commands = NULL;
4386
4387       if (bs->old_val != NULL)
4388         {
4389           value_free (bs->old_val);
4390           bs->old_val = NULL;
4391         }
4392     }
4393 }
4394
4395 /* Called when a command is about to proceed the inferior.  */
4396
4397 static void
4398 breakpoint_about_to_proceed (void)
4399 {
4400   if (!ptid_equal (inferior_ptid, null_ptid))
4401     {
4402       struct thread_info *tp = inferior_thread ();
4403
4404       /* Allow inferior function calls in breakpoint commands to not
4405          interrupt the command list.  When the call finishes
4406          successfully, the inferior will be standing at the same
4407          breakpoint as if nothing happened.  */
4408       if (tp->control.in_infcall)
4409         return;
4410     }
4411
4412   breakpoint_proceeded = 1;
4413 }
4414
4415 /* Return non-zero iff CMD as the first line of a command sequence is `silent'
4416    or its equivalent.  */
4417
4418 static int
4419 command_line_is_silent (struct command_line *cmd)
4420 {
4421   return cmd && (strcmp ("silent", cmd->line) == 0);
4422 }
4423
4424 /* Execute all the commands associated with all the breakpoints at
4425    this location.  Any of these commands could cause the process to
4426    proceed beyond this point, etc.  We look out for such changes by
4427    checking the global "breakpoint_proceeded" after each command.
4428
4429    Returns true if a breakpoint command resumed the inferior.  In that
4430    case, it is the caller's responsibility to recall it again with the
4431    bpstat of the current thread.  */
4432
4433 static int
4434 bpstat_do_actions_1 (bpstat *bsp)
4435 {
4436   bpstat bs;
4437   int again = 0;
4438
4439   /* Avoid endless recursion if a `source' command is contained
4440      in bs->commands.  */
4441   if (executing_breakpoint_commands)
4442     return 0;
4443
4444   scoped_restore save_executing
4445     = make_scoped_restore (&executing_breakpoint_commands, 1);
4446
4447   scoped_restore preventer = prevent_dont_repeat ();
4448
4449   /* This pointer will iterate over the list of bpstat's.  */
4450   bs = *bsp;
4451
4452   breakpoint_proceeded = 0;
4453   for (; bs != NULL; bs = bs->next)
4454     {
4455       struct command_line *cmd = NULL;
4456
4457       /* Take ownership of the BSP's command tree, if it has one.
4458
4459          The command tree could legitimately contain commands like
4460          'step' and 'next', which call clear_proceed_status, which
4461          frees stop_bpstat's command tree.  To make sure this doesn't
4462          free the tree we're executing out from under us, we need to
4463          take ownership of the tree ourselves.  Since a given bpstat's
4464          commands are only executed once, we don't need to copy it; we
4465          can clear the pointer in the bpstat, and make sure we free
4466          the tree when we're done.  */
4467       counted_command_line ccmd = bs->commands;
4468       bs->commands = NULL;
4469       if (ccmd != NULL)
4470         cmd = ccmd.get ();
4471       if (command_line_is_silent (cmd))
4472         {
4473           /* The action has been already done by bpstat_stop_status.  */
4474           cmd = cmd->next;
4475         }
4476
4477       while (cmd != NULL)
4478         {
4479           execute_control_command (cmd);
4480
4481           if (breakpoint_proceeded)
4482             break;
4483           else
4484             cmd = cmd->next;
4485         }
4486
4487       if (breakpoint_proceeded)
4488         {
4489           if (current_ui->async)
4490             /* If we are in async mode, then the target might be still
4491                running, not stopped at any breakpoint, so nothing for
4492                us to do here -- just return to the event loop.  */
4493             ;
4494           else
4495             /* In sync mode, when execute_control_command returns
4496                we're already standing on the next breakpoint.
4497                Breakpoint commands for that stop were not run, since
4498                execute_command does not run breakpoint commands --
4499                only command_line_handler does, but that one is not
4500                involved in execution of breakpoint commands.  So, we
4501                can now execute breakpoint commands.  It should be
4502                noted that making execute_command do bpstat actions is
4503                not an option -- in this case we'll have recursive
4504                invocation of bpstat for each breakpoint with a
4505                command, and can easily blow up GDB stack.  Instead, we
4506                return true, which will trigger the caller to recall us
4507                with the new stop_bpstat.  */
4508             again = 1;
4509           break;
4510         }
4511     }
4512   return again;
4513 }
4514
4515 void
4516 bpstat_do_actions (void)
4517 {
4518   struct cleanup *cleanup_if_error = make_bpstat_clear_actions_cleanup ();
4519
4520   /* Do any commands attached to breakpoint we are stopped at.  */
4521   while (!ptid_equal (inferior_ptid, null_ptid)
4522          && target_has_execution
4523          && !is_exited (inferior_ptid)
4524          && !is_executing (inferior_ptid))
4525     /* Since in sync mode, bpstat_do_actions may resume the inferior,
4526        and only return when it is stopped at the next breakpoint, we
4527        keep doing breakpoint actions until it returns false to
4528        indicate the inferior was not resumed.  */
4529     if (!bpstat_do_actions_1 (&inferior_thread ()->control.stop_bpstat))
4530       break;
4531
4532   discard_cleanups (cleanup_if_error);
4533 }
4534
4535 /* Print out the (old or new) value associated with a watchpoint.  */
4536
4537 static void
4538 watchpoint_value_print (struct value *val, struct ui_file *stream)
4539 {
4540   if (val == NULL)
4541     fprintf_unfiltered (stream, _("<unreadable>"));
4542   else
4543     {
4544       struct value_print_options opts;
4545       get_user_print_options (&opts);
4546       value_print (val, stream, &opts);
4547     }
4548 }
4549
4550 /* Print the "Thread ID hit" part of "Thread ID hit Breakpoint N" if
4551    debugging multiple threads.  */
4552
4553 void
4554 maybe_print_thread_hit_breakpoint (struct ui_out *uiout)
4555 {
4556   if (uiout->is_mi_like_p ())
4557     return;
4558
4559   uiout->text ("\n");
4560
4561   if (show_thread_that_caused_stop ())
4562     {
4563       const char *name;
4564       struct thread_info *thr = inferior_thread ();
4565
4566       uiout->text ("Thread ");
4567       uiout->field_fmt ("thread-id", "%s", print_thread_id (thr));
4568
4569       name = thr->name != NULL ? thr->name : target_thread_name (thr);
4570       if (name != NULL)
4571         {
4572           uiout->text (" \"");
4573           uiout->field_fmt ("name", "%s", name);
4574           uiout->text ("\"");
4575         }
4576
4577       uiout->text (" hit ");
4578     }
4579 }
4580
4581 /* Generic routine for printing messages indicating why we
4582    stopped.  The behavior of this function depends on the value
4583    'print_it' in the bpstat structure.  Under some circumstances we
4584    may decide not to print anything here and delegate the task to
4585    normal_stop().  */
4586
4587 static enum print_stop_action
4588 print_bp_stop_message (bpstat bs)
4589 {
4590   switch (bs->print_it)
4591     {
4592     case print_it_noop:
4593       /* Nothing should be printed for this bpstat entry.  */
4594       return PRINT_UNKNOWN;
4595       break;
4596
4597     case print_it_done:
4598       /* We still want to print the frame, but we already printed the
4599          relevant messages.  */
4600       return PRINT_SRC_AND_LOC;
4601       break;
4602
4603     case print_it_normal:
4604       {
4605         struct breakpoint *b = bs->breakpoint_at;
4606
4607         /* bs->breakpoint_at can be NULL if it was a momentary breakpoint
4608            which has since been deleted.  */
4609         if (b == NULL)
4610           return PRINT_UNKNOWN;
4611
4612         /* Normal case.  Call the breakpoint's print_it method.  */
4613         return b->ops->print_it (bs);
4614       }
4615       break;
4616
4617     default:
4618       internal_error (__FILE__, __LINE__,
4619                       _("print_bp_stop_message: unrecognized enum value"));
4620       break;
4621     }
4622 }
4623
4624 /* A helper function that prints a shared library stopped event.  */
4625
4626 static void
4627 print_solib_event (int is_catchpoint)
4628 {
4629   int any_deleted
4630     = !VEC_empty (char_ptr, current_program_space->deleted_solibs);
4631   int any_added
4632     = !VEC_empty (so_list_ptr, current_program_space->added_solibs);
4633
4634   if (!is_catchpoint)
4635     {
4636       if (any_added || any_deleted)
4637         current_uiout->text (_("Stopped due to shared library event:\n"));
4638       else
4639         current_uiout->text (_("Stopped due to shared library event (no "
4640                                "libraries added or removed)\n"));
4641     }
4642
4643   if (current_uiout->is_mi_like_p ())
4644     current_uiout->field_string ("reason",
4645                                  async_reason_lookup (EXEC_ASYNC_SOLIB_EVENT));
4646
4647   if (any_deleted)
4648     {
4649       char *name;
4650       int ix;
4651
4652       current_uiout->text (_("  Inferior unloaded "));
4653       ui_out_emit_list list_emitter (current_uiout, "removed");
4654       for (ix = 0;
4655            VEC_iterate (char_ptr, current_program_space->deleted_solibs,
4656                         ix, name);
4657            ++ix)
4658         {
4659           if (ix > 0)
4660             current_uiout->text ("    ");
4661           current_uiout->field_string ("library", name);
4662           current_uiout->text ("\n");
4663         }
4664     }
4665
4666   if (any_added)
4667     {
4668       struct so_list *iter;
4669       int ix;
4670
4671       current_uiout->text (_("  Inferior loaded "));
4672       ui_out_emit_list list_emitter (current_uiout, "added");
4673       for (ix = 0;
4674            VEC_iterate (so_list_ptr, current_program_space->added_solibs,
4675                         ix, iter);
4676            ++ix)
4677         {
4678           if (ix > 0)
4679             current_uiout->text ("    ");
4680           current_uiout->field_string ("library", iter->so_name);
4681           current_uiout->text ("\n");
4682         }
4683     }
4684 }
4685
4686 /* Print a message indicating what happened.  This is called from
4687    normal_stop().  The input to this routine is the head of the bpstat
4688    list - a list of the eventpoints that caused this stop.  KIND is
4689    the target_waitkind for the stopping event.  This
4690    routine calls the generic print routine for printing a message
4691    about reasons for stopping.  This will print (for example) the
4692    "Breakpoint n," part of the output.  The return value of this
4693    routine is one of:
4694
4695    PRINT_UNKNOWN: Means we printed nothing.
4696    PRINT_SRC_AND_LOC: Means we printed something, and expect subsequent
4697    code to print the location.  An example is 
4698    "Breakpoint 1, " which should be followed by
4699    the location.
4700    PRINT_SRC_ONLY: Means we printed something, but there is no need
4701    to also print the location part of the message.
4702    An example is the catch/throw messages, which
4703    don't require a location appended to the end.
4704    PRINT_NOTHING: We have done some printing and we don't need any 
4705    further info to be printed.  */
4706
4707 enum print_stop_action
4708 bpstat_print (bpstat bs, int kind)
4709 {
4710   enum print_stop_action val;
4711
4712   /* Maybe another breakpoint in the chain caused us to stop.
4713      (Currently all watchpoints go on the bpstat whether hit or not.
4714      That probably could (should) be changed, provided care is taken
4715      with respect to bpstat_explains_signal).  */
4716   for (; bs; bs = bs->next)
4717     {
4718       val = print_bp_stop_message (bs);
4719       if (val == PRINT_SRC_ONLY 
4720           || val == PRINT_SRC_AND_LOC 
4721           || val == PRINT_NOTHING)
4722         return val;
4723     }
4724
4725   /* If we had hit a shared library event breakpoint,
4726      print_bp_stop_message would print out this message.  If we hit an
4727      OS-level shared library event, do the same thing.  */
4728   if (kind == TARGET_WAITKIND_LOADED)
4729     {
4730       print_solib_event (0);
4731       return PRINT_NOTHING;
4732     }
4733
4734   /* We reached the end of the chain, or we got a null BS to start
4735      with and nothing was printed.  */
4736   return PRINT_UNKNOWN;
4737 }
4738
4739 /* Evaluate the boolean expression EXP and return the result.  */
4740
4741 static bool
4742 breakpoint_cond_eval (expression *exp)
4743 {
4744   struct value *mark = value_mark ();
4745   bool res = value_true (evaluate_expression (exp));
4746
4747   value_free_to_mark (mark);
4748   return res;
4749 }
4750
4751 /* Allocate a new bpstat.  Link it to the FIFO list by BS_LINK_POINTER.  */
4752
4753 bpstats::bpstats (struct bp_location *bl, bpstat **bs_link_pointer)
4754   : next (NULL),
4755     bp_location_at (bl),
4756     breakpoint_at (bl->owner),
4757     commands (NULL),
4758     old_val (NULL),
4759     print (0),
4760     stop (0),
4761     print_it (print_it_normal)
4762 {
4763   incref_bp_location (bl);
4764   **bs_link_pointer = this;
4765   *bs_link_pointer = &next;
4766 }
4767
4768 bpstats::bpstats ()
4769   : next (NULL),
4770     bp_location_at (NULL),
4771     breakpoint_at (NULL),
4772     commands (NULL),
4773     old_val (NULL),
4774     print (0),
4775     stop (0),
4776     print_it (print_it_normal)
4777 {
4778 }
4779 \f
4780 /* The target has stopped with waitstatus WS.  Check if any hardware
4781    watchpoints have triggered, according to the target.  */
4782
4783 int
4784 watchpoints_triggered (struct target_waitstatus *ws)
4785 {
4786   int stopped_by_watchpoint = target_stopped_by_watchpoint ();
4787   CORE_ADDR addr;
4788   struct breakpoint *b;
4789
4790   if (!stopped_by_watchpoint)
4791     {
4792       /* We were not stopped by a watchpoint.  Mark all watchpoints
4793          as not triggered.  */
4794       ALL_BREAKPOINTS (b)
4795         if (is_hardware_watchpoint (b))
4796           {
4797             struct watchpoint *w = (struct watchpoint *) b;
4798
4799             w->watchpoint_triggered = watch_triggered_no;
4800           }
4801
4802       return 0;
4803     }
4804
4805   if (!target_stopped_data_address (&current_target, &addr))
4806     {
4807       /* We were stopped by a watchpoint, but we don't know where.
4808          Mark all watchpoints as unknown.  */
4809       ALL_BREAKPOINTS (b)
4810         if (is_hardware_watchpoint (b))
4811           {
4812             struct watchpoint *w = (struct watchpoint *) b;
4813
4814             w->watchpoint_triggered = watch_triggered_unknown;
4815           }
4816
4817       return 1;
4818     }
4819
4820   /* The target could report the data address.  Mark watchpoints
4821      affected by this data address as triggered, and all others as not
4822      triggered.  */
4823
4824   ALL_BREAKPOINTS (b)
4825     if (is_hardware_watchpoint (b))
4826       {
4827         struct watchpoint *w = (struct watchpoint *) b;
4828         struct bp_location *loc;
4829
4830         w->watchpoint_triggered = watch_triggered_no;
4831         for (loc = b->loc; loc; loc = loc->next)
4832           {
4833             if (is_masked_watchpoint (b))
4834               {
4835                 CORE_ADDR newaddr = addr & w->hw_wp_mask;
4836                 CORE_ADDR start = loc->address & w->hw_wp_mask;
4837
4838                 if (newaddr == start)
4839                   {
4840                     w->watchpoint_triggered = watch_triggered_yes;
4841                     break;
4842                   }
4843               }
4844             /* Exact match not required.  Within range is sufficient.  */
4845             else if (target_watchpoint_addr_within_range (&current_target,
4846                                                          addr, loc->address,
4847                                                          loc->length))
4848               {
4849                 w->watchpoint_triggered = watch_triggered_yes;
4850                 break;
4851               }
4852           }
4853       }
4854
4855   return 1;
4856 }
4857
4858 /* Possible return values for watchpoint_check.  */
4859 enum wp_check_result
4860   {
4861     /* The watchpoint has been deleted.  */
4862     WP_DELETED = 1,
4863
4864     /* The value has changed.  */
4865     WP_VALUE_CHANGED = 2,
4866
4867     /* The value has not changed.  */
4868     WP_VALUE_NOT_CHANGED = 3,
4869
4870     /* Ignore this watchpoint, no matter if the value changed or not.  */
4871     WP_IGNORE = 4,
4872   };
4873
4874 #define BP_TEMPFLAG 1
4875 #define BP_HARDWAREFLAG 2
4876
4877 /* Evaluate watchpoint condition expression and check if its value
4878    changed.  */
4879
4880 static wp_check_result
4881 watchpoint_check (bpstat bs)
4882 {
4883   struct watchpoint *b;
4884   struct frame_info *fr;
4885   int within_current_scope;
4886
4887   /* BS is built from an existing struct breakpoint.  */
4888   gdb_assert (bs->breakpoint_at != NULL);
4889   b = (struct watchpoint *) bs->breakpoint_at;
4890
4891   /* If this is a local watchpoint, we only want to check if the
4892      watchpoint frame is in scope if the current thread is the thread
4893      that was used to create the watchpoint.  */
4894   if (!watchpoint_in_thread_scope (b))
4895     return WP_IGNORE;
4896
4897   if (b->exp_valid_block == NULL)
4898     within_current_scope = 1;
4899   else
4900     {
4901       struct frame_info *frame = get_current_frame ();
4902       struct gdbarch *frame_arch = get_frame_arch (frame);
4903       CORE_ADDR frame_pc = get_frame_pc (frame);
4904
4905       /* stack_frame_destroyed_p() returns a non-zero value if we're
4906          still in the function but the stack frame has already been
4907          invalidated.  Since we can't rely on the values of local
4908          variables after the stack has been destroyed, we are treating
4909          the watchpoint in that state as `not changed' without further
4910          checking.  Don't mark watchpoints as changed if the current
4911          frame is in an epilogue - even if they are in some other
4912          frame, our view of the stack is likely to be wrong and
4913          frame_find_by_id could error out.  */
4914       if (gdbarch_stack_frame_destroyed_p (frame_arch, frame_pc))
4915         return WP_IGNORE;
4916
4917       fr = frame_find_by_id (b->watchpoint_frame);
4918       within_current_scope = (fr != NULL);
4919
4920       /* If we've gotten confused in the unwinder, we might have
4921          returned a frame that can't describe this variable.  */
4922       if (within_current_scope)
4923         {
4924           struct symbol *function;
4925
4926           function = get_frame_function (fr);
4927           if (function == NULL
4928               || !contained_in (b->exp_valid_block,
4929                                 SYMBOL_BLOCK_VALUE (function)))
4930             within_current_scope = 0;
4931         }
4932
4933       if (within_current_scope)
4934         /* If we end up stopping, the current frame will get selected
4935            in normal_stop.  So this call to select_frame won't affect
4936            the user.  */
4937         select_frame (fr);
4938     }
4939
4940   if (within_current_scope)
4941     {
4942       /* We use value_{,free_to_}mark because it could be a *long*
4943          time before we return to the command level and call
4944          free_all_values.  We can't call free_all_values because we
4945          might be in the middle of evaluating a function call.  */
4946
4947       int pc = 0;
4948       struct value *mark;
4949       struct value *new_val;
4950
4951       if (is_masked_watchpoint (b))
4952         /* Since we don't know the exact trigger address (from
4953            stopped_data_address), just tell the user we've triggered
4954            a mask watchpoint.  */
4955         return WP_VALUE_CHANGED;
4956
4957       mark = value_mark ();
4958       fetch_subexp_value (b->exp.get (), &pc, &new_val, NULL, NULL, 0);
4959
4960       if (b->val_bitsize != 0)
4961         new_val = extract_bitfield_from_watchpoint_value (b, new_val);
4962
4963       /* We use value_equal_contents instead of value_equal because
4964          the latter coerces an array to a pointer, thus comparing just
4965          the address of the array instead of its contents.  This is
4966          not what we want.  */
4967       if ((b->val != NULL) != (new_val != NULL)
4968           || (b->val != NULL && !value_equal_contents (b->val, new_val)))
4969         {
4970           if (new_val != NULL)
4971             {
4972               release_value (new_val);
4973               value_free_to_mark (mark);
4974             }
4975           bs->old_val = b->val;
4976           b->val = new_val;
4977           b->val_valid = 1;
4978           return WP_VALUE_CHANGED;
4979         }
4980       else
4981         {
4982           /* Nothing changed.  */
4983           value_free_to_mark (mark);
4984           return WP_VALUE_NOT_CHANGED;
4985         }
4986     }
4987   else
4988     {
4989       /* This seems like the only logical thing to do because
4990          if we temporarily ignored the watchpoint, then when
4991          we reenter the block in which it is valid it contains
4992          garbage (in the case of a function, it may have two
4993          garbage values, one before and one after the prologue).
4994          So we can't even detect the first assignment to it and
4995          watch after that (since the garbage may or may not equal
4996          the first value assigned).  */
4997       /* We print all the stop information in
4998          breakpoint_ops->print_it, but in this case, by the time we
4999          call breakpoint_ops->print_it this bp will be deleted
5000          already.  So we have no choice but print the information
5001          here.  */
5002
5003       SWITCH_THRU_ALL_UIS ()
5004         {
5005           struct ui_out *uiout = current_uiout;
5006
5007           if (uiout->is_mi_like_p ())
5008             uiout->field_string
5009               ("reason", async_reason_lookup (EXEC_ASYNC_WATCHPOINT_SCOPE));
5010           uiout->text ("\nWatchpoint ");
5011           uiout->field_int ("wpnum", b->number);
5012           uiout->text (" deleted because the program has left the block in\n"
5013                        "which its expression is valid.\n");
5014         }
5015
5016       /* Make sure the watchpoint's commands aren't executed.  */
5017       b->commands = NULL;
5018       watchpoint_del_at_next_stop (b);
5019
5020       return WP_DELETED;
5021     }
5022 }
5023
5024 /* Return true if it looks like target has stopped due to hitting
5025    breakpoint location BL.  This function does not check if we should
5026    stop, only if BL explains the stop.  */
5027
5028 static int
5029 bpstat_check_location (const struct bp_location *bl,
5030                        const address_space *aspace, CORE_ADDR bp_addr,
5031                        const struct target_waitstatus *ws)
5032 {
5033   struct breakpoint *b = bl->owner;
5034
5035   /* BL is from an existing breakpoint.  */
5036   gdb_assert (b != NULL);
5037
5038   return b->ops->breakpoint_hit (bl, aspace, bp_addr, ws);
5039 }
5040
5041 /* Determine if the watched values have actually changed, and we
5042    should stop.  If not, set BS->stop to 0.  */
5043
5044 static void
5045 bpstat_check_watchpoint (bpstat bs)
5046 {
5047   const struct bp_location *bl;
5048   struct watchpoint *b;
5049
5050   /* BS is built for existing struct breakpoint.  */
5051   bl = bs->bp_location_at;
5052   gdb_assert (bl != NULL);
5053   b = (struct watchpoint *) bs->breakpoint_at;
5054   gdb_assert (b != NULL);
5055
5056     {
5057       int must_check_value = 0;
5058       
5059       if (b->type == bp_watchpoint)
5060         /* For a software watchpoint, we must always check the
5061            watched value.  */
5062         must_check_value = 1;
5063       else if (b->watchpoint_triggered == watch_triggered_yes)
5064         /* We have a hardware watchpoint (read, write, or access)
5065            and the target earlier reported an address watched by
5066            this watchpoint.  */
5067         must_check_value = 1;
5068       else if (b->watchpoint_triggered == watch_triggered_unknown
5069                && b->type == bp_hardware_watchpoint)
5070         /* We were stopped by a hardware watchpoint, but the target could
5071            not report the data address.  We must check the watchpoint's
5072            value.  Access and read watchpoints are out of luck; without
5073            a data address, we can't figure it out.  */
5074         must_check_value = 1;
5075
5076       if (must_check_value)
5077         {
5078           wp_check_result e;
5079
5080           TRY
5081             {
5082               e = watchpoint_check (bs);
5083             }
5084           CATCH (ex, RETURN_MASK_ALL)
5085             {
5086               exception_fprintf (gdb_stderr, ex,
5087                                  "Error evaluating expression "
5088                                  "for watchpoint %d\n",
5089                                  b->number);
5090
5091               SWITCH_THRU_ALL_UIS ()
5092                 {
5093                   printf_filtered (_("Watchpoint %d deleted.\n"),
5094                                    b->number);
5095                 }
5096               watchpoint_del_at_next_stop (b);
5097               e = WP_DELETED;
5098             }
5099           END_CATCH
5100
5101           switch (e)
5102             {
5103             case WP_DELETED:
5104               /* We've already printed what needs to be printed.  */
5105               bs->print_it = print_it_done;
5106               /* Stop.  */
5107               break;
5108             case WP_IGNORE:
5109               bs->print_it = print_it_noop;
5110               bs->stop = 0;
5111               break;
5112             case WP_VALUE_CHANGED:
5113               if (b->type == bp_read_watchpoint)
5114                 {
5115                   /* There are two cases to consider here:
5116
5117                      1. We're watching the triggered memory for reads.
5118                      In that case, trust the target, and always report
5119                      the watchpoint hit to the user.  Even though
5120                      reads don't cause value changes, the value may
5121                      have changed since the last time it was read, and
5122                      since we're not trapping writes, we will not see
5123                      those, and as such we should ignore our notion of
5124                      old value.
5125
5126                      2. We're watching the triggered memory for both
5127                      reads and writes.  There are two ways this may
5128                      happen:
5129
5130                      2.1. This is a target that can't break on data
5131                      reads only, but can break on accesses (reads or
5132                      writes), such as e.g., x86.  We detect this case
5133                      at the time we try to insert read watchpoints.
5134
5135                      2.2. Otherwise, the target supports read
5136                      watchpoints, but, the user set an access or write
5137                      watchpoint watching the same memory as this read
5138                      watchpoint.
5139
5140                      If we're watching memory writes as well as reads,
5141                      ignore watchpoint hits when we find that the
5142                      value hasn't changed, as reads don't cause
5143                      changes.  This still gives false positives when
5144                      the program writes the same value to memory as
5145                      what there was already in memory (we will confuse
5146                      it for a read), but it's much better than
5147                      nothing.  */
5148
5149                   int other_write_watchpoint = 0;
5150
5151                   if (bl->watchpoint_type == hw_read)
5152                     {
5153                       struct breakpoint *other_b;
5154
5155                       ALL_BREAKPOINTS (other_b)
5156                         if (other_b->type == bp_hardware_watchpoint
5157                             || other_b->type == bp_access_watchpoint)
5158                           {
5159                             struct watchpoint *other_w =
5160                               (struct watchpoint *) other_b;
5161
5162                             if (other_w->watchpoint_triggered
5163                                 == watch_triggered_yes)
5164                               {
5165                                 other_write_watchpoint = 1;
5166                                 break;
5167                               }
5168                           }
5169                     }
5170
5171                   if (other_write_watchpoint
5172                       || bl->watchpoint_type == hw_access)
5173                     {
5174                       /* We're watching the same memory for writes,
5175                          and the value changed since the last time we
5176                          updated it, so this trap must be for a write.
5177                          Ignore it.  */
5178                       bs->print_it = print_it_noop;
5179                       bs->stop = 0;
5180                     }
5181                 }
5182               break;
5183             case WP_VALUE_NOT_CHANGED:
5184               if (b->type == bp_hardware_watchpoint
5185                   || b->type == bp_watchpoint)
5186                 {
5187                   /* Don't stop: write watchpoints shouldn't fire if
5188                      the value hasn't changed.  */
5189                   bs->print_it = print_it_noop;
5190                   bs->stop = 0;
5191                 }
5192               /* Stop.  */
5193               break;
5194             default:
5195               /* Can't happen.  */
5196               break;
5197             }
5198         }
5199       else      /* must_check_value == 0 */
5200         {
5201           /* This is a case where some watchpoint(s) triggered, but
5202              not at the address of this watchpoint, or else no
5203              watchpoint triggered after all.  So don't print
5204              anything for this watchpoint.  */
5205           bs->print_it = print_it_noop;
5206           bs->stop = 0;
5207         }
5208     }
5209 }
5210
5211 /* For breakpoints that are currently marked as telling gdb to stop,
5212    check conditions (condition proper, frame, thread and ignore count)
5213    of breakpoint referred to by BS.  If we should not stop for this
5214    breakpoint, set BS->stop to 0.  */
5215
5216 static void
5217 bpstat_check_breakpoint_conditions (bpstat bs, ptid_t ptid)
5218 {
5219   const struct bp_location *bl;
5220   struct breakpoint *b;
5221   /* Assume stop.  */
5222   bool condition_result = true;
5223   struct expression *cond;
5224
5225   gdb_assert (bs->stop);
5226
5227   /* BS is built for existing struct breakpoint.  */
5228   bl = bs->bp_location_at;
5229   gdb_assert (bl != NULL);
5230   b = bs->breakpoint_at;
5231   gdb_assert (b != NULL);
5232
5233   /* Even if the target evaluated the condition on its end and notified GDB, we
5234      need to do so again since GDB does not know if we stopped due to a
5235      breakpoint or a single step breakpoint.  */
5236
5237   if (frame_id_p (b->frame_id)
5238       && !frame_id_eq (b->frame_id, get_stack_frame_id (get_current_frame ())))
5239     {
5240       bs->stop = 0;
5241       return;
5242     }
5243
5244   /* If this is a thread/task-specific breakpoint, don't waste cpu
5245      evaluating the condition if this isn't the specified
5246      thread/task.  */
5247   if ((b->thread != -1 && b->thread != ptid_to_global_thread_id (ptid))
5248       || (b->task != 0 && b->task != ada_get_task_number (ptid)))
5249
5250     {
5251       bs->stop = 0;
5252       return;
5253     }
5254
5255   /* Evaluate extension language breakpoints that have a "stop" method
5256      implemented.  */
5257   bs->stop = breakpoint_ext_lang_cond_says_stop (b);
5258
5259   if (is_watchpoint (b))
5260     {
5261       struct watchpoint *w = (struct watchpoint *) b;
5262
5263       cond = w->cond_exp.get ();
5264     }
5265   else
5266     cond = bl->cond.get ();
5267
5268   if (cond && b->disposition != disp_del_at_next_stop)
5269     {
5270       int within_current_scope = 1;
5271       struct watchpoint * w;
5272
5273       /* We use value_mark and value_free_to_mark because it could
5274          be a long time before we return to the command level and
5275          call free_all_values.  We can't call free_all_values
5276          because we might be in the middle of evaluating a
5277          function call.  */
5278       struct value *mark = value_mark ();
5279
5280       if (is_watchpoint (b))
5281         w = (struct watchpoint *) b;
5282       else
5283         w = NULL;
5284
5285       /* Need to select the frame, with all that implies so that
5286          the conditions will have the right context.  Because we
5287          use the frame, we will not see an inlined function's
5288          variables when we arrive at a breakpoint at the start
5289          of the inlined function; the current frame will be the
5290          call site.  */
5291       if (w == NULL || w->cond_exp_valid_block == NULL)
5292         select_frame (get_current_frame ());
5293       else
5294         {
5295           struct frame_info *frame;
5296
5297           /* For local watchpoint expressions, which particular
5298              instance of a local is being watched matters, so we
5299              keep track of the frame to evaluate the expression
5300              in.  To evaluate the condition however, it doesn't
5301              really matter which instantiation of the function
5302              where the condition makes sense triggers the
5303              watchpoint.  This allows an expression like "watch
5304              global if q > 10" set in `func', catch writes to
5305              global on all threads that call `func', or catch
5306              writes on all recursive calls of `func' by a single
5307              thread.  We simply always evaluate the condition in
5308              the innermost frame that's executing where it makes
5309              sense to evaluate the condition.  It seems
5310              intuitive.  */
5311           frame = block_innermost_frame (w->cond_exp_valid_block);
5312           if (frame != NULL)
5313             select_frame (frame);
5314           else
5315             within_current_scope = 0;
5316         }
5317       if (within_current_scope)
5318         {
5319           TRY
5320             {
5321               condition_result = breakpoint_cond_eval (cond);
5322             }
5323           CATCH (ex, RETURN_MASK_ALL)
5324             {
5325               exception_fprintf (gdb_stderr, ex,
5326                                  "Error in testing breakpoint condition:\n");
5327             }
5328           END_CATCH
5329         }
5330       else
5331         {
5332           warning (_("Watchpoint condition cannot be tested "
5333                      "in the current scope"));
5334           /* If we failed to set the right context for this
5335              watchpoint, unconditionally report it.  */
5336         }
5337       /* FIXME-someday, should give breakpoint #.  */
5338       value_free_to_mark (mark);
5339     }
5340
5341   if (cond && !condition_result)
5342     {
5343       bs->stop = 0;
5344     }
5345   else if (b->ignore_count > 0)
5346     {
5347       b->ignore_count--;
5348       bs->stop = 0;
5349       /* Increase the hit count even though we don't stop.  */
5350       ++(b->hit_count);
5351       observer_notify_breakpoint_modified (b);
5352     }   
5353 }
5354
5355 /* Returns true if we need to track moribund locations of LOC's type
5356    on the current target.  */
5357
5358 static int
5359 need_moribund_for_location_type (struct bp_location *loc)
5360 {
5361   return ((loc->loc_type == bp_loc_software_breakpoint
5362            && !target_supports_stopped_by_sw_breakpoint ())
5363           || (loc->loc_type == bp_loc_hardware_breakpoint
5364               && !target_supports_stopped_by_hw_breakpoint ()));
5365 }
5366
5367
5368 /* Get a bpstat associated with having just stopped at address
5369    BP_ADDR in thread PTID.
5370
5371    Determine whether we stopped at a breakpoint, etc, or whether we
5372    don't understand this stop.  Result is a chain of bpstat's such
5373    that:
5374
5375    if we don't understand the stop, the result is a null pointer.
5376
5377    if we understand why we stopped, the result is not null.
5378
5379    Each element of the chain refers to a particular breakpoint or
5380    watchpoint at which we have stopped.  (We may have stopped for
5381    several reasons concurrently.)
5382
5383    Each element of the chain has valid next, breakpoint_at,
5384    commands, FIXME??? fields.  */
5385
5386 bpstat
5387 bpstat_stop_status (const address_space *aspace,
5388                     CORE_ADDR bp_addr, ptid_t ptid,
5389                     const struct target_waitstatus *ws)
5390 {
5391   struct breakpoint *b = NULL;
5392   struct bp_location *bl;
5393   struct bp_location *loc;
5394   /* First item of allocated bpstat's.  */
5395   bpstat bs_head = NULL, *bs_link = &bs_head;
5396   /* Pointer to the last thing in the chain currently.  */
5397   bpstat bs;
5398   int ix;
5399   int need_remove_insert;
5400   int removed_any;
5401
5402   /* First, build the bpstat chain with locations that explain a
5403      target stop, while being careful to not set the target running,
5404      as that may invalidate locations (in particular watchpoint
5405      locations are recreated).  Resuming will happen here with
5406      breakpoint conditions or watchpoint expressions that include
5407      inferior function calls.  */
5408
5409   ALL_BREAKPOINTS (b)
5410     {
5411       if (!breakpoint_enabled (b))
5412         continue;
5413
5414       for (bl = b->loc; bl != NULL; bl = bl->next)
5415         {
5416           /* For hardware watchpoints, we look only at the first
5417              location.  The watchpoint_check function will work on the
5418              entire expression, not the individual locations.  For
5419              read watchpoints, the watchpoints_triggered function has
5420              checked all locations already.  */
5421           if (b->type == bp_hardware_watchpoint && bl != b->loc)
5422             break;
5423
5424           if (!bl->enabled || bl->shlib_disabled)
5425             continue;
5426
5427           if (!bpstat_check_location (bl, aspace, bp_addr, ws))
5428             continue;
5429
5430           /* Come here if it's a watchpoint, or if the break address
5431              matches.  */
5432
5433           bs = new bpstats (bl, &bs_link);      /* Alloc a bpstat to
5434                                                    explain stop.  */
5435
5436           /* Assume we stop.  Should we find a watchpoint that is not
5437              actually triggered, or if the condition of the breakpoint
5438              evaluates as false, we'll reset 'stop' to 0.  */
5439           bs->stop = 1;
5440           bs->print = 1;
5441
5442           /* If this is a scope breakpoint, mark the associated
5443              watchpoint as triggered so that we will handle the
5444              out-of-scope event.  We'll get to the watchpoint next
5445              iteration.  */
5446           if (b->type == bp_watchpoint_scope && b->related_breakpoint != b)
5447             {
5448               struct watchpoint *w = (struct watchpoint *) b->related_breakpoint;
5449
5450               w->watchpoint_triggered = watch_triggered_yes;
5451             }
5452         }
5453     }
5454
5455   /* Check if a moribund breakpoint explains the stop.  */
5456   if (!target_supports_stopped_by_sw_breakpoint ()
5457       || !target_supports_stopped_by_hw_breakpoint ())
5458     {
5459       for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
5460         {
5461           if (breakpoint_location_address_match (loc, aspace, bp_addr)
5462               && need_moribund_for_location_type (loc))
5463             {
5464               bs = new bpstats (loc, &bs_link);
5465               /* For hits of moribund locations, we should just proceed.  */
5466               bs->stop = 0;
5467               bs->print = 0;
5468               bs->print_it = print_it_noop;
5469             }
5470         }
5471     }
5472
5473   /* A bit of special processing for shlib breakpoints.  We need to
5474      process solib loading here, so that the lists of loaded and
5475      unloaded libraries are correct before we handle "catch load" and
5476      "catch unload".  */
5477   for (bs = bs_head; bs != NULL; bs = bs->next)
5478     {
5479       if (bs->breakpoint_at && bs->breakpoint_at->type == bp_shlib_event)
5480         {
5481           handle_solib_event ();
5482           break;
5483         }
5484     }
5485
5486   /* Now go through the locations that caused the target to stop, and
5487      check whether we're interested in reporting this stop to higher
5488      layers, or whether we should resume the target transparently.  */
5489
5490   removed_any = 0;
5491
5492   for (bs = bs_head; bs != NULL; bs = bs->next)
5493     {
5494       if (!bs->stop)
5495         continue;
5496
5497       b = bs->breakpoint_at;
5498       b->ops->check_status (bs);
5499       if (bs->stop)
5500         {
5501           bpstat_check_breakpoint_conditions (bs, ptid);
5502
5503           if (bs->stop)
5504             {
5505               ++(b->hit_count);
5506               observer_notify_breakpoint_modified (b);
5507
5508               /* We will stop here.  */
5509               if (b->disposition == disp_disable)
5510                 {
5511                   --(b->enable_count);
5512                   if (b->enable_count <= 0)
5513                     b->enable_state = bp_disabled;
5514                   removed_any = 1;
5515                 }
5516               if (b->silent)
5517                 bs->print = 0;
5518               bs->commands = b->commands;
5519               if (command_line_is_silent (bs->commands
5520                                           ? bs->commands.get () : NULL))
5521                 bs->print = 0;
5522
5523               b->ops->after_condition_true (bs);
5524             }
5525
5526         }
5527
5528       /* Print nothing for this entry if we don't stop or don't
5529          print.  */
5530       if (!bs->stop || !bs->print)
5531         bs->print_it = print_it_noop;
5532     }
5533
5534   /* If we aren't stopping, the value of some hardware watchpoint may
5535      not have changed, but the intermediate memory locations we are
5536      watching may have.  Don't bother if we're stopping; this will get
5537      done later.  */
5538   need_remove_insert = 0;
5539   if (! bpstat_causes_stop (bs_head))
5540     for (bs = bs_head; bs != NULL; bs = bs->next)
5541       if (!bs->stop
5542           && bs->breakpoint_at
5543           && is_hardware_watchpoint (bs->breakpoint_at))
5544         {
5545           struct watchpoint *w = (struct watchpoint *) bs->breakpoint_at;
5546
5547           update_watchpoint (w, 0 /* don't reparse.  */);
5548           need_remove_insert = 1;
5549         }
5550
5551   if (need_remove_insert)
5552     update_global_location_list (UGLL_MAY_INSERT);
5553   else if (removed_any)
5554     update_global_location_list (UGLL_DONT_INSERT);
5555
5556   return bs_head;
5557 }
5558
5559 static void
5560 handle_jit_event (void)
5561 {
5562   struct frame_info *frame;
5563   struct gdbarch *gdbarch;
5564
5565   if (debug_infrun)
5566     fprintf_unfiltered (gdb_stdlog, "handling bp_jit_event\n");
5567
5568   /* Switch terminal for any messages produced by
5569      breakpoint_re_set.  */
5570   target_terminal::ours_for_output ();
5571
5572   frame = get_current_frame ();
5573   gdbarch = get_frame_arch (frame);
5574
5575   jit_event_handler (gdbarch);
5576
5577   target_terminal::inferior ();
5578 }
5579
5580 /* Prepare WHAT final decision for infrun.  */
5581
5582 /* Decide what infrun needs to do with this bpstat.  */
5583
5584 struct bpstat_what
5585 bpstat_what (bpstat bs_head)
5586 {
5587   struct bpstat_what retval;
5588   bpstat bs;
5589
5590   retval.main_action = BPSTAT_WHAT_KEEP_CHECKING;
5591   retval.call_dummy = STOP_NONE;
5592   retval.is_longjmp = 0;
5593
5594   for (bs = bs_head; bs != NULL; bs = bs->next)
5595     {
5596       /* Extract this BS's action.  After processing each BS, we check
5597          if its action overrides all we've seem so far.  */
5598       enum bpstat_what_main_action this_action = BPSTAT_WHAT_KEEP_CHECKING;
5599       enum bptype bptype;
5600
5601       if (bs->breakpoint_at == NULL)
5602         {
5603           /* I suspect this can happen if it was a momentary
5604              breakpoint which has since been deleted.  */
5605           bptype = bp_none;
5606         }
5607       else
5608         bptype = bs->breakpoint_at->type;
5609
5610       switch (bptype)
5611         {
5612         case bp_none:
5613           break;
5614         case bp_breakpoint:
5615         case bp_hardware_breakpoint:
5616         case bp_single_step:
5617         case bp_until:
5618         case bp_finish:
5619         case bp_shlib_event:
5620           if (bs->stop)
5621             {
5622               if (bs->print)
5623                 this_action = BPSTAT_WHAT_STOP_NOISY;
5624               else
5625                 this_action = BPSTAT_WHAT_STOP_SILENT;
5626             }
5627           else
5628             this_action = BPSTAT_WHAT_SINGLE;
5629           break;
5630         case bp_watchpoint:
5631         case bp_hardware_watchpoint:
5632         case bp_read_watchpoint:
5633         case bp_access_watchpoint:
5634           if (bs->stop)
5635             {
5636               if (bs->print)
5637                 this_action = BPSTAT_WHAT_STOP_NOISY;
5638               else
5639                 this_action = BPSTAT_WHAT_STOP_SILENT;
5640             }
5641           else
5642             {
5643               /* There was a watchpoint, but we're not stopping.
5644                  This requires no further action.  */
5645             }
5646           break;
5647         case bp_longjmp:
5648         case bp_longjmp_call_dummy:
5649         case bp_exception:
5650           if (bs->stop)
5651             {
5652               this_action = BPSTAT_WHAT_SET_LONGJMP_RESUME;
5653               retval.is_longjmp = bptype != bp_exception;
5654             }
5655           else
5656             this_action = BPSTAT_WHAT_SINGLE;
5657           break;
5658         case bp_longjmp_resume:
5659         case bp_exception_resume:
5660           if (bs->stop)
5661             {
5662               this_action = BPSTAT_WHAT_CLEAR_LONGJMP_RESUME;
5663               retval.is_longjmp = bptype == bp_longjmp_resume;
5664             }
5665           else
5666             this_action = BPSTAT_WHAT_SINGLE;
5667           break;
5668         case bp_step_resume:
5669           if (bs->stop)
5670             this_action = BPSTAT_WHAT_STEP_RESUME;
5671           else
5672             {
5673               /* It is for the wrong frame.  */
5674               this_action = BPSTAT_WHAT_SINGLE;
5675             }
5676           break;
5677         case bp_hp_step_resume:
5678           if (bs->stop)
5679             this_action = BPSTAT_WHAT_HP_STEP_RESUME;
5680           else
5681             {
5682               /* It is for the wrong frame.  */
5683               this_action = BPSTAT_WHAT_SINGLE;
5684             }
5685           break;
5686         case bp_watchpoint_scope:
5687         case bp_thread_event:
5688         case bp_overlay_event:
5689         case bp_longjmp_master:
5690         case bp_std_terminate_master:
5691         case bp_exception_master:
5692           this_action = BPSTAT_WHAT_SINGLE;
5693           break;
5694         case bp_catchpoint:
5695           if (bs->stop)
5696             {
5697               if (bs->print)
5698                 this_action = BPSTAT_WHAT_STOP_NOISY;
5699               else
5700                 this_action = BPSTAT_WHAT_STOP_SILENT;
5701             }
5702           else
5703             {
5704               /* There was a catchpoint, but we're not stopping.
5705                  This requires no further action.  */
5706             }
5707           break;
5708         case bp_jit_event:
5709           this_action = BPSTAT_WHAT_SINGLE;
5710           break;
5711         case bp_call_dummy:
5712           /* Make sure the action is stop (silent or noisy),
5713              so infrun.c pops the dummy frame.  */
5714           retval.call_dummy = STOP_STACK_DUMMY;
5715           this_action = BPSTAT_WHAT_STOP_SILENT;
5716           break;
5717         case bp_std_terminate:
5718           /* Make sure the action is stop (silent or noisy),
5719              so infrun.c pops the dummy frame.  */
5720           retval.call_dummy = STOP_STD_TERMINATE;
5721           this_action = BPSTAT_WHAT_STOP_SILENT;
5722           break;
5723         case bp_tracepoint:
5724         case bp_fast_tracepoint:
5725         case bp_static_tracepoint:
5726           /* Tracepoint hits should not be reported back to GDB, and
5727              if one got through somehow, it should have been filtered
5728              out already.  */
5729           internal_error (__FILE__, __LINE__,
5730                           _("bpstat_what: tracepoint encountered"));
5731           break;
5732         case bp_gnu_ifunc_resolver:
5733           /* Step over it (and insert bp_gnu_ifunc_resolver_return).  */
5734           this_action = BPSTAT_WHAT_SINGLE;
5735           break;
5736         case bp_gnu_ifunc_resolver_return:
5737           /* The breakpoint will be removed, execution will restart from the
5738              PC of the former breakpoint.  */
5739           this_action = BPSTAT_WHAT_KEEP_CHECKING;
5740           break;
5741
5742         case bp_dprintf:
5743           if (bs->stop)
5744             this_action = BPSTAT_WHAT_STOP_SILENT;
5745           else
5746             this_action = BPSTAT_WHAT_SINGLE;
5747           break;
5748
5749         default:
5750           internal_error (__FILE__, __LINE__,
5751                           _("bpstat_what: unhandled bptype %d"), (int) bptype);
5752         }
5753
5754       retval.main_action = std::max (retval.main_action, this_action);
5755     }
5756
5757   return retval;
5758 }
5759
5760 void
5761 bpstat_run_callbacks (bpstat bs_head)
5762 {
5763   bpstat bs;
5764
5765   for (bs = bs_head; bs != NULL; bs = bs->next)
5766     {
5767       struct breakpoint *b = bs->breakpoint_at;
5768
5769       if (b == NULL)
5770         continue;
5771       switch (b->type)
5772         {
5773         case bp_jit_event:
5774           handle_jit_event ();
5775           break;
5776         case bp_gnu_ifunc_resolver:
5777           gnu_ifunc_resolver_stop (b);
5778           break;
5779         case bp_gnu_ifunc_resolver_return:
5780           gnu_ifunc_resolver_return_stop (b);
5781           break;
5782         }
5783     }
5784 }
5785
5786 /* Nonzero if we should step constantly (e.g. watchpoints on machines
5787    without hardware support).  This isn't related to a specific bpstat,
5788    just to things like whether watchpoints are set.  */
5789
5790 int
5791 bpstat_should_step (void)
5792 {
5793   struct breakpoint *b;
5794
5795   ALL_BREAKPOINTS (b)
5796     if (breakpoint_enabled (b) && b->type == bp_watchpoint && b->loc != NULL)
5797       return 1;
5798   return 0;
5799 }
5800
5801 int
5802 bpstat_causes_stop (bpstat bs)
5803 {
5804   for (; bs != NULL; bs = bs->next)
5805     if (bs->stop)
5806       return 1;
5807
5808   return 0;
5809 }
5810
5811 \f
5812
5813 /* Compute a string of spaces suitable to indent the next line
5814    so it starts at the position corresponding to the table column
5815    named COL_NAME in the currently active table of UIOUT.  */
5816
5817 static char *
5818 wrap_indent_at_field (struct ui_out *uiout, const char *col_name)
5819 {
5820   static char wrap_indent[80];
5821   int i, total_width, width, align;
5822   const char *text;
5823
5824   total_width = 0;
5825   for (i = 1; uiout->query_table_field (i, &width, &align, &text); i++)
5826     {
5827       if (strcmp (text, col_name) == 0)
5828         {
5829           gdb_assert (total_width < sizeof wrap_indent);
5830           memset (wrap_indent, ' ', total_width);
5831           wrap_indent[total_width] = 0;
5832
5833           return wrap_indent;
5834         }
5835
5836       total_width += width + 1;
5837     }
5838
5839   return NULL;
5840 }
5841
5842 /* Determine if the locations of this breakpoint will have their conditions
5843    evaluated by the target, host or a mix of both.  Returns the following:
5844
5845     "host": Host evals condition.
5846     "host or target": Host or Target evals condition.
5847     "target": Target evals condition.
5848 */
5849
5850 static const char *
5851 bp_condition_evaluator (struct breakpoint *b)
5852 {
5853   struct bp_location *bl;
5854   char host_evals = 0;
5855   char target_evals = 0;
5856
5857   if (!b)
5858     return NULL;
5859
5860   if (!is_breakpoint (b))
5861     return NULL;
5862
5863   if (gdb_evaluates_breakpoint_condition_p ()
5864       || !target_supports_evaluation_of_breakpoint_conditions ())
5865     return condition_evaluation_host;
5866
5867   for (bl = b->loc; bl; bl = bl->next)
5868     {
5869       if (bl->cond_bytecode)
5870         target_evals++;
5871       else
5872         host_evals++;
5873     }
5874
5875   if (host_evals && target_evals)
5876     return condition_evaluation_both;
5877   else if (target_evals)
5878     return condition_evaluation_target;
5879   else
5880     return condition_evaluation_host;
5881 }
5882
5883 /* Determine the breakpoint location's condition evaluator.  This is
5884    similar to bp_condition_evaluator, but for locations.  */
5885
5886 static const char *
5887 bp_location_condition_evaluator (struct bp_location *bl)
5888 {
5889   if (bl && !is_breakpoint (bl->owner))
5890     return NULL;
5891
5892   if (gdb_evaluates_breakpoint_condition_p ()
5893       || !target_supports_evaluation_of_breakpoint_conditions ())
5894     return condition_evaluation_host;
5895
5896   if (bl && bl->cond_bytecode)
5897     return condition_evaluation_target;
5898   else
5899     return condition_evaluation_host;
5900 }
5901
5902 /* Print the LOC location out of the list of B->LOC locations.  */
5903
5904 static void
5905 print_breakpoint_location (struct breakpoint *b,
5906                            struct bp_location *loc)
5907 {
5908   struct ui_out *uiout = current_uiout;
5909
5910   scoped_restore_current_program_space restore_pspace;
5911
5912   if (loc != NULL && loc->shlib_disabled)
5913     loc = NULL;
5914
5915   if (loc != NULL)
5916     set_current_program_space (loc->pspace);
5917
5918   if (b->display_canonical)
5919     uiout->field_string ("what", event_location_to_string (b->location.get ()));
5920   else if (loc && loc->symtab)
5921     {
5922       const struct symbol *sym = loc->symbol;
5923
5924       if (sym == NULL)
5925         sym = find_pc_sect_function (loc->address, loc->section);
5926
5927       if (sym)
5928         {
5929           uiout->text ("in ");
5930           uiout->field_string ("func", SYMBOL_PRINT_NAME (sym));
5931           uiout->text (" ");
5932           uiout->wrap_hint (wrap_indent_at_field (uiout, "what"));
5933           uiout->text ("at ");
5934         }
5935       uiout->field_string ("file",
5936                            symtab_to_filename_for_display (loc->symtab));
5937       uiout->text (":");
5938
5939       if (uiout->is_mi_like_p ())
5940         uiout->field_string ("fullname", symtab_to_fullname (loc->symtab));
5941       
5942       uiout->field_int ("line", loc->line_number);
5943     }
5944   else if (loc)
5945     {
5946       string_file stb;
5947
5948       print_address_symbolic (loc->gdbarch, loc->address, &stb,
5949                               demangle, "");
5950       uiout->field_stream ("at", stb);
5951     }
5952   else
5953     {
5954       uiout->field_string ("pending",
5955                            event_location_to_string (b->location.get ()));
5956       /* If extra_string is available, it could be holding a condition
5957          or dprintf arguments.  In either case, make sure it is printed,
5958          too, but only for non-MI streams.  */
5959       if (!uiout->is_mi_like_p () && b->extra_string != NULL)
5960         {
5961           if (b->type == bp_dprintf)
5962             uiout->text (",");
5963           else
5964             uiout->text (" ");
5965           uiout->text (b->extra_string);
5966         }
5967     }
5968
5969   if (loc && is_breakpoint (b)
5970       && breakpoint_condition_evaluation_mode () == condition_evaluation_target
5971       && bp_condition_evaluator (b) == condition_evaluation_both)
5972     {
5973       uiout->text (" (");
5974       uiout->field_string ("evaluated-by",
5975                            bp_location_condition_evaluator (loc));
5976       uiout->text (")");
5977     }
5978 }
5979
5980 static const char *
5981 bptype_string (enum bptype type)
5982 {
5983   struct ep_type_description
5984     {
5985       enum bptype type;
5986       const char *description;
5987     };
5988   static struct ep_type_description bptypes[] =
5989   {
5990     {bp_none, "?deleted?"},
5991     {bp_breakpoint, "breakpoint"},
5992     {bp_hardware_breakpoint, "hw breakpoint"},
5993     {bp_single_step, "sw single-step"},
5994     {bp_until, "until"},
5995     {bp_finish, "finish"},
5996     {bp_watchpoint, "watchpoint"},
5997     {bp_hardware_watchpoint, "hw watchpoint"},
5998     {bp_read_watchpoint, "read watchpoint"},
5999     {bp_access_watchpoint, "acc watchpoint"},
6000     {bp_longjmp, "longjmp"},
6001     {bp_longjmp_resume, "longjmp resume"},
6002     {bp_longjmp_call_dummy, "longjmp for call dummy"},
6003     {bp_exception, "exception"},
6004     {bp_exception_resume, "exception resume"},
6005     {bp_step_resume, "step resume"},
6006     {bp_hp_step_resume, "high-priority step resume"},
6007     {bp_watchpoint_scope, "watchpoint scope"},
6008     {bp_call_dummy, "call dummy"},
6009     {bp_std_terminate, "std::terminate"},
6010     {bp_shlib_event, "shlib events"},
6011     {bp_thread_event, "thread events"},
6012     {bp_overlay_event, "overlay events"},
6013     {bp_longjmp_master, "longjmp master"},
6014     {bp_std_terminate_master, "std::terminate master"},
6015     {bp_exception_master, "exception master"},
6016     {bp_catchpoint, "catchpoint"},
6017     {bp_tracepoint, "tracepoint"},
6018     {bp_fast_tracepoint, "fast tracepoint"},
6019     {bp_static_tracepoint, "static tracepoint"},
6020     {bp_dprintf, "dprintf"},
6021     {bp_jit_event, "jit events"},
6022     {bp_gnu_ifunc_resolver, "STT_GNU_IFUNC resolver"},
6023     {bp_gnu_ifunc_resolver_return, "STT_GNU_IFUNC resolver return"},
6024   };
6025
6026   if (((int) type >= (sizeof (bptypes) / sizeof (bptypes[0])))
6027       || ((int) type != bptypes[(int) type].type))
6028     internal_error (__FILE__, __LINE__,
6029                     _("bptypes table does not describe type #%d."),
6030                     (int) type);
6031
6032   return bptypes[(int) type].description;
6033 }
6034
6035 /* For MI, output a field named 'thread-groups' with a list as the value.
6036    For CLI, prefix the list with the string 'inf'. */
6037
6038 static void
6039 output_thread_groups (struct ui_out *uiout,
6040                       const char *field_name,
6041                       VEC(int) *inf_num,
6042                       int mi_only)
6043 {
6044   int is_mi = uiout->is_mi_like_p ();
6045   int inf;
6046   int i;
6047
6048   /* For backward compatibility, don't display inferiors in CLI unless
6049      there are several.  Always display them for MI. */
6050   if (!is_mi && mi_only)
6051     return;
6052
6053   ui_out_emit_list list_emitter (uiout, field_name);
6054
6055   for (i = 0; VEC_iterate (int, inf_num, i, inf); ++i)
6056     {
6057       if (is_mi)
6058         {
6059           char mi_group[10];
6060
6061           xsnprintf (mi_group, sizeof (mi_group), "i%d", inf);
6062           uiout->field_string (NULL, mi_group);
6063         }
6064       else
6065         {
6066           if (i == 0)
6067             uiout->text (" inf ");
6068           else
6069             uiout->text (", ");
6070         
6071           uiout->text (plongest (inf));
6072         }
6073     }
6074 }
6075
6076 /* Print B to gdb_stdout.  */
6077
6078 static void
6079 print_one_breakpoint_location (struct breakpoint *b,
6080                                struct bp_location *loc,
6081                                int loc_number,
6082                                struct bp_location **last_loc,
6083                                int allflag)
6084 {
6085   struct command_line *l;
6086   static char bpenables[] = "nynny";
6087
6088   struct ui_out *uiout = current_uiout;
6089   int header_of_multiple = 0;
6090   int part_of_multiple = (loc != NULL);
6091   struct value_print_options opts;
6092
6093   get_user_print_options (&opts);
6094
6095   gdb_assert (!loc || loc_number != 0);
6096   /* See comment in print_one_breakpoint concerning treatment of
6097      breakpoints with single disabled location.  */
6098   if (loc == NULL 
6099       && (b->loc != NULL 
6100           && (b->loc->next != NULL || !b->loc->enabled)))
6101     header_of_multiple = 1;
6102   if (loc == NULL)
6103     loc = b->loc;
6104
6105   annotate_record ();
6106
6107   /* 1 */
6108   annotate_field (0);
6109   if (part_of_multiple)
6110     {
6111       char *formatted;
6112       formatted = xstrprintf ("%d.%d", b->number, loc_number);
6113       uiout->field_string ("number", formatted);
6114       xfree (formatted);
6115     }
6116   else
6117     {
6118       uiout->field_int ("number", b->number);
6119     }
6120
6121   /* 2 */
6122   annotate_field (1);
6123   if (part_of_multiple)
6124     uiout->field_skip ("type");
6125   else
6126     uiout->field_string ("type", bptype_string (b->type));
6127
6128   /* 3 */
6129   annotate_field (2);
6130   if (part_of_multiple)
6131     uiout->field_skip ("disp");
6132   else
6133     uiout->field_string ("disp", bpdisp_text (b->disposition));
6134
6135
6136   /* 4 */
6137   annotate_field (3);
6138   if (part_of_multiple)
6139     uiout->field_string ("enabled", loc->enabled ? "y" : "n");
6140   else
6141     uiout->field_fmt ("enabled", "%c", bpenables[(int) b->enable_state]);
6142   uiout->spaces (2);
6143
6144   
6145   /* 5 and 6 */
6146   if (b->ops != NULL && b->ops->print_one != NULL)
6147     {
6148       /* Although the print_one can possibly print all locations,
6149          calling it here is not likely to get any nice result.  So,
6150          make sure there's just one location.  */
6151       gdb_assert (b->loc == NULL || b->loc->next == NULL);
6152       b->ops->print_one (b, last_loc);
6153     }
6154   else
6155     switch (b->type)
6156       {
6157       case bp_none:
6158         internal_error (__FILE__, __LINE__,
6159                         _("print_one_breakpoint: bp_none encountered\n"));
6160         break;
6161
6162       case bp_watchpoint:
6163       case bp_hardware_watchpoint:
6164       case bp_read_watchpoint:
6165       case bp_access_watchpoint:
6166         {
6167           struct watchpoint *w = (struct watchpoint *) b;
6168
6169           /* Field 4, the address, is omitted (which makes the columns
6170              not line up too nicely with the headers, but the effect
6171              is relatively readable).  */
6172           if (opts.addressprint)
6173             uiout->field_skip ("addr");
6174           annotate_field (5);
6175           uiout->field_string ("what", w->exp_string);
6176         }
6177         break;
6178
6179       case bp_breakpoint:
6180       case bp_hardware_breakpoint:
6181       case bp_single_step:
6182       case bp_until:
6183       case bp_finish:
6184       case bp_longjmp:
6185       case bp_longjmp_resume:
6186       case bp_longjmp_call_dummy:
6187       case bp_exception:
6188       case bp_exception_resume:
6189       case bp_step_resume:
6190       case bp_hp_step_resume:
6191       case bp_watchpoint_scope:
6192       case bp_call_dummy:
6193       case bp_std_terminate:
6194       case bp_shlib_event:
6195       case bp_thread_event:
6196       case bp_overlay_event:
6197       case bp_longjmp_master:
6198       case bp_std_terminate_master:
6199       case bp_exception_master:
6200       case bp_tracepoint:
6201       case bp_fast_tracepoint:
6202       case bp_static_tracepoint:
6203       case bp_dprintf:
6204       case bp_jit_event:
6205       case bp_gnu_ifunc_resolver:
6206       case bp_gnu_ifunc_resolver_return:
6207         if (opts.addressprint)
6208           {
6209             annotate_field (4);
6210             if (header_of_multiple)
6211               uiout->field_string ("addr", "<MULTIPLE>");
6212             else if (b->loc == NULL || loc->shlib_disabled)
6213               uiout->field_string ("addr", "<PENDING>");
6214             else
6215               uiout->field_core_addr ("addr",
6216                                       loc->gdbarch, loc->address);
6217           }
6218         annotate_field (5);
6219         if (!header_of_multiple)
6220           print_breakpoint_location (b, loc);
6221         if (b->loc)
6222           *last_loc = b->loc;
6223         break;
6224       }
6225
6226
6227   if (loc != NULL && !header_of_multiple)
6228     {
6229       struct inferior *inf;
6230       VEC(int) *inf_num = NULL;
6231       int mi_only = 1;
6232
6233       ALL_INFERIORS (inf)
6234         {
6235           if (inf->pspace == loc->pspace)
6236             VEC_safe_push (int, inf_num, inf->num);
6237         }
6238
6239         /* For backward compatibility, don't display inferiors in CLI unless
6240            there are several.  Always display for MI. */
6241         if (allflag
6242             || (!gdbarch_has_global_breakpoints (target_gdbarch ())
6243                 && (number_of_program_spaces () > 1
6244                     || number_of_inferiors () > 1)
6245                 /* LOC is for existing B, it cannot be in
6246                    moribund_locations and thus having NULL OWNER.  */
6247                 && loc->owner->type != bp_catchpoint))
6248         mi_only = 0;
6249       output_thread_groups (uiout, "thread-groups", inf_num, mi_only);
6250       VEC_free (int, inf_num);
6251     }
6252
6253   if (!part_of_multiple)
6254     {
6255       if (b->thread != -1)
6256         {
6257           /* FIXME: This seems to be redundant and lost here; see the
6258              "stop only in" line a little further down.  */
6259           uiout->text (" thread ");
6260           uiout->field_int ("thread", b->thread);
6261         }
6262       else if (b->task != 0)
6263         {
6264           uiout->text (" task ");
6265           uiout->field_int ("task", b->task);
6266         }
6267     }
6268
6269   uiout->text ("\n");
6270
6271   if (!part_of_multiple)
6272     b->ops->print_one_detail (b, uiout);
6273
6274   if (part_of_multiple && frame_id_p (b->frame_id))
6275     {
6276       annotate_field (6);
6277       uiout->text ("\tstop only in stack frame at ");
6278       /* FIXME: cagney/2002-12-01: Shouldn't be poking around inside
6279          the frame ID.  */
6280       uiout->field_core_addr ("frame",
6281                               b->gdbarch, b->frame_id.stack_addr);
6282       uiout->text ("\n");
6283     }
6284   
6285   if (!part_of_multiple && b->cond_string)
6286     {
6287       annotate_field (7);
6288       if (is_tracepoint (b))
6289         uiout->text ("\ttrace only if ");
6290       else
6291         uiout->text ("\tstop only if ");
6292       uiout->field_string ("cond", b->cond_string);
6293
6294       /* Print whether the target is doing the breakpoint's condition
6295          evaluation.  If GDB is doing the evaluation, don't print anything.  */
6296       if (is_breakpoint (b)
6297           && breakpoint_condition_evaluation_mode ()
6298           == condition_evaluation_target)
6299         {
6300           uiout->text (" (");
6301           uiout->field_string ("evaluated-by",
6302                                bp_condition_evaluator (b));
6303           uiout->text (" evals)");
6304         }
6305       uiout->text ("\n");
6306     }
6307
6308   if (!part_of_multiple && b->thread != -1)
6309     {
6310       /* FIXME should make an annotation for this.  */
6311       uiout->text ("\tstop only in thread ");
6312       if (uiout->is_mi_like_p ())
6313         uiout->field_int ("thread", b->thread);
6314       else
6315         {
6316           struct thread_info *thr = find_thread_global_id (b->thread);
6317
6318           uiout->field_string ("thread", print_thread_id (thr));
6319         }
6320       uiout->text ("\n");
6321     }
6322   
6323   if (!part_of_multiple)
6324     {
6325       if (b->hit_count)
6326         {
6327           /* FIXME should make an annotation for this.  */
6328           if (is_catchpoint (b))
6329             uiout->text ("\tcatchpoint");
6330           else if (is_tracepoint (b))
6331             uiout->text ("\ttracepoint");
6332           else
6333             uiout->text ("\tbreakpoint");
6334           uiout->text (" already hit ");
6335           uiout->field_int ("times", b->hit_count);
6336           if (b->hit_count == 1)
6337             uiout->text (" time\n");
6338           else
6339             uiout->text (" times\n");
6340         }
6341       else
6342         {
6343           /* Output the count also if it is zero, but only if this is mi.  */
6344           if (uiout->is_mi_like_p ())
6345             uiout->field_int ("times", b->hit_count);
6346         }
6347     }
6348
6349   if (!part_of_multiple && b->ignore_count)
6350     {
6351       annotate_field (8);
6352       uiout->text ("\tignore next ");
6353       uiout->field_int ("ignore", b->ignore_count);
6354       uiout->text (" hits\n");
6355     }
6356
6357   /* Note that an enable count of 1 corresponds to "enable once"
6358      behavior, which is reported by the combination of enablement and
6359      disposition, so we don't need to mention it here.  */
6360   if (!part_of_multiple && b->enable_count > 1)
6361     {
6362       annotate_field (8);
6363       uiout->text ("\tdisable after ");
6364       /* Tweak the wording to clarify that ignore and enable counts
6365          are distinct, and have additive effect.  */
6366       if (b->ignore_count)
6367         uiout->text ("additional ");
6368       else
6369         uiout->text ("next ");
6370       uiout->field_int ("enable", b->enable_count);
6371       uiout->text (" hits\n");
6372     }
6373
6374   if (!part_of_multiple && is_tracepoint (b))
6375     {
6376       struct tracepoint *tp = (struct tracepoint *) b;
6377
6378       if (tp->traceframe_usage)
6379         {
6380           uiout->text ("\ttrace buffer usage ");
6381           uiout->field_int ("traceframe-usage", tp->traceframe_usage);
6382           uiout->text (" bytes\n");
6383         }
6384     }
6385
6386   l = b->commands ? b->commands.get () : NULL;
6387   if (!part_of_multiple && l)
6388     {
6389       annotate_field (9);
6390       ui_out_emit_tuple tuple_emitter (uiout, "script");
6391       print_command_lines (uiout, l, 4);
6392     }
6393
6394   if (is_tracepoint (b))
6395     {
6396       struct tracepoint *t = (struct tracepoint *) b;
6397
6398       if (!part_of_multiple && t->pass_count)
6399         {
6400           annotate_field (10);
6401           uiout->text ("\tpass count ");
6402           uiout->field_int ("pass", t->pass_count);
6403           uiout->text (" \n");
6404         }
6405
6406       /* Don't display it when tracepoint or tracepoint location is
6407          pending.   */
6408       if (!header_of_multiple && loc != NULL && !loc->shlib_disabled)
6409         {
6410           annotate_field (11);
6411
6412           if (uiout->is_mi_like_p ())
6413             uiout->field_string ("installed",
6414                                  loc->inserted ? "y" : "n");
6415           else
6416             {
6417               if (loc->inserted)
6418                 uiout->text ("\t");
6419               else
6420                 uiout->text ("\tnot ");
6421               uiout->text ("installed on target\n");
6422             }
6423         }
6424     }
6425
6426   if (uiout->is_mi_like_p () && !part_of_multiple)
6427     {
6428       if (is_watchpoint (b))
6429         {
6430           struct watchpoint *w = (struct watchpoint *) b;
6431
6432           uiout->field_string ("original-location", w->exp_string);
6433         }
6434       else if (b->location != NULL
6435                && event_location_to_string (b->location.get ()) != NULL)
6436         uiout->field_string ("original-location",
6437                              event_location_to_string (b->location.get ()));
6438     }
6439 }
6440
6441 static void
6442 print_one_breakpoint (struct breakpoint *b,
6443                       struct bp_location **last_loc, 
6444                       int allflag)
6445 {
6446   struct ui_out *uiout = current_uiout;
6447
6448   {
6449     ui_out_emit_tuple tuple_emitter (uiout, "bkpt");
6450
6451     print_one_breakpoint_location (b, NULL, 0, last_loc, allflag);
6452   }
6453
6454   /* If this breakpoint has custom print function,
6455      it's already printed.  Otherwise, print individual
6456      locations, if any.  */
6457   if (b->ops == NULL || b->ops->print_one == NULL)
6458     {
6459       /* If breakpoint has a single location that is disabled, we
6460          print it as if it had several locations, since otherwise it's
6461          hard to represent "breakpoint enabled, location disabled"
6462          situation.
6463
6464          Note that while hardware watchpoints have several locations
6465          internally, that's not a property exposed to user.  */
6466       if (b->loc 
6467           && !is_hardware_watchpoint (b)
6468           && (b->loc->next || !b->loc->enabled))
6469         {
6470           struct bp_location *loc;
6471           int n = 1;
6472
6473           for (loc = b->loc; loc; loc = loc->next, ++n)
6474             {
6475               ui_out_emit_tuple tuple_emitter (uiout, NULL);
6476               print_one_breakpoint_location (b, loc, n, last_loc, allflag);
6477             }
6478         }
6479     }
6480 }
6481
6482 static int
6483 breakpoint_address_bits (struct breakpoint *b)
6484 {
6485   int print_address_bits = 0;
6486   struct bp_location *loc;
6487
6488   /* Software watchpoints that aren't watching memory don't have an
6489      address to print.  */
6490   if (is_no_memory_software_watchpoint (b))
6491     return 0;
6492
6493   for (loc = b->loc; loc; loc = loc->next)
6494     {
6495       int addr_bit;
6496
6497       addr_bit = gdbarch_addr_bit (loc->gdbarch);
6498       if (addr_bit > print_address_bits)
6499         print_address_bits = addr_bit;
6500     }
6501
6502   return print_address_bits;
6503 }
6504
6505 /* See breakpoint.h.  */
6506
6507 void
6508 print_breakpoint (breakpoint *b)
6509 {
6510   struct bp_location *dummy_loc = NULL;
6511   print_one_breakpoint (b, &dummy_loc, 0);
6512 }
6513
6514 /* Return true if this breakpoint was set by the user, false if it is
6515    internal or momentary.  */
6516
6517 int
6518 user_breakpoint_p (struct breakpoint *b)
6519 {
6520   return b->number > 0;
6521 }
6522
6523 /* See breakpoint.h.  */
6524
6525 int
6526 pending_breakpoint_p (struct breakpoint *b)
6527 {
6528   return b->loc == NULL;
6529 }
6530
6531 /* Print information on user settable breakpoint (watchpoint, etc)
6532    number BNUM.  If BNUM is -1 print all user-settable breakpoints.
6533    If ALLFLAG is non-zero, include non-user-settable breakpoints.  If
6534    FILTER is non-NULL, call it on each breakpoint and only include the
6535    ones for which it returns non-zero.  Return the total number of
6536    breakpoints listed.  */
6537
6538 static int
6539 breakpoint_1 (const char *args, int allflag, 
6540               int (*filter) (const struct breakpoint *))
6541 {
6542   struct breakpoint *b;
6543   struct bp_location *last_loc = NULL;
6544   int nr_printable_breakpoints;
6545   struct value_print_options opts;
6546   int print_address_bits = 0;
6547   int print_type_col_width = 14;
6548   struct ui_out *uiout = current_uiout;
6549
6550   get_user_print_options (&opts);
6551
6552   /* Compute the number of rows in the table, as well as the size
6553      required for address fields.  */
6554   nr_printable_breakpoints = 0;
6555   ALL_BREAKPOINTS (b)
6556     {
6557       /* If we have a filter, only list the breakpoints it accepts.  */
6558       if (filter && !filter (b))
6559         continue;
6560
6561       /* If we have an "args" string, it is a list of breakpoints to 
6562          accept.  Skip the others.  */
6563       if (args != NULL && *args != '\0')
6564         {
6565           if (allflag && parse_and_eval_long (args) != b->number)
6566             continue;
6567           if (!allflag && !number_is_in_list (args, b->number))
6568             continue;
6569         }
6570
6571       if (allflag || user_breakpoint_p (b))
6572         {
6573           int addr_bit, type_len;
6574
6575           addr_bit = breakpoint_address_bits (b);
6576           if (addr_bit > print_address_bits)
6577             print_address_bits = addr_bit;
6578
6579           type_len = strlen (bptype_string (b->type));
6580           if (type_len > print_type_col_width)
6581             print_type_col_width = type_len;
6582
6583           nr_printable_breakpoints++;
6584         }
6585     }
6586
6587   {
6588     ui_out_emit_table table_emitter (uiout,
6589                                      opts.addressprint ? 6 : 5,
6590                                      nr_printable_breakpoints,
6591                                      "BreakpointTable");
6592
6593     if (nr_printable_breakpoints > 0)
6594       annotate_breakpoints_headers ();
6595     if (nr_printable_breakpoints > 0)
6596       annotate_field (0);
6597     uiout->table_header (7, ui_left, "number", "Num"); /* 1 */
6598     if (nr_printable_breakpoints > 0)
6599       annotate_field (1);
6600     uiout->table_header (print_type_col_width, ui_left, "type", "Type"); /* 2 */
6601     if (nr_printable_breakpoints > 0)
6602       annotate_field (2);
6603     uiout->table_header (4, ui_left, "disp", "Disp"); /* 3 */
6604     if (nr_printable_breakpoints > 0)
6605       annotate_field (3);
6606     uiout->table_header (3, ui_left, "enabled", "Enb"); /* 4 */
6607     if (opts.addressprint)
6608       {
6609         if (nr_printable_breakpoints > 0)
6610           annotate_field (4);
6611         if (print_address_bits <= 32)
6612           uiout->table_header (10, ui_left, "addr", "Address"); /* 5 */
6613         else
6614           uiout->table_header (18, ui_left, "addr", "Address"); /* 5 */
6615       }
6616     if (nr_printable_breakpoints > 0)
6617       annotate_field (5);
6618     uiout->table_header (40, ui_noalign, "what", "What"); /* 6 */
6619     uiout->table_body ();
6620     if (nr_printable_breakpoints > 0)
6621       annotate_breakpoints_table ();
6622
6623     ALL_BREAKPOINTS (b)
6624       {
6625         QUIT;
6626         /* If we have a filter, only list the breakpoints it accepts.  */
6627         if (filter && !filter (b))
6628           continue;
6629
6630         /* If we have an "args" string, it is a list of breakpoints to 
6631            accept.  Skip the others.  */
6632
6633         if (args != NULL && *args != '\0')
6634           {
6635             if (allflag)        /* maintenance info breakpoint */
6636               {
6637                 if (parse_and_eval_long (args) != b->number)
6638                   continue;
6639               }
6640             else                /* all others */
6641               {
6642                 if (!number_is_in_list (args, b->number))
6643                   continue;
6644               }
6645           }
6646         /* We only print out user settable breakpoints unless the
6647            allflag is set.  */
6648         if (allflag || user_breakpoint_p (b))
6649           print_one_breakpoint (b, &last_loc, allflag);
6650       }
6651   }
6652
6653   if (nr_printable_breakpoints == 0)
6654     {
6655       /* If there's a filter, let the caller decide how to report
6656          empty list.  */
6657       if (!filter)
6658         {
6659           if (args == NULL || *args == '\0')
6660             uiout->message ("No breakpoints or watchpoints.\n");
6661           else
6662             uiout->message ("No breakpoint or watchpoint matching '%s'.\n",
6663                             args);
6664         }
6665     }
6666   else
6667     {
6668       if (last_loc && !server_command)
6669         set_next_address (last_loc->gdbarch, last_loc->address);
6670     }
6671
6672   /* FIXME?  Should this be moved up so that it is only called when
6673      there have been breakpoints? */
6674   annotate_breakpoints_table_end ();
6675
6676   return nr_printable_breakpoints;
6677 }
6678
6679 /* Display the value of default-collect in a way that is generally
6680    compatible with the breakpoint list.  */
6681
6682 static void
6683 default_collect_info (void)
6684 {
6685   struct ui_out *uiout = current_uiout;
6686
6687   /* If it has no value (which is frequently the case), say nothing; a
6688      message like "No default-collect." gets in user's face when it's
6689      not wanted.  */
6690   if (!*default_collect)
6691     return;
6692
6693   /* The following phrase lines up nicely with per-tracepoint collect
6694      actions.  */
6695   uiout->text ("default collect ");
6696   uiout->field_string ("default-collect", default_collect);
6697   uiout->text (" \n");
6698 }
6699   
6700 static void
6701 info_breakpoints_command (const char *args, int from_tty)
6702 {
6703   breakpoint_1 (args, 0, NULL);
6704
6705   default_collect_info ();
6706 }
6707
6708 /* Temporary non-const overload.  */
6709
6710 static void
6711 info_breakpoints_command (char *args, int from_tty)
6712 {
6713   info_breakpoints_command ((const char *) args, from_tty);
6714 }
6715
6716 static void
6717 info_watchpoints_command (char *args, int from_tty)
6718 {
6719   int num_printed = breakpoint_1 (args, 0, is_watchpoint);
6720   struct ui_out *uiout = current_uiout;
6721
6722   if (num_printed == 0)
6723     {
6724       if (args == NULL || *args == '\0')
6725         uiout->message ("No watchpoints.\n");
6726       else
6727         uiout->message ("No watchpoint matching '%s'.\n", args);
6728     }
6729 }
6730
6731 static void
6732 maintenance_info_breakpoints (const char *args, int from_tty)
6733 {
6734   breakpoint_1 (args, 1, NULL);
6735
6736   default_collect_info ();
6737 }
6738
6739 static int
6740 breakpoint_has_pc (struct breakpoint *b,
6741                    struct program_space *pspace,
6742                    CORE_ADDR pc, struct obj_section *section)
6743 {
6744   struct bp_location *bl = b->loc;
6745
6746   for (; bl; bl = bl->next)
6747     {
6748       if (bl->pspace == pspace
6749           && bl->address == pc
6750           && (!overlay_debugging || bl->section == section))
6751         return 1;         
6752     }
6753   return 0;
6754 }
6755
6756 /* Print a message describing any user-breakpoints set at PC.  This
6757    concerns with logical breakpoints, so we match program spaces, not
6758    address spaces.  */
6759
6760 static void
6761 describe_other_breakpoints (struct gdbarch *gdbarch,
6762                             struct program_space *pspace, CORE_ADDR pc,
6763                             struct obj_section *section, int thread)
6764 {
6765   int others = 0;
6766   struct breakpoint *b;
6767
6768   ALL_BREAKPOINTS (b)
6769     others += (user_breakpoint_p (b)
6770                && breakpoint_has_pc (b, pspace, pc, section));
6771   if (others > 0)
6772     {
6773       if (others == 1)
6774         printf_filtered (_("Note: breakpoint "));
6775       else /* if (others == ???) */
6776         printf_filtered (_("Note: breakpoints "));
6777       ALL_BREAKPOINTS (b)
6778         if (user_breakpoint_p (b) && breakpoint_has_pc (b, pspace, pc, section))
6779           {
6780             others--;
6781             printf_filtered ("%d", b->number);
6782             if (b->thread == -1 && thread != -1)
6783               printf_filtered (" (all threads)");
6784             else if (b->thread != -1)
6785               printf_filtered (" (thread %d)", b->thread);
6786             printf_filtered ("%s%s ",
6787                              ((b->enable_state == bp_disabled
6788                                || b->enable_state == bp_call_disabled)
6789                               ? " (disabled)"
6790                               : ""),
6791                              (others > 1) ? "," 
6792                              : ((others == 1) ? " and" : ""));
6793           }
6794       printf_filtered (_("also set at pc "));
6795       fputs_filtered (paddress (gdbarch, pc), gdb_stdout);
6796       printf_filtered (".\n");
6797     }
6798 }
6799 \f
6800
6801 /* Return true iff it is meaningful to use the address member of
6802    BPT locations.  For some breakpoint types, the locations' address members
6803    are irrelevant and it makes no sense to attempt to compare them to other
6804    addresses (or use them for any other purpose either).
6805
6806    More specifically, each of the following breakpoint types will
6807    always have a zero valued location address and we don't want to mark
6808    breakpoints of any of these types to be a duplicate of an actual
6809    breakpoint location at address zero:
6810
6811       bp_watchpoint
6812       bp_catchpoint
6813
6814 */
6815
6816 static int
6817 breakpoint_address_is_meaningful (struct breakpoint *bpt)
6818 {
6819   enum bptype type = bpt->type;
6820
6821   return (type != bp_watchpoint && type != bp_catchpoint);
6822 }
6823
6824 /* Assuming LOC1 and LOC2's owners are hardware watchpoints, returns
6825    true if LOC1 and LOC2 represent the same watchpoint location.  */
6826
6827 static int
6828 watchpoint_locations_match (struct bp_location *loc1, 
6829                             struct bp_location *loc2)
6830 {
6831   struct watchpoint *w1 = (struct watchpoint *) loc1->owner;
6832   struct watchpoint *w2 = (struct watchpoint *) loc2->owner;
6833
6834   /* Both of them must exist.  */
6835   gdb_assert (w1 != NULL);
6836   gdb_assert (w2 != NULL);
6837
6838   /* If the target can evaluate the condition expression in hardware,
6839      then we we need to insert both watchpoints even if they are at
6840      the same place.  Otherwise the watchpoint will only trigger when
6841      the condition of whichever watchpoint was inserted evaluates to
6842      true, not giving a chance for GDB to check the condition of the
6843      other watchpoint.  */
6844   if ((w1->cond_exp
6845        && target_can_accel_watchpoint_condition (loc1->address, 
6846                                                  loc1->length,
6847                                                  loc1->watchpoint_type,
6848                                                  w1->cond_exp.get ()))
6849       || (w2->cond_exp
6850           && target_can_accel_watchpoint_condition (loc2->address, 
6851                                                     loc2->length,
6852                                                     loc2->watchpoint_type,
6853                                                     w2->cond_exp.get ())))
6854     return 0;
6855
6856   /* Note that this checks the owner's type, not the location's.  In
6857      case the target does not support read watchpoints, but does
6858      support access watchpoints, we'll have bp_read_watchpoint
6859      watchpoints with hw_access locations.  Those should be considered
6860      duplicates of hw_read locations.  The hw_read locations will
6861      become hw_access locations later.  */
6862   return (loc1->owner->type == loc2->owner->type
6863           && loc1->pspace->aspace == loc2->pspace->aspace
6864           && loc1->address == loc2->address
6865           && loc1->length == loc2->length);
6866 }
6867
6868 /* See breakpoint.h.  */
6869
6870 int
6871 breakpoint_address_match (const address_space *aspace1, CORE_ADDR addr1,
6872                           const address_space *aspace2, CORE_ADDR addr2)
6873 {
6874   return ((gdbarch_has_global_breakpoints (target_gdbarch ())
6875            || aspace1 == aspace2)
6876           && addr1 == addr2);
6877 }
6878
6879 /* Returns true if {ASPACE2,ADDR2} falls within the range determined by
6880    {ASPACE1,ADDR1,LEN1}.  In most targets, this can only be true if ASPACE1
6881    matches ASPACE2.  On targets that have global breakpoints, the address
6882    space doesn't really matter.  */
6883
6884 static int
6885 breakpoint_address_match_range (const address_space *aspace1,
6886                                 CORE_ADDR addr1,
6887                                 int len1, const address_space *aspace2,
6888                                 CORE_ADDR addr2)
6889 {
6890   return ((gdbarch_has_global_breakpoints (target_gdbarch ())
6891            || aspace1 == aspace2)
6892           && addr2 >= addr1 && addr2 < addr1 + len1);
6893 }
6894
6895 /* Returns true if {ASPACE,ADDR} matches the breakpoint BL.  BL may be
6896    a ranged breakpoint.  In most targets, a match happens only if ASPACE
6897    matches the breakpoint's address space.  On targets that have global
6898    breakpoints, the address space doesn't really matter.  */
6899
6900 static int
6901 breakpoint_location_address_match (struct bp_location *bl,
6902                                    const address_space *aspace,
6903                                    CORE_ADDR addr)
6904 {
6905   return (breakpoint_address_match (bl->pspace->aspace, bl->address,
6906                                     aspace, addr)
6907           || (bl->length
6908               && breakpoint_address_match_range (bl->pspace->aspace,
6909                                                  bl->address, bl->length,
6910                                                  aspace, addr)));
6911 }
6912
6913 /* Returns true if the [ADDR,ADDR+LEN) range in ASPACE overlaps
6914    breakpoint BL.  BL may be a ranged breakpoint.  In most targets, a
6915    match happens only if ASPACE matches the breakpoint's address
6916    space.  On targets that have global breakpoints, the address space
6917    doesn't really matter.  */
6918
6919 static int
6920 breakpoint_location_address_range_overlap (struct bp_location *bl,
6921                                            const address_space *aspace,
6922                                            CORE_ADDR addr, int len)
6923 {
6924   if (gdbarch_has_global_breakpoints (target_gdbarch ())
6925       || bl->pspace->aspace == aspace)
6926     {
6927       int bl_len = bl->length != 0 ? bl->length : 1;
6928
6929       if (mem_ranges_overlap (addr, len, bl->address, bl_len))
6930         return 1;
6931     }
6932   return 0;
6933 }
6934
6935 /* If LOC1 and LOC2's owners are not tracepoints, returns false directly.
6936    Then, if LOC1 and LOC2 represent the same tracepoint location, returns
6937    true, otherwise returns false.  */
6938
6939 static int
6940 tracepoint_locations_match (struct bp_location *loc1,
6941                             struct bp_location *loc2)
6942 {
6943   if (is_tracepoint (loc1->owner) && is_tracepoint (loc2->owner))
6944     /* Since tracepoint locations are never duplicated with others', tracepoint
6945        locations at the same address of different tracepoints are regarded as
6946        different locations.  */
6947     return (loc1->address == loc2->address && loc1->owner == loc2->owner);
6948   else
6949     return 0;
6950 }
6951
6952 /* Assuming LOC1 and LOC2's types' have meaningful target addresses
6953    (breakpoint_address_is_meaningful), returns true if LOC1 and LOC2
6954    represent the same location.  */
6955
6956 static int
6957 breakpoint_locations_match (struct bp_location *loc1, 
6958                             struct bp_location *loc2)
6959 {
6960   int hw_point1, hw_point2;
6961
6962   /* Both of them must not be in moribund_locations.  */
6963   gdb_assert (loc1->owner != NULL);
6964   gdb_assert (loc2->owner != NULL);
6965
6966   hw_point1 = is_hardware_watchpoint (loc1->owner);
6967   hw_point2 = is_hardware_watchpoint (loc2->owner);
6968
6969   if (hw_point1 != hw_point2)
6970     return 0;
6971   else if (hw_point1)
6972     return watchpoint_locations_match (loc1, loc2);
6973   else if (is_tracepoint (loc1->owner) || is_tracepoint (loc2->owner))
6974     return tracepoint_locations_match (loc1, loc2);
6975   else
6976     /* We compare bp_location.length in order to cover ranged breakpoints.  */
6977     return (breakpoint_address_match (loc1->pspace->aspace, loc1->address,
6978                                      loc2->pspace->aspace, loc2->address)
6979             && loc1->length == loc2->length);
6980 }
6981
6982 static void
6983 breakpoint_adjustment_warning (CORE_ADDR from_addr, CORE_ADDR to_addr,
6984                                int bnum, int have_bnum)
6985 {
6986   /* The longest string possibly returned by hex_string_custom
6987      is 50 chars.  These must be at least that big for safety.  */
6988   char astr1[64];
6989   char astr2[64];
6990
6991   strcpy (astr1, hex_string_custom ((unsigned long) from_addr, 8));
6992   strcpy (astr2, hex_string_custom ((unsigned long) to_addr, 8));
6993   if (have_bnum)
6994     warning (_("Breakpoint %d address previously adjusted from %s to %s."),
6995              bnum, astr1, astr2);
6996   else
6997     warning (_("Breakpoint address adjusted from %s to %s."), astr1, astr2);
6998 }
6999
7000 /* Adjust a breakpoint's address to account for architectural
7001    constraints on breakpoint placement.  Return the adjusted address.
7002    Note: Very few targets require this kind of adjustment.  For most
7003    targets, this function is simply the identity function.  */
7004
7005 static CORE_ADDR
7006 adjust_breakpoint_address (struct gdbarch *gdbarch,
7007                            CORE_ADDR bpaddr, enum bptype bptype)
7008 {
7009   if (!gdbarch_adjust_breakpoint_address_p (gdbarch))
7010     {
7011       /* Very few targets need any kind of breakpoint adjustment.  */
7012       return bpaddr;
7013     }
7014   else if (bptype == bp_watchpoint
7015            || bptype == bp_hardware_watchpoint
7016            || bptype == bp_read_watchpoint
7017            || bptype == bp_access_watchpoint
7018            || bptype == bp_catchpoint)
7019     {
7020       /* Watchpoints and the various bp_catch_* eventpoints should not
7021          have their addresses modified.  */
7022       return bpaddr;
7023     }
7024   else if (bptype == bp_single_step)
7025     {
7026       /* Single-step breakpoints should not have their addresses
7027          modified.  If there's any architectural constrain that
7028          applies to this address, then it should have already been
7029          taken into account when the breakpoint was created in the
7030          first place.  If we didn't do this, stepping through e.g.,
7031          Thumb-2 IT blocks would break.  */
7032       return bpaddr;
7033     }
7034   else
7035     {
7036       CORE_ADDR adjusted_bpaddr;
7037
7038       /* Some targets have architectural constraints on the placement
7039          of breakpoint instructions.  Obtain the adjusted address.  */
7040       adjusted_bpaddr = gdbarch_adjust_breakpoint_address (gdbarch, bpaddr);
7041
7042       /* An adjusted breakpoint address can significantly alter
7043          a user's expectations.  Print a warning if an adjustment
7044          is required.  */
7045       if (adjusted_bpaddr != bpaddr)
7046         breakpoint_adjustment_warning (bpaddr, adjusted_bpaddr, 0, 0);
7047
7048       return adjusted_bpaddr;
7049     }
7050 }
7051
7052 bp_location::bp_location (const bp_location_ops *ops, breakpoint *owner)
7053 {
7054   bp_location *loc = this;
7055
7056   gdb_assert (ops != NULL);
7057
7058   loc->ops = ops;
7059   loc->owner = owner;
7060   loc->cond_bytecode = NULL;
7061   loc->shlib_disabled = 0;
7062   loc->enabled = 1;
7063
7064   switch (owner->type)
7065     {
7066     case bp_breakpoint:
7067     case bp_single_step:
7068     case bp_until:
7069     case bp_finish:
7070     case bp_longjmp:
7071     case bp_longjmp_resume:
7072     case bp_longjmp_call_dummy:
7073     case bp_exception:
7074     case bp_exception_resume:
7075     case bp_step_resume:
7076     case bp_hp_step_resume:
7077     case bp_watchpoint_scope:
7078     case bp_call_dummy:
7079     case bp_std_terminate:
7080     case bp_shlib_event:
7081     case bp_thread_event:
7082     case bp_overlay_event:
7083     case bp_jit_event:
7084     case bp_longjmp_master:
7085     case bp_std_terminate_master:
7086     case bp_exception_master:
7087     case bp_gnu_ifunc_resolver:
7088     case bp_gnu_ifunc_resolver_return:
7089     case bp_dprintf:
7090       loc->loc_type = bp_loc_software_breakpoint;
7091       mark_breakpoint_location_modified (loc);
7092       break;
7093     case bp_hardware_breakpoint:
7094       loc->loc_type = bp_loc_hardware_breakpoint;
7095       mark_breakpoint_location_modified (loc);
7096       break;
7097     case bp_hardware_watchpoint:
7098     case bp_read_watchpoint:
7099     case bp_access_watchpoint:
7100       loc->loc_type = bp_loc_hardware_watchpoint;
7101       break;
7102     case bp_watchpoint:
7103     case bp_catchpoint:
7104     case bp_tracepoint:
7105     case bp_fast_tracepoint:
7106     case bp_static_tracepoint:
7107       loc->loc_type = bp_loc_other;
7108       break;
7109     default:
7110       internal_error (__FILE__, __LINE__, _("unknown breakpoint type"));
7111     }
7112
7113   loc->refc = 1;
7114 }
7115
7116 /* Allocate a struct bp_location.  */
7117
7118 static struct bp_location *
7119 allocate_bp_location (struct breakpoint *bpt)
7120 {
7121   return bpt->ops->allocate_location (bpt);
7122 }
7123
7124 static void
7125 free_bp_location (struct bp_location *loc)
7126 {
7127   loc->ops->dtor (loc);
7128   delete loc;
7129 }
7130
7131 /* Increment reference count.  */
7132
7133 static void
7134 incref_bp_location (struct bp_location *bl)
7135 {
7136   ++bl->refc;
7137 }
7138
7139 /* Decrement reference count.  If the reference count reaches 0,
7140    destroy the bp_location.  Sets *BLP to NULL.  */
7141
7142 static void
7143 decref_bp_location (struct bp_location **blp)
7144 {
7145   gdb_assert ((*blp)->refc > 0);
7146
7147   if (--(*blp)->refc == 0)
7148     free_bp_location (*blp);
7149   *blp = NULL;
7150 }
7151
7152 /* Add breakpoint B at the end of the global breakpoint chain.  */
7153
7154 static breakpoint *
7155 add_to_breakpoint_chain (std::unique_ptr<breakpoint> &&b)
7156 {
7157   struct breakpoint *b1;
7158   struct breakpoint *result = b.get ();
7159
7160   /* Add this breakpoint to the end of the chain so that a list of
7161      breakpoints will come out in order of increasing numbers.  */
7162
7163   b1 = breakpoint_chain;
7164   if (b1 == 0)
7165     breakpoint_chain = b.release ();
7166   else
7167     {
7168       while (b1->next)
7169         b1 = b1->next;
7170       b1->next = b.release ();
7171     }
7172
7173   return result;
7174 }
7175
7176 /* Initializes breakpoint B with type BPTYPE and no locations yet.  */
7177
7178 static void
7179 init_raw_breakpoint_without_location (struct breakpoint *b,
7180                                       struct gdbarch *gdbarch,
7181                                       enum bptype bptype,
7182                                       const struct breakpoint_ops *ops)
7183 {
7184   gdb_assert (ops != NULL);
7185
7186   b->ops = ops;
7187   b->type = bptype;
7188   b->gdbarch = gdbarch;
7189   b->language = current_language->la_language;
7190   b->input_radix = input_radix;
7191   b->related_breakpoint = b;
7192 }
7193
7194 /* Helper to set_raw_breakpoint below.  Creates a breakpoint
7195    that has type BPTYPE and has no locations as yet.  */
7196
7197 static struct breakpoint *
7198 set_raw_breakpoint_without_location (struct gdbarch *gdbarch,
7199                                      enum bptype bptype,
7200                                      const struct breakpoint_ops *ops)
7201 {
7202   std::unique_ptr<breakpoint> b = new_breakpoint_from_type (bptype);
7203
7204   init_raw_breakpoint_without_location (b.get (), gdbarch, bptype, ops);
7205   return add_to_breakpoint_chain (std::move (b));
7206 }
7207
7208 /* Initialize loc->function_name.  EXPLICIT_LOC says no indirect function
7209    resolutions should be made as the user specified the location explicitly
7210    enough.  */
7211
7212 static void
7213 set_breakpoint_location_function (struct bp_location *loc, int explicit_loc)
7214 {
7215   gdb_assert (loc->owner != NULL);
7216
7217   if (loc->owner->type == bp_breakpoint
7218       || loc->owner->type == bp_hardware_breakpoint
7219       || is_tracepoint (loc->owner))
7220     {
7221       int is_gnu_ifunc;
7222       const char *function_name;
7223       CORE_ADDR func_addr;
7224
7225       find_pc_partial_function_gnu_ifunc (loc->address, &function_name,
7226                                           &func_addr, NULL, &is_gnu_ifunc);
7227
7228       if (is_gnu_ifunc && !explicit_loc)
7229         {
7230           struct breakpoint *b = loc->owner;
7231
7232           gdb_assert (loc->pspace == current_program_space);
7233           if (gnu_ifunc_resolve_name (function_name,
7234                                       &loc->requested_address))
7235             {
7236               /* Recalculate ADDRESS based on new REQUESTED_ADDRESS.  */
7237               loc->address = adjust_breakpoint_address (loc->gdbarch,
7238                                                         loc->requested_address,
7239                                                         b->type);
7240             }
7241           else if (b->type == bp_breakpoint && b->loc == loc
7242                    && loc->next == NULL && b->related_breakpoint == b)
7243             {
7244               /* Create only the whole new breakpoint of this type but do not
7245                  mess more complicated breakpoints with multiple locations.  */
7246               b->type = bp_gnu_ifunc_resolver;
7247               /* Remember the resolver's address for use by the return
7248                  breakpoint.  */
7249               loc->related_address = func_addr;
7250             }
7251         }
7252
7253       if (function_name)
7254         loc->function_name = xstrdup (function_name);
7255     }
7256 }
7257
7258 /* Attempt to determine architecture of location identified by SAL.  */
7259 struct gdbarch *
7260 get_sal_arch (struct symtab_and_line sal)
7261 {
7262   if (sal.section)
7263     return get_objfile_arch (sal.section->objfile);
7264   if (sal.symtab)
7265     return get_objfile_arch (SYMTAB_OBJFILE (sal.symtab));
7266
7267   return NULL;
7268 }
7269
7270 /* Low level routine for partially initializing a breakpoint of type
7271    BPTYPE.  The newly created breakpoint's address, section, source
7272    file name, and line number are provided by SAL.
7273
7274    It is expected that the caller will complete the initialization of
7275    the newly created breakpoint struct as well as output any status
7276    information regarding the creation of a new breakpoint.  */
7277
7278 static void
7279 init_raw_breakpoint (struct breakpoint *b, struct gdbarch *gdbarch,
7280                      struct symtab_and_line sal, enum bptype bptype,
7281                      const struct breakpoint_ops *ops)
7282 {
7283   init_raw_breakpoint_without_location (b, gdbarch, bptype, ops);
7284
7285   add_location_to_breakpoint (b, &sal);
7286
7287   if (bptype != bp_catchpoint)
7288     gdb_assert (sal.pspace != NULL);
7289
7290   /* Store the program space that was used to set the breakpoint,
7291      except for ordinary breakpoints, which are independent of the
7292      program space.  */
7293   if (bptype != bp_breakpoint && bptype != bp_hardware_breakpoint)
7294     b->pspace = sal.pspace;
7295 }
7296
7297 /* set_raw_breakpoint is a low level routine for allocating and
7298    partially initializing a breakpoint of type BPTYPE.  The newly
7299    created breakpoint's address, section, source file name, and line
7300    number are provided by SAL.  The newly created and partially
7301    initialized breakpoint is added to the breakpoint chain and
7302    is also returned as the value of this function.
7303
7304    It is expected that the caller will complete the initialization of
7305    the newly created breakpoint struct as well as output any status
7306    information regarding the creation of a new breakpoint.  In
7307    particular, set_raw_breakpoint does NOT set the breakpoint
7308    number!  Care should be taken to not allow an error to occur
7309    prior to completing the initialization of the breakpoint.  If this
7310    should happen, a bogus breakpoint will be left on the chain.  */
7311
7312 struct breakpoint *
7313 set_raw_breakpoint (struct gdbarch *gdbarch,
7314                     struct symtab_and_line sal, enum bptype bptype,
7315                     const struct breakpoint_ops *ops)
7316 {
7317   std::unique_ptr<breakpoint> b = new_breakpoint_from_type (bptype);
7318
7319   init_raw_breakpoint (b.get (), gdbarch, sal, bptype, ops);
7320   return add_to_breakpoint_chain (std::move (b));
7321 }
7322
7323 /* Call this routine when stepping and nexting to enable a breakpoint
7324    if we do a longjmp() or 'throw' in TP.  FRAME is the frame which
7325    initiated the operation.  */
7326
7327 void
7328 set_longjmp_breakpoint (struct thread_info *tp, struct frame_id frame)
7329 {
7330   struct breakpoint *b, *b_tmp;
7331   int thread = tp->global_num;
7332
7333   /* To avoid having to rescan all objfile symbols at every step,
7334      we maintain a list of continually-inserted but always disabled
7335      longjmp "master" breakpoints.  Here, we simply create momentary
7336      clones of those and enable them for the requested thread.  */
7337   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7338     if (b->pspace == current_program_space
7339         && (b->type == bp_longjmp_master
7340             || b->type == bp_exception_master))
7341       {
7342         enum bptype type = b->type == bp_longjmp_master ? bp_longjmp : bp_exception;
7343         struct breakpoint *clone;
7344
7345         /* longjmp_breakpoint_ops ensures INITIATING_FRAME is cleared again
7346            after their removal.  */
7347         clone = momentary_breakpoint_from_master (b, type,
7348                                                   &momentary_breakpoint_ops, 1);
7349         clone->thread = thread;
7350       }
7351
7352   tp->initiating_frame = frame;
7353 }
7354
7355 /* Delete all longjmp breakpoints from THREAD.  */
7356 void
7357 delete_longjmp_breakpoint (int thread)
7358 {
7359   struct breakpoint *b, *b_tmp;
7360
7361   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7362     if (b->type == bp_longjmp || b->type == bp_exception)
7363       {
7364         if (b->thread == thread)
7365           delete_breakpoint (b);
7366       }
7367 }
7368
7369 void
7370 delete_longjmp_breakpoint_at_next_stop (int thread)
7371 {
7372   struct breakpoint *b, *b_tmp;
7373
7374   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7375     if (b->type == bp_longjmp || b->type == bp_exception)
7376       {
7377         if (b->thread == thread)
7378           b->disposition = disp_del_at_next_stop;
7379       }
7380 }
7381
7382 /* Place breakpoints of type bp_longjmp_call_dummy to catch longjmp for
7383    INFERIOR_PTID thread.  Chain them all by RELATED_BREAKPOINT and return
7384    pointer to any of them.  Return NULL if this system cannot place longjmp
7385    breakpoints.  */
7386
7387 struct breakpoint *
7388 set_longjmp_breakpoint_for_call_dummy (void)
7389 {
7390   struct breakpoint *b, *retval = NULL;
7391
7392   ALL_BREAKPOINTS (b)
7393     if (b->pspace == current_program_space && b->type == bp_longjmp_master)
7394       {
7395         struct breakpoint *new_b;
7396
7397         new_b = momentary_breakpoint_from_master (b, bp_longjmp_call_dummy,
7398                                                   &momentary_breakpoint_ops,
7399                                                   1);
7400         new_b->thread = ptid_to_global_thread_id (inferior_ptid);
7401
7402         /* Link NEW_B into the chain of RETVAL breakpoints.  */
7403
7404         gdb_assert (new_b->related_breakpoint == new_b);
7405         if (retval == NULL)
7406           retval = new_b;
7407         new_b->related_breakpoint = retval;
7408         while (retval->related_breakpoint != new_b->related_breakpoint)
7409           retval = retval->related_breakpoint;
7410         retval->related_breakpoint = new_b;
7411       }
7412
7413   return retval;
7414 }
7415
7416 /* Verify all existing dummy frames and their associated breakpoints for
7417    TP.  Remove those which can no longer be found in the current frame
7418    stack.
7419
7420    You should call this function only at places where it is safe to currently
7421    unwind the whole stack.  Failed stack unwind would discard live dummy
7422    frames.  */
7423
7424 void
7425 check_longjmp_breakpoint_for_call_dummy (struct thread_info *tp)
7426 {
7427   struct breakpoint *b, *b_tmp;
7428
7429   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7430     if (b->type == bp_longjmp_call_dummy && b->thread == tp->global_num)
7431       {
7432         struct breakpoint *dummy_b = b->related_breakpoint;
7433
7434         while (dummy_b != b && dummy_b->type != bp_call_dummy)
7435           dummy_b = dummy_b->related_breakpoint;
7436         if (dummy_b->type != bp_call_dummy
7437             || frame_find_by_id (dummy_b->frame_id) != NULL)
7438           continue;
7439         
7440         dummy_frame_discard (dummy_b->frame_id, tp->ptid);
7441
7442         while (b->related_breakpoint != b)
7443           {
7444             if (b_tmp == b->related_breakpoint)
7445               b_tmp = b->related_breakpoint->next;
7446             delete_breakpoint (b->related_breakpoint);
7447           }
7448         delete_breakpoint (b);
7449       }
7450 }
7451
7452 void
7453 enable_overlay_breakpoints (void)
7454 {
7455   struct breakpoint *b;
7456
7457   ALL_BREAKPOINTS (b)
7458     if (b->type == bp_overlay_event)
7459     {
7460       b->enable_state = bp_enabled;
7461       update_global_location_list (UGLL_MAY_INSERT);
7462       overlay_events_enabled = 1;
7463     }
7464 }
7465
7466 void
7467 disable_overlay_breakpoints (void)
7468 {
7469   struct breakpoint *b;
7470
7471   ALL_BREAKPOINTS (b)
7472     if (b->type == bp_overlay_event)
7473     {
7474       b->enable_state = bp_disabled;
7475       update_global_location_list (UGLL_DONT_INSERT);
7476       overlay_events_enabled = 0;
7477     }
7478 }
7479
7480 /* Set an active std::terminate breakpoint for each std::terminate
7481    master breakpoint.  */
7482 void
7483 set_std_terminate_breakpoint (void)
7484 {
7485   struct breakpoint *b, *b_tmp;
7486
7487   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7488     if (b->pspace == current_program_space
7489         && b->type == bp_std_terminate_master)
7490       {
7491         momentary_breakpoint_from_master (b, bp_std_terminate,
7492                                           &momentary_breakpoint_ops, 1);
7493       }
7494 }
7495
7496 /* Delete all the std::terminate breakpoints.  */
7497 void
7498 delete_std_terminate_breakpoint (void)
7499 {
7500   struct breakpoint *b, *b_tmp;
7501
7502   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7503     if (b->type == bp_std_terminate)
7504       delete_breakpoint (b);
7505 }
7506
7507 struct breakpoint *
7508 create_thread_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7509 {
7510   struct breakpoint *b;
7511
7512   b = create_internal_breakpoint (gdbarch, address, bp_thread_event,
7513                                   &internal_breakpoint_ops);
7514
7515   b->enable_state = bp_enabled;
7516   /* location has to be used or breakpoint_re_set will delete me.  */
7517   b->location = new_address_location (b->loc->address, NULL, 0);
7518
7519   update_global_location_list_nothrow (UGLL_MAY_INSERT);
7520
7521   return b;
7522 }
7523
7524 struct lang_and_radix
7525   {
7526     enum language lang;
7527     int radix;
7528   };
7529
7530 /* Create a breakpoint for JIT code registration and unregistration.  */
7531
7532 struct breakpoint *
7533 create_jit_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7534 {
7535   return create_internal_breakpoint (gdbarch, address, bp_jit_event,
7536                                      &internal_breakpoint_ops);
7537 }
7538
7539 /* Remove JIT code registration and unregistration breakpoint(s).  */
7540
7541 void
7542 remove_jit_event_breakpoints (void)
7543 {
7544   struct breakpoint *b, *b_tmp;
7545
7546   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7547     if (b->type == bp_jit_event
7548         && b->loc->pspace == current_program_space)
7549       delete_breakpoint (b);
7550 }
7551
7552 void
7553 remove_solib_event_breakpoints (void)
7554 {
7555   struct breakpoint *b, *b_tmp;
7556
7557   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7558     if (b->type == bp_shlib_event
7559         && b->loc->pspace == current_program_space)
7560       delete_breakpoint (b);
7561 }
7562
7563 /* See breakpoint.h.  */
7564
7565 void
7566 remove_solib_event_breakpoints_at_next_stop (void)
7567 {
7568   struct breakpoint *b, *b_tmp;
7569
7570   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7571     if (b->type == bp_shlib_event
7572         && b->loc->pspace == current_program_space)
7573       b->disposition = disp_del_at_next_stop;
7574 }
7575
7576 /* Helper for create_solib_event_breakpoint /
7577    create_and_insert_solib_event_breakpoint.  Allows specifying which
7578    INSERT_MODE to pass through to update_global_location_list.  */
7579
7580 static struct breakpoint *
7581 create_solib_event_breakpoint_1 (struct gdbarch *gdbarch, CORE_ADDR address,
7582                                  enum ugll_insert_mode insert_mode)
7583 {
7584   struct breakpoint *b;
7585
7586   b = create_internal_breakpoint (gdbarch, address, bp_shlib_event,
7587                                   &internal_breakpoint_ops);
7588   update_global_location_list_nothrow (insert_mode);
7589   return b;
7590 }
7591
7592 struct breakpoint *
7593 create_solib_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7594 {
7595   return create_solib_event_breakpoint_1 (gdbarch, address, UGLL_MAY_INSERT);
7596 }
7597
7598 /* See breakpoint.h.  */
7599
7600 struct breakpoint *
7601 create_and_insert_solib_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7602 {
7603   struct breakpoint *b;
7604
7605   /* Explicitly tell update_global_location_list to insert
7606      locations.  */
7607   b = create_solib_event_breakpoint_1 (gdbarch, address, UGLL_INSERT);
7608   if (!b->loc->inserted)
7609     {
7610       delete_breakpoint (b);
7611       return NULL;
7612     }
7613   return b;
7614 }
7615
7616 /* Disable any breakpoints that are on code in shared libraries.  Only
7617    apply to enabled breakpoints, disabled ones can just stay disabled.  */
7618
7619 void
7620 disable_breakpoints_in_shlibs (void)
7621 {
7622   struct bp_location *loc, **locp_tmp;
7623
7624   ALL_BP_LOCATIONS (loc, locp_tmp)
7625   {
7626     /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
7627     struct breakpoint *b = loc->owner;
7628
7629     /* We apply the check to all breakpoints, including disabled for
7630        those with loc->duplicate set.  This is so that when breakpoint
7631        becomes enabled, or the duplicate is removed, gdb will try to
7632        insert all breakpoints.  If we don't set shlib_disabled here,
7633        we'll try to insert those breakpoints and fail.  */
7634     if (((b->type == bp_breakpoint)
7635          || (b->type == bp_jit_event)
7636          || (b->type == bp_hardware_breakpoint)
7637          || (is_tracepoint (b)))
7638         && loc->pspace == current_program_space
7639         && !loc->shlib_disabled
7640         && solib_name_from_address (loc->pspace, loc->address)
7641         )
7642       {
7643         loc->shlib_disabled = 1;
7644       }
7645   }
7646 }
7647
7648 /* Disable any breakpoints and tracepoints that are in SOLIB upon
7649    notification of unloaded_shlib.  Only apply to enabled breakpoints,
7650    disabled ones can just stay disabled.  */
7651
7652 static void
7653 disable_breakpoints_in_unloaded_shlib (struct so_list *solib)
7654 {
7655   struct bp_location *loc, **locp_tmp;
7656   int disabled_shlib_breaks = 0;
7657
7658   ALL_BP_LOCATIONS (loc, locp_tmp)
7659   {
7660     /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
7661     struct breakpoint *b = loc->owner;
7662
7663     if (solib->pspace == loc->pspace
7664         && !loc->shlib_disabled
7665         && (((b->type == bp_breakpoint
7666               || b->type == bp_jit_event
7667               || b->type == bp_hardware_breakpoint)
7668              && (loc->loc_type == bp_loc_hardware_breakpoint
7669                  || loc->loc_type == bp_loc_software_breakpoint))
7670             || is_tracepoint (b))
7671         && solib_contains_address_p (solib, loc->address))
7672       {
7673         loc->shlib_disabled = 1;
7674         /* At this point, we cannot rely on remove_breakpoint
7675            succeeding so we must mark the breakpoint as not inserted
7676            to prevent future errors occurring in remove_breakpoints.  */
7677         loc->inserted = 0;
7678
7679         /* This may cause duplicate notifications for the same breakpoint.  */
7680         observer_notify_breakpoint_modified (b);
7681
7682         if (!disabled_shlib_breaks)
7683           {
7684             target_terminal::ours_for_output ();
7685             warning (_("Temporarily disabling breakpoints "
7686                        "for unloaded shared library \"%s\""),
7687                      solib->so_name);
7688           }
7689         disabled_shlib_breaks = 1;
7690       }
7691   }
7692 }
7693
7694 /* Disable any breakpoints and tracepoints in OBJFILE upon
7695    notification of free_objfile.  Only apply to enabled breakpoints,
7696    disabled ones can just stay disabled.  */
7697
7698 static void
7699 disable_breakpoints_in_freed_objfile (struct objfile *objfile)
7700 {
7701   struct breakpoint *b;
7702
7703   if (objfile == NULL)
7704     return;
7705
7706   /* OBJF_SHARED|OBJF_USERLOADED objfiles are dynamic modules manually
7707      managed by the user with add-symbol-file/remove-symbol-file.
7708      Similarly to how breakpoints in shared libraries are handled in
7709      response to "nosharedlibrary", mark breakpoints in such modules
7710      shlib_disabled so they end up uninserted on the next global
7711      location list update.  Shared libraries not loaded by the user
7712      aren't handled here -- they're already handled in
7713      disable_breakpoints_in_unloaded_shlib, called by solib.c's
7714      solib_unloaded observer.  We skip objfiles that are not
7715      OBJF_SHARED as those aren't considered dynamic objects (e.g. the
7716      main objfile).  */
7717   if ((objfile->flags & OBJF_SHARED) == 0
7718       || (objfile->flags & OBJF_USERLOADED) == 0)
7719     return;
7720
7721   ALL_BREAKPOINTS (b)
7722     {
7723       struct bp_location *loc;
7724       int bp_modified = 0;
7725
7726       if (!is_breakpoint (b) && !is_tracepoint (b))
7727         continue;
7728
7729       for (loc = b->loc; loc != NULL; loc = loc->next)
7730         {
7731           CORE_ADDR loc_addr = loc->address;
7732
7733           if (loc->loc_type != bp_loc_hardware_breakpoint
7734               && loc->loc_type != bp_loc_software_breakpoint)
7735             continue;
7736
7737           if (loc->shlib_disabled != 0)
7738             continue;
7739
7740           if (objfile->pspace != loc->pspace)
7741             continue;
7742
7743           if (loc->loc_type != bp_loc_hardware_breakpoint
7744               && loc->loc_type != bp_loc_software_breakpoint)
7745             continue;
7746
7747           if (is_addr_in_objfile (loc_addr, objfile))
7748             {
7749               loc->shlib_disabled = 1;
7750               /* At this point, we don't know whether the object was
7751                  unmapped from the inferior or not, so leave the
7752                  inserted flag alone.  We'll handle failure to
7753                  uninsert quietly, in case the object was indeed
7754                  unmapped.  */
7755
7756               mark_breakpoint_location_modified (loc);
7757
7758               bp_modified = 1;
7759             }
7760         }
7761
7762       if (bp_modified)
7763         observer_notify_breakpoint_modified (b);
7764     }
7765 }
7766
7767 /* FORK & VFORK catchpoints.  */
7768
7769 /* An instance of this type is used to represent a fork or vfork
7770    catchpoint.  A breakpoint is really of this type iff its ops pointer points
7771    to CATCH_FORK_BREAKPOINT_OPS.  */
7772
7773 struct fork_catchpoint : public breakpoint
7774 {
7775   /* Process id of a child process whose forking triggered this
7776      catchpoint.  This field is only valid immediately after this
7777      catchpoint has triggered.  */
7778   ptid_t forked_inferior_pid;
7779 };
7780
7781 /* Implement the "insert" breakpoint_ops method for fork
7782    catchpoints.  */
7783
7784 static int
7785 insert_catch_fork (struct bp_location *bl)
7786 {
7787   return target_insert_fork_catchpoint (ptid_get_pid (inferior_ptid));
7788 }
7789
7790 /* Implement the "remove" breakpoint_ops method for fork
7791    catchpoints.  */
7792
7793 static int
7794 remove_catch_fork (struct bp_location *bl, enum remove_bp_reason reason)
7795 {
7796   return target_remove_fork_catchpoint (ptid_get_pid (inferior_ptid));
7797 }
7798
7799 /* Implement the "breakpoint_hit" breakpoint_ops method for fork
7800    catchpoints.  */
7801
7802 static int
7803 breakpoint_hit_catch_fork (const struct bp_location *bl,
7804                            const address_space *aspace, CORE_ADDR bp_addr,
7805                            const struct target_waitstatus *ws)
7806 {
7807   struct fork_catchpoint *c = (struct fork_catchpoint *) bl->owner;
7808
7809   if (ws->kind != TARGET_WAITKIND_FORKED)
7810     return 0;
7811
7812   c->forked_inferior_pid = ws->value.related_pid;
7813   return 1;
7814 }
7815
7816 /* Implement the "print_it" breakpoint_ops method for fork
7817    catchpoints.  */
7818
7819 static enum print_stop_action
7820 print_it_catch_fork (bpstat bs)
7821 {
7822   struct ui_out *uiout = current_uiout;
7823   struct breakpoint *b = bs->breakpoint_at;
7824   struct fork_catchpoint *c = (struct fork_catchpoint *) bs->breakpoint_at;
7825
7826   annotate_catchpoint (b->number);
7827   maybe_print_thread_hit_breakpoint (uiout);
7828   if (b->disposition == disp_del)
7829     uiout->text ("Temporary catchpoint ");
7830   else
7831     uiout->text ("Catchpoint ");
7832   if (uiout->is_mi_like_p ())
7833     {
7834       uiout->field_string ("reason", async_reason_lookup (EXEC_ASYNC_FORK));
7835       uiout->field_string ("disp", bpdisp_text (b->disposition));
7836     }
7837   uiout->field_int ("bkptno", b->number);
7838   uiout->text (" (forked process ");
7839   uiout->field_int ("newpid", ptid_get_pid (c->forked_inferior_pid));
7840   uiout->text ("), ");
7841   return PRINT_SRC_AND_LOC;
7842 }
7843
7844 /* Implement the "print_one" breakpoint_ops method for fork
7845    catchpoints.  */
7846
7847 static void
7848 print_one_catch_fork (struct breakpoint *b, struct bp_location **last_loc)
7849 {
7850   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
7851   struct value_print_options opts;
7852   struct ui_out *uiout = current_uiout;
7853
7854   get_user_print_options (&opts);
7855
7856   /* Field 4, the address, is omitted (which makes the columns not
7857      line up too nicely with the headers, but the effect is relatively
7858      readable).  */
7859   if (opts.addressprint)
7860     uiout->field_skip ("addr");
7861   annotate_field (5);
7862   uiout->text ("fork");
7863   if (!ptid_equal (c->forked_inferior_pid, null_ptid))
7864     {
7865       uiout->text (", process ");
7866       uiout->field_int ("what", ptid_get_pid (c->forked_inferior_pid));
7867       uiout->spaces (1);
7868     }
7869
7870   if (uiout->is_mi_like_p ())
7871     uiout->field_string ("catch-type", "fork");
7872 }
7873
7874 /* Implement the "print_mention" breakpoint_ops method for fork
7875    catchpoints.  */
7876
7877 static void
7878 print_mention_catch_fork (struct breakpoint *b)
7879 {
7880   printf_filtered (_("Catchpoint %d (fork)"), b->number);
7881 }
7882
7883 /* Implement the "print_recreate" breakpoint_ops method for fork
7884    catchpoints.  */
7885
7886 static void
7887 print_recreate_catch_fork (struct breakpoint *b, struct ui_file *fp)
7888 {
7889   fprintf_unfiltered (fp, "catch fork");
7890   print_recreate_thread (b, fp);
7891 }
7892
7893 /* The breakpoint_ops structure to be used in fork catchpoints.  */
7894
7895 static struct breakpoint_ops catch_fork_breakpoint_ops;
7896
7897 /* Implement the "insert" breakpoint_ops method for vfork
7898    catchpoints.  */
7899
7900 static int
7901 insert_catch_vfork (struct bp_location *bl)
7902 {
7903   return target_insert_vfork_catchpoint (ptid_get_pid (inferior_ptid));
7904 }
7905
7906 /* Implement the "remove" breakpoint_ops method for vfork
7907    catchpoints.  */
7908
7909 static int
7910 remove_catch_vfork (struct bp_location *bl, enum remove_bp_reason reason)
7911 {
7912   return target_remove_vfork_catchpoint (ptid_get_pid (inferior_ptid));
7913 }
7914
7915 /* Implement the "breakpoint_hit" breakpoint_ops method for vfork
7916    catchpoints.  */
7917
7918 static int
7919 breakpoint_hit_catch_vfork (const struct bp_location *bl,
7920                             const address_space *aspace, CORE_ADDR bp_addr,
7921                             const struct target_waitstatus *ws)
7922 {
7923   struct fork_catchpoint *c = (struct fork_catchpoint *) bl->owner;
7924
7925   if (ws->kind != TARGET_WAITKIND_VFORKED)
7926     return 0;
7927
7928   c->forked_inferior_pid = ws->value.related_pid;
7929   return 1;
7930 }
7931
7932 /* Implement the "print_it" breakpoint_ops method for vfork
7933    catchpoints.  */
7934
7935 static enum print_stop_action
7936 print_it_catch_vfork (bpstat bs)
7937 {
7938   struct ui_out *uiout = current_uiout;
7939   struct breakpoint *b = bs->breakpoint_at;
7940   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
7941
7942   annotate_catchpoint (b->number);
7943   maybe_print_thread_hit_breakpoint (uiout);
7944   if (b->disposition == disp_del)
7945     uiout->text ("Temporary catchpoint ");
7946   else
7947     uiout->text ("Catchpoint ");
7948   if (uiout->is_mi_like_p ())
7949     {
7950       uiout->field_string ("reason", async_reason_lookup (EXEC_ASYNC_VFORK));
7951       uiout->field_string ("disp", bpdisp_text (b->disposition));
7952     }
7953   uiout->field_int ("bkptno", b->number);
7954   uiout->text (" (vforked process ");
7955   uiout->field_int ("newpid", ptid_get_pid (c->forked_inferior_pid));
7956   uiout->text ("), ");
7957   return PRINT_SRC_AND_LOC;
7958 }
7959
7960 /* Implement the "print_one" breakpoint_ops method for vfork
7961    catchpoints.  */
7962
7963 static void
7964 print_one_catch_vfork (struct breakpoint *b, struct bp_location **last_loc)
7965 {
7966   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
7967   struct value_print_options opts;
7968   struct ui_out *uiout = current_uiout;
7969
7970   get_user_print_options (&opts);
7971   /* Field 4, the address, is omitted (which makes the columns not
7972      line up too nicely with the headers, but the effect is relatively
7973      readable).  */
7974   if (opts.addressprint)
7975     uiout->field_skip ("addr");
7976   annotate_field (5);
7977   uiout->text ("vfork");
7978   if (!ptid_equal (c->forked_inferior_pid, null_ptid))
7979     {
7980       uiout->text (", process ");
7981       uiout->field_int ("what", ptid_get_pid (c->forked_inferior_pid));
7982       uiout->spaces (1);
7983     }
7984
7985   if (uiout->is_mi_like_p ())
7986     uiout->field_string ("catch-type", "vfork");
7987 }
7988
7989 /* Implement the "print_mention" breakpoint_ops method for vfork
7990    catchpoints.  */
7991
7992 static void
7993 print_mention_catch_vfork (struct breakpoint *b)
7994 {
7995   printf_filtered (_("Catchpoint %d (vfork)"), b->number);
7996 }
7997
7998 /* Implement the "print_recreate" breakpoint_ops method for vfork
7999    catchpoints.  */
8000
8001 static void
8002 print_recreate_catch_vfork (struct breakpoint *b, struct ui_file *fp)
8003 {
8004   fprintf_unfiltered (fp, "catch vfork");
8005   print_recreate_thread (b, fp);
8006 }
8007
8008 /* The breakpoint_ops structure to be used in vfork catchpoints.  */
8009
8010 static struct breakpoint_ops catch_vfork_breakpoint_ops;
8011
8012 /* An instance of this type is used to represent an solib catchpoint.
8013    A breakpoint is really of this type iff its ops pointer points to
8014    CATCH_SOLIB_BREAKPOINT_OPS.  */
8015
8016 struct solib_catchpoint : public breakpoint
8017 {
8018   ~solib_catchpoint () override;
8019
8020   /* True for "catch load", false for "catch unload".  */
8021   unsigned char is_load;
8022
8023   /* Regular expression to match, if any.  COMPILED is only valid when
8024      REGEX is non-NULL.  */
8025   char *regex;
8026   std::unique_ptr<compiled_regex> compiled;
8027 };
8028
8029 solib_catchpoint::~solib_catchpoint ()
8030 {
8031   xfree (this->regex);
8032 }
8033
8034 static int
8035 insert_catch_solib (struct bp_location *ignore)
8036 {
8037   return 0;
8038 }
8039
8040 static int
8041 remove_catch_solib (struct bp_location *ignore, enum remove_bp_reason reason)
8042 {
8043   return 0;
8044 }
8045
8046 static int
8047 breakpoint_hit_catch_solib (const struct bp_location *bl,
8048                             const address_space *aspace,
8049                             CORE_ADDR bp_addr,
8050                             const struct target_waitstatus *ws)
8051 {
8052   struct solib_catchpoint *self = (struct solib_catchpoint *) bl->owner;
8053   struct breakpoint *other;
8054
8055   if (ws->kind == TARGET_WAITKIND_LOADED)
8056     return 1;
8057
8058   ALL_BREAKPOINTS (other)
8059   {
8060     struct bp_location *other_bl;
8061
8062     if (other == bl->owner)
8063       continue;
8064
8065     if (other->type != bp_shlib_event)
8066       continue;
8067
8068     if (self->pspace != NULL && other->pspace != self->pspace)
8069       continue;
8070
8071     for (other_bl = other->loc; other_bl != NULL; other_bl = other_bl->next)
8072       {
8073         if (other->ops->breakpoint_hit (other_bl, aspace, bp_addr, ws))
8074           return 1;
8075       }
8076   }
8077
8078   return 0;
8079 }
8080
8081 static void
8082 check_status_catch_solib (struct bpstats *bs)
8083 {
8084   struct solib_catchpoint *self
8085     = (struct solib_catchpoint *) bs->breakpoint_at;
8086   int ix;
8087
8088   if (self->is_load)
8089     {
8090       struct so_list *iter;
8091
8092       for (ix = 0;
8093            VEC_iterate (so_list_ptr, current_program_space->added_solibs,
8094                         ix, iter);
8095            ++ix)
8096         {
8097           if (!self->regex
8098               || self->compiled->exec (iter->so_name, 0, NULL, 0) == 0)
8099             return;
8100         }
8101     }
8102   else
8103     {
8104       char *iter;
8105
8106       for (ix = 0;
8107            VEC_iterate (char_ptr, current_program_space->deleted_solibs,
8108                         ix, iter);
8109            ++ix)
8110         {
8111           if (!self->regex
8112               || self->compiled->exec (iter, 0, NULL, 0) == 0)
8113             return;
8114         }
8115     }
8116
8117   bs->stop = 0;
8118   bs->print_it = print_it_noop;
8119 }
8120
8121 static enum print_stop_action
8122 print_it_catch_solib (bpstat bs)
8123 {
8124   struct breakpoint *b = bs->breakpoint_at;
8125   struct ui_out *uiout = current_uiout;
8126
8127   annotate_catchpoint (b->number);
8128   maybe_print_thread_hit_breakpoint (uiout);
8129   if (b->disposition == disp_del)
8130     uiout->text ("Temporary catchpoint ");
8131   else
8132     uiout->text ("Catchpoint ");
8133   uiout->field_int ("bkptno", b->number);
8134   uiout->text ("\n");
8135   if (uiout->is_mi_like_p ())
8136     uiout->field_string ("disp", bpdisp_text (b->disposition));
8137   print_solib_event (1);
8138   return PRINT_SRC_AND_LOC;
8139 }
8140
8141 static void
8142 print_one_catch_solib (struct breakpoint *b, struct bp_location **locs)
8143 {
8144   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8145   struct value_print_options opts;
8146   struct ui_out *uiout = current_uiout;
8147   char *msg;
8148
8149   get_user_print_options (&opts);
8150   /* Field 4, the address, is omitted (which makes the columns not
8151      line up too nicely with the headers, but the effect is relatively
8152      readable).  */
8153   if (opts.addressprint)
8154     {
8155       annotate_field (4);
8156       uiout->field_skip ("addr");
8157     }
8158
8159   annotate_field (5);
8160   if (self->is_load)
8161     {
8162       if (self->regex)
8163         msg = xstrprintf (_("load of library matching %s"), self->regex);
8164       else
8165         msg = xstrdup (_("load of library"));
8166     }
8167   else
8168     {
8169       if (self->regex)
8170         msg = xstrprintf (_("unload of library matching %s"), self->regex);
8171       else
8172         msg = xstrdup (_("unload of library"));
8173     }
8174   uiout->field_string ("what", msg);
8175   xfree (msg);
8176
8177   if (uiout->is_mi_like_p ())
8178     uiout->field_string ("catch-type", self->is_load ? "load" : "unload");
8179 }
8180
8181 static void
8182 print_mention_catch_solib (struct breakpoint *b)
8183 {
8184   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8185
8186   printf_filtered (_("Catchpoint %d (%s)"), b->number,
8187                    self->is_load ? "load" : "unload");
8188 }
8189
8190 static void
8191 print_recreate_catch_solib (struct breakpoint *b, struct ui_file *fp)
8192 {
8193   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8194
8195   fprintf_unfiltered (fp, "%s %s",
8196                       b->disposition == disp_del ? "tcatch" : "catch",
8197                       self->is_load ? "load" : "unload");
8198   if (self->regex)
8199     fprintf_unfiltered (fp, " %s", self->regex);
8200   fprintf_unfiltered (fp, "\n");
8201 }
8202
8203 static struct breakpoint_ops catch_solib_breakpoint_ops;
8204
8205 /* Shared helper function (MI and CLI) for creating and installing
8206    a shared object event catchpoint.  If IS_LOAD is non-zero then
8207    the events to be caught are load events, otherwise they are
8208    unload events.  If IS_TEMP is non-zero the catchpoint is a
8209    temporary one.  If ENABLED is non-zero the catchpoint is
8210    created in an enabled state.  */
8211
8212 void
8213 add_solib_catchpoint (const char *arg, int is_load, int is_temp, int enabled)
8214 {
8215   struct gdbarch *gdbarch = get_current_arch ();
8216
8217   if (!arg)
8218     arg = "";
8219   arg = skip_spaces (arg);
8220
8221   std::unique_ptr<solib_catchpoint> c (new solib_catchpoint ());
8222
8223   if (*arg != '\0')
8224     {
8225       c->compiled.reset (new compiled_regex (arg, REG_NOSUB,
8226                                              _("Invalid regexp")));
8227       c->regex = xstrdup (arg);
8228     }
8229
8230   c->is_load = is_load;
8231   init_catchpoint (c.get (), gdbarch, is_temp, NULL,
8232                    &catch_solib_breakpoint_ops);
8233
8234   c->enable_state = enabled ? bp_enabled : bp_disabled;
8235
8236   install_breakpoint (0, std::move (c), 1);
8237 }
8238
8239 /* A helper function that does all the work for "catch load" and
8240    "catch unload".  */
8241
8242 static void
8243 catch_load_or_unload (char *arg, int from_tty, int is_load,
8244                       struct cmd_list_element *command)
8245 {
8246   int tempflag;
8247   const int enabled = 1;
8248
8249   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
8250
8251   add_solib_catchpoint (arg, is_load, tempflag, enabled);
8252 }
8253
8254 static void
8255 catch_load_command_1 (char *arg, int from_tty,
8256                       struct cmd_list_element *command)
8257 {
8258   catch_load_or_unload (arg, from_tty, 1, command);
8259 }
8260
8261 static void
8262 catch_unload_command_1 (char *arg, int from_tty,
8263                         struct cmd_list_element *command)
8264 {
8265   catch_load_or_unload (arg, from_tty, 0, command);
8266 }
8267
8268 /* Initialize a new breakpoint of the bp_catchpoint kind.  If TEMPFLAG
8269    is non-zero, then make the breakpoint temporary.  If COND_STRING is
8270    not NULL, then store it in the breakpoint.  OPS, if not NULL, is
8271    the breakpoint_ops structure associated to the catchpoint.  */
8272
8273 void
8274 init_catchpoint (struct breakpoint *b,
8275                  struct gdbarch *gdbarch, int tempflag,
8276                  const char *cond_string,
8277                  const struct breakpoint_ops *ops)
8278 {
8279   symtab_and_line sal;
8280   sal.pspace = current_program_space;
8281
8282   init_raw_breakpoint (b, gdbarch, sal, bp_catchpoint, ops);
8283
8284   b->cond_string = (cond_string == NULL) ? NULL : xstrdup (cond_string);
8285   b->disposition = tempflag ? disp_del : disp_donttouch;
8286 }
8287
8288 void
8289 install_breakpoint (int internal, std::unique_ptr<breakpoint> &&arg, int update_gll)
8290 {
8291   breakpoint *b = add_to_breakpoint_chain (std::move (arg));
8292   set_breakpoint_number (internal, b);
8293   if (is_tracepoint (b))
8294     set_tracepoint_count (breakpoint_count);
8295   if (!internal)
8296     mention (b);
8297   observer_notify_breakpoint_created (b);
8298
8299   if (update_gll)
8300     update_global_location_list (UGLL_MAY_INSERT);
8301 }
8302
8303 static void
8304 create_fork_vfork_event_catchpoint (struct gdbarch *gdbarch,
8305                                     int tempflag, const char *cond_string,
8306                                     const struct breakpoint_ops *ops)
8307 {
8308   std::unique_ptr<fork_catchpoint> c (new fork_catchpoint ());
8309
8310   init_catchpoint (c.get (), gdbarch, tempflag, cond_string, ops);
8311
8312   c->forked_inferior_pid = null_ptid;
8313
8314   install_breakpoint (0, std::move (c), 1);
8315 }
8316
8317 /* Exec catchpoints.  */
8318
8319 /* An instance of this type is used to represent an exec catchpoint.
8320    A breakpoint is really of this type iff its ops pointer points to
8321    CATCH_EXEC_BREAKPOINT_OPS.  */
8322
8323 struct exec_catchpoint : public breakpoint
8324 {
8325   ~exec_catchpoint () override;
8326
8327   /* Filename of a program whose exec triggered this catchpoint.
8328      This field is only valid immediately after this catchpoint has
8329      triggered.  */
8330   char *exec_pathname;
8331 };
8332
8333 /* Exec catchpoint destructor.  */
8334
8335 exec_catchpoint::~exec_catchpoint ()
8336 {
8337   xfree (this->exec_pathname);
8338 }
8339
8340 static int
8341 insert_catch_exec (struct bp_location *bl)
8342 {
8343   return target_insert_exec_catchpoint (ptid_get_pid (inferior_ptid));
8344 }
8345
8346 static int
8347 remove_catch_exec (struct bp_location *bl, enum remove_bp_reason reason)
8348 {
8349   return target_remove_exec_catchpoint (ptid_get_pid (inferior_ptid));
8350 }
8351
8352 static int
8353 breakpoint_hit_catch_exec (const struct bp_location *bl,
8354                            const address_space *aspace, CORE_ADDR bp_addr,
8355                            const struct target_waitstatus *ws)
8356 {
8357   struct exec_catchpoint *c = (struct exec_catchpoint *) bl->owner;
8358
8359   if (ws->kind != TARGET_WAITKIND_EXECD)
8360     return 0;
8361
8362   c->exec_pathname = xstrdup (ws->value.execd_pathname);
8363   return 1;
8364 }
8365
8366 static enum print_stop_action
8367 print_it_catch_exec (bpstat bs)
8368 {
8369   struct ui_out *uiout = current_uiout;
8370   struct breakpoint *b = bs->breakpoint_at;
8371   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
8372
8373   annotate_catchpoint (b->number);
8374   maybe_print_thread_hit_breakpoint (uiout);
8375   if (b->disposition == disp_del)
8376     uiout->text ("Temporary catchpoint ");
8377   else
8378     uiout->text ("Catchpoint ");
8379   if (uiout->is_mi_like_p ())
8380     {
8381       uiout->field_string ("reason", async_reason_lookup (EXEC_ASYNC_EXEC));
8382       uiout->field_string ("disp", bpdisp_text (b->disposition));
8383     }
8384   uiout->field_int ("bkptno", b->number);
8385   uiout->text (" (exec'd ");
8386   uiout->field_string ("new-exec", c->exec_pathname);
8387   uiout->text ("), ");
8388
8389   return PRINT_SRC_AND_LOC;
8390 }
8391
8392 static void
8393 print_one_catch_exec (struct breakpoint *b, struct bp_location **last_loc)
8394 {
8395   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
8396   struct value_print_options opts;
8397   struct ui_out *uiout = current_uiout;
8398
8399   get_user_print_options (&opts);
8400
8401   /* Field 4, the address, is omitted (which makes the columns
8402      not line up too nicely with the headers, but the effect
8403      is relatively readable).  */
8404   if (opts.addressprint)
8405     uiout->field_skip ("addr");
8406   annotate_field (5);
8407   uiout->text ("exec");
8408   if (c->exec_pathname != NULL)
8409     {
8410       uiout->text (", program \"");
8411       uiout->field_string ("what", c->exec_pathname);
8412       uiout->text ("\" ");
8413     }
8414
8415   if (uiout->is_mi_like_p ())
8416     uiout->field_string ("catch-type", "exec");
8417 }
8418
8419 static void
8420 print_mention_catch_exec (struct breakpoint *b)
8421 {
8422   printf_filtered (_("Catchpoint %d (exec)"), b->number);
8423 }
8424
8425 /* Implement the "print_recreate" breakpoint_ops method for exec
8426    catchpoints.  */
8427
8428 static void
8429 print_recreate_catch_exec (struct breakpoint *b, struct ui_file *fp)
8430 {
8431   fprintf_unfiltered (fp, "catch exec");
8432   print_recreate_thread (b, fp);
8433 }
8434
8435 static struct breakpoint_ops catch_exec_breakpoint_ops;
8436
8437 static int
8438 hw_breakpoint_used_count (void)
8439 {
8440   int i = 0;
8441   struct breakpoint *b;
8442   struct bp_location *bl;
8443
8444   ALL_BREAKPOINTS (b)
8445   {
8446     if (b->type == bp_hardware_breakpoint && breakpoint_enabled (b))
8447       for (bl = b->loc; bl; bl = bl->next)
8448         {
8449           /* Special types of hardware breakpoints may use more than
8450              one register.  */
8451           i += b->ops->resources_needed (bl);
8452         }
8453   }
8454
8455   return i;
8456 }
8457
8458 /* Returns the resources B would use if it were a hardware
8459    watchpoint.  */
8460
8461 static int
8462 hw_watchpoint_use_count (struct breakpoint *b)
8463 {
8464   int i = 0;
8465   struct bp_location *bl;
8466
8467   if (!breakpoint_enabled (b))
8468     return 0;
8469
8470   for (bl = b->loc; bl; bl = bl->next)
8471     {
8472       /* Special types of hardware watchpoints may use more than
8473          one register.  */
8474       i += b->ops->resources_needed (bl);
8475     }
8476
8477   return i;
8478 }
8479
8480 /* Returns the sum the used resources of all hardware watchpoints of
8481    type TYPE in the breakpoints list.  Also returns in OTHER_TYPE_USED
8482    the sum of the used resources of all hardware watchpoints of other
8483    types _not_ TYPE.  */
8484
8485 static int
8486 hw_watchpoint_used_count_others (struct breakpoint *except,
8487                                  enum bptype type, int *other_type_used)
8488 {
8489   int i = 0;
8490   struct breakpoint *b;
8491
8492   *other_type_used = 0;
8493   ALL_BREAKPOINTS (b)
8494     {
8495       if (b == except)
8496         continue;
8497       if (!breakpoint_enabled (b))
8498         continue;
8499
8500       if (b->type == type)
8501         i += hw_watchpoint_use_count (b);
8502       else if (is_hardware_watchpoint (b))
8503         *other_type_used = 1;
8504     }
8505
8506   return i;
8507 }
8508
8509 void
8510 disable_watchpoints_before_interactive_call_start (void)
8511 {
8512   struct breakpoint *b;
8513
8514   ALL_BREAKPOINTS (b)
8515   {
8516     if (is_watchpoint (b) && breakpoint_enabled (b))
8517       {
8518         b->enable_state = bp_call_disabled;
8519         update_global_location_list (UGLL_DONT_INSERT);
8520       }
8521   }
8522 }
8523
8524 void
8525 enable_watchpoints_after_interactive_call_stop (void)
8526 {
8527   struct breakpoint *b;
8528
8529   ALL_BREAKPOINTS (b)
8530   {
8531     if (is_watchpoint (b) && b->enable_state == bp_call_disabled)
8532       {
8533         b->enable_state = bp_enabled;
8534         update_global_location_list (UGLL_MAY_INSERT);
8535       }
8536   }
8537 }
8538
8539 void
8540 disable_breakpoints_before_startup (void)
8541 {
8542   current_program_space->executing_startup = 1;
8543   update_global_location_list (UGLL_DONT_INSERT);
8544 }
8545
8546 void
8547 enable_breakpoints_after_startup (void)
8548 {
8549   current_program_space->executing_startup = 0;
8550   breakpoint_re_set ();
8551 }
8552
8553 /* Create a new single-step breakpoint for thread THREAD, with no
8554    locations.  */
8555
8556 static struct breakpoint *
8557 new_single_step_breakpoint (int thread, struct gdbarch *gdbarch)
8558 {
8559   std::unique_ptr<breakpoint> b (new breakpoint ());
8560
8561   init_raw_breakpoint_without_location (b.get (), gdbarch, bp_single_step,
8562                                         &momentary_breakpoint_ops);
8563
8564   b->disposition = disp_donttouch;
8565   b->frame_id = null_frame_id;
8566
8567   b->thread = thread;
8568   gdb_assert (b->thread != 0);
8569
8570   return add_to_breakpoint_chain (std::move (b));
8571 }
8572
8573 /* Set a momentary breakpoint of type TYPE at address specified by
8574    SAL.  If FRAME_ID is valid, the breakpoint is restricted to that
8575    frame.  */
8576
8577 breakpoint_up
8578 set_momentary_breakpoint (struct gdbarch *gdbarch, struct symtab_and_line sal,
8579                           struct frame_id frame_id, enum bptype type)
8580 {
8581   struct breakpoint *b;
8582
8583   /* If FRAME_ID is valid, it should be a real frame, not an inlined or
8584      tail-called one.  */
8585   gdb_assert (!frame_id_artificial_p (frame_id));
8586
8587   b = set_raw_breakpoint (gdbarch, sal, type, &momentary_breakpoint_ops);
8588   b->enable_state = bp_enabled;
8589   b->disposition = disp_donttouch;
8590   b->frame_id = frame_id;
8591
8592   /* If we're debugging a multi-threaded program, then we want
8593      momentary breakpoints to be active in only a single thread of
8594      control.  */
8595   if (in_thread_list (inferior_ptid))
8596     b->thread = ptid_to_global_thread_id (inferior_ptid);
8597
8598   update_global_location_list_nothrow (UGLL_MAY_INSERT);
8599
8600   return breakpoint_up (b);
8601 }
8602
8603 /* Make a momentary breakpoint based on the master breakpoint ORIG.
8604    The new breakpoint will have type TYPE, use OPS as its
8605    breakpoint_ops, and will set enabled to LOC_ENABLED.  */
8606
8607 static struct breakpoint *
8608 momentary_breakpoint_from_master (struct breakpoint *orig,
8609                                   enum bptype type,
8610                                   const struct breakpoint_ops *ops,
8611                                   int loc_enabled)
8612 {
8613   struct breakpoint *copy;
8614
8615   copy = set_raw_breakpoint_without_location (orig->gdbarch, type, ops);
8616   copy->loc = allocate_bp_location (copy);
8617   set_breakpoint_location_function (copy->loc, 1);
8618
8619   copy->loc->gdbarch = orig->loc->gdbarch;
8620   copy->loc->requested_address = orig->loc->requested_address;
8621   copy->loc->address = orig->loc->address;
8622   copy->loc->section = orig->loc->section;
8623   copy->loc->pspace = orig->loc->pspace;
8624   copy->loc->probe = orig->loc->probe;
8625   copy->loc->line_number = orig->loc->line_number;
8626   copy->loc->symtab = orig->loc->symtab;
8627   copy->loc->enabled = loc_enabled;
8628   copy->frame_id = orig->frame_id;
8629   copy->thread = orig->thread;
8630   copy->pspace = orig->pspace;
8631
8632   copy->enable_state = bp_enabled;
8633   copy->disposition = disp_donttouch;
8634   copy->number = internal_breakpoint_number--;
8635
8636   update_global_location_list_nothrow (UGLL_DONT_INSERT);
8637   return copy;
8638 }
8639
8640 /* Make a deep copy of momentary breakpoint ORIG.  Returns NULL if
8641    ORIG is NULL.  */
8642
8643 struct breakpoint *
8644 clone_momentary_breakpoint (struct breakpoint *orig)
8645 {
8646   /* If there's nothing to clone, then return nothing.  */
8647   if (orig == NULL)
8648     return NULL;
8649
8650   return momentary_breakpoint_from_master (orig, orig->type, orig->ops, 0);
8651 }
8652
8653 breakpoint_up
8654 set_momentary_breakpoint_at_pc (struct gdbarch *gdbarch, CORE_ADDR pc,
8655                                 enum bptype type)
8656 {
8657   struct symtab_and_line sal;
8658
8659   sal = find_pc_line (pc, 0);
8660   sal.pc = pc;
8661   sal.section = find_pc_overlay (pc);
8662   sal.explicit_pc = 1;
8663
8664   return set_momentary_breakpoint (gdbarch, sal, null_frame_id, type);
8665 }
8666 \f
8667
8668 /* Tell the user we have just set a breakpoint B.  */
8669
8670 static void
8671 mention (struct breakpoint *b)
8672 {
8673   b->ops->print_mention (b);
8674   if (current_uiout->is_mi_like_p ())
8675     return;
8676   printf_filtered ("\n");
8677 }
8678 \f
8679
8680 static int bp_loc_is_permanent (struct bp_location *loc);
8681
8682 static struct bp_location *
8683 add_location_to_breakpoint (struct breakpoint *b,
8684                             const struct symtab_and_line *sal)
8685 {
8686   struct bp_location *loc, **tmp;
8687   CORE_ADDR adjusted_address;
8688   struct gdbarch *loc_gdbarch = get_sal_arch (*sal);
8689
8690   if (loc_gdbarch == NULL)
8691     loc_gdbarch = b->gdbarch;
8692
8693   /* Adjust the breakpoint's address prior to allocating a location.
8694      Once we call allocate_bp_location(), that mostly uninitialized
8695      location will be placed on the location chain.  Adjustment of the
8696      breakpoint may cause target_read_memory() to be called and we do
8697      not want its scan of the location chain to find a breakpoint and
8698      location that's only been partially initialized.  */
8699   adjusted_address = adjust_breakpoint_address (loc_gdbarch,
8700                                                 sal->pc, b->type);
8701
8702   /* Sort the locations by their ADDRESS.  */
8703   loc = allocate_bp_location (b);
8704   for (tmp = &(b->loc); *tmp != NULL && (*tmp)->address <= adjusted_address;
8705        tmp = &((*tmp)->next))
8706     ;
8707   loc->next = *tmp;
8708   *tmp = loc;
8709
8710   loc->requested_address = sal->pc;
8711   loc->address = adjusted_address;
8712   loc->pspace = sal->pspace;
8713   loc->probe.probe = sal->probe;
8714   loc->probe.objfile = sal->objfile;
8715   gdb_assert (loc->pspace != NULL);
8716   loc->section = sal->section;
8717   loc->gdbarch = loc_gdbarch;
8718   loc->line_number = sal->line;
8719   loc->symtab = sal->symtab;
8720   loc->symbol = sal->symbol;
8721
8722   set_breakpoint_location_function (loc,
8723                                     sal->explicit_pc || sal->explicit_line);
8724
8725   /* While by definition, permanent breakpoints are already present in the
8726      code, we don't mark the location as inserted.  Normally one would expect
8727      that GDB could rely on that breakpoint instruction to stop the program,
8728      thus removing the need to insert its own breakpoint, except that executing
8729      the breakpoint instruction can kill the target instead of reporting a
8730      SIGTRAP.  E.g., on SPARC, when interrupts are disabled, executing the
8731      instruction resets the CPU, so QEMU 2.0.0 for SPARC correspondingly dies
8732      with "Trap 0x02 while interrupts disabled, Error state".  Letting the
8733      breakpoint be inserted normally results in QEMU knowing about the GDB
8734      breakpoint, and thus trap before the breakpoint instruction is executed.
8735      (If GDB later needs to continue execution past the permanent breakpoint,
8736      it manually increments the PC, thus avoiding executing the breakpoint
8737      instruction.)  */
8738   if (bp_loc_is_permanent (loc))
8739     loc->permanent = 1;
8740
8741   return loc;
8742 }
8743 \f
8744
8745 /* See breakpoint.h.  */
8746
8747 int
8748 program_breakpoint_here_p (struct gdbarch *gdbarch, CORE_ADDR address)
8749 {
8750   int len;
8751   CORE_ADDR addr;
8752   const gdb_byte *bpoint;
8753   gdb_byte *target_mem;
8754
8755   addr = address;
8756   bpoint = gdbarch_breakpoint_from_pc (gdbarch, &addr, &len);
8757
8758   /* Software breakpoints unsupported?  */
8759   if (bpoint == NULL)
8760     return 0;
8761
8762   target_mem = (gdb_byte *) alloca (len);
8763
8764   /* Enable the automatic memory restoration from breakpoints while
8765      we read the memory.  Otherwise we could say about our temporary
8766      breakpoints they are permanent.  */
8767   scoped_restore restore_memory
8768     = make_scoped_restore_show_memory_breakpoints (0);
8769
8770   if (target_read_memory (address, target_mem, len) == 0
8771       && memcmp (target_mem, bpoint, len) == 0)
8772     return 1;
8773
8774   return 0;
8775 }
8776
8777 /* Return 1 if LOC is pointing to a permanent breakpoint,
8778    return 0 otherwise.  */
8779
8780 static int
8781 bp_loc_is_permanent (struct bp_location *loc)
8782 {
8783   gdb_assert (loc != NULL);
8784
8785   /* If we have a catchpoint or a watchpoint, just return 0.  We should not
8786      attempt to read from the addresses the locations of these breakpoint types
8787      point to.  program_breakpoint_here_p, below, will attempt to read
8788      memory.  */
8789   if (!breakpoint_address_is_meaningful (loc->owner))
8790     return 0;
8791
8792   scoped_restore_current_pspace_and_thread restore_pspace_thread;
8793   switch_to_program_space_and_thread (loc->pspace);
8794   return program_breakpoint_here_p (loc->gdbarch, loc->address);
8795 }
8796
8797 /* Build a command list for the dprintf corresponding to the current
8798    settings of the dprintf style options.  */
8799
8800 static void
8801 update_dprintf_command_list (struct breakpoint *b)
8802 {
8803   char *dprintf_args = b->extra_string;
8804   char *printf_line = NULL;
8805
8806   if (!dprintf_args)
8807     return;
8808
8809   dprintf_args = skip_spaces (dprintf_args);
8810
8811   /* Allow a comma, as it may have terminated a location, but don't
8812      insist on it.  */
8813   if (*dprintf_args == ',')
8814     ++dprintf_args;
8815   dprintf_args = skip_spaces (dprintf_args);
8816
8817   if (*dprintf_args != '"')
8818     error (_("Bad format string, missing '\"'."));
8819
8820   if (strcmp (dprintf_style, dprintf_style_gdb) == 0)
8821     printf_line = xstrprintf ("printf %s", dprintf_args);
8822   else if (strcmp (dprintf_style, dprintf_style_call) == 0)
8823     {
8824       if (!dprintf_function)
8825         error (_("No function supplied for dprintf call"));
8826
8827       if (dprintf_channel && strlen (dprintf_channel) > 0)
8828         printf_line = xstrprintf ("call (void) %s (%s,%s)",
8829                                   dprintf_function,
8830                                   dprintf_channel,
8831                                   dprintf_args);
8832       else
8833         printf_line = xstrprintf ("call (void) %s (%s)",
8834                                   dprintf_function,
8835                                   dprintf_args);
8836     }
8837   else if (strcmp (dprintf_style, dprintf_style_agent) == 0)
8838     {
8839       if (target_can_run_breakpoint_commands ())
8840         printf_line = xstrprintf ("agent-printf %s", dprintf_args);
8841       else
8842         {
8843           warning (_("Target cannot run dprintf commands, falling back to GDB printf"));
8844           printf_line = xstrprintf ("printf %s", dprintf_args);
8845         }
8846     }
8847   else
8848     internal_error (__FILE__, __LINE__,
8849                     _("Invalid dprintf style."));
8850
8851   gdb_assert (printf_line != NULL);
8852   /* Manufacture a printf sequence.  */
8853   {
8854     struct command_line *printf_cmd_line = XNEW (struct command_line);
8855
8856     printf_cmd_line->control_type = simple_control;
8857     printf_cmd_line->body_count = 0;
8858     printf_cmd_line->body_list = NULL;
8859     printf_cmd_line->next = NULL;
8860     printf_cmd_line->line = printf_line;
8861
8862     breakpoint_set_commands (b, command_line_up (printf_cmd_line));
8863   }
8864 }
8865
8866 /* Update all dprintf commands, making their command lists reflect
8867    current style settings.  */
8868
8869 static void
8870 update_dprintf_commands (char *args, int from_tty,
8871                          struct cmd_list_element *c)
8872 {
8873   struct breakpoint *b;
8874
8875   ALL_BREAKPOINTS (b)
8876     {
8877       if (b->type == bp_dprintf)
8878         update_dprintf_command_list (b);
8879     }
8880 }
8881
8882 /* Create a breakpoint with SAL as location.  Use LOCATION
8883    as a description of the location, and COND_STRING
8884    as condition expression.  If LOCATION is NULL then create an
8885    "address location" from the address in the SAL.  */
8886
8887 static void
8888 init_breakpoint_sal (struct breakpoint *b, struct gdbarch *gdbarch,
8889                      gdb::array_view<const symtab_and_line> sals,
8890                      event_location_up &&location,
8891                      gdb::unique_xmalloc_ptr<char> filter,
8892                      gdb::unique_xmalloc_ptr<char> cond_string,
8893                      gdb::unique_xmalloc_ptr<char> extra_string,
8894                      enum bptype type, enum bpdisp disposition,
8895                      int thread, int task, int ignore_count,
8896                      const struct breakpoint_ops *ops, int from_tty,
8897                      int enabled, int internal, unsigned flags,
8898                      int display_canonical)
8899 {
8900   int i;
8901
8902   if (type == bp_hardware_breakpoint)
8903     {
8904       int target_resources_ok;
8905
8906       i = hw_breakpoint_used_count ();
8907       target_resources_ok =
8908         target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
8909                                             i + 1, 0);
8910       if (target_resources_ok == 0)
8911         error (_("No hardware breakpoint support in the target."));
8912       else if (target_resources_ok < 0)
8913         error (_("Hardware breakpoints used exceeds limit."));
8914     }
8915
8916   gdb_assert (!sals.empty ());
8917
8918   for (const auto &sal : sals)
8919     {
8920       struct bp_location *loc;
8921
8922       if (from_tty)
8923         {
8924           struct gdbarch *loc_gdbarch = get_sal_arch (sal);
8925           if (!loc_gdbarch)
8926             loc_gdbarch = gdbarch;
8927
8928           describe_other_breakpoints (loc_gdbarch,
8929                                       sal.pspace, sal.pc, sal.section, thread);
8930         }
8931
8932       if (&sal == &sals[0])
8933         {
8934           init_raw_breakpoint (b, gdbarch, sal, type, ops);
8935           b->thread = thread;
8936           b->task = task;
8937
8938           b->cond_string = cond_string.release ();
8939           b->extra_string = extra_string.release ();
8940           b->ignore_count = ignore_count;
8941           b->enable_state = enabled ? bp_enabled : bp_disabled;
8942           b->disposition = disposition;
8943
8944           if ((flags & CREATE_BREAKPOINT_FLAGS_INSERTED) != 0)
8945             b->loc->inserted = 1;
8946
8947           if (type == bp_static_tracepoint)
8948             {
8949               struct tracepoint *t = (struct tracepoint *) b;
8950               struct static_tracepoint_marker marker;
8951
8952               if (strace_marker_p (b))
8953                 {
8954                   /* We already know the marker exists, otherwise, we
8955                      wouldn't see a sal for it.  */
8956                   const char *p
8957                     = &event_location_to_string (b->location.get ())[3];
8958                   const char *endp;
8959                   char *marker_str;
8960
8961                   p = skip_spaces (p);
8962
8963                   endp = skip_to_space (p);
8964
8965                   marker_str = savestring (p, endp - p);
8966                   t->static_trace_marker_id = marker_str;
8967
8968                   printf_filtered (_("Probed static tracepoint "
8969                                      "marker \"%s\"\n"),
8970                                    t->static_trace_marker_id);
8971                 }
8972               else if (target_static_tracepoint_marker_at (sal.pc, &marker))
8973                 {
8974                   t->static_trace_marker_id = xstrdup (marker.str_id);
8975                   release_static_tracepoint_marker (&marker);
8976
8977                   printf_filtered (_("Probed static tracepoint "
8978                                      "marker \"%s\"\n"),
8979                                    t->static_trace_marker_id);
8980                 }
8981               else
8982                 warning (_("Couldn't determine the static "
8983                            "tracepoint marker to probe"));
8984             }
8985
8986           loc = b->loc;
8987         }
8988       else
8989         {
8990           loc = add_location_to_breakpoint (b, &sal);
8991           if ((flags & CREATE_BREAKPOINT_FLAGS_INSERTED) != 0)
8992             loc->inserted = 1;
8993         }
8994
8995       if (b->cond_string)
8996         {
8997           const char *arg = b->cond_string;
8998
8999           loc->cond = parse_exp_1 (&arg, loc->address,
9000                                    block_for_pc (loc->address), 0);
9001           if (*arg)
9002               error (_("Garbage '%s' follows condition"), arg);
9003         }
9004
9005       /* Dynamic printf requires and uses additional arguments on the
9006          command line, otherwise it's an error.  */
9007       if (type == bp_dprintf)
9008         {
9009           if (b->extra_string)
9010             update_dprintf_command_list (b);
9011           else
9012             error (_("Format string required"));
9013         }
9014       else if (b->extra_string)
9015         error (_("Garbage '%s' at end of command"), b->extra_string);
9016     }
9017
9018   b->display_canonical = display_canonical;
9019   if (location != NULL)
9020     b->location = std::move (location);
9021   else
9022     b->location = new_address_location (b->loc->address, NULL, 0);
9023   b->filter = filter.release ();
9024 }
9025
9026 static void
9027 create_breakpoint_sal (struct gdbarch *gdbarch,
9028                        gdb::array_view<const symtab_and_line> sals,
9029                        event_location_up &&location,
9030                        gdb::unique_xmalloc_ptr<char> filter,
9031                        gdb::unique_xmalloc_ptr<char> cond_string,
9032                        gdb::unique_xmalloc_ptr<char> extra_string,
9033                        enum bptype type, enum bpdisp disposition,
9034                        int thread, int task, int ignore_count,
9035                        const struct breakpoint_ops *ops, int from_tty,
9036                        int enabled, int internal, unsigned flags,
9037                        int display_canonical)
9038 {
9039   std::unique_ptr<breakpoint> b = new_breakpoint_from_type (type);
9040
9041   init_breakpoint_sal (b.get (), gdbarch,
9042                        sals, std::move (location),
9043                        std::move (filter),
9044                        std::move (cond_string),
9045                        std::move (extra_string),
9046                        type, disposition,
9047                        thread, task, ignore_count,
9048                        ops, from_tty,
9049                        enabled, internal, flags,
9050                        display_canonical);
9051
9052   install_breakpoint (internal, std::move (b), 0);
9053 }
9054
9055 /* Add SALS.nelts breakpoints to the breakpoint table.  For each
9056    SALS.sal[i] breakpoint, include the corresponding ADDR_STRING[i]
9057    value.  COND_STRING, if not NULL, specified the condition to be
9058    used for all breakpoints.  Essentially the only case where
9059    SALS.nelts is not 1 is when we set a breakpoint on an overloaded
9060    function.  In that case, it's still not possible to specify
9061    separate conditions for different overloaded functions, so
9062    we take just a single condition string.
9063    
9064    NOTE: If the function succeeds, the caller is expected to cleanup
9065    the arrays ADDR_STRING, COND_STRING, and SALS (but not the
9066    array contents).  If the function fails (error() is called), the
9067    caller is expected to cleanups both the ADDR_STRING, COND_STRING,
9068    COND and SALS arrays and each of those arrays contents.  */
9069
9070 static void
9071 create_breakpoints_sal (struct gdbarch *gdbarch,
9072                         struct linespec_result *canonical,
9073                         gdb::unique_xmalloc_ptr<char> cond_string,
9074                         gdb::unique_xmalloc_ptr<char> extra_string,
9075                         enum bptype type, enum bpdisp disposition,
9076                         int thread, int task, int ignore_count,
9077                         const struct breakpoint_ops *ops, int from_tty,
9078                         int enabled, int internal, unsigned flags)
9079 {
9080   if (canonical->pre_expanded)
9081     gdb_assert (canonical->lsals.size () == 1);
9082
9083   for (const auto &lsal : canonical->lsals)
9084     {
9085       /* Note that 'location' can be NULL in the case of a plain
9086          'break', without arguments.  */
9087       event_location_up location
9088         = (canonical->location != NULL
9089            ? copy_event_location (canonical->location.get ()) : NULL);
9090       gdb::unique_xmalloc_ptr<char> filter_string
9091         (lsal.canonical != NULL ? xstrdup (lsal.canonical) : NULL);
9092
9093       create_breakpoint_sal (gdbarch, lsal.sals,
9094                              std::move (location),
9095                              std::move (filter_string),
9096                              std::move (cond_string),
9097                              std::move (extra_string),
9098                              type, disposition,
9099                              thread, task, ignore_count, ops,
9100                              from_tty, enabled, internal, flags,
9101                              canonical->special_display);
9102     }
9103 }
9104
9105 /* Parse LOCATION which is assumed to be a SAL specification possibly
9106    followed by conditionals.  On return, SALS contains an array of SAL
9107    addresses found.  LOCATION points to the end of the SAL (for
9108    linespec locations).
9109
9110    The array and the line spec strings are allocated on the heap, it is
9111    the caller's responsibility to free them.  */
9112
9113 static void
9114 parse_breakpoint_sals (const struct event_location *location,
9115                        struct linespec_result *canonical)
9116 {
9117   struct symtab_and_line cursal;
9118
9119   if (event_location_type (location) == LINESPEC_LOCATION)
9120     {
9121       const char *address = get_linespec_location (location);
9122
9123       if (address == NULL)
9124         {
9125           /* The last displayed codepoint, if it's valid, is our default
9126              breakpoint address.  */
9127           if (last_displayed_sal_is_valid ())
9128             {
9129               /* Set sal's pspace, pc, symtab, and line to the values
9130                  corresponding to the last call to print_frame_info.
9131                  Be sure to reinitialize LINE with NOTCURRENT == 0
9132                  as the breakpoint line number is inappropriate otherwise.
9133                  find_pc_line would adjust PC, re-set it back.  */
9134               symtab_and_line sal = get_last_displayed_sal ();
9135               CORE_ADDR pc = sal.pc;
9136
9137               sal = find_pc_line (pc, 0);
9138
9139               /* "break" without arguments is equivalent to "break *PC"
9140                  where PC is the last displayed codepoint's address.  So
9141                  make sure to set sal.explicit_pc to prevent GDB from
9142                  trying to expand the list of sals to include all other
9143                  instances with the same symtab and line.  */
9144               sal.pc = pc;
9145               sal.explicit_pc = 1;
9146
9147               struct linespec_sals lsal;
9148               lsal.sals = {sal};
9149               lsal.canonical = NULL;
9150
9151               canonical->lsals.push_back (std::move (lsal));
9152               return;
9153             }
9154           else
9155             error (_("No default breakpoint address now."));
9156         }
9157     }
9158
9159   /* Force almost all breakpoints to be in terms of the
9160      current_source_symtab (which is decode_line_1's default).
9161      This should produce the results we want almost all of the
9162      time while leaving default_breakpoint_* alone.
9163
9164      ObjC: However, don't match an Objective-C method name which
9165      may have a '+' or '-' succeeded by a '['.  */
9166   cursal = get_current_source_symtab_and_line ();
9167   if (last_displayed_sal_is_valid ())
9168     {
9169       const char *address = NULL;
9170
9171       if (event_location_type (location) == LINESPEC_LOCATION)
9172         address = get_linespec_location (location);
9173
9174       if (!cursal.symtab
9175           || (address != NULL
9176               && strchr ("+-", address[0]) != NULL
9177               && address[1] != '['))
9178         {
9179           decode_line_full (location, DECODE_LINE_FUNFIRSTLINE, NULL,
9180                             get_last_displayed_symtab (),
9181                             get_last_displayed_line (),
9182                             canonical, NULL, NULL);
9183           return;
9184         }
9185     }
9186
9187   decode_line_full (location, DECODE_LINE_FUNFIRSTLINE, NULL,
9188                     cursal.symtab, cursal.line, canonical, NULL, NULL);
9189 }
9190
9191
9192 /* Convert each SAL into a real PC.  Verify that the PC can be
9193    inserted as a breakpoint.  If it can't throw an error.  */
9194
9195 static void
9196 breakpoint_sals_to_pc (std::vector<symtab_and_line> &sals)
9197 {    
9198   for (auto &sal : sals)
9199     resolve_sal_pc (&sal);
9200 }
9201
9202 /* Fast tracepoints may have restrictions on valid locations.  For
9203    instance, a fast tracepoint using a jump instead of a trap will
9204    likely have to overwrite more bytes than a trap would, and so can
9205    only be placed where the instruction is longer than the jump, or a
9206    multi-instruction sequence does not have a jump into the middle of
9207    it, etc.  */
9208
9209 static void
9210 check_fast_tracepoint_sals (struct gdbarch *gdbarch,
9211                             gdb::array_view<const symtab_and_line> sals)
9212 {
9213   int rslt;
9214   char *msg;
9215   struct cleanup *old_chain;
9216
9217   for (const auto &sal : sals)
9218     {
9219       struct gdbarch *sarch;
9220
9221       sarch = get_sal_arch (sal);
9222       /* We fall back to GDBARCH if there is no architecture
9223          associated with SAL.  */
9224       if (sarch == NULL)
9225         sarch = gdbarch;
9226       rslt = gdbarch_fast_tracepoint_valid_at (sarch, sal.pc, &msg);
9227       old_chain = make_cleanup (xfree, msg);
9228
9229       if (!rslt)
9230         error (_("May not have a fast tracepoint at %s%s"),
9231                paddress (sarch, sal.pc), (msg ? msg : ""));
9232
9233       do_cleanups (old_chain);
9234     }
9235 }
9236
9237 /* Given TOK, a string specification of condition and thread, as
9238    accepted by the 'break' command, extract the condition
9239    string and thread number and set *COND_STRING and *THREAD.
9240    PC identifies the context at which the condition should be parsed.
9241    If no condition is found, *COND_STRING is set to NULL.
9242    If no thread is found, *THREAD is set to -1.  */
9243
9244 static void
9245 find_condition_and_thread (const char *tok, CORE_ADDR pc,
9246                            char **cond_string, int *thread, int *task,
9247                            char **rest)
9248 {
9249   *cond_string = NULL;
9250   *thread = -1;
9251   *task = 0;
9252   *rest = NULL;
9253
9254   while (tok && *tok)
9255     {
9256       const char *end_tok;
9257       int toklen;
9258       const char *cond_start = NULL;
9259       const char *cond_end = NULL;
9260
9261       tok = skip_spaces (tok);
9262
9263       if ((*tok == '"' || *tok == ',') && rest)
9264         {
9265           *rest = savestring (tok, strlen (tok));
9266           return;
9267         }
9268
9269       end_tok = skip_to_space (tok);
9270
9271       toklen = end_tok - tok;
9272
9273       if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
9274         {
9275           tok = cond_start = end_tok + 1;
9276           parse_exp_1 (&tok, pc, block_for_pc (pc), 0);
9277           cond_end = tok;
9278           *cond_string = savestring (cond_start, cond_end - cond_start);
9279         }
9280       else if (toklen >= 1 && strncmp (tok, "thread", toklen) == 0)
9281         {
9282           const char *tmptok;
9283           struct thread_info *thr;
9284
9285           tok = end_tok + 1;
9286           thr = parse_thread_id (tok, &tmptok);
9287           if (tok == tmptok)
9288             error (_("Junk after thread keyword."));
9289           *thread = thr->global_num;
9290           tok = tmptok;
9291         }
9292       else if (toklen >= 1 && strncmp (tok, "task", toklen) == 0)
9293         {
9294           char *tmptok;
9295
9296           tok = end_tok + 1;
9297           *task = strtol (tok, &tmptok, 0);
9298           if (tok == tmptok)
9299             error (_("Junk after task keyword."));
9300           if (!valid_task_id (*task))
9301             error (_("Unknown task %d."), *task);
9302           tok = tmptok;
9303         }
9304       else if (rest)
9305         {
9306           *rest = savestring (tok, strlen (tok));
9307           return;
9308         }
9309       else
9310         error (_("Junk at end of arguments."));
9311     }
9312 }
9313
9314 /* Decode a static tracepoint marker spec.  */
9315
9316 static std::vector<symtab_and_line>
9317 decode_static_tracepoint_spec (const char **arg_p)
9318 {
9319   VEC(static_tracepoint_marker_p) *markers = NULL;
9320   const char *p = &(*arg_p)[3];
9321   const char *endp;
9322   int i;
9323
9324   p = skip_spaces (p);
9325
9326   endp = skip_to_space (p);
9327
9328   std::string marker_str (p, endp - p);
9329
9330   markers = target_static_tracepoint_markers_by_strid (marker_str.c_str ());
9331   if (VEC_empty(static_tracepoint_marker_p, markers))
9332     error (_("No known static tracepoint marker named %s"),
9333            marker_str.c_str ());
9334
9335   std::vector<symtab_and_line> sals;
9336   sals.reserve (VEC_length(static_tracepoint_marker_p, markers));
9337
9338   for (i = 0; i < VEC_length(static_tracepoint_marker_p, markers); i++)
9339     {
9340       struct static_tracepoint_marker *marker;
9341
9342       marker = VEC_index (static_tracepoint_marker_p, markers, i);
9343
9344       symtab_and_line sal = find_pc_line (marker->address, 0);
9345       sal.pc = marker->address;
9346       sals.push_back (sal);
9347
9348       release_static_tracepoint_marker (marker);
9349     }
9350
9351   *arg_p = endp;
9352   return sals;
9353 }
9354
9355 /* See breakpoint.h.  */
9356
9357 int
9358 create_breakpoint (struct gdbarch *gdbarch,
9359                    const struct event_location *location,
9360                    const char *cond_string,
9361                    int thread, const char *extra_string,
9362                    int parse_extra,
9363                    int tempflag, enum bptype type_wanted,
9364                    int ignore_count,
9365                    enum auto_boolean pending_break_support,
9366                    const struct breakpoint_ops *ops,
9367                    int from_tty, int enabled, int internal,
9368                    unsigned flags)
9369 {
9370   struct linespec_result canonical;
9371   struct cleanup *bkpt_chain = NULL;
9372   int pending = 0;
9373   int task = 0;
9374   int prev_bkpt_count = breakpoint_count;
9375
9376   gdb_assert (ops != NULL);
9377
9378   /* If extra_string isn't useful, set it to NULL.  */
9379   if (extra_string != NULL && *extra_string == '\0')
9380     extra_string = NULL;
9381
9382   TRY
9383     {
9384       ops->create_sals_from_location (location, &canonical, type_wanted);
9385     }
9386   CATCH (e, RETURN_MASK_ERROR)
9387     {
9388       /* If caller is interested in rc value from parse, set
9389          value.  */
9390       if (e.error == NOT_FOUND_ERROR)
9391         {
9392           /* If pending breakpoint support is turned off, throw
9393              error.  */
9394
9395           if (pending_break_support == AUTO_BOOLEAN_FALSE)
9396             throw_exception (e);
9397
9398           exception_print (gdb_stderr, e);
9399
9400           /* If pending breakpoint support is auto query and the user
9401              selects no, then simply return the error code.  */
9402           if (pending_break_support == AUTO_BOOLEAN_AUTO
9403               && !nquery (_("Make %s pending on future shared library load? "),
9404                           bptype_string (type_wanted)))
9405             return 0;
9406
9407           /* At this point, either the user was queried about setting
9408              a pending breakpoint and selected yes, or pending
9409              breakpoint behavior is on and thus a pending breakpoint
9410              is defaulted on behalf of the user.  */
9411           pending = 1;
9412         }
9413       else
9414         throw_exception (e);
9415     }
9416   END_CATCH
9417
9418   if (!pending && canonical.lsals.empty ())
9419     return 0;
9420
9421   /* ----------------------------- SNIP -----------------------------
9422      Anything added to the cleanup chain beyond this point is assumed
9423      to be part of a breakpoint.  If the breakpoint create succeeds
9424      then the memory is not reclaimed.  */
9425   bkpt_chain = make_cleanup (null_cleanup, 0);
9426
9427   /* Resolve all line numbers to PC's and verify that the addresses
9428      are ok for the target.  */
9429   if (!pending)
9430     {
9431       for (auto &lsal : canonical.lsals)
9432         breakpoint_sals_to_pc (lsal.sals);
9433     }
9434
9435   /* Fast tracepoints may have additional restrictions on location.  */
9436   if (!pending && type_wanted == bp_fast_tracepoint)
9437     {
9438       for (const auto &lsal : canonical.lsals)
9439         check_fast_tracepoint_sals (gdbarch, lsal.sals);
9440     }
9441
9442   /* Verify that condition can be parsed, before setting any
9443      breakpoints.  Allocate a separate condition expression for each
9444      breakpoint.  */
9445   if (!pending)
9446     {
9447       gdb::unique_xmalloc_ptr<char> cond_string_copy;
9448       gdb::unique_xmalloc_ptr<char> extra_string_copy;
9449
9450       if (parse_extra)
9451         {
9452           char *rest;
9453           char *cond;
9454
9455           const linespec_sals &lsal = canonical.lsals[0];
9456
9457           /* Here we only parse 'arg' to separate condition
9458              from thread number, so parsing in context of first
9459              sal is OK.  When setting the breakpoint we'll
9460              re-parse it in context of each sal.  */
9461
9462           find_condition_and_thread (extra_string, lsal.sals[0].pc,
9463                                      &cond, &thread, &task, &rest);
9464           cond_string_copy.reset (cond);
9465           extra_string_copy.reset (rest);
9466         }
9467       else
9468         {
9469           if (type_wanted != bp_dprintf
9470               && extra_string != NULL && *extra_string != '\0')
9471                 error (_("Garbage '%s' at end of location"), extra_string);
9472
9473           /* Create a private copy of condition string.  */
9474           if (cond_string)
9475             cond_string_copy.reset (xstrdup (cond_string));
9476           /* Create a private copy of any extra string.  */
9477           if (extra_string)
9478             extra_string_copy.reset (xstrdup (extra_string));
9479         }
9480
9481       ops->create_breakpoints_sal (gdbarch, &canonical,
9482                                    std::move (cond_string_copy),
9483                                    std::move (extra_string_copy),
9484                                    type_wanted,
9485                                    tempflag ? disp_del : disp_donttouch,
9486                                    thread, task, ignore_count, ops,
9487                                    from_tty, enabled, internal, flags);
9488     }
9489   else
9490     {
9491       std::unique_ptr <breakpoint> b = new_breakpoint_from_type (type_wanted);
9492
9493       init_raw_breakpoint_without_location (b.get (), gdbarch, type_wanted, ops);
9494       b->location = copy_event_location (location);
9495
9496       if (parse_extra)
9497         b->cond_string = NULL;
9498       else
9499         {
9500           /* Create a private copy of condition string.  */
9501           b->cond_string = cond_string != NULL ? xstrdup (cond_string) : NULL;
9502           b->thread = thread;
9503         }
9504
9505       /* Create a private copy of any extra string.  */
9506       b->extra_string = extra_string != NULL ? xstrdup (extra_string) : NULL;
9507       b->ignore_count = ignore_count;
9508       b->disposition = tempflag ? disp_del : disp_donttouch;
9509       b->condition_not_parsed = 1;
9510       b->enable_state = enabled ? bp_enabled : bp_disabled;
9511       if ((type_wanted != bp_breakpoint
9512            && type_wanted != bp_hardware_breakpoint) || thread != -1)
9513         b->pspace = current_program_space;
9514
9515       install_breakpoint (internal, std::move (b), 0);
9516     }
9517   
9518   if (canonical.lsals.size () > 1)
9519     {
9520       warning (_("Multiple breakpoints were set.\nUse the "
9521                  "\"delete\" command to delete unwanted breakpoints."));
9522       prev_breakpoint_count = prev_bkpt_count;
9523     }
9524
9525   /* That's it.  Discard the cleanups for data inserted into the
9526      breakpoint.  */
9527   discard_cleanups (bkpt_chain);
9528
9529   /* error call may happen here - have BKPT_CHAIN already discarded.  */
9530   update_global_location_list (UGLL_MAY_INSERT);
9531
9532   return 1;
9533 }
9534
9535 /* Set a breakpoint.
9536    ARG is a string describing breakpoint address,
9537    condition, and thread.
9538    FLAG specifies if a breakpoint is hardware on,
9539    and if breakpoint is temporary, using BP_HARDWARE_FLAG
9540    and BP_TEMPFLAG.  */
9541
9542 static void
9543 break_command_1 (const char *arg, int flag, int from_tty)
9544 {
9545   int tempflag = flag & BP_TEMPFLAG;
9546   enum bptype type_wanted = (flag & BP_HARDWAREFLAG
9547                              ? bp_hardware_breakpoint
9548                              : bp_breakpoint);
9549   struct breakpoint_ops *ops;
9550
9551   event_location_up location = string_to_event_location (&arg, current_language);
9552
9553   /* Matching breakpoints on probes.  */
9554   if (location != NULL
9555       && event_location_type (location.get ()) == PROBE_LOCATION)
9556     ops = &bkpt_probe_breakpoint_ops;
9557   else
9558     ops = &bkpt_breakpoint_ops;
9559
9560   create_breakpoint (get_current_arch (),
9561                      location.get (),
9562                      NULL, 0, arg, 1 /* parse arg */,
9563                      tempflag, type_wanted,
9564                      0 /* Ignore count */,
9565                      pending_break_support,
9566                      ops,
9567                      from_tty,
9568                      1 /* enabled */,
9569                      0 /* internal */,
9570                      0);
9571 }
9572
9573 /* Helper function for break_command_1 and disassemble_command.  */
9574
9575 void
9576 resolve_sal_pc (struct symtab_and_line *sal)
9577 {
9578   CORE_ADDR pc;
9579
9580   if (sal->pc == 0 && sal->symtab != NULL)
9581     {
9582       if (!find_line_pc (sal->symtab, sal->line, &pc))
9583         error (_("No line %d in file \"%s\"."),
9584                sal->line, symtab_to_filename_for_display (sal->symtab));
9585       sal->pc = pc;
9586
9587       /* If this SAL corresponds to a breakpoint inserted using a line
9588          number, then skip the function prologue if necessary.  */
9589       if (sal->explicit_line)
9590         skip_prologue_sal (sal);
9591     }
9592
9593   if (sal->section == 0 && sal->symtab != NULL)
9594     {
9595       const struct blockvector *bv;
9596       const struct block *b;
9597       struct symbol *sym;
9598
9599       bv = blockvector_for_pc_sect (sal->pc, 0, &b,
9600                                     SYMTAB_COMPUNIT (sal->symtab));
9601       if (bv != NULL)
9602         {
9603           sym = block_linkage_function (b);
9604           if (sym != NULL)
9605             {
9606               fixup_symbol_section (sym, SYMTAB_OBJFILE (sal->symtab));
9607               sal->section = SYMBOL_OBJ_SECTION (SYMTAB_OBJFILE (sal->symtab),
9608                                                  sym);
9609             }
9610           else
9611             {
9612               /* It really is worthwhile to have the section, so we'll
9613                  just have to look harder. This case can be executed
9614                  if we have line numbers but no functions (as can
9615                  happen in assembly source).  */
9616
9617               scoped_restore_current_pspace_and_thread restore_pspace_thread;
9618               switch_to_program_space_and_thread (sal->pspace);
9619
9620               bound_minimal_symbol msym = lookup_minimal_symbol_by_pc (sal->pc);
9621               if (msym.minsym)
9622                 sal->section = MSYMBOL_OBJ_SECTION (msym.objfile, msym.minsym);
9623             }
9624         }
9625     }
9626 }
9627
9628 void
9629 break_command (const char *arg, int from_tty)
9630 {
9631   break_command_1 (arg, 0, from_tty);
9632 }
9633
9634 void
9635 tbreak_command (const char *arg, int from_tty)
9636 {
9637   break_command_1 (arg, BP_TEMPFLAG, from_tty);
9638 }
9639
9640 static void
9641 hbreak_command (const char *arg, int from_tty)
9642 {
9643   break_command_1 (arg, BP_HARDWAREFLAG, from_tty);
9644 }
9645
9646 static void
9647 thbreak_command (const char *arg, int from_tty)
9648 {
9649   break_command_1 (arg, (BP_TEMPFLAG | BP_HARDWAREFLAG), from_tty);
9650 }
9651
9652 static void
9653 stop_command (const char *arg, int from_tty)
9654 {
9655   printf_filtered (_("Specify the type of breakpoint to set.\n\
9656 Usage: stop in <function | address>\n\
9657        stop at <line>\n"));
9658 }
9659
9660 static void
9661 stopin_command (const char *arg, int from_tty)
9662 {
9663   int badInput = 0;
9664
9665   if (arg == (char *) NULL)
9666     badInput = 1;
9667   else if (*arg != '*')
9668     {
9669       const char *argptr = arg;
9670       int hasColon = 0;
9671
9672       /* Look for a ':'.  If this is a line number specification, then
9673          say it is bad, otherwise, it should be an address or
9674          function/method name.  */
9675       while (*argptr && !hasColon)
9676         {
9677           hasColon = (*argptr == ':');
9678           argptr++;
9679         }
9680
9681       if (hasColon)
9682         badInput = (*argptr != ':');    /* Not a class::method */
9683       else
9684         badInput = isdigit (*arg);      /* a simple line number */
9685     }
9686
9687   if (badInput)
9688     printf_filtered (_("Usage: stop in <function | address>\n"));
9689   else
9690     break_command_1 (arg, 0, from_tty);
9691 }
9692
9693 static void
9694 stopat_command (const char *arg, int from_tty)
9695 {
9696   int badInput = 0;
9697
9698   if (arg == (char *) NULL || *arg == '*')      /* no line number */
9699     badInput = 1;
9700   else
9701     {
9702       const char *argptr = arg;
9703       int hasColon = 0;
9704
9705       /* Look for a ':'.  If there is a '::' then get out, otherwise
9706          it is probably a line number.  */
9707       while (*argptr && !hasColon)
9708         {
9709           hasColon = (*argptr == ':');
9710           argptr++;
9711         }
9712
9713       if (hasColon)
9714         badInput = (*argptr == ':');    /* we have class::method */
9715       else
9716         badInput = !isdigit (*arg);     /* not a line number */
9717     }
9718
9719   if (badInput)
9720     printf_filtered (_("Usage: stop at <line>\n"));
9721   else
9722     break_command_1 (arg, 0, from_tty);
9723 }
9724
9725 /* The dynamic printf command is mostly like a regular breakpoint, but
9726    with a prewired command list consisting of a single output command,
9727    built from extra arguments supplied on the dprintf command
9728    line.  */
9729
9730 static void
9731 dprintf_command (const char *arg, int from_tty)
9732 {
9733   event_location_up location = string_to_event_location (&arg, current_language);
9734
9735   /* If non-NULL, ARG should have been advanced past the location;
9736      the next character must be ','.  */
9737   if (arg != NULL)
9738     {
9739       if (arg[0] != ',' || arg[1] == '\0')
9740         error (_("Format string required"));
9741       else
9742         {
9743           /* Skip the comma.  */
9744           ++arg;
9745         }
9746     }
9747
9748   create_breakpoint (get_current_arch (),
9749                      location.get (),
9750                      NULL, 0, arg, 1 /* parse arg */,
9751                      0, bp_dprintf,
9752                      0 /* Ignore count */,
9753                      pending_break_support,
9754                      &dprintf_breakpoint_ops,
9755                      from_tty,
9756                      1 /* enabled */,
9757                      0 /* internal */,
9758                      0);
9759 }
9760
9761 static void
9762 agent_printf_command (const char *arg, int from_tty)
9763 {
9764   error (_("May only run agent-printf on the target"));
9765 }
9766
9767 /* Implement the "breakpoint_hit" breakpoint_ops method for
9768    ranged breakpoints.  */
9769
9770 static int
9771 breakpoint_hit_ranged_breakpoint (const struct bp_location *bl,
9772                                   const address_space *aspace,
9773                                   CORE_ADDR bp_addr,
9774                                   const struct target_waitstatus *ws)
9775 {
9776   if (ws->kind != TARGET_WAITKIND_STOPPED
9777       || ws->value.sig != GDB_SIGNAL_TRAP)
9778     return 0;
9779
9780   return breakpoint_address_match_range (bl->pspace->aspace, bl->address,
9781                                          bl->length, aspace, bp_addr);
9782 }
9783
9784 /* Implement the "resources_needed" breakpoint_ops method for
9785    ranged breakpoints.  */
9786
9787 static int
9788 resources_needed_ranged_breakpoint (const struct bp_location *bl)
9789 {
9790   return target_ranged_break_num_registers ();
9791 }
9792
9793 /* Implement the "print_it" breakpoint_ops method for
9794    ranged breakpoints.  */
9795
9796 static enum print_stop_action
9797 print_it_ranged_breakpoint (bpstat bs)
9798 {
9799   struct breakpoint *b = bs->breakpoint_at;
9800   struct bp_location *bl = b->loc;
9801   struct ui_out *uiout = current_uiout;
9802
9803   gdb_assert (b->type == bp_hardware_breakpoint);
9804
9805   /* Ranged breakpoints have only one location.  */
9806   gdb_assert (bl && bl->next == NULL);
9807
9808   annotate_breakpoint (b->number);
9809
9810   maybe_print_thread_hit_breakpoint (uiout);
9811
9812   if (b->disposition == disp_del)
9813     uiout->text ("Temporary ranged breakpoint ");
9814   else
9815     uiout->text ("Ranged breakpoint ");
9816   if (uiout->is_mi_like_p ())
9817     {
9818       uiout->field_string ("reason",
9819                       async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
9820       uiout->field_string ("disp", bpdisp_text (b->disposition));
9821     }
9822   uiout->field_int ("bkptno", b->number);
9823   uiout->text (", ");
9824
9825   return PRINT_SRC_AND_LOC;
9826 }
9827
9828 /* Implement the "print_one" breakpoint_ops method for
9829    ranged breakpoints.  */
9830
9831 static void
9832 print_one_ranged_breakpoint (struct breakpoint *b,
9833                              struct bp_location **last_loc)
9834 {
9835   struct bp_location *bl = b->loc;
9836   struct value_print_options opts;
9837   struct ui_out *uiout = current_uiout;
9838
9839   /* Ranged breakpoints have only one location.  */
9840   gdb_assert (bl && bl->next == NULL);
9841
9842   get_user_print_options (&opts);
9843
9844   if (opts.addressprint)
9845     /* We don't print the address range here, it will be printed later
9846        by print_one_detail_ranged_breakpoint.  */
9847     uiout->field_skip ("addr");
9848   annotate_field (5);
9849   print_breakpoint_location (b, bl);
9850   *last_loc = bl;
9851 }
9852
9853 /* Implement the "print_one_detail" breakpoint_ops method for
9854    ranged breakpoints.  */
9855
9856 static void
9857 print_one_detail_ranged_breakpoint (const struct breakpoint *b,
9858                                     struct ui_out *uiout)
9859 {
9860   CORE_ADDR address_start, address_end;
9861   struct bp_location *bl = b->loc;
9862   string_file stb;
9863
9864   gdb_assert (bl);
9865
9866   address_start = bl->address;
9867   address_end = address_start + bl->length - 1;
9868
9869   uiout->text ("\taddress range: ");
9870   stb.printf ("[%s, %s]",
9871               print_core_address (bl->gdbarch, address_start),
9872               print_core_address (bl->gdbarch, address_end));
9873   uiout->field_stream ("addr", stb);
9874   uiout->text ("\n");
9875 }
9876
9877 /* Implement the "print_mention" breakpoint_ops method for
9878    ranged breakpoints.  */
9879
9880 static void
9881 print_mention_ranged_breakpoint (struct breakpoint *b)
9882 {
9883   struct bp_location *bl = b->loc;
9884   struct ui_out *uiout = current_uiout;
9885
9886   gdb_assert (bl);
9887   gdb_assert (b->type == bp_hardware_breakpoint);
9888
9889   if (uiout->is_mi_like_p ())
9890     return;
9891
9892   printf_filtered (_("Hardware assisted ranged breakpoint %d from %s to %s."),
9893                    b->number, paddress (bl->gdbarch, bl->address),
9894                    paddress (bl->gdbarch, bl->address + bl->length - 1));
9895 }
9896
9897 /* Implement the "print_recreate" breakpoint_ops method for
9898    ranged breakpoints.  */
9899
9900 static void
9901 print_recreate_ranged_breakpoint (struct breakpoint *b, struct ui_file *fp)
9902 {
9903   fprintf_unfiltered (fp, "break-range %s, %s",
9904                       event_location_to_string (b->location.get ()),
9905                       event_location_to_string (b->location_range_end.get ()));
9906   print_recreate_thread (b, fp);
9907 }
9908
9909 /* The breakpoint_ops structure to be used in ranged breakpoints.  */
9910
9911 static struct breakpoint_ops ranged_breakpoint_ops;
9912
9913 /* Find the address where the end of the breakpoint range should be
9914    placed, given the SAL of the end of the range.  This is so that if
9915    the user provides a line number, the end of the range is set to the
9916    last instruction of the given line.  */
9917
9918 static CORE_ADDR
9919 find_breakpoint_range_end (struct symtab_and_line sal)
9920 {
9921   CORE_ADDR end;
9922
9923   /* If the user provided a PC value, use it.  Otherwise,
9924      find the address of the end of the given location.  */
9925   if (sal.explicit_pc)
9926     end = sal.pc;
9927   else
9928     {
9929       int ret;
9930       CORE_ADDR start;
9931
9932       ret = find_line_pc_range (sal, &start, &end);
9933       if (!ret)
9934         error (_("Could not find location of the end of the range."));
9935
9936       /* find_line_pc_range returns the start of the next line.  */
9937       end--;
9938     }
9939
9940   return end;
9941 }
9942
9943 /* Implement the "break-range" CLI command.  */
9944
9945 static void
9946 break_range_command (const char *arg, int from_tty)
9947 {
9948   const char *arg_start;
9949   struct linespec_result canonical_start, canonical_end;
9950   int bp_count, can_use_bp, length;
9951   CORE_ADDR end;
9952   struct breakpoint *b;
9953
9954   /* We don't support software ranged breakpoints.  */
9955   if (target_ranged_break_num_registers () < 0)
9956     error (_("This target does not support hardware ranged breakpoints."));
9957
9958   bp_count = hw_breakpoint_used_count ();
9959   bp_count += target_ranged_break_num_registers ();
9960   can_use_bp = target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
9961                                                    bp_count, 0);
9962   if (can_use_bp < 0)
9963     error (_("Hardware breakpoints used exceeds limit."));
9964
9965   arg = skip_spaces (arg);
9966   if (arg == NULL || arg[0] == '\0')
9967     error(_("No address range specified."));
9968
9969   arg_start = arg;
9970   event_location_up start_location = string_to_event_location (&arg,
9971                                                                current_language);
9972   parse_breakpoint_sals (start_location.get (), &canonical_start);
9973
9974   if (arg[0] != ',')
9975     error (_("Too few arguments."));
9976   else if (canonical_start.lsals.empty ())
9977     error (_("Could not find location of the beginning of the range."));
9978
9979   const linespec_sals &lsal_start = canonical_start.lsals[0];
9980
9981   if (canonical_start.lsals.size () > 1
9982       || lsal_start.sals.size () != 1)
9983     error (_("Cannot create a ranged breakpoint with multiple locations."));
9984
9985   const symtab_and_line &sal_start = lsal_start.sals[0];
9986   std::string addr_string_start (arg_start, arg - arg_start);
9987
9988   arg++;        /* Skip the comma.  */
9989   arg = skip_spaces (arg);
9990
9991   /* Parse the end location.  */
9992
9993   arg_start = arg;
9994
9995   /* We call decode_line_full directly here instead of using
9996      parse_breakpoint_sals because we need to specify the start location's
9997      symtab and line as the default symtab and line for the end of the
9998      range.  This makes it possible to have ranges like "foo.c:27, +14",
9999      where +14 means 14 lines from the start location.  */
10000   event_location_up end_location = string_to_event_location (&arg,
10001                                                              current_language);
10002   decode_line_full (end_location.get (), DECODE_LINE_FUNFIRSTLINE, NULL,
10003                     sal_start.symtab, sal_start.line,
10004                     &canonical_end, NULL, NULL);
10005
10006   if (canonical_end.lsals.empty ())
10007     error (_("Could not find location of the end of the range."));
10008
10009   const linespec_sals &lsal_end = canonical_end.lsals[0];
10010   if (canonical_end.lsals.size () > 1
10011       || lsal_end.sals.size () != 1)
10012     error (_("Cannot create a ranged breakpoint with multiple locations."));
10013
10014   const symtab_and_line &sal_end = lsal_end.sals[0];
10015
10016   end = find_breakpoint_range_end (sal_end);
10017   if (sal_start.pc > end)
10018     error (_("Invalid address range, end precedes start."));
10019
10020   length = end - sal_start.pc + 1;
10021   if (length < 0)
10022     /* Length overflowed.  */
10023     error (_("Address range too large."));
10024   else if (length == 1)
10025     {
10026       /* This range is simple enough to be handled by
10027          the `hbreak' command.  */
10028       hbreak_command (&addr_string_start[0], 1);
10029
10030       return;
10031     }
10032
10033   /* Now set up the breakpoint.  */
10034   b = set_raw_breakpoint (get_current_arch (), sal_start,
10035                           bp_hardware_breakpoint, &ranged_breakpoint_ops);
10036   set_breakpoint_count (breakpoint_count + 1);
10037   b->number = breakpoint_count;
10038   b->disposition = disp_donttouch;
10039   b->location = std::move (start_location);
10040   b->location_range_end = std::move (end_location);
10041   b->loc->length = length;
10042
10043   mention (b);
10044   observer_notify_breakpoint_created (b);
10045   update_global_location_list (UGLL_MAY_INSERT);
10046 }
10047
10048 /*  Return non-zero if EXP is verified as constant.  Returned zero
10049     means EXP is variable.  Also the constant detection may fail for
10050     some constant expressions and in such case still falsely return
10051     zero.  */
10052
10053 static int
10054 watchpoint_exp_is_const (const struct expression *exp)
10055 {
10056   int i = exp->nelts;
10057
10058   while (i > 0)
10059     {
10060       int oplenp, argsp;
10061
10062       /* We are only interested in the descriptor of each element.  */
10063       operator_length (exp, i, &oplenp, &argsp);
10064       i -= oplenp;
10065
10066       switch (exp->elts[i].opcode)
10067         {
10068         case BINOP_ADD:
10069         case BINOP_SUB:
10070         case BINOP_MUL:
10071         case BINOP_DIV:
10072         case BINOP_REM:
10073         case BINOP_MOD:
10074         case BINOP_LSH:
10075         case BINOP_RSH:
10076         case BINOP_LOGICAL_AND:
10077         case BINOP_LOGICAL_OR:
10078         case BINOP_BITWISE_AND:
10079         case BINOP_BITWISE_IOR:
10080         case BINOP_BITWISE_XOR:
10081         case BINOP_EQUAL:
10082         case BINOP_NOTEQUAL:
10083         case BINOP_LESS:
10084         case BINOP_GTR:
10085         case BINOP_LEQ:
10086         case BINOP_GEQ:
10087         case BINOP_REPEAT:
10088         case BINOP_COMMA:
10089         case BINOP_EXP:
10090         case BINOP_MIN:
10091         case BINOP_MAX:
10092         case BINOP_INTDIV:
10093         case BINOP_CONCAT:
10094         case TERNOP_COND:
10095         case TERNOP_SLICE:
10096
10097         case OP_LONG:
10098         case OP_FLOAT:
10099         case OP_LAST:
10100         case OP_COMPLEX:
10101         case OP_STRING:
10102         case OP_ARRAY:
10103         case OP_TYPE:
10104         case OP_TYPEOF:
10105         case OP_DECLTYPE:
10106         case OP_TYPEID:
10107         case OP_NAME:
10108         case OP_OBJC_NSSTRING:
10109
10110         case UNOP_NEG:
10111         case UNOP_LOGICAL_NOT:
10112         case UNOP_COMPLEMENT:
10113         case UNOP_ADDR:
10114         case UNOP_HIGH:
10115         case UNOP_CAST:
10116
10117         case UNOP_CAST_TYPE:
10118         case UNOP_REINTERPRET_CAST:
10119         case UNOP_DYNAMIC_CAST:
10120           /* Unary, binary and ternary operators: We have to check
10121              their operands.  If they are constant, then so is the
10122              result of that operation.  For instance, if A and B are
10123              determined to be constants, then so is "A + B".
10124
10125              UNOP_IND is one exception to the rule above, because the
10126              value of *ADDR is not necessarily a constant, even when
10127              ADDR is.  */
10128           break;
10129
10130         case OP_VAR_VALUE:
10131           /* Check whether the associated symbol is a constant.
10132
10133              We use SYMBOL_CLASS rather than TYPE_CONST because it's
10134              possible that a buggy compiler could mark a variable as
10135              constant even when it is not, and TYPE_CONST would return
10136              true in this case, while SYMBOL_CLASS wouldn't.
10137
10138              We also have to check for function symbols because they
10139              are always constant.  */
10140           {
10141             struct symbol *s = exp->elts[i + 2].symbol;
10142
10143             if (SYMBOL_CLASS (s) != LOC_BLOCK
10144                 && SYMBOL_CLASS (s) != LOC_CONST
10145                 && SYMBOL_CLASS (s) != LOC_CONST_BYTES)
10146               return 0;
10147             break;
10148           }
10149
10150         /* The default action is to return 0 because we are using
10151            the optimistic approach here: If we don't know something,
10152            then it is not a constant.  */
10153         default:
10154           return 0;
10155         }
10156     }
10157
10158   return 1;
10159 }
10160
10161 /* Watchpoint destructor.  */
10162
10163 watchpoint::~watchpoint ()
10164 {
10165   xfree (this->exp_string);
10166   xfree (this->exp_string_reparse);
10167   value_free (this->val);
10168 }
10169
10170 /* Implement the "re_set" breakpoint_ops method for watchpoints.  */
10171
10172 static void
10173 re_set_watchpoint (struct breakpoint *b)
10174 {
10175   struct watchpoint *w = (struct watchpoint *) b;
10176
10177   /* Watchpoint can be either on expression using entirely global
10178      variables, or it can be on local variables.
10179
10180      Watchpoints of the first kind are never auto-deleted, and even
10181      persist across program restarts.  Since they can use variables
10182      from shared libraries, we need to reparse expression as libraries
10183      are loaded and unloaded.
10184
10185      Watchpoints on local variables can also change meaning as result
10186      of solib event.  For example, if a watchpoint uses both a local
10187      and a global variables in expression, it's a local watchpoint,
10188      but unloading of a shared library will make the expression
10189      invalid.  This is not a very common use case, but we still
10190      re-evaluate expression, to avoid surprises to the user.
10191
10192      Note that for local watchpoints, we re-evaluate it only if
10193      watchpoints frame id is still valid.  If it's not, it means the
10194      watchpoint is out of scope and will be deleted soon.  In fact,
10195      I'm not sure we'll ever be called in this case.
10196
10197      If a local watchpoint's frame id is still valid, then
10198      w->exp_valid_block is likewise valid, and we can safely use it.
10199
10200      Don't do anything about disabled watchpoints, since they will be
10201      reevaluated again when enabled.  */
10202   update_watchpoint (w, 1 /* reparse */);
10203 }
10204
10205 /* Implement the "insert" breakpoint_ops method for hardware watchpoints.  */
10206
10207 static int
10208 insert_watchpoint (struct bp_location *bl)
10209 {
10210   struct watchpoint *w = (struct watchpoint *) bl->owner;
10211   int length = w->exact ? 1 : bl->length;
10212
10213   return target_insert_watchpoint (bl->address, length, bl->watchpoint_type,
10214                                    w->cond_exp.get ());
10215 }
10216
10217 /* Implement the "remove" breakpoint_ops method for hardware watchpoints.  */
10218
10219 static int
10220 remove_watchpoint (struct bp_location *bl, enum remove_bp_reason reason)
10221 {
10222   struct watchpoint *w = (struct watchpoint *) bl->owner;
10223   int length = w->exact ? 1 : bl->length;
10224
10225   return target_remove_watchpoint (bl->address, length, bl->watchpoint_type,
10226                                    w->cond_exp.get ());
10227 }
10228
10229 static int
10230 breakpoint_hit_watchpoint (const struct bp_location *bl,
10231                            const address_space *aspace, CORE_ADDR bp_addr,
10232                            const struct target_waitstatus *ws)
10233 {
10234   struct breakpoint *b = bl->owner;
10235   struct watchpoint *w = (struct watchpoint *) b;
10236
10237   /* Continuable hardware watchpoints are treated as non-existent if the
10238      reason we stopped wasn't a hardware watchpoint (we didn't stop on
10239      some data address).  Otherwise gdb won't stop on a break instruction
10240      in the code (not from a breakpoint) when a hardware watchpoint has
10241      been defined.  Also skip watchpoints which we know did not trigger
10242      (did not match the data address).  */
10243   if (is_hardware_watchpoint (b)
10244       && w->watchpoint_triggered == watch_triggered_no)
10245     return 0;
10246
10247   return 1;
10248 }
10249
10250 static void
10251 check_status_watchpoint (bpstat bs)
10252 {
10253   gdb_assert (is_watchpoint (bs->breakpoint_at));
10254
10255   bpstat_check_watchpoint (bs);
10256 }
10257
10258 /* Implement the "resources_needed" breakpoint_ops method for
10259    hardware watchpoints.  */
10260
10261 static int
10262 resources_needed_watchpoint (const struct bp_location *bl)
10263 {
10264   struct watchpoint *w = (struct watchpoint *) bl->owner;
10265   int length = w->exact? 1 : bl->length;
10266
10267   return target_region_ok_for_hw_watchpoint (bl->address, length);
10268 }
10269
10270 /* Implement the "works_in_software_mode" breakpoint_ops method for
10271    hardware watchpoints.  */
10272
10273 static int
10274 works_in_software_mode_watchpoint (const struct breakpoint *b)
10275 {
10276   /* Read and access watchpoints only work with hardware support.  */
10277   return b->type == bp_watchpoint || b->type == bp_hardware_watchpoint;
10278 }
10279
10280 static enum print_stop_action
10281 print_it_watchpoint (bpstat bs)
10282 {
10283   struct breakpoint *b;
10284   enum print_stop_action result;
10285   struct watchpoint *w;
10286   struct ui_out *uiout = current_uiout;
10287
10288   gdb_assert (bs->bp_location_at != NULL);
10289
10290   b = bs->breakpoint_at;
10291   w = (struct watchpoint *) b;
10292
10293   annotate_watchpoint (b->number);
10294   maybe_print_thread_hit_breakpoint (uiout);
10295
10296   string_file stb;
10297
10298   gdb::optional<ui_out_emit_tuple> tuple_emitter;
10299   switch (b->type)
10300     {
10301     case bp_watchpoint:
10302     case bp_hardware_watchpoint:
10303       if (uiout->is_mi_like_p ())
10304         uiout->field_string
10305           ("reason", async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
10306       mention (b);
10307       tuple_emitter.emplace (uiout, "value");
10308       uiout->text ("\nOld value = ");
10309       watchpoint_value_print (bs->old_val, &stb);
10310       uiout->field_stream ("old", stb);
10311       uiout->text ("\nNew value = ");
10312       watchpoint_value_print (w->val, &stb);
10313       uiout->field_stream ("new", stb);
10314       uiout->text ("\n");
10315       /* More than one watchpoint may have been triggered.  */
10316       result = PRINT_UNKNOWN;
10317       break;
10318
10319     case bp_read_watchpoint:
10320       if (uiout->is_mi_like_p ())
10321         uiout->field_string
10322           ("reason", async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
10323       mention (b);
10324       tuple_emitter.emplace (uiout, "value");
10325       uiout->text ("\nValue = ");
10326       watchpoint_value_print (w->val, &stb);
10327       uiout->field_stream ("value", stb);
10328       uiout->text ("\n");
10329       result = PRINT_UNKNOWN;
10330       break;
10331
10332     case bp_access_watchpoint:
10333       if (bs->old_val != NULL)
10334         {
10335           if (uiout->is_mi_like_p ())
10336             uiout->field_string
10337               ("reason",
10338                async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10339           mention (b);
10340           tuple_emitter.emplace (uiout, "value");
10341           uiout->text ("\nOld value = ");
10342           watchpoint_value_print (bs->old_val, &stb);
10343           uiout->field_stream ("old", stb);
10344           uiout->text ("\nNew value = ");
10345         }
10346       else
10347         {
10348           mention (b);
10349           if (uiout->is_mi_like_p ())
10350             uiout->field_string
10351               ("reason",
10352                async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10353           tuple_emitter.emplace (uiout, "value");
10354           uiout->text ("\nValue = ");
10355         }
10356       watchpoint_value_print (w->val, &stb);
10357       uiout->field_stream ("new", stb);
10358       uiout->text ("\n");
10359       result = PRINT_UNKNOWN;
10360       break;
10361     default:
10362       result = PRINT_UNKNOWN;
10363     }
10364
10365   return result;
10366 }
10367
10368 /* Implement the "print_mention" breakpoint_ops method for hardware
10369    watchpoints.  */
10370
10371 static void
10372 print_mention_watchpoint (struct breakpoint *b)
10373 {
10374   struct watchpoint *w = (struct watchpoint *) b;
10375   struct ui_out *uiout = current_uiout;
10376   const char *tuple_name;
10377
10378   switch (b->type)
10379     {
10380     case bp_watchpoint:
10381       uiout->text ("Watchpoint ");
10382       tuple_name = "wpt";
10383       break;
10384     case bp_hardware_watchpoint:
10385       uiout->text ("Hardware watchpoint ");
10386       tuple_name = "wpt";
10387       break;
10388     case bp_read_watchpoint:
10389       uiout->text ("Hardware read watchpoint ");
10390       tuple_name = "hw-rwpt";
10391       break;
10392     case bp_access_watchpoint:
10393       uiout->text ("Hardware access (read/write) watchpoint ");
10394       tuple_name = "hw-awpt";
10395       break;
10396     default:
10397       internal_error (__FILE__, __LINE__,
10398                       _("Invalid hardware watchpoint type."));
10399     }
10400
10401   ui_out_emit_tuple tuple_emitter (uiout, tuple_name);
10402   uiout->field_int ("number", b->number);
10403   uiout->text (": ");
10404   uiout->field_string ("exp", w->exp_string);
10405 }
10406
10407 /* Implement the "print_recreate" breakpoint_ops method for
10408    watchpoints.  */
10409
10410 static void
10411 print_recreate_watchpoint (struct breakpoint *b, struct ui_file *fp)
10412 {
10413   struct watchpoint *w = (struct watchpoint *) b;
10414
10415   switch (b->type)
10416     {
10417     case bp_watchpoint:
10418     case bp_hardware_watchpoint:
10419       fprintf_unfiltered (fp, "watch");
10420       break;
10421     case bp_read_watchpoint:
10422       fprintf_unfiltered (fp, "rwatch");
10423       break;
10424     case bp_access_watchpoint:
10425       fprintf_unfiltered (fp, "awatch");
10426       break;
10427     default:
10428       internal_error (__FILE__, __LINE__,
10429                       _("Invalid watchpoint type."));
10430     }
10431
10432   fprintf_unfiltered (fp, " %s", w->exp_string);
10433   print_recreate_thread (b, fp);
10434 }
10435
10436 /* Implement the "explains_signal" breakpoint_ops method for
10437    watchpoints.  */
10438
10439 static int
10440 explains_signal_watchpoint (struct breakpoint *b, enum gdb_signal sig)
10441 {
10442   /* A software watchpoint cannot cause a signal other than
10443      GDB_SIGNAL_TRAP.  */
10444   if (b->type == bp_watchpoint && sig != GDB_SIGNAL_TRAP)
10445     return 0;
10446
10447   return 1;
10448 }
10449
10450 /* The breakpoint_ops structure to be used in hardware watchpoints.  */
10451
10452 static struct breakpoint_ops watchpoint_breakpoint_ops;
10453
10454 /* Implement the "insert" breakpoint_ops method for
10455    masked hardware watchpoints.  */
10456
10457 static int
10458 insert_masked_watchpoint (struct bp_location *bl)
10459 {
10460   struct watchpoint *w = (struct watchpoint *) bl->owner;
10461
10462   return target_insert_mask_watchpoint (bl->address, w->hw_wp_mask,
10463                                         bl->watchpoint_type);
10464 }
10465
10466 /* Implement the "remove" breakpoint_ops method for
10467    masked hardware watchpoints.  */
10468
10469 static int
10470 remove_masked_watchpoint (struct bp_location *bl, enum remove_bp_reason reason)
10471 {
10472   struct watchpoint *w = (struct watchpoint *) bl->owner;
10473
10474   return target_remove_mask_watchpoint (bl->address, w->hw_wp_mask,
10475                                         bl->watchpoint_type);
10476 }
10477
10478 /* Implement the "resources_needed" breakpoint_ops method for
10479    masked hardware watchpoints.  */
10480
10481 static int
10482 resources_needed_masked_watchpoint (const struct bp_location *bl)
10483 {
10484   struct watchpoint *w = (struct watchpoint *) bl->owner;
10485
10486   return target_masked_watch_num_registers (bl->address, w->hw_wp_mask);
10487 }
10488
10489 /* Implement the "works_in_software_mode" breakpoint_ops method for
10490    masked hardware watchpoints.  */
10491
10492 static int
10493 works_in_software_mode_masked_watchpoint (const struct breakpoint *b)
10494 {
10495   return 0;
10496 }
10497
10498 /* Implement the "print_it" breakpoint_ops method for
10499    masked hardware watchpoints.  */
10500
10501 static enum print_stop_action
10502 print_it_masked_watchpoint (bpstat bs)
10503 {
10504   struct breakpoint *b = bs->breakpoint_at;
10505   struct ui_out *uiout = current_uiout;
10506
10507   /* Masked watchpoints have only one location.  */
10508   gdb_assert (b->loc && b->loc->next == NULL);
10509
10510   annotate_watchpoint (b->number);
10511   maybe_print_thread_hit_breakpoint (uiout);
10512
10513   switch (b->type)
10514     {
10515     case bp_hardware_watchpoint:
10516       if (uiout->is_mi_like_p ())
10517         uiout->field_string
10518           ("reason", async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
10519       break;
10520
10521     case bp_read_watchpoint:
10522       if (uiout->is_mi_like_p ())
10523         uiout->field_string
10524           ("reason", async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
10525       break;
10526
10527     case bp_access_watchpoint:
10528       if (uiout->is_mi_like_p ())
10529         uiout->field_string
10530           ("reason",
10531            async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10532       break;
10533     default:
10534       internal_error (__FILE__, __LINE__,
10535                       _("Invalid hardware watchpoint type."));
10536     }
10537
10538   mention (b);
10539   uiout->text (_("\n\
10540 Check the underlying instruction at PC for the memory\n\
10541 address and value which triggered this watchpoint.\n"));
10542   uiout->text ("\n");
10543
10544   /* More than one watchpoint may have been triggered.  */
10545   return PRINT_UNKNOWN;
10546 }
10547
10548 /* Implement the "print_one_detail" breakpoint_ops method for
10549    masked hardware watchpoints.  */
10550
10551 static void
10552 print_one_detail_masked_watchpoint (const struct breakpoint *b,
10553                                     struct ui_out *uiout)
10554 {
10555   struct watchpoint *w = (struct watchpoint *) b;
10556
10557   /* Masked watchpoints have only one location.  */
10558   gdb_assert (b->loc && b->loc->next == NULL);
10559
10560   uiout->text ("\tmask ");
10561   uiout->field_core_addr ("mask", b->loc->gdbarch, w->hw_wp_mask);
10562   uiout->text ("\n");
10563 }
10564
10565 /* Implement the "print_mention" breakpoint_ops method for
10566    masked hardware watchpoints.  */
10567
10568 static void
10569 print_mention_masked_watchpoint (struct breakpoint *b)
10570 {
10571   struct watchpoint *w = (struct watchpoint *) b;
10572   struct ui_out *uiout = current_uiout;
10573   const char *tuple_name;
10574
10575   switch (b->type)
10576     {
10577     case bp_hardware_watchpoint:
10578       uiout->text ("Masked hardware watchpoint ");
10579       tuple_name = "wpt";
10580       break;
10581     case bp_read_watchpoint:
10582       uiout->text ("Masked hardware read watchpoint ");
10583       tuple_name = "hw-rwpt";
10584       break;
10585     case bp_access_watchpoint:
10586       uiout->text ("Masked hardware access (read/write) watchpoint ");
10587       tuple_name = "hw-awpt";
10588       break;
10589     default:
10590       internal_error (__FILE__, __LINE__,
10591                       _("Invalid hardware watchpoint type."));
10592     }
10593
10594   ui_out_emit_tuple tuple_emitter (uiout, tuple_name);
10595   uiout->field_int ("number", b->number);
10596   uiout->text (": ");
10597   uiout->field_string ("exp", w->exp_string);
10598 }
10599
10600 /* Implement the "print_recreate" breakpoint_ops method for
10601    masked hardware watchpoints.  */
10602
10603 static void
10604 print_recreate_masked_watchpoint (struct breakpoint *b, struct ui_file *fp)
10605 {
10606   struct watchpoint *w = (struct watchpoint *) b;
10607   char tmp[40];
10608
10609   switch (b->type)
10610     {
10611     case bp_hardware_watchpoint:
10612       fprintf_unfiltered (fp, "watch");
10613       break;
10614     case bp_read_watchpoint:
10615       fprintf_unfiltered (fp, "rwatch");
10616       break;
10617     case bp_access_watchpoint:
10618       fprintf_unfiltered (fp, "awatch");
10619       break;
10620     default:
10621       internal_error (__FILE__, __LINE__,
10622                       _("Invalid hardware watchpoint type."));
10623     }
10624
10625   sprintf_vma (tmp, w->hw_wp_mask);
10626   fprintf_unfiltered (fp, " %s mask 0x%s", w->exp_string, tmp);
10627   print_recreate_thread (b, fp);
10628 }
10629
10630 /* The breakpoint_ops structure to be used in masked hardware watchpoints.  */
10631
10632 static struct breakpoint_ops masked_watchpoint_breakpoint_ops;
10633
10634 /* Tell whether the given watchpoint is a masked hardware watchpoint.  */
10635
10636 static int
10637 is_masked_watchpoint (const struct breakpoint *b)
10638 {
10639   return b->ops == &masked_watchpoint_breakpoint_ops;
10640 }
10641
10642 /* accessflag:  hw_write:  watch write, 
10643                 hw_read:   watch read, 
10644                 hw_access: watch access (read or write) */
10645 static void
10646 watch_command_1 (const char *arg, int accessflag, int from_tty,
10647                  int just_location, int internal)
10648 {
10649   struct breakpoint *scope_breakpoint = NULL;
10650   const struct block *exp_valid_block = NULL, *cond_exp_valid_block = NULL;
10651   struct value *val, *mark, *result;
10652   int saved_bitpos = 0, saved_bitsize = 0;
10653   const char *exp_start = NULL;
10654   const char *exp_end = NULL;
10655   const char *tok, *end_tok;
10656   int toklen = -1;
10657   const char *cond_start = NULL;
10658   const char *cond_end = NULL;
10659   enum bptype bp_type;
10660   int thread = -1;
10661   int pc = 0;
10662   /* Flag to indicate whether we are going to use masks for
10663      the hardware watchpoint.  */
10664   int use_mask = 0;
10665   CORE_ADDR mask = 0;
10666
10667   /* Make sure that we actually have parameters to parse.  */
10668   if (arg != NULL && arg[0] != '\0')
10669     {
10670       const char *value_start;
10671
10672       exp_end = arg + strlen (arg);
10673
10674       /* Look for "parameter value" pairs at the end
10675          of the arguments string.  */
10676       for (tok = exp_end - 1; tok > arg; tok--)
10677         {
10678           /* Skip whitespace at the end of the argument list.  */
10679           while (tok > arg && (*tok == ' ' || *tok == '\t'))
10680             tok--;
10681
10682           /* Find the beginning of the last token.
10683              This is the value of the parameter.  */
10684           while (tok > arg && (*tok != ' ' && *tok != '\t'))
10685             tok--;
10686           value_start = tok + 1;
10687
10688           /* Skip whitespace.  */
10689           while (tok > arg && (*tok == ' ' || *tok == '\t'))
10690             tok--;
10691
10692           end_tok = tok;
10693
10694           /* Find the beginning of the second to last token.
10695              This is the parameter itself.  */
10696           while (tok > arg && (*tok != ' ' && *tok != '\t'))
10697             tok--;
10698           tok++;
10699           toklen = end_tok - tok + 1;
10700
10701           if (toklen == 6 && startswith (tok, "thread"))
10702             {
10703               struct thread_info *thr;
10704               /* At this point we've found a "thread" token, which means
10705                  the user is trying to set a watchpoint that triggers
10706                  only in a specific thread.  */
10707               const char *endp;
10708
10709               if (thread != -1)
10710                 error(_("You can specify only one thread."));
10711
10712               /* Extract the thread ID from the next token.  */
10713               thr = parse_thread_id (value_start, &endp);
10714
10715               /* Check if the user provided a valid thread ID.  */
10716               if (*endp != ' ' && *endp != '\t' && *endp != '\0')
10717                 invalid_thread_id_error (value_start);
10718
10719               thread = thr->global_num;
10720             }
10721           else if (toklen == 4 && startswith (tok, "mask"))
10722             {
10723               /* We've found a "mask" token, which means the user wants to
10724                  create a hardware watchpoint that is going to have the mask
10725                  facility.  */
10726               struct value *mask_value, *mark;
10727
10728               if (use_mask)
10729                 error(_("You can specify only one mask."));
10730
10731               use_mask = just_location = 1;
10732
10733               mark = value_mark ();
10734               mask_value = parse_to_comma_and_eval (&value_start);
10735               mask = value_as_address (mask_value);
10736               value_free_to_mark (mark);
10737             }
10738           else
10739             /* We didn't recognize what we found.  We should stop here.  */
10740             break;
10741
10742           /* Truncate the string and get rid of the "parameter value" pair before
10743              the arguments string is parsed by the parse_exp_1 function.  */
10744           exp_end = tok;
10745         }
10746     }
10747   else
10748     exp_end = arg;
10749
10750   /* Parse the rest of the arguments.  From here on out, everything
10751      is in terms of a newly allocated string instead of the original
10752      ARG.  */
10753   innermost_block = NULL;
10754   std::string expression (arg, exp_end - arg);
10755   exp_start = arg = expression.c_str ();
10756   expression_up exp = parse_exp_1 (&arg, 0, 0, 0);
10757   exp_end = arg;
10758   /* Remove trailing whitespace from the expression before saving it.
10759      This makes the eventual display of the expression string a bit
10760      prettier.  */
10761   while (exp_end > exp_start && (exp_end[-1] == ' ' || exp_end[-1] == '\t'))
10762     --exp_end;
10763
10764   /* Checking if the expression is not constant.  */
10765   if (watchpoint_exp_is_const (exp.get ()))
10766     {
10767       int len;
10768
10769       len = exp_end - exp_start;
10770       while (len > 0 && isspace (exp_start[len - 1]))
10771         len--;
10772       error (_("Cannot watch constant value `%.*s'."), len, exp_start);
10773     }
10774
10775   exp_valid_block = innermost_block;
10776   mark = value_mark ();
10777   fetch_subexp_value (exp.get (), &pc, &val, &result, NULL, just_location);
10778
10779   if (val != NULL && just_location)
10780     {
10781       saved_bitpos = value_bitpos (val);
10782       saved_bitsize = value_bitsize (val);
10783     }
10784
10785   if (just_location)
10786     {
10787       int ret;
10788
10789       exp_valid_block = NULL;
10790       val = value_addr (result);
10791       release_value (val);
10792       value_free_to_mark (mark);
10793
10794       if (use_mask)
10795         {
10796           ret = target_masked_watch_num_registers (value_as_address (val),
10797                                                    mask);
10798           if (ret == -1)
10799             error (_("This target does not support masked watchpoints."));
10800           else if (ret == -2)
10801             error (_("Invalid mask or memory region."));
10802         }
10803     }
10804   else if (val != NULL)
10805     release_value (val);
10806
10807   tok = skip_spaces (arg);
10808   end_tok = skip_to_space (tok);
10809
10810   toklen = end_tok - tok;
10811   if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
10812     {
10813       innermost_block = NULL;
10814       tok = cond_start = end_tok + 1;
10815       parse_exp_1 (&tok, 0, 0, 0);
10816
10817       /* The watchpoint expression may not be local, but the condition
10818          may still be.  E.g.: `watch global if local > 0'.  */
10819       cond_exp_valid_block = innermost_block;
10820
10821       cond_end = tok;
10822     }
10823   if (*tok)
10824     error (_("Junk at end of command."));
10825
10826   frame_info *wp_frame = block_innermost_frame (exp_valid_block);
10827
10828   /* Save this because create_internal_breakpoint below invalidates
10829      'wp_frame'.  */
10830   frame_id watchpoint_frame = get_frame_id (wp_frame);
10831
10832   /* If the expression is "local", then set up a "watchpoint scope"
10833      breakpoint at the point where we've left the scope of the watchpoint
10834      expression.  Create the scope breakpoint before the watchpoint, so
10835      that we will encounter it first in bpstat_stop_status.  */
10836   if (exp_valid_block != NULL && wp_frame != NULL)
10837     {
10838       frame_id caller_frame_id = frame_unwind_caller_id (wp_frame);
10839
10840       if (frame_id_p (caller_frame_id))
10841         {
10842           gdbarch *caller_arch = frame_unwind_caller_arch (wp_frame);
10843           CORE_ADDR caller_pc = frame_unwind_caller_pc (wp_frame);
10844
10845           scope_breakpoint
10846             = create_internal_breakpoint (caller_arch, caller_pc,
10847                                           bp_watchpoint_scope,
10848                                           &momentary_breakpoint_ops);
10849
10850           /* create_internal_breakpoint could invalidate WP_FRAME.  */
10851           wp_frame = NULL;
10852
10853           scope_breakpoint->enable_state = bp_enabled;
10854
10855           /* Automatically delete the breakpoint when it hits.  */
10856           scope_breakpoint->disposition = disp_del;
10857
10858           /* Only break in the proper frame (help with recursion).  */
10859           scope_breakpoint->frame_id = caller_frame_id;
10860
10861           /* Set the address at which we will stop.  */
10862           scope_breakpoint->loc->gdbarch = caller_arch;
10863           scope_breakpoint->loc->requested_address = caller_pc;
10864           scope_breakpoint->loc->address
10865             = adjust_breakpoint_address (scope_breakpoint->loc->gdbarch,
10866                                          scope_breakpoint->loc->requested_address,
10867                                          scope_breakpoint->type);
10868         }
10869     }
10870
10871   /* Now set up the breakpoint.  We create all watchpoints as hardware
10872      watchpoints here even if hardware watchpoints are turned off, a call
10873      to update_watchpoint later in this function will cause the type to
10874      drop back to bp_watchpoint (software watchpoint) if required.  */
10875
10876   if (accessflag == hw_read)
10877     bp_type = bp_read_watchpoint;
10878   else if (accessflag == hw_access)
10879     bp_type = bp_access_watchpoint;
10880   else
10881     bp_type = bp_hardware_watchpoint;
10882
10883   std::unique_ptr<watchpoint> w (new watchpoint ());
10884
10885   if (use_mask)
10886     init_raw_breakpoint_without_location (w.get (), NULL, bp_type,
10887                                           &masked_watchpoint_breakpoint_ops);
10888   else
10889     init_raw_breakpoint_without_location (w.get (), NULL, bp_type,
10890                                           &watchpoint_breakpoint_ops);
10891   w->thread = thread;
10892   w->disposition = disp_donttouch;
10893   w->pspace = current_program_space;
10894   w->exp = std::move (exp);
10895   w->exp_valid_block = exp_valid_block;
10896   w->cond_exp_valid_block = cond_exp_valid_block;
10897   if (just_location)
10898     {
10899       struct type *t = value_type (val);
10900       CORE_ADDR addr = value_as_address (val);
10901
10902       w->exp_string_reparse
10903         = current_language->la_watch_location_expression (t, addr).release ();
10904
10905       w->exp_string = xstrprintf ("-location %.*s",
10906                                   (int) (exp_end - exp_start), exp_start);
10907     }
10908   else
10909     w->exp_string = savestring (exp_start, exp_end - exp_start);
10910
10911   if (use_mask)
10912     {
10913       w->hw_wp_mask = mask;
10914     }
10915   else
10916     {
10917       w->val = val;
10918       w->val_bitpos = saved_bitpos;
10919       w->val_bitsize = saved_bitsize;
10920       w->val_valid = 1;
10921     }
10922
10923   if (cond_start)
10924     w->cond_string = savestring (cond_start, cond_end - cond_start);
10925   else
10926     w->cond_string = 0;
10927
10928   if (frame_id_p (watchpoint_frame))
10929     {
10930       w->watchpoint_frame = watchpoint_frame;
10931       w->watchpoint_thread = inferior_ptid;
10932     }
10933   else
10934     {
10935       w->watchpoint_frame = null_frame_id;
10936       w->watchpoint_thread = null_ptid;
10937     }
10938
10939   if (scope_breakpoint != NULL)
10940     {
10941       /* The scope breakpoint is related to the watchpoint.  We will
10942          need to act on them together.  */
10943       w->related_breakpoint = scope_breakpoint;
10944       scope_breakpoint->related_breakpoint = w.get ();
10945     }
10946
10947   if (!just_location)
10948     value_free_to_mark (mark);
10949
10950   /* Finally update the new watchpoint.  This creates the locations
10951      that should be inserted.  */
10952   update_watchpoint (w.get (), 1);
10953
10954   install_breakpoint (internal, std::move (w), 1);
10955 }
10956
10957 /* Return count of debug registers needed to watch the given expression.
10958    If the watchpoint cannot be handled in hardware return zero.  */
10959
10960 static int
10961 can_use_hardware_watchpoint (struct value *v)
10962 {
10963   int found_memory_cnt = 0;
10964   struct value *head = v;
10965
10966   /* Did the user specifically forbid us to use hardware watchpoints? */
10967   if (!can_use_hw_watchpoints)
10968     return 0;
10969
10970   /* Make sure that the value of the expression depends only upon
10971      memory contents, and values computed from them within GDB.  If we
10972      find any register references or function calls, we can't use a
10973      hardware watchpoint.
10974
10975      The idea here is that evaluating an expression generates a series
10976      of values, one holding the value of every subexpression.  (The
10977      expression a*b+c has five subexpressions: a, b, a*b, c, and
10978      a*b+c.)  GDB's values hold almost enough information to establish
10979      the criteria given above --- they identify memory lvalues,
10980      register lvalues, computed values, etcetera.  So we can evaluate
10981      the expression, and then scan the chain of values that leaves
10982      behind to decide whether we can detect any possible change to the
10983      expression's final value using only hardware watchpoints.
10984
10985      However, I don't think that the values returned by inferior
10986      function calls are special in any way.  So this function may not
10987      notice that an expression involving an inferior function call
10988      can't be watched with hardware watchpoints.  FIXME.  */
10989   for (; v; v = value_next (v))
10990     {
10991       if (VALUE_LVAL (v) == lval_memory)
10992         {
10993           if (v != head && value_lazy (v))
10994             /* A lazy memory lvalue in the chain is one that GDB never
10995                needed to fetch; we either just used its address (e.g.,
10996                `a' in `a.b') or we never needed it at all (e.g., `a'
10997                in `a,b').  This doesn't apply to HEAD; if that is
10998                lazy then it was not readable, but watch it anyway.  */
10999             ;
11000           else
11001             {
11002               /* Ahh, memory we actually used!  Check if we can cover
11003                  it with hardware watchpoints.  */
11004               struct type *vtype = check_typedef (value_type (v));
11005
11006               /* We only watch structs and arrays if user asked for it
11007                  explicitly, never if they just happen to appear in a
11008                  middle of some value chain.  */
11009               if (v == head
11010                   || (TYPE_CODE (vtype) != TYPE_CODE_STRUCT
11011                       && TYPE_CODE (vtype) != TYPE_CODE_ARRAY))
11012                 {
11013                   CORE_ADDR vaddr = value_address (v);
11014                   int len;
11015                   int num_regs;
11016
11017                   len = (target_exact_watchpoints
11018                          && is_scalar_type_recursive (vtype))?
11019                     1 : TYPE_LENGTH (value_type (v));
11020
11021                   num_regs = target_region_ok_for_hw_watchpoint (vaddr, len);
11022                   if (!num_regs)
11023                     return 0;
11024                   else
11025                     found_memory_cnt += num_regs;
11026                 }
11027             }
11028         }
11029       else if (VALUE_LVAL (v) != not_lval
11030                && deprecated_value_modifiable (v) == 0)
11031         return 0;       /* These are values from the history (e.g., $1).  */
11032       else if (VALUE_LVAL (v) == lval_register)
11033         return 0;       /* Cannot watch a register with a HW watchpoint.  */
11034     }
11035
11036   /* The expression itself looks suitable for using a hardware
11037      watchpoint, but give the target machine a chance to reject it.  */
11038   return found_memory_cnt;
11039 }
11040
11041 void
11042 watch_command_wrapper (const char *arg, int from_tty, int internal)
11043 {
11044   watch_command_1 (arg, hw_write, from_tty, 0, internal);
11045 }
11046
11047 /* A helper function that looks for the "-location" argument and then
11048    calls watch_command_1.  */
11049
11050 static void
11051 watch_maybe_just_location (const char *arg, int accessflag, int from_tty)
11052 {
11053   int just_location = 0;
11054
11055   if (arg
11056       && (check_for_argument (&arg, "-location", sizeof ("-location") - 1)
11057           || check_for_argument (&arg, "-l", sizeof ("-l") - 1)))
11058     {
11059       arg = skip_spaces (arg);
11060       just_location = 1;
11061     }
11062
11063   watch_command_1 (arg, accessflag, from_tty, just_location, 0);
11064 }
11065
11066 static void
11067 watch_command (const char *arg, int from_tty)
11068 {
11069   watch_maybe_just_location (arg, hw_write, from_tty);
11070 }
11071
11072 void
11073 rwatch_command_wrapper (const char *arg, int from_tty, int internal)
11074 {
11075   watch_command_1 (arg, hw_read, from_tty, 0, internal);
11076 }
11077
11078 static void
11079 rwatch_command (const char *arg, int from_tty)
11080 {
11081   watch_maybe_just_location (arg, hw_read, from_tty);
11082 }
11083
11084 void
11085 awatch_command_wrapper (const char *arg, int from_tty, int internal)
11086 {
11087   watch_command_1 (arg, hw_access, from_tty, 0, internal);
11088 }
11089
11090 static void
11091 awatch_command (const char *arg, int from_tty)
11092 {
11093   watch_maybe_just_location (arg, hw_access, from_tty);
11094 }
11095 \f
11096
11097 /* Data for the FSM that manages the until(location)/advance commands
11098    in infcmd.c.  Here because it uses the mechanisms of
11099    breakpoints.  */
11100
11101 struct until_break_fsm
11102 {
11103   /* The base class.  */
11104   struct thread_fsm thread_fsm;
11105
11106   /* The thread that as current when the command was executed.  */
11107   int thread;
11108
11109   /* The breakpoint set at the destination location.  */
11110   struct breakpoint *location_breakpoint;
11111
11112   /* Breakpoint set at the return address in the caller frame.  May be
11113      NULL.  */
11114   struct breakpoint *caller_breakpoint;
11115 };
11116
11117 static void until_break_fsm_clean_up (struct thread_fsm *self,
11118                                       struct thread_info *thread);
11119 static int until_break_fsm_should_stop (struct thread_fsm *self,
11120                                         struct thread_info *thread);
11121 static enum async_reply_reason
11122   until_break_fsm_async_reply_reason (struct thread_fsm *self);
11123
11124 /* until_break_fsm's vtable.  */
11125
11126 static struct thread_fsm_ops until_break_fsm_ops =
11127 {
11128   NULL, /* dtor */
11129   until_break_fsm_clean_up,
11130   until_break_fsm_should_stop,
11131   NULL, /* return_value */
11132   until_break_fsm_async_reply_reason,
11133 };
11134
11135 /* Allocate a new until_break_command_fsm.  */
11136
11137 static struct until_break_fsm *
11138 new_until_break_fsm (struct interp *cmd_interp, int thread,
11139                      breakpoint_up &&location_breakpoint,
11140                      breakpoint_up &&caller_breakpoint)
11141 {
11142   struct until_break_fsm *sm;
11143
11144   sm = XCNEW (struct until_break_fsm);
11145   thread_fsm_ctor (&sm->thread_fsm, &until_break_fsm_ops, cmd_interp);
11146
11147   sm->thread = thread;
11148   sm->location_breakpoint = location_breakpoint.release ();
11149   sm->caller_breakpoint = caller_breakpoint.release ();
11150
11151   return sm;
11152 }
11153
11154 /* Implementation of the 'should_stop' FSM method for the
11155    until(location)/advance commands.  */
11156
11157 static int
11158 until_break_fsm_should_stop (struct thread_fsm *self,
11159                              struct thread_info *tp)
11160 {
11161   struct until_break_fsm *sm = (struct until_break_fsm *) self;
11162
11163   if (bpstat_find_breakpoint (tp->control.stop_bpstat,
11164                               sm->location_breakpoint) != NULL
11165       || (sm->caller_breakpoint != NULL
11166           && bpstat_find_breakpoint (tp->control.stop_bpstat,
11167                                      sm->caller_breakpoint) != NULL))
11168     thread_fsm_set_finished (self);
11169
11170   return 1;
11171 }
11172
11173 /* Implementation of the 'clean_up' FSM method for the
11174    until(location)/advance commands.  */
11175
11176 static void
11177 until_break_fsm_clean_up (struct thread_fsm *self,
11178                           struct thread_info *thread)
11179 {
11180   struct until_break_fsm *sm = (struct until_break_fsm *) self;
11181
11182   /* Clean up our temporary breakpoints.  */
11183   if (sm->location_breakpoint != NULL)
11184     {
11185       delete_breakpoint (sm->location_breakpoint);
11186       sm->location_breakpoint = NULL;
11187     }
11188   if (sm->caller_breakpoint != NULL)
11189     {
11190       delete_breakpoint (sm->caller_breakpoint);
11191       sm->caller_breakpoint = NULL;
11192     }
11193   delete_longjmp_breakpoint (sm->thread);
11194 }
11195
11196 /* Implementation of the 'async_reply_reason' FSM method for the
11197    until(location)/advance commands.  */
11198
11199 static enum async_reply_reason
11200 until_break_fsm_async_reply_reason (struct thread_fsm *self)
11201 {
11202   return EXEC_ASYNC_LOCATION_REACHED;
11203 }
11204
11205 void
11206 until_break_command (const char *arg, int from_tty, int anywhere)
11207 {
11208   struct frame_info *frame;
11209   struct gdbarch *frame_gdbarch;
11210   struct frame_id stack_frame_id;
11211   struct frame_id caller_frame_id;
11212   struct cleanup *old_chain;
11213   int thread;
11214   struct thread_info *tp;
11215   struct until_break_fsm *sm;
11216
11217   clear_proceed_status (0);
11218
11219   /* Set a breakpoint where the user wants it and at return from
11220      this function.  */
11221
11222   event_location_up location = string_to_event_location (&arg, current_language);
11223
11224   std::vector<symtab_and_line> sals
11225     = (last_displayed_sal_is_valid ()
11226        ? decode_line_1 (location.get (), DECODE_LINE_FUNFIRSTLINE, NULL,
11227                         get_last_displayed_symtab (),
11228                         get_last_displayed_line ())
11229        : decode_line_1 (location.get (), DECODE_LINE_FUNFIRSTLINE,
11230                         NULL, (struct symtab *) NULL, 0));
11231
11232   if (sals.size () != 1)
11233     error (_("Couldn't get information on specified line."));
11234
11235   symtab_and_line &sal = sals[0];
11236
11237   if (*arg)
11238     error (_("Junk at end of arguments."));
11239
11240   resolve_sal_pc (&sal);
11241
11242   tp = inferior_thread ();
11243   thread = tp->global_num;
11244
11245   old_chain = make_cleanup (null_cleanup, NULL);
11246
11247   /* Note linespec handling above invalidates the frame chain.
11248      Installing a breakpoint also invalidates the frame chain (as it
11249      may need to switch threads), so do any frame handling before
11250      that.  */
11251
11252   frame = get_selected_frame (NULL);
11253   frame_gdbarch = get_frame_arch (frame);
11254   stack_frame_id = get_stack_frame_id (frame);
11255   caller_frame_id = frame_unwind_caller_id (frame);
11256
11257   /* Keep within the current frame, or in frames called by the current
11258      one.  */
11259
11260   breakpoint_up caller_breakpoint;
11261   if (frame_id_p (caller_frame_id))
11262     {
11263       struct symtab_and_line sal2;
11264       struct gdbarch *caller_gdbarch;
11265
11266       sal2 = find_pc_line (frame_unwind_caller_pc (frame), 0);
11267       sal2.pc = frame_unwind_caller_pc (frame);
11268       caller_gdbarch = frame_unwind_caller_arch (frame);
11269       caller_breakpoint = set_momentary_breakpoint (caller_gdbarch,
11270                                                     sal2,
11271                                                     caller_frame_id,
11272                                                     bp_until);
11273
11274       set_longjmp_breakpoint (tp, caller_frame_id);
11275       make_cleanup (delete_longjmp_breakpoint_cleanup, &thread);
11276     }
11277
11278   /* set_momentary_breakpoint could invalidate FRAME.  */
11279   frame = NULL;
11280
11281   breakpoint_up location_breakpoint;
11282   if (anywhere)
11283     /* If the user told us to continue until a specified location,
11284        we don't specify a frame at which we need to stop.  */
11285     location_breakpoint = set_momentary_breakpoint (frame_gdbarch, sal,
11286                                                     null_frame_id, bp_until);
11287   else
11288     /* Otherwise, specify the selected frame, because we want to stop
11289        only at the very same frame.  */
11290     location_breakpoint = set_momentary_breakpoint (frame_gdbarch, sal,
11291                                                     stack_frame_id, bp_until);
11292
11293   sm = new_until_break_fsm (command_interp (), tp->global_num,
11294                             std::move (location_breakpoint),
11295                             std::move (caller_breakpoint));
11296   tp->thread_fsm = &sm->thread_fsm;
11297
11298   discard_cleanups (old_chain);
11299
11300   proceed (-1, GDB_SIGNAL_DEFAULT);
11301 }
11302
11303 /* This function attempts to parse an optional "if <cond>" clause
11304    from the arg string.  If one is not found, it returns NULL.
11305
11306    Else, it returns a pointer to the condition string.  (It does not
11307    attempt to evaluate the string against a particular block.)  And,
11308    it updates arg to point to the first character following the parsed
11309    if clause in the arg string.  */
11310
11311 const char *
11312 ep_parse_optional_if_clause (const char **arg)
11313 {
11314   const char *cond_string;
11315
11316   if (((*arg)[0] != 'i') || ((*arg)[1] != 'f') || !isspace ((*arg)[2]))
11317     return NULL;
11318
11319   /* Skip the "if" keyword.  */
11320   (*arg) += 2;
11321
11322   /* Skip any extra leading whitespace, and record the start of the
11323      condition string.  */
11324   *arg = skip_spaces (*arg);
11325   cond_string = *arg;
11326
11327   /* Assume that the condition occupies the remainder of the arg
11328      string.  */
11329   (*arg) += strlen (cond_string);
11330
11331   return cond_string;
11332 }
11333
11334 /* Commands to deal with catching events, such as signals, exceptions,
11335    process start/exit, etc.  */
11336
11337 typedef enum
11338 {
11339   catch_fork_temporary, catch_vfork_temporary,
11340   catch_fork_permanent, catch_vfork_permanent
11341 }
11342 catch_fork_kind;
11343
11344 static void
11345 catch_fork_command_1 (char *arg_entry, int from_tty,
11346                       struct cmd_list_element *command)
11347 {
11348   const char *arg = arg_entry;
11349   struct gdbarch *gdbarch = get_current_arch ();
11350   const char *cond_string = NULL;
11351   catch_fork_kind fork_kind;
11352   int tempflag;
11353
11354   fork_kind = (catch_fork_kind) (uintptr_t) get_cmd_context (command);
11355   tempflag = (fork_kind == catch_fork_temporary
11356               || fork_kind == catch_vfork_temporary);
11357
11358   if (!arg)
11359     arg = "";
11360   arg = skip_spaces (arg);
11361
11362   /* The allowed syntax is:
11363      catch [v]fork
11364      catch [v]fork if <cond>
11365
11366      First, check if there's an if clause.  */
11367   cond_string = ep_parse_optional_if_clause (&arg);
11368
11369   if ((*arg != '\0') && !isspace (*arg))
11370     error (_("Junk at end of arguments."));
11371
11372   /* If this target supports it, create a fork or vfork catchpoint
11373      and enable reporting of such events.  */
11374   switch (fork_kind)
11375     {
11376     case catch_fork_temporary:
11377     case catch_fork_permanent:
11378       create_fork_vfork_event_catchpoint (gdbarch, tempflag, cond_string,
11379                                           &catch_fork_breakpoint_ops);
11380       break;
11381     case catch_vfork_temporary:
11382     case catch_vfork_permanent:
11383       create_fork_vfork_event_catchpoint (gdbarch, tempflag, cond_string,
11384                                           &catch_vfork_breakpoint_ops);
11385       break;
11386     default:
11387       error (_("unsupported or unknown fork kind; cannot catch it"));
11388       break;
11389     }
11390 }
11391
11392 static void
11393 catch_exec_command_1 (char *arg_entry, int from_tty,
11394                       struct cmd_list_element *command)
11395 {
11396   const char *arg = arg_entry;
11397   struct gdbarch *gdbarch = get_current_arch ();
11398   int tempflag;
11399   const char *cond_string = NULL;
11400
11401   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
11402
11403   if (!arg)
11404     arg = "";
11405   arg = skip_spaces (arg);
11406
11407   /* The allowed syntax is:
11408      catch exec
11409      catch exec if <cond>
11410
11411      First, check if there's an if clause.  */
11412   cond_string = ep_parse_optional_if_clause (&arg);
11413
11414   if ((*arg != '\0') && !isspace (*arg))
11415     error (_("Junk at end of arguments."));
11416
11417   std::unique_ptr<exec_catchpoint> c (new exec_catchpoint ());
11418   init_catchpoint (c.get (), gdbarch, tempflag, cond_string,
11419                    &catch_exec_breakpoint_ops);
11420   c->exec_pathname = NULL;
11421
11422   install_breakpoint (0, std::move (c), 1);
11423 }
11424
11425 void
11426 init_ada_exception_breakpoint (struct breakpoint *b,
11427                                struct gdbarch *gdbarch,
11428                                struct symtab_and_line sal,
11429                                const char *addr_string,
11430                                const struct breakpoint_ops *ops,
11431                                int tempflag,
11432                                int enabled,
11433                                int from_tty)
11434 {
11435   if (from_tty)
11436     {
11437       struct gdbarch *loc_gdbarch = get_sal_arch (sal);
11438       if (!loc_gdbarch)
11439         loc_gdbarch = gdbarch;
11440
11441       describe_other_breakpoints (loc_gdbarch,
11442                                   sal.pspace, sal.pc, sal.section, -1);
11443       /* FIXME: brobecker/2006-12-28: Actually, re-implement a special
11444          version for exception catchpoints, because two catchpoints
11445          used for different exception names will use the same address.
11446          In this case, a "breakpoint ... also set at..." warning is
11447          unproductive.  Besides, the warning phrasing is also a bit
11448          inappropriate, we should use the word catchpoint, and tell
11449          the user what type of catchpoint it is.  The above is good
11450          enough for now, though.  */
11451     }
11452
11453   init_raw_breakpoint (b, gdbarch, sal, bp_breakpoint, ops);
11454
11455   b->enable_state = enabled ? bp_enabled : bp_disabled;
11456   b->disposition = tempflag ? disp_del : disp_donttouch;
11457   b->location = string_to_event_location (&addr_string,
11458                                           language_def (language_ada));
11459   b->language = language_ada;
11460 }
11461
11462 static void
11463 catch_command (const char *arg, int from_tty)
11464 {
11465   error (_("Catch requires an event name."));
11466 }
11467 \f
11468
11469 static void
11470 tcatch_command (const char *arg, int from_tty)
11471 {
11472   error (_("Catch requires an event name."));
11473 }
11474
11475 /* Compare two breakpoints and return a strcmp-like result.  */
11476
11477 static int
11478 compare_breakpoints (const breakpoint *a, const breakpoint *b)
11479 {
11480   uintptr_t ua = (uintptr_t) a;
11481   uintptr_t ub = (uintptr_t) b;
11482
11483   if (a->number < b->number)
11484     return -1;
11485   else if (a->number > b->number)
11486     return 1;
11487
11488   /* Now sort by address, in case we see, e..g, two breakpoints with
11489      the number 0.  */
11490   if (ua < ub)
11491     return -1;
11492   return ua > ub ? 1 : 0;
11493 }
11494
11495 /* Delete breakpoints by address or line.  */
11496
11497 static void
11498 clear_command (const char *arg, int from_tty)
11499 {
11500   struct breakpoint *b;
11501   int default_match;
11502   int i;
11503
11504   std::vector<symtab_and_line> decoded_sals;
11505   symtab_and_line last_sal;
11506   gdb::array_view<symtab_and_line> sals;
11507   if (arg)
11508     {
11509       decoded_sals
11510         = decode_line_with_current_source (arg,
11511                                            (DECODE_LINE_FUNFIRSTLINE
11512                                             | DECODE_LINE_LIST_MODE));
11513       default_match = 0;
11514       sals = decoded_sals;
11515     }
11516   else
11517     {
11518       /* Set sal's line, symtab, pc, and pspace to the values
11519          corresponding to the last call to print_frame_info.  If the
11520          codepoint is not valid, this will set all the fields to 0.  */
11521       last_sal = get_last_displayed_sal ();
11522       if (last_sal.symtab == 0)
11523         error (_("No source file specified."));
11524
11525       default_match = 1;
11526       sals = last_sal;
11527     }
11528
11529   /* We don't call resolve_sal_pc here.  That's not as bad as it
11530      seems, because all existing breakpoints typically have both
11531      file/line and pc set.  So, if clear is given file/line, we can
11532      match this to existing breakpoint without obtaining pc at all.
11533
11534      We only support clearing given the address explicitly 
11535      present in breakpoint table.  Say, we've set breakpoint 
11536      at file:line.  There were several PC values for that file:line,
11537      due to optimization, all in one block.
11538
11539      We've picked one PC value.  If "clear" is issued with another
11540      PC corresponding to the same file:line, the breakpoint won't
11541      be cleared.  We probably can still clear the breakpoint, but 
11542      since the other PC value is never presented to user, user
11543      can only find it by guessing, and it does not seem important
11544      to support that.  */
11545
11546   /* For each line spec given, delete bps which correspond to it.  Do
11547      it in two passes, solely to preserve the current behavior that
11548      from_tty is forced true if we delete more than one
11549      breakpoint.  */
11550
11551   std::vector<struct breakpoint *> found;
11552   for (const auto &sal : sals)
11553     {
11554       const char *sal_fullname;
11555
11556       /* If exact pc given, clear bpts at that pc.
11557          If line given (pc == 0), clear all bpts on specified line.
11558          If defaulting, clear all bpts on default line
11559          or at default pc.
11560
11561          defaulting    sal.pc != 0    tests to do
11562
11563          0              1             pc
11564          1              1             pc _and_ line
11565          0              0             line
11566          1              0             <can't happen> */
11567
11568       sal_fullname = (sal.symtab == NULL
11569                       ? NULL : symtab_to_fullname (sal.symtab));
11570
11571       /* Find all matching breakpoints and add them to 'found'.  */
11572       ALL_BREAKPOINTS (b)
11573         {
11574           int match = 0;
11575           /* Are we going to delete b?  */
11576           if (b->type != bp_none && !is_watchpoint (b))
11577             {
11578               struct bp_location *loc = b->loc;
11579               for (; loc; loc = loc->next)
11580                 {
11581                   /* If the user specified file:line, don't allow a PC
11582                      match.  This matches historical gdb behavior.  */
11583                   int pc_match = (!sal.explicit_line
11584                                   && sal.pc
11585                                   && (loc->pspace == sal.pspace)
11586                                   && (loc->address == sal.pc)
11587                                   && (!section_is_overlay (loc->section)
11588                                       || loc->section == sal.section));
11589                   int line_match = 0;
11590
11591                   if ((default_match || sal.explicit_line)
11592                       && loc->symtab != NULL
11593                       && sal_fullname != NULL
11594                       && sal.pspace == loc->pspace
11595                       && loc->line_number == sal.line
11596                       && filename_cmp (symtab_to_fullname (loc->symtab),
11597                                        sal_fullname) == 0)
11598                     line_match = 1;
11599
11600                   if (pc_match || line_match)
11601                     {
11602                       match = 1;
11603                       break;
11604                     }
11605                 }
11606             }
11607
11608           if (match)
11609             found.push_back (b);
11610         }
11611     }
11612
11613   /* Now go thru the 'found' chain and delete them.  */
11614   if (found.empty ())
11615     {
11616       if (arg)
11617         error (_("No breakpoint at %s."), arg);
11618       else
11619         error (_("No breakpoint at this line."));
11620     }
11621
11622   /* Remove duplicates from the vec.  */
11623   std::sort (found.begin (), found.end (),
11624              [] (const breakpoint *a, const breakpoint *b)
11625              {
11626                return compare_breakpoints (a, b) < 0;
11627              });
11628   found.erase (std::unique (found.begin (), found.end (),
11629                             [] (const breakpoint *a, const breakpoint *b)
11630                             {
11631                               return compare_breakpoints (a, b) == 0;
11632                             }),
11633                found.end ());
11634
11635   if (found.size () > 1)
11636     from_tty = 1;       /* Always report if deleted more than one.  */
11637   if (from_tty)
11638     {
11639       if (found.size () == 1)
11640         printf_unfiltered (_("Deleted breakpoint "));
11641       else
11642         printf_unfiltered (_("Deleted breakpoints "));
11643     }
11644
11645   for (breakpoint *iter : found)
11646     {
11647       if (from_tty)
11648         printf_unfiltered ("%d ", iter->number);
11649       delete_breakpoint (iter);
11650     }
11651   if (from_tty)
11652     putchar_unfiltered ('\n');
11653 }
11654 \f
11655 /* Delete breakpoint in BS if they are `delete' breakpoints and
11656    all breakpoints that are marked for deletion, whether hit or not.
11657    This is called after any breakpoint is hit, or after errors.  */
11658
11659 void
11660 breakpoint_auto_delete (bpstat bs)
11661 {
11662   struct breakpoint *b, *b_tmp;
11663
11664   for (; bs; bs = bs->next)
11665     if (bs->breakpoint_at
11666         && bs->breakpoint_at->disposition == disp_del
11667         && bs->stop)
11668       delete_breakpoint (bs->breakpoint_at);
11669
11670   ALL_BREAKPOINTS_SAFE (b, b_tmp)
11671   {
11672     if (b->disposition == disp_del_at_next_stop)
11673       delete_breakpoint (b);
11674   }
11675 }
11676
11677 /* A comparison function for bp_location AP and BP being interfaced to
11678    qsort.  Sort elements primarily by their ADDRESS (no matter what
11679    does breakpoint_address_is_meaningful say for its OWNER),
11680    secondarily by ordering first permanent elements and
11681    terciarily just ensuring the array is sorted stable way despite
11682    qsort being an unstable algorithm.  */
11683
11684 static int
11685 bp_locations_compare (const void *ap, const void *bp)
11686 {
11687   const struct bp_location *a = *(const struct bp_location **) ap;
11688   const struct bp_location *b = *(const struct bp_location **) bp;
11689
11690   if (a->address != b->address)
11691     return (a->address > b->address) - (a->address < b->address);
11692
11693   /* Sort locations at the same address by their pspace number, keeping
11694      locations of the same inferior (in a multi-inferior environment)
11695      grouped.  */
11696
11697   if (a->pspace->num != b->pspace->num)
11698     return ((a->pspace->num > b->pspace->num)
11699             - (a->pspace->num < b->pspace->num));
11700
11701   /* Sort permanent breakpoints first.  */
11702   if (a->permanent != b->permanent)
11703     return (a->permanent < b->permanent) - (a->permanent > b->permanent);
11704
11705   /* Make the internal GDB representation stable across GDB runs
11706      where A and B memory inside GDB can differ.  Breakpoint locations of
11707      the same type at the same address can be sorted in arbitrary order.  */
11708
11709   if (a->owner->number != b->owner->number)
11710     return ((a->owner->number > b->owner->number)
11711             - (a->owner->number < b->owner->number));
11712
11713   return (a > b) - (a < b);
11714 }
11715
11716 /* Set bp_locations_placed_address_before_address_max and
11717    bp_locations_shadow_len_after_address_max according to the current
11718    content of the bp_locations array.  */
11719
11720 static void
11721 bp_locations_target_extensions_update (void)
11722 {
11723   struct bp_location *bl, **blp_tmp;
11724
11725   bp_locations_placed_address_before_address_max = 0;
11726   bp_locations_shadow_len_after_address_max = 0;
11727
11728   ALL_BP_LOCATIONS (bl, blp_tmp)
11729     {
11730       CORE_ADDR start, end, addr;
11731
11732       if (!bp_location_has_shadow (bl))
11733         continue;
11734
11735       start = bl->target_info.placed_address;
11736       end = start + bl->target_info.shadow_len;
11737
11738       gdb_assert (bl->address >= start);
11739       addr = bl->address - start;
11740       if (addr > bp_locations_placed_address_before_address_max)
11741         bp_locations_placed_address_before_address_max = addr;
11742
11743       /* Zero SHADOW_LEN would not pass bp_location_has_shadow.  */
11744
11745       gdb_assert (bl->address < end);
11746       addr = end - bl->address;
11747       if (addr > bp_locations_shadow_len_after_address_max)
11748         bp_locations_shadow_len_after_address_max = addr;
11749     }
11750 }
11751
11752 /* Download tracepoint locations if they haven't been.  */
11753
11754 static void
11755 download_tracepoint_locations (void)
11756 {
11757   struct breakpoint *b;
11758   enum tribool can_download_tracepoint = TRIBOOL_UNKNOWN;
11759
11760   scoped_restore_current_pspace_and_thread restore_pspace_thread;
11761
11762   ALL_TRACEPOINTS (b)
11763     {
11764       struct bp_location *bl;
11765       struct tracepoint *t;
11766       int bp_location_downloaded = 0;
11767
11768       if ((b->type == bp_fast_tracepoint
11769            ? !may_insert_fast_tracepoints
11770            : !may_insert_tracepoints))
11771         continue;
11772
11773       if (can_download_tracepoint == TRIBOOL_UNKNOWN)
11774         {
11775           if (target_can_download_tracepoint ())
11776             can_download_tracepoint = TRIBOOL_TRUE;
11777           else
11778             can_download_tracepoint = TRIBOOL_FALSE;
11779         }
11780
11781       if (can_download_tracepoint == TRIBOOL_FALSE)
11782         break;
11783
11784       for (bl = b->loc; bl; bl = bl->next)
11785         {
11786           /* In tracepoint, locations are _never_ duplicated, so
11787              should_be_inserted is equivalent to
11788              unduplicated_should_be_inserted.  */
11789           if (!should_be_inserted (bl) || bl->inserted)
11790             continue;
11791
11792           switch_to_program_space_and_thread (bl->pspace);
11793
11794           target_download_tracepoint (bl);
11795
11796           bl->inserted = 1;
11797           bp_location_downloaded = 1;
11798         }
11799       t = (struct tracepoint *) b;
11800       t->number_on_target = b->number;
11801       if (bp_location_downloaded)
11802         observer_notify_breakpoint_modified (b);
11803     }
11804 }
11805
11806 /* Swap the insertion/duplication state between two locations.  */
11807
11808 static void
11809 swap_insertion (struct bp_location *left, struct bp_location *right)
11810 {
11811   const int left_inserted = left->inserted;
11812   const int left_duplicate = left->duplicate;
11813   const int left_needs_update = left->needs_update;
11814   const struct bp_target_info left_target_info = left->target_info;
11815
11816   /* Locations of tracepoints can never be duplicated.  */
11817   if (is_tracepoint (left->owner))
11818     gdb_assert (!left->duplicate);
11819   if (is_tracepoint (right->owner))
11820     gdb_assert (!right->duplicate);
11821
11822   left->inserted = right->inserted;
11823   left->duplicate = right->duplicate;
11824   left->needs_update = right->needs_update;
11825   left->target_info = right->target_info;
11826   right->inserted = left_inserted;
11827   right->duplicate = left_duplicate;
11828   right->needs_update = left_needs_update;
11829   right->target_info = left_target_info;
11830 }
11831
11832 /* Force the re-insertion of the locations at ADDRESS.  This is called
11833    once a new/deleted/modified duplicate location is found and we are evaluating
11834    conditions on the target's side.  Such conditions need to be updated on
11835    the target.  */
11836
11837 static void
11838 force_breakpoint_reinsertion (struct bp_location *bl)
11839 {
11840   struct bp_location **locp = NULL, **loc2p;
11841   struct bp_location *loc;
11842   CORE_ADDR address = 0;
11843   int pspace_num;
11844
11845   address = bl->address;
11846   pspace_num = bl->pspace->num;
11847
11848   /* This is only meaningful if the target is
11849      evaluating conditions and if the user has
11850      opted for condition evaluation on the target's
11851      side.  */
11852   if (gdb_evaluates_breakpoint_condition_p ()
11853       || !target_supports_evaluation_of_breakpoint_conditions ())
11854     return;
11855
11856   /* Flag all breakpoint locations with this address and
11857      the same program space as the location
11858      as "its condition has changed".  We need to
11859      update the conditions on the target's side.  */
11860   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, address)
11861     {
11862       loc = *loc2p;
11863
11864       if (!is_breakpoint (loc->owner)
11865           || pspace_num != loc->pspace->num)
11866         continue;
11867
11868       /* Flag the location appropriately.  We use a different state to
11869          let everyone know that we already updated the set of locations
11870          with addr bl->address and program space bl->pspace.  This is so
11871          we don't have to keep calling these functions just to mark locations
11872          that have already been marked.  */
11873       loc->condition_changed = condition_updated;
11874
11875       /* Free the agent expression bytecode as well.  We will compute
11876          it later on.  */
11877       loc->cond_bytecode.reset ();
11878     }
11879 }
11880 /* Called whether new breakpoints are created, or existing breakpoints
11881    deleted, to update the global location list and recompute which
11882    locations are duplicate of which.
11883
11884    The INSERT_MODE flag determines whether locations may not, may, or
11885    shall be inserted now.  See 'enum ugll_insert_mode' for more
11886    info.  */
11887
11888 static void
11889 update_global_location_list (enum ugll_insert_mode insert_mode)
11890 {
11891   struct breakpoint *b;
11892   struct bp_location **locp, *loc;
11893   /* Last breakpoint location address that was marked for update.  */
11894   CORE_ADDR last_addr = 0;
11895   /* Last breakpoint location program space that was marked for update.  */
11896   int last_pspace_num = -1;
11897
11898   /* Used in the duplicates detection below.  When iterating over all
11899      bp_locations, points to the first bp_location of a given address.
11900      Breakpoints and watchpoints of different types are never
11901      duplicates of each other.  Keep one pointer for each type of
11902      breakpoint/watchpoint, so we only need to loop over all locations
11903      once.  */
11904   struct bp_location *bp_loc_first;  /* breakpoint */
11905   struct bp_location *wp_loc_first;  /* hardware watchpoint */
11906   struct bp_location *awp_loc_first; /* access watchpoint */
11907   struct bp_location *rwp_loc_first; /* read watchpoint */
11908
11909   /* Saved former bp_locations array which we compare against the newly
11910      built bp_locations from the current state of ALL_BREAKPOINTS.  */
11911   struct bp_location **old_locp;
11912   unsigned old_locations_count;
11913   gdb::unique_xmalloc_ptr<struct bp_location *> old_locations (bp_locations);
11914
11915   old_locations_count = bp_locations_count;
11916   bp_locations = NULL;
11917   bp_locations_count = 0;
11918
11919   ALL_BREAKPOINTS (b)
11920     for (loc = b->loc; loc; loc = loc->next)
11921       bp_locations_count++;
11922
11923   bp_locations = XNEWVEC (struct bp_location *, bp_locations_count);
11924   locp = bp_locations;
11925   ALL_BREAKPOINTS (b)
11926     for (loc = b->loc; loc; loc = loc->next)
11927       *locp++ = loc;
11928   qsort (bp_locations, bp_locations_count, sizeof (*bp_locations),
11929          bp_locations_compare);
11930
11931   bp_locations_target_extensions_update ();
11932
11933   /* Identify bp_location instances that are no longer present in the
11934      new list, and therefore should be freed.  Note that it's not
11935      necessary that those locations should be removed from inferior --
11936      if there's another location at the same address (previously
11937      marked as duplicate), we don't need to remove/insert the
11938      location.
11939      
11940      LOCP is kept in sync with OLD_LOCP, each pointing to the current
11941      and former bp_location array state respectively.  */
11942
11943   locp = bp_locations;
11944   for (old_locp = old_locations.get ();
11945        old_locp < old_locations.get () + old_locations_count;
11946        old_locp++)
11947     {
11948       struct bp_location *old_loc = *old_locp;
11949       struct bp_location **loc2p;
11950
11951       /* Tells if 'old_loc' is found among the new locations.  If
11952          not, we have to free it.  */
11953       int found_object = 0;
11954       /* Tells if the location should remain inserted in the target.  */
11955       int keep_in_target = 0;
11956       int removed = 0;
11957
11958       /* Skip LOCP entries which will definitely never be needed.
11959          Stop either at or being the one matching OLD_LOC.  */
11960       while (locp < bp_locations + bp_locations_count
11961              && (*locp)->address < old_loc->address)
11962         locp++;
11963
11964       for (loc2p = locp;
11965            (loc2p < bp_locations + bp_locations_count
11966             && (*loc2p)->address == old_loc->address);
11967            loc2p++)
11968         {
11969           /* Check if this is a new/duplicated location or a duplicated
11970              location that had its condition modified.  If so, we want to send
11971              its condition to the target if evaluation of conditions is taking
11972              place there.  */
11973           if ((*loc2p)->condition_changed == condition_modified
11974               && (last_addr != old_loc->address
11975                   || last_pspace_num != old_loc->pspace->num))
11976             {
11977               force_breakpoint_reinsertion (*loc2p);
11978               last_pspace_num = old_loc->pspace->num;
11979             }
11980
11981           if (*loc2p == old_loc)
11982             found_object = 1;
11983         }
11984
11985       /* We have already handled this address, update it so that we don't
11986          have to go through updates again.  */
11987       last_addr = old_loc->address;
11988
11989       /* Target-side condition evaluation: Handle deleted locations.  */
11990       if (!found_object)
11991         force_breakpoint_reinsertion (old_loc);
11992
11993       /* If this location is no longer present, and inserted, look if
11994          there's maybe a new location at the same address.  If so,
11995          mark that one inserted, and don't remove this one.  This is
11996          needed so that we don't have a time window where a breakpoint
11997          at certain location is not inserted.  */
11998
11999       if (old_loc->inserted)
12000         {
12001           /* If the location is inserted now, we might have to remove
12002              it.  */
12003
12004           if (found_object && should_be_inserted (old_loc))
12005             {
12006               /* The location is still present in the location list,
12007                  and still should be inserted.  Don't do anything.  */
12008               keep_in_target = 1;
12009             }
12010           else
12011             {
12012               /* This location still exists, but it won't be kept in the
12013                  target since it may have been disabled.  We proceed to
12014                  remove its target-side condition.  */
12015
12016               /* The location is either no longer present, or got
12017                  disabled.  See if there's another location at the
12018                  same address, in which case we don't need to remove
12019                  this one from the target.  */
12020
12021               /* OLD_LOC comes from existing struct breakpoint.  */
12022               if (breakpoint_address_is_meaningful (old_loc->owner))
12023                 {
12024                   for (loc2p = locp;
12025                        (loc2p < bp_locations + bp_locations_count
12026                         && (*loc2p)->address == old_loc->address);
12027                        loc2p++)
12028                     {
12029                       struct bp_location *loc2 = *loc2p;
12030
12031                       if (breakpoint_locations_match (loc2, old_loc))
12032                         {
12033                           /* Read watchpoint locations are switched to
12034                              access watchpoints, if the former are not
12035                              supported, but the latter are.  */
12036                           if (is_hardware_watchpoint (old_loc->owner))
12037                             {
12038                               gdb_assert (is_hardware_watchpoint (loc2->owner));
12039                               loc2->watchpoint_type = old_loc->watchpoint_type;
12040                             }
12041
12042                           /* loc2 is a duplicated location. We need to check
12043                              if it should be inserted in case it will be
12044                              unduplicated.  */
12045                           if (loc2 != old_loc
12046                               && unduplicated_should_be_inserted (loc2))
12047                             {
12048                               swap_insertion (old_loc, loc2);
12049                               keep_in_target = 1;
12050                               break;
12051                             }
12052                         }
12053                     }
12054                 }
12055             }
12056
12057           if (!keep_in_target)
12058             {
12059               if (remove_breakpoint (old_loc))
12060                 {
12061                   /* This is just about all we can do.  We could keep
12062                      this location on the global list, and try to
12063                      remove it next time, but there's no particular
12064                      reason why we will succeed next time.
12065                      
12066                      Note that at this point, old_loc->owner is still
12067                      valid, as delete_breakpoint frees the breakpoint
12068                      only after calling us.  */
12069                   printf_filtered (_("warning: Error removing "
12070                                      "breakpoint %d\n"), 
12071                                    old_loc->owner->number);
12072                 }
12073               removed = 1;
12074             }
12075         }
12076
12077       if (!found_object)
12078         {
12079           if (removed && target_is_non_stop_p ()
12080               && need_moribund_for_location_type (old_loc))
12081             {
12082               /* This location was removed from the target.  In
12083                  non-stop mode, a race condition is possible where
12084                  we've removed a breakpoint, but stop events for that
12085                  breakpoint are already queued and will arrive later.
12086                  We apply an heuristic to be able to distinguish such
12087                  SIGTRAPs from other random SIGTRAPs: we keep this
12088                  breakpoint location for a bit, and will retire it
12089                  after we see some number of events.  The theory here
12090                  is that reporting of events should, "on the average",
12091                  be fair, so after a while we'll see events from all
12092                  threads that have anything of interest, and no longer
12093                  need to keep this breakpoint location around.  We
12094                  don't hold locations forever so to reduce chances of
12095                  mistaking a non-breakpoint SIGTRAP for a breakpoint
12096                  SIGTRAP.
12097
12098                  The heuristic failing can be disastrous on
12099                  decr_pc_after_break targets.
12100
12101                  On decr_pc_after_break targets, like e.g., x86-linux,
12102                  if we fail to recognize a late breakpoint SIGTRAP,
12103                  because events_till_retirement has reached 0 too
12104                  soon, we'll fail to do the PC adjustment, and report
12105                  a random SIGTRAP to the user.  When the user resumes
12106                  the inferior, it will most likely immediately crash
12107                  with SIGILL/SIGBUS/SIGSEGV, or worse, get silently
12108                  corrupted, because of being resumed e.g., in the
12109                  middle of a multi-byte instruction, or skipped a
12110                  one-byte instruction.  This was actually seen happen
12111                  on native x86-linux, and should be less rare on
12112                  targets that do not support new thread events, like
12113                  remote, due to the heuristic depending on
12114                  thread_count.
12115
12116                  Mistaking a random SIGTRAP for a breakpoint trap
12117                  causes similar symptoms (PC adjustment applied when
12118                  it shouldn't), but then again, playing with SIGTRAPs
12119                  behind the debugger's back is asking for trouble.
12120
12121                  Since hardware watchpoint traps are always
12122                  distinguishable from other traps, so we don't need to
12123                  apply keep hardware watchpoint moribund locations
12124                  around.  We simply always ignore hardware watchpoint
12125                  traps we can no longer explain.  */
12126
12127               old_loc->events_till_retirement = 3 * (thread_count () + 1);
12128               old_loc->owner = NULL;
12129
12130               VEC_safe_push (bp_location_p, moribund_locations, old_loc);
12131             }
12132           else
12133             {
12134               old_loc->owner = NULL;
12135               decref_bp_location (&old_loc);
12136             }
12137         }
12138     }
12139
12140   /* Rescan breakpoints at the same address and section, marking the
12141      first one as "first" and any others as "duplicates".  This is so
12142      that the bpt instruction is only inserted once.  If we have a
12143      permanent breakpoint at the same place as BPT, make that one the
12144      official one, and the rest as duplicates.  Permanent breakpoints
12145      are sorted first for the same address.
12146
12147      Do the same for hardware watchpoints, but also considering the
12148      watchpoint's type (regular/access/read) and length.  */
12149
12150   bp_loc_first = NULL;
12151   wp_loc_first = NULL;
12152   awp_loc_first = NULL;
12153   rwp_loc_first = NULL;
12154   ALL_BP_LOCATIONS (loc, locp)
12155     {
12156       /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always
12157          non-NULL.  */
12158       struct bp_location **loc_first_p;
12159       b = loc->owner;
12160
12161       if (!unduplicated_should_be_inserted (loc)
12162           || !breakpoint_address_is_meaningful (b)
12163           /* Don't detect duplicate for tracepoint locations because they are
12164            never duplicated.  See the comments in field `duplicate' of
12165            `struct bp_location'.  */
12166           || is_tracepoint (b))
12167         {
12168           /* Clear the condition modification flag.  */
12169           loc->condition_changed = condition_unchanged;
12170           continue;
12171         }
12172
12173       if (b->type == bp_hardware_watchpoint)
12174         loc_first_p = &wp_loc_first;
12175       else if (b->type == bp_read_watchpoint)
12176         loc_first_p = &rwp_loc_first;
12177       else if (b->type == bp_access_watchpoint)
12178         loc_first_p = &awp_loc_first;
12179       else
12180         loc_first_p = &bp_loc_first;
12181
12182       if (*loc_first_p == NULL
12183           || (overlay_debugging && loc->section != (*loc_first_p)->section)
12184           || !breakpoint_locations_match (loc, *loc_first_p))
12185         {
12186           *loc_first_p = loc;
12187           loc->duplicate = 0;
12188
12189           if (is_breakpoint (loc->owner) && loc->condition_changed)
12190             {
12191               loc->needs_update = 1;
12192               /* Clear the condition modification flag.  */
12193               loc->condition_changed = condition_unchanged;
12194             }
12195           continue;
12196         }
12197
12198
12199       /* This and the above ensure the invariant that the first location
12200          is not duplicated, and is the inserted one.
12201          All following are marked as duplicated, and are not inserted.  */
12202       if (loc->inserted)
12203         swap_insertion (loc, *loc_first_p);
12204       loc->duplicate = 1;
12205
12206       /* Clear the condition modification flag.  */
12207       loc->condition_changed = condition_unchanged;
12208     }
12209
12210   if (insert_mode == UGLL_INSERT || breakpoints_should_be_inserted_now ())
12211     {
12212       if (insert_mode != UGLL_DONT_INSERT)
12213         insert_breakpoint_locations ();
12214       else
12215         {
12216           /* Even though the caller told us to not insert new
12217              locations, we may still need to update conditions on the
12218              target's side of breakpoints that were already inserted
12219              if the target is evaluating breakpoint conditions.  We
12220              only update conditions for locations that are marked
12221              "needs_update".  */
12222           update_inserted_breakpoint_locations ();
12223         }
12224     }
12225
12226   if (insert_mode != UGLL_DONT_INSERT)
12227     download_tracepoint_locations ();
12228 }
12229
12230 void
12231 breakpoint_retire_moribund (void)
12232 {
12233   struct bp_location *loc;
12234   int ix;
12235
12236   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
12237     if (--(loc->events_till_retirement) == 0)
12238       {
12239         decref_bp_location (&loc);
12240         VEC_unordered_remove (bp_location_p, moribund_locations, ix);
12241         --ix;
12242       }
12243 }
12244
12245 static void
12246 update_global_location_list_nothrow (enum ugll_insert_mode insert_mode)
12247 {
12248
12249   TRY
12250     {
12251       update_global_location_list (insert_mode);
12252     }
12253   CATCH (e, RETURN_MASK_ERROR)
12254     {
12255     }
12256   END_CATCH
12257 }
12258
12259 /* Clear BKP from a BPS.  */
12260
12261 static void
12262 bpstat_remove_bp_location (bpstat bps, struct breakpoint *bpt)
12263 {
12264   bpstat bs;
12265
12266   for (bs = bps; bs; bs = bs->next)
12267     if (bs->breakpoint_at == bpt)
12268       {
12269         bs->breakpoint_at = NULL;
12270         bs->old_val = NULL;
12271         /* bs->commands will be freed later.  */
12272       }
12273 }
12274
12275 /* Callback for iterate_over_threads.  */
12276 static int
12277 bpstat_remove_breakpoint_callback (struct thread_info *th, void *data)
12278 {
12279   struct breakpoint *bpt = (struct breakpoint *) data;
12280
12281   bpstat_remove_bp_location (th->control.stop_bpstat, bpt);
12282   return 0;
12283 }
12284
12285 /* Helper for breakpoint and tracepoint breakpoint_ops->mention
12286    callbacks.  */
12287
12288 static void
12289 say_where (struct breakpoint *b)
12290 {
12291   struct value_print_options opts;
12292
12293   get_user_print_options (&opts);
12294
12295   /* i18n: cagney/2005-02-11: Below needs to be merged into a
12296      single string.  */
12297   if (b->loc == NULL)
12298     {
12299       /* For pending locations, the output differs slightly based
12300          on b->extra_string.  If this is non-NULL, it contains either
12301          a condition or dprintf arguments.  */
12302       if (b->extra_string == NULL)
12303         {
12304           printf_filtered (_(" (%s) pending."),
12305                            event_location_to_string (b->location.get ()));
12306         }
12307       else if (b->type == bp_dprintf)
12308         {
12309           printf_filtered (_(" (%s,%s) pending."),
12310                            event_location_to_string (b->location.get ()),
12311                            b->extra_string);
12312         }
12313       else
12314         {
12315           printf_filtered (_(" (%s %s) pending."),
12316                            event_location_to_string (b->location.get ()),
12317                            b->extra_string);
12318         }
12319     }
12320   else
12321     {
12322       if (opts.addressprint || b->loc->symtab == NULL)
12323         {
12324           printf_filtered (" at ");
12325           fputs_filtered (paddress (b->loc->gdbarch, b->loc->address),
12326                           gdb_stdout);
12327         }
12328       if (b->loc->symtab != NULL)
12329         {
12330           /* If there is a single location, we can print the location
12331              more nicely.  */
12332           if (b->loc->next == NULL)
12333             printf_filtered (": file %s, line %d.",
12334                              symtab_to_filename_for_display (b->loc->symtab),
12335                              b->loc->line_number);
12336           else
12337             /* This is not ideal, but each location may have a
12338                different file name, and this at least reflects the
12339                real situation somewhat.  */
12340             printf_filtered (": %s.",
12341                              event_location_to_string (b->location.get ()));
12342         }
12343
12344       if (b->loc->next)
12345         {
12346           struct bp_location *loc = b->loc;
12347           int n = 0;
12348           for (; loc; loc = loc->next)
12349             ++n;
12350           printf_filtered (" (%d locations)", n);
12351         }
12352     }
12353 }
12354
12355 /* Default bp_location_ops methods.  */
12356
12357 static void
12358 bp_location_dtor (struct bp_location *self)
12359 {
12360   xfree (self->function_name);
12361 }
12362
12363 static const struct bp_location_ops bp_location_ops =
12364 {
12365   bp_location_dtor
12366 };
12367
12368 /* Destructor for the breakpoint base class.  */
12369
12370 breakpoint::~breakpoint ()
12371 {
12372   xfree (this->cond_string);
12373   xfree (this->extra_string);
12374   xfree (this->filter);
12375 }
12376
12377 static struct bp_location *
12378 base_breakpoint_allocate_location (struct breakpoint *self)
12379 {
12380   return new bp_location (&bp_location_ops, self);
12381 }
12382
12383 static void
12384 base_breakpoint_re_set (struct breakpoint *b)
12385 {
12386   /* Nothing to re-set. */
12387 }
12388
12389 #define internal_error_pure_virtual_called() \
12390   gdb_assert_not_reached ("pure virtual function called")
12391
12392 static int
12393 base_breakpoint_insert_location (struct bp_location *bl)
12394 {
12395   internal_error_pure_virtual_called ();
12396 }
12397
12398 static int
12399 base_breakpoint_remove_location (struct bp_location *bl,
12400                                  enum remove_bp_reason reason)
12401 {
12402   internal_error_pure_virtual_called ();
12403 }
12404
12405 static int
12406 base_breakpoint_breakpoint_hit (const struct bp_location *bl,
12407                                 const address_space *aspace,
12408                                 CORE_ADDR bp_addr,
12409                                 const struct target_waitstatus *ws)
12410 {
12411   internal_error_pure_virtual_called ();
12412 }
12413
12414 static void
12415 base_breakpoint_check_status (bpstat bs)
12416 {
12417   /* Always stop.   */
12418 }
12419
12420 /* A "works_in_software_mode" breakpoint_ops method that just internal
12421    errors.  */
12422
12423 static int
12424 base_breakpoint_works_in_software_mode (const struct breakpoint *b)
12425 {
12426   internal_error_pure_virtual_called ();
12427 }
12428
12429 /* A "resources_needed" breakpoint_ops method that just internal
12430    errors.  */
12431
12432 static int
12433 base_breakpoint_resources_needed (const struct bp_location *bl)
12434 {
12435   internal_error_pure_virtual_called ();
12436 }
12437
12438 static enum print_stop_action
12439 base_breakpoint_print_it (bpstat bs)
12440 {
12441   internal_error_pure_virtual_called ();
12442 }
12443
12444 static void
12445 base_breakpoint_print_one_detail (const struct breakpoint *self,
12446                                   struct ui_out *uiout)
12447 {
12448   /* nothing */
12449 }
12450
12451 static void
12452 base_breakpoint_print_mention (struct breakpoint *b)
12453 {
12454   internal_error_pure_virtual_called ();
12455 }
12456
12457 static void
12458 base_breakpoint_print_recreate (struct breakpoint *b, struct ui_file *fp)
12459 {
12460   internal_error_pure_virtual_called ();
12461 }
12462
12463 static void
12464 base_breakpoint_create_sals_from_location
12465   (const struct event_location *location,
12466    struct linespec_result *canonical,
12467    enum bptype type_wanted)
12468 {
12469   internal_error_pure_virtual_called ();
12470 }
12471
12472 static void
12473 base_breakpoint_create_breakpoints_sal (struct gdbarch *gdbarch,
12474                                         struct linespec_result *c,
12475                                         gdb::unique_xmalloc_ptr<char> cond_string,
12476                                         gdb::unique_xmalloc_ptr<char> extra_string,
12477                                         enum bptype type_wanted,
12478                                         enum bpdisp disposition,
12479                                         int thread,
12480                                         int task, int ignore_count,
12481                                         const struct breakpoint_ops *o,
12482                                         int from_tty, int enabled,
12483                                         int internal, unsigned flags)
12484 {
12485   internal_error_pure_virtual_called ();
12486 }
12487
12488 static std::vector<symtab_and_line>
12489 base_breakpoint_decode_location (struct breakpoint *b,
12490                                  const struct event_location *location,
12491                                  struct program_space *search_pspace)
12492 {
12493   internal_error_pure_virtual_called ();
12494 }
12495
12496 /* The default 'explains_signal' method.  */
12497
12498 static int
12499 base_breakpoint_explains_signal (struct breakpoint *b, enum gdb_signal sig)
12500 {
12501   return 1;
12502 }
12503
12504 /* The default "after_condition_true" method.  */
12505
12506 static void
12507 base_breakpoint_after_condition_true (struct bpstats *bs)
12508 {
12509   /* Nothing to do.   */
12510 }
12511
12512 struct breakpoint_ops base_breakpoint_ops =
12513 {
12514   base_breakpoint_allocate_location,
12515   base_breakpoint_re_set,
12516   base_breakpoint_insert_location,
12517   base_breakpoint_remove_location,
12518   base_breakpoint_breakpoint_hit,
12519   base_breakpoint_check_status,
12520   base_breakpoint_resources_needed,
12521   base_breakpoint_works_in_software_mode,
12522   base_breakpoint_print_it,
12523   NULL,
12524   base_breakpoint_print_one_detail,
12525   base_breakpoint_print_mention,
12526   base_breakpoint_print_recreate,
12527   base_breakpoint_create_sals_from_location,
12528   base_breakpoint_create_breakpoints_sal,
12529   base_breakpoint_decode_location,
12530   base_breakpoint_explains_signal,
12531   base_breakpoint_after_condition_true,
12532 };
12533
12534 /* Default breakpoint_ops methods.  */
12535
12536 static void
12537 bkpt_re_set (struct breakpoint *b)
12538 {
12539   /* FIXME: is this still reachable?  */
12540   if (breakpoint_event_location_empty_p (b))
12541     {
12542       /* Anything without a location can't be re-set.  */
12543       delete_breakpoint (b);
12544       return;
12545     }
12546
12547   breakpoint_re_set_default (b);
12548 }
12549
12550 static int
12551 bkpt_insert_location (struct bp_location *bl)
12552 {
12553   CORE_ADDR addr = bl->target_info.reqstd_address;
12554
12555   bl->target_info.kind = breakpoint_kind (bl, &addr);
12556   bl->target_info.placed_address = addr;
12557
12558   if (bl->loc_type == bp_loc_hardware_breakpoint)
12559     return target_insert_hw_breakpoint (bl->gdbarch, &bl->target_info);
12560   else
12561     return target_insert_breakpoint (bl->gdbarch, &bl->target_info);
12562 }
12563
12564 static int
12565 bkpt_remove_location (struct bp_location *bl, enum remove_bp_reason reason)
12566 {
12567   if (bl->loc_type == bp_loc_hardware_breakpoint)
12568     return target_remove_hw_breakpoint (bl->gdbarch, &bl->target_info);
12569   else
12570     return target_remove_breakpoint (bl->gdbarch, &bl->target_info, reason);
12571 }
12572
12573 static int
12574 bkpt_breakpoint_hit (const struct bp_location *bl,
12575                      const address_space *aspace, CORE_ADDR bp_addr,
12576                      const struct target_waitstatus *ws)
12577 {
12578   if (ws->kind != TARGET_WAITKIND_STOPPED
12579       || ws->value.sig != GDB_SIGNAL_TRAP)
12580     return 0;
12581
12582   if (!breakpoint_address_match (bl->pspace->aspace, bl->address,
12583                                  aspace, bp_addr))
12584     return 0;
12585
12586   if (overlay_debugging         /* unmapped overlay section */
12587       && section_is_overlay (bl->section)
12588       && !section_is_mapped (bl->section))
12589     return 0;
12590
12591   return 1;
12592 }
12593
12594 static int
12595 dprintf_breakpoint_hit (const struct bp_location *bl,
12596                         const address_space *aspace, CORE_ADDR bp_addr,
12597                         const struct target_waitstatus *ws)
12598 {
12599   if (dprintf_style == dprintf_style_agent
12600       && target_can_run_breakpoint_commands ())
12601     {
12602       /* An agent-style dprintf never causes a stop.  If we see a trap
12603          for this address it must be for a breakpoint that happens to
12604          be set at the same address.  */
12605       return 0;
12606     }
12607
12608   return bkpt_breakpoint_hit (bl, aspace, bp_addr, ws);
12609 }
12610
12611 static int
12612 bkpt_resources_needed (const struct bp_location *bl)
12613 {
12614   gdb_assert (bl->owner->type == bp_hardware_breakpoint);
12615
12616   return 1;
12617 }
12618
12619 static enum print_stop_action
12620 bkpt_print_it (bpstat bs)
12621 {
12622   struct breakpoint *b;
12623   const struct bp_location *bl;
12624   int bp_temp;
12625   struct ui_out *uiout = current_uiout;
12626
12627   gdb_assert (bs->bp_location_at != NULL);
12628
12629   bl = bs->bp_location_at;
12630   b = bs->breakpoint_at;
12631
12632   bp_temp = b->disposition == disp_del;
12633   if (bl->address != bl->requested_address)
12634     breakpoint_adjustment_warning (bl->requested_address,
12635                                    bl->address,
12636                                    b->number, 1);
12637   annotate_breakpoint (b->number);
12638   maybe_print_thread_hit_breakpoint (uiout);
12639
12640   if (bp_temp)
12641     uiout->text ("Temporary breakpoint ");
12642   else
12643     uiout->text ("Breakpoint ");
12644   if (uiout->is_mi_like_p ())
12645     {
12646       uiout->field_string ("reason",
12647                            async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
12648       uiout->field_string ("disp", bpdisp_text (b->disposition));
12649     }
12650   uiout->field_int ("bkptno", b->number);
12651   uiout->text (", ");
12652
12653   return PRINT_SRC_AND_LOC;
12654 }
12655
12656 static void
12657 bkpt_print_mention (struct breakpoint *b)
12658 {
12659   if (current_uiout->is_mi_like_p ())
12660     return;
12661
12662   switch (b->type)
12663     {
12664     case bp_breakpoint:
12665     case bp_gnu_ifunc_resolver:
12666       if (b->disposition == disp_del)
12667         printf_filtered (_("Temporary breakpoint"));
12668       else
12669         printf_filtered (_("Breakpoint"));
12670       printf_filtered (_(" %d"), b->number);
12671       if (b->type == bp_gnu_ifunc_resolver)
12672         printf_filtered (_(" at gnu-indirect-function resolver"));
12673       break;
12674     case bp_hardware_breakpoint:
12675       printf_filtered (_("Hardware assisted breakpoint %d"), b->number);
12676       break;
12677     case bp_dprintf:
12678       printf_filtered (_("Dprintf %d"), b->number);
12679       break;
12680     }
12681
12682   say_where (b);
12683 }
12684
12685 static void
12686 bkpt_print_recreate (struct breakpoint *tp, struct ui_file *fp)
12687 {
12688   if (tp->type == bp_breakpoint && tp->disposition == disp_del)
12689     fprintf_unfiltered (fp, "tbreak");
12690   else if (tp->type == bp_breakpoint)
12691     fprintf_unfiltered (fp, "break");
12692   else if (tp->type == bp_hardware_breakpoint
12693            && tp->disposition == disp_del)
12694     fprintf_unfiltered (fp, "thbreak");
12695   else if (tp->type == bp_hardware_breakpoint)
12696     fprintf_unfiltered (fp, "hbreak");
12697   else
12698     internal_error (__FILE__, __LINE__,
12699                     _("unhandled breakpoint type %d"), (int) tp->type);
12700
12701   fprintf_unfiltered (fp, " %s",
12702                       event_location_to_string (tp->location.get ()));
12703
12704   /* Print out extra_string if this breakpoint is pending.  It might
12705      contain, for example, conditions that were set by the user.  */
12706   if (tp->loc == NULL && tp->extra_string != NULL)
12707     fprintf_unfiltered (fp, " %s", tp->extra_string);
12708
12709   print_recreate_thread (tp, fp);
12710 }
12711
12712 static void
12713 bkpt_create_sals_from_location (const struct event_location *location,
12714                                 struct linespec_result *canonical,
12715                                 enum bptype type_wanted)
12716 {
12717   create_sals_from_location_default (location, canonical, type_wanted);
12718 }
12719
12720 static void
12721 bkpt_create_breakpoints_sal (struct gdbarch *gdbarch,
12722                              struct linespec_result *canonical,
12723                              gdb::unique_xmalloc_ptr<char> cond_string,
12724                              gdb::unique_xmalloc_ptr<char> extra_string,
12725                              enum bptype type_wanted,
12726                              enum bpdisp disposition,
12727                              int thread,
12728                              int task, int ignore_count,
12729                              const struct breakpoint_ops *ops,
12730                              int from_tty, int enabled,
12731                              int internal, unsigned flags)
12732 {
12733   create_breakpoints_sal_default (gdbarch, canonical,
12734                                   std::move (cond_string),
12735                                   std::move (extra_string),
12736                                   type_wanted,
12737                                   disposition, thread, task,
12738                                   ignore_count, ops, from_tty,
12739                                   enabled, internal, flags);
12740 }
12741
12742 static std::vector<symtab_and_line>
12743 bkpt_decode_location (struct breakpoint *b,
12744                       const struct event_location *location,
12745                       struct program_space *search_pspace)
12746 {
12747   return decode_location_default (b, location, search_pspace);
12748 }
12749
12750 /* Virtual table for internal breakpoints.  */
12751
12752 static void
12753 internal_bkpt_re_set (struct breakpoint *b)
12754 {
12755   switch (b->type)
12756     {
12757       /* Delete overlay event and longjmp master breakpoints; they
12758          will be reset later by breakpoint_re_set.  */
12759     case bp_overlay_event:
12760     case bp_longjmp_master:
12761     case bp_std_terminate_master:
12762     case bp_exception_master:
12763       delete_breakpoint (b);
12764       break;
12765
12766       /* This breakpoint is special, it's set up when the inferior
12767          starts and we really don't want to touch it.  */
12768     case bp_shlib_event:
12769
12770       /* Like bp_shlib_event, this breakpoint type is special.  Once
12771          it is set up, we do not want to touch it.  */
12772     case bp_thread_event:
12773       break;
12774     }
12775 }
12776
12777 static void
12778 internal_bkpt_check_status (bpstat bs)
12779 {
12780   if (bs->breakpoint_at->type == bp_shlib_event)
12781     {
12782       /* If requested, stop when the dynamic linker notifies GDB of
12783          events.  This allows the user to get control and place
12784          breakpoints in initializer routines for dynamically loaded
12785          objects (among other things).  */
12786       bs->stop = stop_on_solib_events;
12787       bs->print = stop_on_solib_events;
12788     }
12789   else
12790     bs->stop = 0;
12791 }
12792
12793 static enum print_stop_action
12794 internal_bkpt_print_it (bpstat bs)
12795 {
12796   struct breakpoint *b;
12797
12798   b = bs->breakpoint_at;
12799
12800   switch (b->type)
12801     {
12802     case bp_shlib_event:
12803       /* Did we stop because the user set the stop_on_solib_events
12804          variable?  (If so, we report this as a generic, "Stopped due
12805          to shlib event" message.) */
12806       print_solib_event (0);
12807       break;
12808
12809     case bp_thread_event:
12810       /* Not sure how we will get here.
12811          GDB should not stop for these breakpoints.  */
12812       printf_filtered (_("Thread Event Breakpoint: gdb should not stop!\n"));
12813       break;
12814
12815     case bp_overlay_event:
12816       /* By analogy with the thread event, GDB should not stop for these.  */
12817       printf_filtered (_("Overlay Event Breakpoint: gdb should not stop!\n"));
12818       break;
12819
12820     case bp_longjmp_master:
12821       /* These should never be enabled.  */
12822       printf_filtered (_("Longjmp Master Breakpoint: gdb should not stop!\n"));
12823       break;
12824
12825     case bp_std_terminate_master:
12826       /* These should never be enabled.  */
12827       printf_filtered (_("std::terminate Master Breakpoint: "
12828                          "gdb should not stop!\n"));
12829       break;
12830
12831     case bp_exception_master:
12832       /* These should never be enabled.  */
12833       printf_filtered (_("Exception Master Breakpoint: "
12834                          "gdb should not stop!\n"));
12835       break;
12836     }
12837
12838   return PRINT_NOTHING;
12839 }
12840
12841 static void
12842 internal_bkpt_print_mention (struct breakpoint *b)
12843 {
12844   /* Nothing to mention.  These breakpoints are internal.  */
12845 }
12846
12847 /* Virtual table for momentary breakpoints  */
12848
12849 static void
12850 momentary_bkpt_re_set (struct breakpoint *b)
12851 {
12852   /* Keep temporary breakpoints, which can be encountered when we step
12853      over a dlopen call and solib_add is resetting the breakpoints.
12854      Otherwise these should have been blown away via the cleanup chain
12855      or by breakpoint_init_inferior when we rerun the executable.  */
12856 }
12857
12858 static void
12859 momentary_bkpt_check_status (bpstat bs)
12860 {
12861   /* Nothing.  The point of these breakpoints is causing a stop.  */
12862 }
12863
12864 static enum print_stop_action
12865 momentary_bkpt_print_it (bpstat bs)
12866 {
12867   return PRINT_UNKNOWN;
12868 }
12869
12870 static void
12871 momentary_bkpt_print_mention (struct breakpoint *b)
12872 {
12873   /* Nothing to mention.  These breakpoints are internal.  */
12874 }
12875
12876 /* Ensure INITIATING_FRAME is cleared when no such breakpoint exists.
12877
12878    It gets cleared already on the removal of the first one of such placed
12879    breakpoints.  This is OK as they get all removed altogether.  */
12880
12881 longjmp_breakpoint::~longjmp_breakpoint ()
12882 {
12883   thread_info *tp = find_thread_global_id (this->thread);
12884
12885   if (tp != NULL)
12886     tp->initiating_frame = null_frame_id;
12887 }
12888
12889 /* Specific methods for probe breakpoints.  */
12890
12891 static int
12892 bkpt_probe_insert_location (struct bp_location *bl)
12893 {
12894   int v = bkpt_insert_location (bl);
12895
12896   if (v == 0)
12897     {
12898       /* The insertion was successful, now let's set the probe's semaphore
12899          if needed.  */
12900       if (bl->probe.probe->pops->set_semaphore != NULL)
12901         bl->probe.probe->pops->set_semaphore (bl->probe.probe,
12902                                               bl->probe.objfile,
12903                                               bl->gdbarch);
12904     }
12905
12906   return v;
12907 }
12908
12909 static int
12910 bkpt_probe_remove_location (struct bp_location *bl,
12911                             enum remove_bp_reason reason)
12912 {
12913   /* Let's clear the semaphore before removing the location.  */
12914   if (bl->probe.probe->pops->clear_semaphore != NULL)
12915     bl->probe.probe->pops->clear_semaphore (bl->probe.probe,
12916                                             bl->probe.objfile,
12917                                             bl->gdbarch);
12918
12919   return bkpt_remove_location (bl, reason);
12920 }
12921
12922 static void
12923 bkpt_probe_create_sals_from_location (const struct event_location *location,
12924                                       struct linespec_result *canonical,
12925                                       enum bptype type_wanted)
12926 {
12927   struct linespec_sals lsal;
12928
12929   lsal.sals = parse_probes (location, NULL, canonical);
12930   lsal.canonical
12931     = xstrdup (event_location_to_string (canonical->location.get ()));
12932   canonical->lsals.push_back (std::move (lsal));
12933 }
12934
12935 static std::vector<symtab_and_line>
12936 bkpt_probe_decode_location (struct breakpoint *b,
12937                             const struct event_location *location,
12938                             struct program_space *search_pspace)
12939 {
12940   std::vector<symtab_and_line> sals = parse_probes (location, search_pspace, NULL);
12941   if (sals.empty ())
12942     error (_("probe not found"));
12943   return sals;
12944 }
12945
12946 /* The breakpoint_ops structure to be used in tracepoints.  */
12947
12948 static void
12949 tracepoint_re_set (struct breakpoint *b)
12950 {
12951   breakpoint_re_set_default (b);
12952 }
12953
12954 static int
12955 tracepoint_breakpoint_hit (const struct bp_location *bl,
12956                            const address_space *aspace, CORE_ADDR bp_addr,
12957                            const struct target_waitstatus *ws)
12958 {
12959   /* By definition, the inferior does not report stops at
12960      tracepoints.  */
12961   return 0;
12962 }
12963
12964 static void
12965 tracepoint_print_one_detail (const struct breakpoint *self,
12966                              struct ui_out *uiout)
12967 {
12968   struct tracepoint *tp = (struct tracepoint *) self;
12969   if (tp->static_trace_marker_id)
12970     {
12971       gdb_assert (self->type == bp_static_tracepoint);
12972
12973       uiout->text ("\tmarker id is ");
12974       uiout->field_string ("static-tracepoint-marker-string-id",
12975                            tp->static_trace_marker_id);
12976       uiout->text ("\n");
12977     }
12978 }
12979
12980 static void
12981 tracepoint_print_mention (struct breakpoint *b)
12982 {
12983   if (current_uiout->is_mi_like_p ())
12984     return;
12985
12986   switch (b->type)
12987     {
12988     case bp_tracepoint:
12989       printf_filtered (_("Tracepoint"));
12990       printf_filtered (_(" %d"), b->number);
12991       break;
12992     case bp_fast_tracepoint:
12993       printf_filtered (_("Fast tracepoint"));
12994       printf_filtered (_(" %d"), b->number);
12995       break;
12996     case bp_static_tracepoint:
12997       printf_filtered (_("Static tracepoint"));
12998       printf_filtered (_(" %d"), b->number);
12999       break;
13000     default:
13001       internal_error (__FILE__, __LINE__,
13002                       _("unhandled tracepoint type %d"), (int) b->type);
13003     }
13004
13005   say_where (b);
13006 }
13007
13008 static void
13009 tracepoint_print_recreate (struct breakpoint *self, struct ui_file *fp)
13010 {
13011   struct tracepoint *tp = (struct tracepoint *) self;
13012
13013   if (self->type == bp_fast_tracepoint)
13014     fprintf_unfiltered (fp, "ftrace");
13015   else if (self->type == bp_static_tracepoint)
13016     fprintf_unfiltered (fp, "strace");
13017   else if (self->type == bp_tracepoint)
13018     fprintf_unfiltered (fp, "trace");
13019   else
13020     internal_error (__FILE__, __LINE__,
13021                     _("unhandled tracepoint type %d"), (int) self->type);
13022
13023   fprintf_unfiltered (fp, " %s",
13024                       event_location_to_string (self->location.get ()));
13025   print_recreate_thread (self, fp);
13026
13027   if (tp->pass_count)
13028     fprintf_unfiltered (fp, "  passcount %d\n", tp->pass_count);
13029 }
13030
13031 static void
13032 tracepoint_create_sals_from_location (const struct event_location *location,
13033                                       struct linespec_result *canonical,
13034                                       enum bptype type_wanted)
13035 {
13036   create_sals_from_location_default (location, canonical, type_wanted);
13037 }
13038
13039 static void
13040 tracepoint_create_breakpoints_sal (struct gdbarch *gdbarch,
13041                                    struct linespec_result *canonical,
13042                                    gdb::unique_xmalloc_ptr<char> cond_string,
13043                                    gdb::unique_xmalloc_ptr<char> extra_string,
13044                                    enum bptype type_wanted,
13045                                    enum bpdisp disposition,
13046                                    int thread,
13047                                    int task, int ignore_count,
13048                                    const struct breakpoint_ops *ops,
13049                                    int from_tty, int enabled,
13050                                    int internal, unsigned flags)
13051 {
13052   create_breakpoints_sal_default (gdbarch, canonical,
13053                                   std::move (cond_string),
13054                                   std::move (extra_string),
13055                                   type_wanted,
13056                                   disposition, thread, task,
13057                                   ignore_count, ops, from_tty,
13058                                   enabled, internal, flags);
13059 }
13060
13061 static std::vector<symtab_and_line>
13062 tracepoint_decode_location (struct breakpoint *b,
13063                             const struct event_location *location,
13064                             struct program_space *search_pspace)
13065 {
13066   return decode_location_default (b, location, search_pspace);
13067 }
13068
13069 struct breakpoint_ops tracepoint_breakpoint_ops;
13070
13071 /* The breakpoint_ops structure to be use on tracepoints placed in a
13072    static probe.  */
13073
13074 static void
13075 tracepoint_probe_create_sals_from_location
13076   (const struct event_location *location,
13077    struct linespec_result *canonical,
13078    enum bptype type_wanted)
13079 {
13080   /* We use the same method for breakpoint on probes.  */
13081   bkpt_probe_create_sals_from_location (location, canonical, type_wanted);
13082 }
13083
13084 static std::vector<symtab_and_line>
13085 tracepoint_probe_decode_location (struct breakpoint *b,
13086                                   const struct event_location *location,
13087                                   struct program_space *search_pspace)
13088 {
13089   /* We use the same method for breakpoint on probes.  */
13090   return bkpt_probe_decode_location (b, location, search_pspace);
13091 }
13092
13093 static struct breakpoint_ops tracepoint_probe_breakpoint_ops;
13094
13095 /* Dprintf breakpoint_ops methods.  */
13096
13097 static void
13098 dprintf_re_set (struct breakpoint *b)
13099 {
13100   breakpoint_re_set_default (b);
13101
13102   /* extra_string should never be non-NULL for dprintf.  */
13103   gdb_assert (b->extra_string != NULL);
13104
13105   /* 1 - connect to target 1, that can run breakpoint commands.
13106      2 - create a dprintf, which resolves fine.
13107      3 - disconnect from target 1
13108      4 - connect to target 2, that can NOT run breakpoint commands.
13109
13110      After steps #3/#4, you'll want the dprintf command list to
13111      be updated, because target 1 and 2 may well return different
13112      answers for target_can_run_breakpoint_commands().
13113      Given absence of finer grained resetting, we get to do
13114      it all the time.  */
13115   if (b->extra_string != NULL)
13116     update_dprintf_command_list (b);
13117 }
13118
13119 /* Implement the "print_recreate" breakpoint_ops method for dprintf.  */
13120
13121 static void
13122 dprintf_print_recreate (struct breakpoint *tp, struct ui_file *fp)
13123 {
13124   fprintf_unfiltered (fp, "dprintf %s,%s",
13125                       event_location_to_string (tp->location.get ()),
13126                       tp->extra_string);
13127   print_recreate_thread (tp, fp);
13128 }
13129
13130 /* Implement the "after_condition_true" breakpoint_ops method for
13131    dprintf.
13132
13133    dprintf's are implemented with regular commands in their command
13134    list, but we run the commands here instead of before presenting the
13135    stop to the user, as dprintf's don't actually cause a stop.  This
13136    also makes it so that the commands of multiple dprintfs at the same
13137    address are all handled.  */
13138
13139 static void
13140 dprintf_after_condition_true (struct bpstats *bs)
13141 {
13142   struct bpstats tmp_bs;
13143   struct bpstats *tmp_bs_p = &tmp_bs;
13144
13145   /* dprintf's never cause a stop.  This wasn't set in the
13146      check_status hook instead because that would make the dprintf's
13147      condition not be evaluated.  */
13148   bs->stop = 0;
13149
13150   /* Run the command list here.  Take ownership of it instead of
13151      copying.  We never want these commands to run later in
13152      bpstat_do_actions, if a breakpoint that causes a stop happens to
13153      be set at same address as this dprintf, or even if running the
13154      commands here throws.  */
13155   tmp_bs.commands = bs->commands;
13156   bs->commands = NULL;
13157
13158   bpstat_do_actions_1 (&tmp_bs_p);
13159
13160   /* 'tmp_bs.commands' will usually be NULL by now, but
13161      bpstat_do_actions_1 may return early without processing the whole
13162      list.  */
13163 }
13164
13165 /* The breakpoint_ops structure to be used on static tracepoints with
13166    markers (`-m').  */
13167
13168 static void
13169 strace_marker_create_sals_from_location (const struct event_location *location,
13170                                          struct linespec_result *canonical,
13171                                          enum bptype type_wanted)
13172 {
13173   struct linespec_sals lsal;
13174   const char *arg_start, *arg;
13175
13176   arg = arg_start = get_linespec_location (location);
13177   lsal.sals = decode_static_tracepoint_spec (&arg);
13178
13179   std::string str (arg_start, arg - arg_start);
13180   const char *ptr = str.c_str ();
13181   canonical->location = new_linespec_location (&ptr);
13182
13183   lsal.canonical
13184     = xstrdup (event_location_to_string (canonical->location.get ()));
13185   canonical->lsals.push_back (std::move (lsal));
13186 }
13187
13188 static void
13189 strace_marker_create_breakpoints_sal (struct gdbarch *gdbarch,
13190                                       struct linespec_result *canonical,
13191                                       gdb::unique_xmalloc_ptr<char> cond_string,
13192                                       gdb::unique_xmalloc_ptr<char> extra_string,
13193                                       enum bptype type_wanted,
13194                                       enum bpdisp disposition,
13195                                       int thread,
13196                                       int task, int ignore_count,
13197                                       const struct breakpoint_ops *ops,
13198                                       int from_tty, int enabled,
13199                                       int internal, unsigned flags)
13200 {
13201   const linespec_sals &lsal = canonical->lsals[0];
13202
13203   /* If the user is creating a static tracepoint by marker id
13204      (strace -m MARKER_ID), then store the sals index, so that
13205      breakpoint_re_set can try to match up which of the newly
13206      found markers corresponds to this one, and, don't try to
13207      expand multiple locations for each sal, given than SALS
13208      already should contain all sals for MARKER_ID.  */
13209
13210   for (size_t i = 0; i < lsal.sals.size (); i++)
13211     {
13212       event_location_up location
13213         = copy_event_location (canonical->location.get ());
13214
13215       std::unique_ptr<tracepoint> tp (new tracepoint ());
13216       init_breakpoint_sal (tp.get (), gdbarch, lsal.sals[i],
13217                            std::move (location), NULL,
13218                            std::move (cond_string),
13219                            std::move (extra_string),
13220                            type_wanted, disposition,
13221                            thread, task, ignore_count, ops,
13222                            from_tty, enabled, internal, flags,
13223                            canonical->special_display);
13224       /* Given that its possible to have multiple markers with
13225          the same string id, if the user is creating a static
13226          tracepoint by marker id ("strace -m MARKER_ID"), then
13227          store the sals index, so that breakpoint_re_set can
13228          try to match up which of the newly found markers
13229          corresponds to this one  */
13230       tp->static_trace_marker_id_idx = i;
13231
13232       install_breakpoint (internal, std::move (tp), 0);
13233     }
13234 }
13235
13236 static std::vector<symtab_and_line>
13237 strace_marker_decode_location (struct breakpoint *b,
13238                                const struct event_location *location,
13239                                struct program_space *search_pspace)
13240 {
13241   struct tracepoint *tp = (struct tracepoint *) b;
13242   const char *s = get_linespec_location (location);
13243
13244   std::vector<symtab_and_line> sals = decode_static_tracepoint_spec (&s);
13245   if (sals.size () > tp->static_trace_marker_id_idx)
13246     {
13247       sals[0] = sals[tp->static_trace_marker_id_idx];
13248       sals.resize (1);
13249       return sals;
13250     }
13251   else
13252     error (_("marker %s not found"), tp->static_trace_marker_id);
13253 }
13254
13255 static struct breakpoint_ops strace_marker_breakpoint_ops;
13256
13257 static int
13258 strace_marker_p (struct breakpoint *b)
13259 {
13260   return b->ops == &strace_marker_breakpoint_ops;
13261 }
13262
13263 /* Delete a breakpoint and clean up all traces of it in the data
13264    structures.  */
13265
13266 void
13267 delete_breakpoint (struct breakpoint *bpt)
13268 {
13269   struct breakpoint *b;
13270
13271   gdb_assert (bpt != NULL);
13272
13273   /* Has this bp already been deleted?  This can happen because
13274      multiple lists can hold pointers to bp's.  bpstat lists are
13275      especial culprits.
13276
13277      One example of this happening is a watchpoint's scope bp.  When
13278      the scope bp triggers, we notice that the watchpoint is out of
13279      scope, and delete it.  We also delete its scope bp.  But the
13280      scope bp is marked "auto-deleting", and is already on a bpstat.
13281      That bpstat is then checked for auto-deleting bp's, which are
13282      deleted.
13283
13284      A real solution to this problem might involve reference counts in
13285      bp's, and/or giving them pointers back to their referencing
13286      bpstat's, and teaching delete_breakpoint to only free a bp's
13287      storage when no more references were extent.  A cheaper bandaid
13288      was chosen.  */
13289   if (bpt->type == bp_none)
13290     return;
13291
13292   /* At least avoid this stale reference until the reference counting
13293      of breakpoints gets resolved.  */
13294   if (bpt->related_breakpoint != bpt)
13295     {
13296       struct breakpoint *related;
13297       struct watchpoint *w;
13298
13299       if (bpt->type == bp_watchpoint_scope)
13300         w = (struct watchpoint *) bpt->related_breakpoint;
13301       else if (bpt->related_breakpoint->type == bp_watchpoint_scope)
13302         w = (struct watchpoint *) bpt;
13303       else
13304         w = NULL;
13305       if (w != NULL)
13306         watchpoint_del_at_next_stop (w);
13307
13308       /* Unlink bpt from the bpt->related_breakpoint ring.  */
13309       for (related = bpt; related->related_breakpoint != bpt;
13310            related = related->related_breakpoint);
13311       related->related_breakpoint = bpt->related_breakpoint;
13312       bpt->related_breakpoint = bpt;
13313     }
13314
13315   /* watch_command_1 creates a watchpoint but only sets its number if
13316      update_watchpoint succeeds in creating its bp_locations.  If there's
13317      a problem in that process, we'll be asked to delete the half-created
13318      watchpoint.  In that case, don't announce the deletion.  */
13319   if (bpt->number)
13320     observer_notify_breakpoint_deleted (bpt);
13321
13322   if (breakpoint_chain == bpt)
13323     breakpoint_chain = bpt->next;
13324
13325   ALL_BREAKPOINTS (b)
13326     if (b->next == bpt)
13327     {
13328       b->next = bpt->next;
13329       break;
13330     }
13331
13332   /* Be sure no bpstat's are pointing at the breakpoint after it's
13333      been freed.  */
13334   /* FIXME, how can we find all bpstat's?  We just check stop_bpstat
13335      in all threads for now.  Note that we cannot just remove bpstats
13336      pointing at bpt from the stop_bpstat list entirely, as breakpoint
13337      commands are associated with the bpstat; if we remove it here,
13338      then the later call to bpstat_do_actions (&stop_bpstat); in
13339      event-top.c won't do anything, and temporary breakpoints with
13340      commands won't work.  */
13341
13342   iterate_over_threads (bpstat_remove_breakpoint_callback, bpt);
13343
13344   /* Now that breakpoint is removed from breakpoint list, update the
13345      global location list.  This will remove locations that used to
13346      belong to this breakpoint.  Do this before freeing the breakpoint
13347      itself, since remove_breakpoint looks at location's owner.  It
13348      might be better design to have location completely
13349      self-contained, but it's not the case now.  */
13350   update_global_location_list (UGLL_DONT_INSERT);
13351
13352   /* On the chance that someone will soon try again to delete this
13353      same bp, we mark it as deleted before freeing its storage.  */
13354   bpt->type = bp_none;
13355   delete bpt;
13356 }
13357
13358 /* Iterator function to call a user-provided callback function once
13359    for each of B and its related breakpoints.  */
13360
13361 static void
13362 iterate_over_related_breakpoints (struct breakpoint *b,
13363                                   gdb::function_view<void (breakpoint *)> function)
13364 {
13365   struct breakpoint *related;
13366
13367   related = b;
13368   do
13369     {
13370       struct breakpoint *next;
13371
13372       /* FUNCTION may delete RELATED.  */
13373       next = related->related_breakpoint;
13374
13375       if (next == related)
13376         {
13377           /* RELATED is the last ring entry.  */
13378           function (related);
13379
13380           /* FUNCTION may have deleted it, so we'd never reach back to
13381              B.  There's nothing left to do anyway, so just break
13382              out.  */
13383           break;
13384         }
13385       else
13386         function (related);
13387
13388       related = next;
13389     }
13390   while (related != b);
13391 }
13392
13393 static void
13394 delete_command (const char *arg, int from_tty)
13395 {
13396   struct breakpoint *b, *b_tmp;
13397
13398   dont_repeat ();
13399
13400   if (arg == 0)
13401     {
13402       int breaks_to_delete = 0;
13403
13404       /* Delete all breakpoints if no argument.  Do not delete
13405          internal breakpoints, these have to be deleted with an
13406          explicit breakpoint number argument.  */
13407       ALL_BREAKPOINTS (b)
13408         if (user_breakpoint_p (b))
13409           {
13410             breaks_to_delete = 1;
13411             break;
13412           }
13413
13414       /* Ask user only if there are some breakpoints to delete.  */
13415       if (!from_tty
13416           || (breaks_to_delete && query (_("Delete all breakpoints? "))))
13417         {
13418           ALL_BREAKPOINTS_SAFE (b, b_tmp)
13419             if (user_breakpoint_p (b))
13420               delete_breakpoint (b);
13421         }
13422     }
13423   else
13424     map_breakpoint_numbers
13425       (arg, [&] (breakpoint *b)
13426        {
13427          iterate_over_related_breakpoints (b, delete_breakpoint);
13428        });
13429 }
13430
13431 /* Return true if all locations of B bound to PSPACE are pending.  If
13432    PSPACE is NULL, all locations of all program spaces are
13433    considered.  */
13434
13435 static int
13436 all_locations_are_pending (struct breakpoint *b, struct program_space *pspace)
13437 {
13438   struct bp_location *loc;
13439
13440   for (loc = b->loc; loc != NULL; loc = loc->next)
13441     if ((pspace == NULL
13442          || loc->pspace == pspace)
13443         && !loc->shlib_disabled
13444         && !loc->pspace->executing_startup)
13445       return 0;
13446   return 1;
13447 }
13448
13449 /* Subroutine of update_breakpoint_locations to simplify it.
13450    Return non-zero if multiple fns in list LOC have the same name.
13451    Null names are ignored.  */
13452
13453 static int
13454 ambiguous_names_p (struct bp_location *loc)
13455 {
13456   struct bp_location *l;
13457   htab_t htab = htab_create_alloc (13, htab_hash_string,
13458                                    (int (*) (const void *, 
13459                                              const void *)) streq,
13460                                    NULL, xcalloc, xfree);
13461
13462   for (l = loc; l != NULL; l = l->next)
13463     {
13464       const char **slot;
13465       const char *name = l->function_name;
13466
13467       /* Allow for some names to be NULL, ignore them.  */
13468       if (name == NULL)
13469         continue;
13470
13471       slot = (const char **) htab_find_slot (htab, (const void *) name,
13472                                              INSERT);
13473       /* NOTE: We can assume slot != NULL here because xcalloc never
13474          returns NULL.  */
13475       if (*slot != NULL)
13476         {
13477           htab_delete (htab);
13478           return 1;
13479         }
13480       *slot = name;
13481     }
13482
13483   htab_delete (htab);
13484   return 0;
13485 }
13486
13487 /* When symbols change, it probably means the sources changed as well,
13488    and it might mean the static tracepoint markers are no longer at
13489    the same address or line numbers they used to be at last we
13490    checked.  Losing your static tracepoints whenever you rebuild is
13491    undesirable.  This function tries to resync/rematch gdb static
13492    tracepoints with the markers on the target, for static tracepoints
13493    that have not been set by marker id.  Static tracepoint that have
13494    been set by marker id are reset by marker id in breakpoint_re_set.
13495    The heuristic is:
13496
13497    1) For a tracepoint set at a specific address, look for a marker at
13498    the old PC.  If one is found there, assume to be the same marker.
13499    If the name / string id of the marker found is different from the
13500    previous known name, assume that means the user renamed the marker
13501    in the sources, and output a warning.
13502
13503    2) For a tracepoint set at a given line number, look for a marker
13504    at the new address of the old line number.  If one is found there,
13505    assume to be the same marker.  If the name / string id of the
13506    marker found is different from the previous known name, assume that
13507    means the user renamed the marker in the sources, and output a
13508    warning.
13509
13510    3) If a marker is no longer found at the same address or line, it
13511    may mean the marker no longer exists.  But it may also just mean
13512    the code changed a bit.  Maybe the user added a few lines of code
13513    that made the marker move up or down (in line number terms).  Ask
13514    the target for info about the marker with the string id as we knew
13515    it.  If found, update line number and address in the matching
13516    static tracepoint.  This will get confused if there's more than one
13517    marker with the same ID (possible in UST, although unadvised
13518    precisely because it confuses tools).  */
13519
13520 static struct symtab_and_line
13521 update_static_tracepoint (struct breakpoint *b, struct symtab_and_line sal)
13522 {
13523   struct tracepoint *tp = (struct tracepoint *) b;
13524   struct static_tracepoint_marker marker;
13525   CORE_ADDR pc;
13526
13527   pc = sal.pc;
13528   if (sal.line)
13529     find_line_pc (sal.symtab, sal.line, &pc);
13530
13531   if (target_static_tracepoint_marker_at (pc, &marker))
13532     {
13533       if (strcmp (tp->static_trace_marker_id, marker.str_id) != 0)
13534         warning (_("static tracepoint %d changed probed marker from %s to %s"),
13535                  b->number,
13536                  tp->static_trace_marker_id, marker.str_id);
13537
13538       xfree (tp->static_trace_marker_id);
13539       tp->static_trace_marker_id = xstrdup (marker.str_id);
13540       release_static_tracepoint_marker (&marker);
13541
13542       return sal;
13543     }
13544
13545   /* Old marker wasn't found on target at lineno.  Try looking it up
13546      by string ID.  */
13547   if (!sal.explicit_pc
13548       && sal.line != 0
13549       && sal.symtab != NULL
13550       && tp->static_trace_marker_id != NULL)
13551     {
13552       VEC(static_tracepoint_marker_p) *markers;
13553
13554       markers
13555         = target_static_tracepoint_markers_by_strid (tp->static_trace_marker_id);
13556
13557       if (!VEC_empty(static_tracepoint_marker_p, markers))
13558         {
13559           struct symbol *sym;
13560           struct static_tracepoint_marker *tpmarker;
13561           struct ui_out *uiout = current_uiout;
13562           struct explicit_location explicit_loc;
13563
13564           tpmarker = VEC_index (static_tracepoint_marker_p, markers, 0);
13565
13566           xfree (tp->static_trace_marker_id);
13567           tp->static_trace_marker_id = xstrdup (tpmarker->str_id);
13568
13569           warning (_("marker for static tracepoint %d (%s) not "
13570                      "found at previous line number"),
13571                    b->number, tp->static_trace_marker_id);
13572
13573           symtab_and_line sal2 = find_pc_line (tpmarker->address, 0);
13574           sym = find_pc_sect_function (tpmarker->address, NULL);
13575           uiout->text ("Now in ");
13576           if (sym)
13577             {
13578               uiout->field_string ("func", SYMBOL_PRINT_NAME (sym));
13579               uiout->text (" at ");
13580             }
13581           uiout->field_string ("file",
13582                                symtab_to_filename_for_display (sal2.symtab));
13583           uiout->text (":");
13584
13585           if (uiout->is_mi_like_p ())
13586             {
13587               const char *fullname = symtab_to_fullname (sal2.symtab);
13588
13589               uiout->field_string ("fullname", fullname);
13590             }
13591
13592           uiout->field_int ("line", sal2.line);
13593           uiout->text ("\n");
13594
13595           b->loc->line_number = sal2.line;
13596           b->loc->symtab = sym != NULL ? sal2.symtab : NULL;
13597
13598           b->location.reset (NULL);
13599           initialize_explicit_location (&explicit_loc);
13600           explicit_loc.source_filename
13601             = ASTRDUP (symtab_to_filename_for_display (sal2.symtab));
13602           explicit_loc.line_offset.offset = b->loc->line_number;
13603           explicit_loc.line_offset.sign = LINE_OFFSET_NONE;
13604           b->location = new_explicit_location (&explicit_loc);
13605
13606           /* Might be nice to check if function changed, and warn if
13607              so.  */
13608
13609           release_static_tracepoint_marker (tpmarker);
13610         }
13611     }
13612   return sal;
13613 }
13614
13615 /* Returns 1 iff locations A and B are sufficiently same that
13616    we don't need to report breakpoint as changed.  */
13617
13618 static int
13619 locations_are_equal (struct bp_location *a, struct bp_location *b)
13620 {
13621   while (a && b)
13622     {
13623       if (a->address != b->address)
13624         return 0;
13625
13626       if (a->shlib_disabled != b->shlib_disabled)
13627         return 0;
13628
13629       if (a->enabled != b->enabled)
13630         return 0;
13631
13632       a = a->next;
13633       b = b->next;
13634     }
13635
13636   if ((a == NULL) != (b == NULL))
13637     return 0;
13638
13639   return 1;
13640 }
13641
13642 /* Split all locations of B that are bound to PSPACE out of B's
13643    location list to a separate list and return that list's head.  If
13644    PSPACE is NULL, hoist out all locations of B.  */
13645
13646 static struct bp_location *
13647 hoist_existing_locations (struct breakpoint *b, struct program_space *pspace)
13648 {
13649   struct bp_location head;
13650   struct bp_location *i = b->loc;
13651   struct bp_location **i_link = &b->loc;
13652   struct bp_location *hoisted = &head;
13653
13654   if (pspace == NULL)
13655     {
13656       i = b->loc;
13657       b->loc = NULL;
13658       return i;
13659     }
13660
13661   head.next = NULL;
13662
13663   while (i != NULL)
13664     {
13665       if (i->pspace == pspace)
13666         {
13667           *i_link = i->next;
13668           i->next = NULL;
13669           hoisted->next = i;
13670           hoisted = i;
13671         }
13672       else
13673         i_link = &i->next;
13674       i = *i_link;
13675     }
13676
13677   return head.next;
13678 }
13679
13680 /* Create new breakpoint locations for B (a hardware or software
13681    breakpoint) based on SALS and SALS_END.  If SALS_END.NELTS is not
13682    zero, then B is a ranged breakpoint.  Only recreates locations for
13683    FILTER_PSPACE.  Locations of other program spaces are left
13684    untouched.  */
13685
13686 void
13687 update_breakpoint_locations (struct breakpoint *b,
13688                              struct program_space *filter_pspace,
13689                              gdb::array_view<const symtab_and_line> sals,
13690                              gdb::array_view<const symtab_and_line> sals_end)
13691 {
13692   int i;
13693   struct bp_location *existing_locations;
13694
13695   if (!sals_end.empty () && (sals.size () != 1 || sals_end.size () != 1))
13696     {
13697       /* Ranged breakpoints have only one start location and one end
13698          location.  */
13699       b->enable_state = bp_disabled;
13700       printf_unfiltered (_("Could not reset ranged breakpoint %d: "
13701                            "multiple locations found\n"),
13702                          b->number);
13703       return;
13704     }
13705
13706   /* If there's no new locations, and all existing locations are
13707      pending, don't do anything.  This optimizes the common case where
13708      all locations are in the same shared library, that was unloaded.
13709      We'd like to retain the location, so that when the library is
13710      loaded again, we don't loose the enabled/disabled status of the
13711      individual locations.  */
13712   if (all_locations_are_pending (b, filter_pspace) && sals.empty ())
13713     return;
13714
13715   existing_locations = hoist_existing_locations (b, filter_pspace);
13716
13717   for (const auto &sal : sals)
13718     {
13719       struct bp_location *new_loc;
13720
13721       switch_to_program_space_and_thread (sal.pspace);
13722
13723       new_loc = add_location_to_breakpoint (b, &sal);
13724
13725       /* Reparse conditions, they might contain references to the
13726          old symtab.  */
13727       if (b->cond_string != NULL)
13728         {
13729           const char *s;
13730
13731           s = b->cond_string;
13732           TRY
13733             {
13734               new_loc->cond = parse_exp_1 (&s, sal.pc,
13735                                            block_for_pc (sal.pc),
13736                                            0);
13737             }
13738           CATCH (e, RETURN_MASK_ERROR)
13739             {
13740               warning (_("failed to reevaluate condition "
13741                          "for breakpoint %d: %s"), 
13742                        b->number, e.message);
13743               new_loc->enabled = 0;
13744             }
13745           END_CATCH
13746         }
13747
13748       if (!sals_end.empty ())
13749         {
13750           CORE_ADDR end = find_breakpoint_range_end (sals_end[0]);
13751
13752           new_loc->length = end - sals[0].pc + 1;
13753         }
13754     }
13755
13756   /* If possible, carry over 'disable' status from existing
13757      breakpoints.  */
13758   {
13759     struct bp_location *e = existing_locations;
13760     /* If there are multiple breakpoints with the same function name,
13761        e.g. for inline functions, comparing function names won't work.
13762        Instead compare pc addresses; this is just a heuristic as things
13763        may have moved, but in practice it gives the correct answer
13764        often enough until a better solution is found.  */
13765     int have_ambiguous_names = ambiguous_names_p (b->loc);
13766
13767     for (; e; e = e->next)
13768       {
13769         if (!e->enabled && e->function_name)
13770           {
13771             struct bp_location *l = b->loc;
13772             if (have_ambiguous_names)
13773               {
13774                 for (; l; l = l->next)
13775                   if (breakpoint_locations_match (e, l))
13776                     {
13777                       l->enabled = 0;
13778                       break;
13779                     }
13780               }
13781             else
13782               {
13783                 for (; l; l = l->next)
13784                   if (l->function_name
13785                       && strcmp (e->function_name, l->function_name) == 0)
13786                     {
13787                       l->enabled = 0;
13788                       break;
13789                     }
13790               }
13791           }
13792       }
13793   }
13794
13795   if (!locations_are_equal (existing_locations, b->loc))
13796     observer_notify_breakpoint_modified (b);
13797 }
13798
13799 /* Find the SaL locations corresponding to the given LOCATION.
13800    On return, FOUND will be 1 if any SaL was found, zero otherwise.  */
13801
13802 static std::vector<symtab_and_line>
13803 location_to_sals (struct breakpoint *b, struct event_location *location,
13804                   struct program_space *search_pspace, int *found)
13805 {
13806   struct gdb_exception exception = exception_none;
13807
13808   gdb_assert (b->ops != NULL);
13809
13810   std::vector<symtab_and_line> sals;
13811
13812   TRY
13813     {
13814       sals = b->ops->decode_location (b, location, search_pspace);
13815     }
13816   CATCH (e, RETURN_MASK_ERROR)
13817     {
13818       int not_found_and_ok = 0;
13819
13820       exception = e;
13821
13822       /* For pending breakpoints, it's expected that parsing will
13823          fail until the right shared library is loaded.  User has
13824          already told to create pending breakpoints and don't need
13825          extra messages.  If breakpoint is in bp_shlib_disabled
13826          state, then user already saw the message about that
13827          breakpoint being disabled, and don't want to see more
13828          errors.  */
13829       if (e.error == NOT_FOUND_ERROR
13830           && (b->condition_not_parsed
13831               || (b->loc != NULL
13832                   && search_pspace != NULL
13833                   && b->loc->pspace != search_pspace)
13834               || (b->loc && b->loc->shlib_disabled)
13835               || (b->loc && b->loc->pspace->executing_startup)
13836               || b->enable_state == bp_disabled))
13837         not_found_and_ok = 1;
13838
13839       if (!not_found_and_ok)
13840         {
13841           /* We surely don't want to warn about the same breakpoint
13842              10 times.  One solution, implemented here, is disable
13843              the breakpoint on error.  Another solution would be to
13844              have separate 'warning emitted' flag.  Since this
13845              happens only when a binary has changed, I don't know
13846              which approach is better.  */
13847           b->enable_state = bp_disabled;
13848           throw_exception (e);
13849         }
13850     }
13851   END_CATCH
13852
13853   if (exception.reason == 0 || exception.error != NOT_FOUND_ERROR)
13854     {
13855       for (auto &sal : sals)
13856         resolve_sal_pc (&sal);
13857       if (b->condition_not_parsed && b->extra_string != NULL)
13858         {
13859           char *cond_string, *extra_string;
13860           int thread, task;
13861
13862           find_condition_and_thread (b->extra_string, sals[0].pc,
13863                                      &cond_string, &thread, &task,
13864                                      &extra_string);
13865           gdb_assert (b->cond_string == NULL);
13866           if (cond_string)
13867             b->cond_string = cond_string;
13868           b->thread = thread;
13869           b->task = task;
13870           if (extra_string)
13871             {
13872               xfree (b->extra_string);
13873               b->extra_string = extra_string;
13874             }
13875           b->condition_not_parsed = 0;
13876         }
13877
13878       if (b->type == bp_static_tracepoint && !strace_marker_p (b))
13879         sals[0] = update_static_tracepoint (b, sals[0]);
13880
13881       *found = 1;
13882     }
13883   else
13884     *found = 0;
13885
13886   return sals;
13887 }
13888
13889 /* The default re_set method, for typical hardware or software
13890    breakpoints.  Reevaluate the breakpoint and recreate its
13891    locations.  */
13892
13893 static void
13894 breakpoint_re_set_default (struct breakpoint *b)
13895 {
13896   struct program_space *filter_pspace = current_program_space;
13897   std::vector<symtab_and_line> expanded, expanded_end;
13898
13899   int found;
13900   std::vector<symtab_and_line> sals = location_to_sals (b, b->location.get (),
13901                                                         filter_pspace, &found);
13902   if (found)
13903     expanded = std::move (sals);
13904
13905   if (b->location_range_end != NULL)
13906     {
13907       std::vector<symtab_and_line> sals_end
13908         = location_to_sals (b, b->location_range_end.get (),
13909                             filter_pspace, &found);
13910       if (found)
13911         expanded_end = std::move (sals_end);
13912     }
13913
13914   update_breakpoint_locations (b, filter_pspace, expanded, expanded_end);
13915 }
13916
13917 /* Default method for creating SALs from an address string.  It basically
13918    calls parse_breakpoint_sals.  Return 1 for success, zero for failure.  */
13919
13920 static void
13921 create_sals_from_location_default (const struct event_location *location,
13922                                    struct linespec_result *canonical,
13923                                    enum bptype type_wanted)
13924 {
13925   parse_breakpoint_sals (location, canonical);
13926 }
13927
13928 /* Call create_breakpoints_sal for the given arguments.  This is the default
13929    function for the `create_breakpoints_sal' method of
13930    breakpoint_ops.  */
13931
13932 static void
13933 create_breakpoints_sal_default (struct gdbarch *gdbarch,
13934                                 struct linespec_result *canonical,
13935                                 gdb::unique_xmalloc_ptr<char> cond_string,
13936                                 gdb::unique_xmalloc_ptr<char> extra_string,
13937                                 enum bptype type_wanted,
13938                                 enum bpdisp disposition,
13939                                 int thread,
13940                                 int task, int ignore_count,
13941                                 const struct breakpoint_ops *ops,
13942                                 int from_tty, int enabled,
13943                                 int internal, unsigned flags)
13944 {
13945   create_breakpoints_sal (gdbarch, canonical,
13946                           std::move (cond_string),
13947                           std::move (extra_string),
13948                           type_wanted, disposition,
13949                           thread, task, ignore_count, ops, from_tty,
13950                           enabled, internal, flags);
13951 }
13952
13953 /* Decode the line represented by S by calling decode_line_full.  This is the
13954    default function for the `decode_location' method of breakpoint_ops.  */
13955
13956 static std::vector<symtab_and_line>
13957 decode_location_default (struct breakpoint *b,
13958                          const struct event_location *location,
13959                          struct program_space *search_pspace)
13960 {
13961   struct linespec_result canonical;
13962
13963   decode_line_full (location, DECODE_LINE_FUNFIRSTLINE, search_pspace,
13964                     (struct symtab *) NULL, 0,
13965                     &canonical, multiple_symbols_all,
13966                     b->filter);
13967
13968   /* We should get 0 or 1 resulting SALs.  */
13969   gdb_assert (canonical.lsals.size () < 2);
13970
13971   if (!canonical.lsals.empty ())
13972     {
13973       const linespec_sals &lsal = canonical.lsals[0];
13974       return std::move (lsal.sals);
13975     }
13976   return {};
13977 }
13978
13979 /* Reset a breakpoint.  */
13980
13981 static void
13982 breakpoint_re_set_one (breakpoint *b)
13983 {
13984   input_radix = b->input_radix;
13985   set_language (b->language);
13986
13987   b->ops->re_set (b);
13988 }
13989
13990 /* Re-set breakpoint locations for the current program space.
13991    Locations bound to other program spaces are left untouched.  */
13992
13993 void
13994 breakpoint_re_set (void)
13995 {
13996   struct breakpoint *b, *b_tmp;
13997
13998   {
13999     scoped_restore_current_language save_language;
14000     scoped_restore save_input_radix = make_scoped_restore (&input_radix);
14001     scoped_restore_current_pspace_and_thread restore_pspace_thread;
14002
14003     /* Note: we must not try to insert locations until after all
14004        breakpoints have been re-set.  Otherwise, e.g., when re-setting
14005        breakpoint 1, we'd insert the locations of breakpoint 2, which
14006        hadn't been re-set yet, and thus may have stale locations.  */
14007
14008     ALL_BREAKPOINTS_SAFE (b, b_tmp)
14009       {
14010         TRY
14011           {
14012             breakpoint_re_set_one (b);
14013           }
14014         CATCH (ex, RETURN_MASK_ALL)
14015           {
14016             exception_fprintf (gdb_stderr, ex,
14017                                "Error in re-setting breakpoint %d: ",
14018                                b->number);
14019           }
14020         END_CATCH
14021       }
14022
14023     jit_breakpoint_re_set ();
14024   }
14025
14026   create_overlay_event_breakpoint ();
14027   create_longjmp_master_breakpoint ();
14028   create_std_terminate_master_breakpoint ();
14029   create_exception_master_breakpoint ();
14030
14031   /* Now we can insert.  */
14032   update_global_location_list (UGLL_MAY_INSERT);
14033 }
14034 \f
14035 /* Reset the thread number of this breakpoint:
14036
14037    - If the breakpoint is for all threads, leave it as-is.
14038    - Else, reset it to the current thread for inferior_ptid.  */
14039 void
14040 breakpoint_re_set_thread (struct breakpoint *b)
14041 {
14042   if (b->thread != -1)
14043     {
14044       if (in_thread_list (inferior_ptid))
14045         b->thread = ptid_to_global_thread_id (inferior_ptid);
14046
14047       /* We're being called after following a fork.  The new fork is
14048          selected as current, and unless this was a vfork will have a
14049          different program space from the original thread.  Reset that
14050          as well.  */
14051       b->loc->pspace = current_program_space;
14052     }
14053 }
14054
14055 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
14056    If from_tty is nonzero, it prints a message to that effect,
14057    which ends with a period (no newline).  */
14058
14059 void
14060 set_ignore_count (int bptnum, int count, int from_tty)
14061 {
14062   struct breakpoint *b;
14063
14064   if (count < 0)
14065     count = 0;
14066
14067   ALL_BREAKPOINTS (b)
14068     if (b->number == bptnum)
14069     {
14070       if (is_tracepoint (b))
14071         {
14072           if (from_tty && count != 0)
14073             printf_filtered (_("Ignore count ignored for tracepoint %d."),
14074                              bptnum);
14075           return;
14076         }
14077       
14078       b->ignore_count = count;
14079       if (from_tty)
14080         {
14081           if (count == 0)
14082             printf_filtered (_("Will stop next time "
14083                                "breakpoint %d is reached."),
14084                              bptnum);
14085           else if (count == 1)
14086             printf_filtered (_("Will ignore next crossing of breakpoint %d."),
14087                              bptnum);
14088           else
14089             printf_filtered (_("Will ignore next %d "
14090                                "crossings of breakpoint %d."),
14091                              count, bptnum);
14092         }
14093       observer_notify_breakpoint_modified (b);
14094       return;
14095     }
14096
14097   error (_("No breakpoint number %d."), bptnum);
14098 }
14099
14100 /* Command to set ignore-count of breakpoint N to COUNT.  */
14101
14102 static void
14103 ignore_command (const char *args, int from_tty)
14104 {
14105   const char *p = args;
14106   int num;
14107
14108   if (p == 0)
14109     error_no_arg (_("a breakpoint number"));
14110
14111   num = get_number (&p);
14112   if (num == 0)
14113     error (_("bad breakpoint number: '%s'"), args);
14114   if (*p == 0)
14115     error (_("Second argument (specified ignore-count) is missing."));
14116
14117   set_ignore_count (num,
14118                     longest_to_int (value_as_long (parse_and_eval (p))),
14119                     from_tty);
14120   if (from_tty)
14121     printf_filtered ("\n");
14122 }
14123 \f
14124
14125 /* Call FUNCTION on each of the breakpoints with numbers in the range
14126    defined by BP_NUM_RANGE (an inclusive range).  */
14127
14128 static void
14129 map_breakpoint_number_range (std::pair<int, int> bp_num_range,
14130                              gdb::function_view<void (breakpoint *)> function)
14131 {
14132   if (bp_num_range.first == 0)
14133     {
14134       warning (_("bad breakpoint number at or near '%d'"),
14135                bp_num_range.first);
14136     }
14137   else
14138     {
14139       struct breakpoint *b, *tmp;
14140
14141       for (int i = bp_num_range.first; i <= bp_num_range.second; i++)
14142         {
14143           bool match = false;
14144
14145           ALL_BREAKPOINTS_SAFE (b, tmp)
14146             if (b->number == i)
14147               {
14148                 match = true;
14149                 function (b);
14150                 break;
14151               }
14152           if (!match)
14153             printf_unfiltered (_("No breakpoint number %d.\n"), i);
14154         }
14155     }
14156 }
14157
14158 /* Call FUNCTION on each of the breakpoints whose numbers are given in
14159    ARGS.  */
14160
14161 static void
14162 map_breakpoint_numbers (const char *args,
14163                         gdb::function_view<void (breakpoint *)> function)
14164 {
14165   if (args == NULL || *args == '\0')
14166     error_no_arg (_("one or more breakpoint numbers"));
14167
14168   number_or_range_parser parser (args);
14169
14170   while (!parser.finished ())
14171     {
14172       int num = parser.get_number ();
14173       map_breakpoint_number_range (std::make_pair (num, num), function);
14174     }
14175 }
14176
14177 /* Return the breakpoint location structure corresponding to the
14178    BP_NUM and LOC_NUM values.  */
14179
14180 static struct bp_location *
14181 find_location_by_number (int bp_num, int loc_num)
14182 {
14183   struct breakpoint *b;
14184
14185   ALL_BREAKPOINTS (b)
14186     if (b->number == bp_num)
14187       {
14188         break;
14189       }
14190
14191   if (!b || b->number != bp_num)
14192     error (_("Bad breakpoint number '%d'"), bp_num);
14193   
14194   if (loc_num == 0)
14195     error (_("Bad breakpoint location number '%d'"), loc_num);
14196
14197   int n = 0;
14198   for (bp_location *loc = b->loc; loc != NULL; loc = loc->next)
14199     if (++n == loc_num)
14200       return loc;
14201
14202   error (_("Bad breakpoint location number '%d'"), loc_num);
14203 }
14204
14205 /* Modes of operation for extract_bp_num.  */
14206 enum class extract_bp_kind
14207 {
14208   /* Extracting a breakpoint number.  */
14209   bp,
14210
14211   /* Extracting a location number.  */
14212   loc,
14213 };
14214
14215 /* Extract a breakpoint or location number (as determined by KIND)
14216    from the string starting at START.  TRAILER is a character which
14217    can be found after the number.  If you don't want a trailer, use
14218    '\0'.  If END_OUT is not NULL, it is set to point after the parsed
14219    string.  This always returns a positive integer.  */
14220
14221 static int
14222 extract_bp_num (extract_bp_kind kind, const char *start,
14223                 int trailer, const char **end_out = NULL)
14224 {
14225   const char *end = start;
14226   int num = get_number_trailer (&end, trailer);
14227   if (num < 0)
14228     error (kind == extract_bp_kind::bp
14229            ? _("Negative breakpoint number '%.*s'")
14230            : _("Negative breakpoint location number '%.*s'"),
14231            int (end - start), start);
14232   if (num == 0)
14233     error (kind == extract_bp_kind::bp
14234            ? _("Bad breakpoint number '%.*s'")
14235            : _("Bad breakpoint location number '%.*s'"),
14236            int (end - start), start);
14237
14238   if (end_out != NULL)
14239     *end_out = end;
14240   return num;
14241 }
14242
14243 /* Extract a breakpoint or location range (as determined by KIND) in
14244    the form NUM1-NUM2 stored at &ARG[arg_offset].  Returns a std::pair
14245    representing the (inclusive) range.  The returned pair's elements
14246    are always positive integers.  */
14247
14248 static std::pair<int, int>
14249 extract_bp_or_bp_range (extract_bp_kind kind,
14250                         const std::string &arg,
14251                         std::string::size_type arg_offset)
14252 {
14253   std::pair<int, int> range;
14254   const char *bp_loc = &arg[arg_offset];
14255   std::string::size_type dash = arg.find ('-', arg_offset);
14256   if (dash != std::string::npos)
14257     {
14258       /* bp_loc is a range (x-z).  */
14259       if (arg.length () == dash + 1)
14260         error (kind == extract_bp_kind::bp
14261                ? _("Bad breakpoint number at or near: '%s'")
14262                : _("Bad breakpoint location number at or near: '%s'"),
14263                bp_loc);
14264
14265       const char *end;
14266       const char *start_first = bp_loc;
14267       const char *start_second = &arg[dash + 1];
14268       range.first = extract_bp_num (kind, start_first, '-');
14269       range.second = extract_bp_num (kind, start_second, '\0', &end);
14270
14271       if (range.first > range.second)
14272         error (kind == extract_bp_kind::bp
14273                ? _("Inverted breakpoint range at '%.*s'")
14274                : _("Inverted breakpoint location range at '%.*s'"),
14275                int (end - start_first), start_first);
14276     }
14277   else
14278     {
14279       /* bp_loc is a single value.  */
14280       range.first = extract_bp_num (kind, bp_loc, '\0');
14281       range.second = range.first;
14282     }
14283   return range;
14284 }
14285
14286 /* Extract the breakpoint/location range specified by ARG.  Returns
14287    the breakpoint range in BP_NUM_RANGE, and the location range in
14288    BP_LOC_RANGE.
14289
14290    ARG may be in any of the following forms:
14291
14292    x     where 'x' is a breakpoint number.
14293    x-y   where 'x' and 'y' specify a breakpoint numbers range.
14294    x.y   where 'x' is a breakpoint number and 'y' a location number.
14295    x.y-z where 'x' is a breakpoint number and 'y' and 'z' specify a
14296          location number range.
14297 */
14298
14299 static void
14300 extract_bp_number_and_location (const std::string &arg,
14301                                 std::pair<int, int> &bp_num_range,
14302                                 std::pair<int, int> &bp_loc_range)
14303 {
14304   std::string::size_type dot = arg.find ('.');
14305
14306   if (dot != std::string::npos)
14307     {
14308       /* Handle 'x.y' and 'x.y-z' cases.  */
14309
14310       if (arg.length () == dot + 1 || dot == 0)
14311         error (_("Bad breakpoint number at or near: '%s'"), arg.c_str ());
14312
14313       bp_num_range.first
14314         = extract_bp_num (extract_bp_kind::bp, arg.c_str (), '.');
14315       bp_num_range.second = bp_num_range.first;
14316
14317       bp_loc_range = extract_bp_or_bp_range (extract_bp_kind::loc,
14318                                              arg, dot + 1);
14319     }
14320   else
14321     {
14322       /* Handle x and x-y cases.  */
14323
14324       bp_num_range = extract_bp_or_bp_range (extract_bp_kind::bp, arg, 0);
14325       bp_loc_range.first = 0;
14326       bp_loc_range.second = 0;
14327     }
14328 }
14329
14330 /* Enable or disable a breakpoint location BP_NUM.LOC_NUM.  ENABLE
14331    specifies whether to enable or disable.  */
14332
14333 static void
14334 enable_disable_bp_num_loc (int bp_num, int loc_num, bool enable)
14335 {
14336   struct bp_location *loc = find_location_by_number (bp_num, loc_num);
14337   if (loc != NULL)
14338     {
14339       if (loc->enabled != enable)
14340         {
14341           loc->enabled = enable;
14342           mark_breakpoint_location_modified (loc);
14343         }
14344       if (target_supports_enable_disable_tracepoint ()
14345           && current_trace_status ()->running && loc->owner
14346           && is_tracepoint (loc->owner))
14347         target_disable_tracepoint (loc);
14348     }
14349   update_global_location_list (UGLL_DONT_INSERT);
14350 }
14351
14352 /* Enable or disable a range of breakpoint locations.  BP_NUM is the
14353    number of the breakpoint, and BP_LOC_RANGE specifies the
14354    (inclusive) range of location numbers of that breakpoint to
14355    enable/disable.  ENABLE specifies whether to enable or disable the
14356    location.  */
14357
14358 static void
14359 enable_disable_breakpoint_location_range (int bp_num,
14360                                           std::pair<int, int> &bp_loc_range,
14361                                           bool enable)
14362 {
14363   for (int i = bp_loc_range.first; i <= bp_loc_range.second; i++)
14364     enable_disable_bp_num_loc (bp_num, i, enable);
14365 }
14366
14367 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
14368    If from_tty is nonzero, it prints a message to that effect,
14369    which ends with a period (no newline).  */
14370
14371 void
14372 disable_breakpoint (struct breakpoint *bpt)
14373 {
14374   /* Never disable a watchpoint scope breakpoint; we want to
14375      hit them when we leave scope so we can delete both the
14376      watchpoint and its scope breakpoint at that time.  */
14377   if (bpt->type == bp_watchpoint_scope)
14378     return;
14379
14380   bpt->enable_state = bp_disabled;
14381
14382   /* Mark breakpoint locations modified.  */
14383   mark_breakpoint_modified (bpt);
14384
14385   if (target_supports_enable_disable_tracepoint ()
14386       && current_trace_status ()->running && is_tracepoint (bpt))
14387     {
14388       struct bp_location *location;
14389      
14390       for (location = bpt->loc; location; location = location->next)
14391         target_disable_tracepoint (location);
14392     }
14393
14394   update_global_location_list (UGLL_DONT_INSERT);
14395
14396   observer_notify_breakpoint_modified (bpt);
14397 }
14398
14399 /* Enable or disable the breakpoint(s) or breakpoint location(s)
14400    specified in ARGS.  ARGS may be in any of the formats handled by
14401    extract_bp_number_and_location.  ENABLE specifies whether to enable
14402    or disable the breakpoints/locations.  */
14403
14404 static void
14405 enable_disable_command (const char *args, int from_tty, bool enable)
14406 {
14407   if (args == 0)
14408     {
14409       struct breakpoint *bpt;
14410
14411       ALL_BREAKPOINTS (bpt)
14412         if (user_breakpoint_p (bpt))
14413           {
14414             if (enable)
14415               enable_breakpoint (bpt);
14416             else
14417               disable_breakpoint (bpt);
14418           }
14419     }
14420   else
14421     {
14422       std::string num = extract_arg (&args);
14423
14424       while (!num.empty ())
14425         {
14426           std::pair<int, int> bp_num_range, bp_loc_range;
14427
14428           extract_bp_number_and_location (num, bp_num_range, bp_loc_range);
14429
14430           if (bp_loc_range.first == bp_loc_range.second
14431               && bp_loc_range.first == 0)
14432             {
14433               /* Handle breakpoint ids with formats 'x' or 'x-z'.  */
14434               map_breakpoint_number_range (bp_num_range,
14435                                            enable
14436                                            ? enable_breakpoint
14437                                            : disable_breakpoint);
14438             }
14439           else
14440             {
14441               /* Handle breakpoint ids with formats 'x.y' or
14442                  'x.y-z'.  */
14443               enable_disable_breakpoint_location_range
14444                 (bp_num_range.first, bp_loc_range, enable);
14445             }
14446           num = extract_arg (&args);
14447         }
14448     }
14449 }
14450
14451 /* The disable command disables the specified breakpoints/locations
14452    (or all defined breakpoints) so they're no longer effective in
14453    stopping the inferior.  ARGS may be in any of the forms defined in
14454    extract_bp_number_and_location.  */
14455
14456 static void
14457 disable_command (const char *args, int from_tty)
14458 {
14459   enable_disable_command (args, from_tty, false);
14460 }
14461
14462 static void
14463 enable_breakpoint_disp (struct breakpoint *bpt, enum bpdisp disposition,
14464                         int count)
14465 {
14466   int target_resources_ok;
14467
14468   if (bpt->type == bp_hardware_breakpoint)
14469     {
14470       int i;
14471       i = hw_breakpoint_used_count ();
14472       target_resources_ok = 
14473         target_can_use_hardware_watchpoint (bp_hardware_breakpoint, 
14474                                             i + 1, 0);
14475       if (target_resources_ok == 0)
14476         error (_("No hardware breakpoint support in the target."));
14477       else if (target_resources_ok < 0)
14478         error (_("Hardware breakpoints used exceeds limit."));
14479     }
14480
14481   if (is_watchpoint (bpt))
14482     {
14483       /* Initialize it just to avoid a GCC false warning.  */
14484       enum enable_state orig_enable_state = bp_disabled;
14485
14486       TRY
14487         {
14488           struct watchpoint *w = (struct watchpoint *) bpt;
14489
14490           orig_enable_state = bpt->enable_state;
14491           bpt->enable_state = bp_enabled;
14492           update_watchpoint (w, 1 /* reparse */);
14493         }
14494       CATCH (e, RETURN_MASK_ALL)
14495         {
14496           bpt->enable_state = orig_enable_state;
14497           exception_fprintf (gdb_stderr, e, _("Cannot enable watchpoint %d: "),
14498                              bpt->number);
14499           return;
14500         }
14501       END_CATCH
14502     }
14503
14504   bpt->enable_state = bp_enabled;
14505
14506   /* Mark breakpoint locations modified.  */
14507   mark_breakpoint_modified (bpt);
14508
14509   if (target_supports_enable_disable_tracepoint ()
14510       && current_trace_status ()->running && is_tracepoint (bpt))
14511     {
14512       struct bp_location *location;
14513
14514       for (location = bpt->loc; location; location = location->next)
14515         target_enable_tracepoint (location);
14516     }
14517
14518   bpt->disposition = disposition;
14519   bpt->enable_count = count;
14520   update_global_location_list (UGLL_MAY_INSERT);
14521
14522   observer_notify_breakpoint_modified (bpt);
14523 }
14524
14525
14526 void
14527 enable_breakpoint (struct breakpoint *bpt)
14528 {
14529   enable_breakpoint_disp (bpt, bpt->disposition, 0);
14530 }
14531
14532 /* The enable command enables the specified breakpoints/locations (or
14533    all defined breakpoints) so they once again become (or continue to
14534    be) effective in stopping the inferior.  ARGS may be in any of the
14535    forms defined in extract_bp_number_and_location.  */
14536
14537 static void
14538 enable_command (const char *args, int from_tty)
14539 {
14540   enable_disable_command (args, from_tty, true);
14541 }
14542
14543 static void
14544 enable_once_command (const char *args, int from_tty)
14545 {
14546   map_breakpoint_numbers
14547     (args, [&] (breakpoint *b)
14548      {
14549        iterate_over_related_breakpoints
14550          (b, [&] (breakpoint *bpt)
14551           {
14552             enable_breakpoint_disp (bpt, disp_disable, 1);
14553           });
14554      });
14555 }
14556
14557 static void
14558 enable_count_command (const char *args, int from_tty)
14559 {
14560   int count;
14561
14562   if (args == NULL)
14563     error_no_arg (_("hit count"));
14564
14565   count = get_number (&args);
14566
14567   map_breakpoint_numbers
14568     (args, [&] (breakpoint *b)
14569      {
14570        iterate_over_related_breakpoints
14571          (b, [&] (breakpoint *bpt)
14572           {
14573             enable_breakpoint_disp (bpt, disp_disable, count);
14574           });
14575      });
14576 }
14577
14578 static void
14579 enable_delete_command (const char *args, int from_tty)
14580 {
14581   map_breakpoint_numbers
14582     (args, [&] (breakpoint *b)
14583      {
14584        iterate_over_related_breakpoints
14585          (b, [&] (breakpoint *bpt)
14586           {
14587             enable_breakpoint_disp (bpt, disp_del, 1);
14588           });
14589      });
14590 }
14591 \f
14592 static void
14593 set_breakpoint_cmd (const char *args, int from_tty)
14594 {
14595 }
14596
14597 static void
14598 show_breakpoint_cmd (const char *args, int from_tty)
14599 {
14600 }
14601
14602 /* Invalidate last known value of any hardware watchpoint if
14603    the memory which that value represents has been written to by
14604    GDB itself.  */
14605
14606 static void
14607 invalidate_bp_value_on_memory_change (struct inferior *inferior,
14608                                       CORE_ADDR addr, ssize_t len,
14609                                       const bfd_byte *data)
14610 {
14611   struct breakpoint *bp;
14612
14613   ALL_BREAKPOINTS (bp)
14614     if (bp->enable_state == bp_enabled
14615         && bp->type == bp_hardware_watchpoint)
14616       {
14617         struct watchpoint *wp = (struct watchpoint *) bp;
14618
14619         if (wp->val_valid && wp->val)
14620           {
14621             struct bp_location *loc;
14622
14623             for (loc = bp->loc; loc != NULL; loc = loc->next)
14624               if (loc->loc_type == bp_loc_hardware_watchpoint
14625                   && loc->address + loc->length > addr
14626                   && addr + len > loc->address)
14627                 {
14628                   value_free (wp->val);
14629                   wp->val = NULL;
14630                   wp->val_valid = 0;
14631                 }
14632           }
14633       }
14634 }
14635
14636 /* Create and insert a breakpoint for software single step.  */
14637
14638 void
14639 insert_single_step_breakpoint (struct gdbarch *gdbarch,
14640                                const address_space *aspace,
14641                                CORE_ADDR next_pc)
14642 {
14643   struct thread_info *tp = inferior_thread ();
14644   struct symtab_and_line sal;
14645   CORE_ADDR pc = next_pc;
14646
14647   if (tp->control.single_step_breakpoints == NULL)
14648     {
14649       tp->control.single_step_breakpoints
14650         = new_single_step_breakpoint (tp->global_num, gdbarch);
14651     }
14652
14653   sal = find_pc_line (pc, 0);
14654   sal.pc = pc;
14655   sal.section = find_pc_overlay (pc);
14656   sal.explicit_pc = 1;
14657   add_location_to_breakpoint (tp->control.single_step_breakpoints, &sal);
14658
14659   update_global_location_list (UGLL_INSERT);
14660 }
14661
14662 /* Insert single step breakpoints according to the current state.  */
14663
14664 int
14665 insert_single_step_breakpoints (struct gdbarch *gdbarch)
14666 {
14667   struct regcache *regcache = get_current_regcache ();
14668   std::vector<CORE_ADDR> next_pcs;
14669
14670   next_pcs = gdbarch_software_single_step (gdbarch, regcache);
14671
14672   if (!next_pcs.empty ())
14673     {
14674       struct frame_info *frame = get_current_frame ();
14675       const address_space *aspace = get_frame_address_space (frame);
14676
14677       for (CORE_ADDR pc : next_pcs)
14678         insert_single_step_breakpoint (gdbarch, aspace, pc);
14679
14680       return 1;
14681     }
14682   else
14683     return 0;
14684 }
14685
14686 /* See breakpoint.h.  */
14687
14688 int
14689 breakpoint_has_location_inserted_here (struct breakpoint *bp,
14690                                        const address_space *aspace,
14691                                        CORE_ADDR pc)
14692 {
14693   struct bp_location *loc;
14694
14695   for (loc = bp->loc; loc != NULL; loc = loc->next)
14696     if (loc->inserted
14697         && breakpoint_location_address_match (loc, aspace, pc))
14698       return 1;
14699
14700   return 0;
14701 }
14702
14703 /* Check whether a software single-step breakpoint is inserted at
14704    PC.  */
14705
14706 int
14707 single_step_breakpoint_inserted_here_p (const address_space *aspace,
14708                                         CORE_ADDR pc)
14709 {
14710   struct breakpoint *bpt;
14711
14712   ALL_BREAKPOINTS (bpt)
14713     {
14714       if (bpt->type == bp_single_step
14715           && breakpoint_has_location_inserted_here (bpt, aspace, pc))
14716         return 1;
14717     }
14718   return 0;
14719 }
14720
14721 /* Tracepoint-specific operations.  */
14722
14723 /* Set tracepoint count to NUM.  */
14724 static void
14725 set_tracepoint_count (int num)
14726 {
14727   tracepoint_count = num;
14728   set_internalvar_integer (lookup_internalvar ("tpnum"), num);
14729 }
14730
14731 static void
14732 trace_command (const char *arg, int from_tty)
14733 {
14734   struct breakpoint_ops *ops;
14735
14736   event_location_up location = string_to_event_location (&arg,
14737                                                          current_language);
14738   if (location != NULL
14739       && event_location_type (location.get ()) == PROBE_LOCATION)
14740     ops = &tracepoint_probe_breakpoint_ops;
14741   else
14742     ops = &tracepoint_breakpoint_ops;
14743
14744   create_breakpoint (get_current_arch (),
14745                      location.get (),
14746                      NULL, 0, arg, 1 /* parse arg */,
14747                      0 /* tempflag */,
14748                      bp_tracepoint /* type_wanted */,
14749                      0 /* Ignore count */,
14750                      pending_break_support,
14751                      ops,
14752                      from_tty,
14753                      1 /* enabled */,
14754                      0 /* internal */, 0);
14755 }
14756
14757 static void
14758 ftrace_command (const char *arg, int from_tty)
14759 {
14760   event_location_up location = string_to_event_location (&arg,
14761                                                          current_language);
14762   create_breakpoint (get_current_arch (),
14763                      location.get (),
14764                      NULL, 0, arg, 1 /* parse arg */,
14765                      0 /* tempflag */,
14766                      bp_fast_tracepoint /* type_wanted */,
14767                      0 /* Ignore count */,
14768                      pending_break_support,
14769                      &tracepoint_breakpoint_ops,
14770                      from_tty,
14771                      1 /* enabled */,
14772                      0 /* internal */, 0);
14773 }
14774
14775 /* strace command implementation.  Creates a static tracepoint.  */
14776
14777 static void
14778 strace_command (const char *arg, int from_tty)
14779 {
14780   struct breakpoint_ops *ops;
14781   event_location_up location;
14782
14783   /* Decide if we are dealing with a static tracepoint marker (`-m'),
14784      or with a normal static tracepoint.  */
14785   if (arg && startswith (arg, "-m") && isspace (arg[2]))
14786     {
14787       ops = &strace_marker_breakpoint_ops;
14788       location = new_linespec_location (&arg);
14789     }
14790   else
14791     {
14792       ops = &tracepoint_breakpoint_ops;
14793       location = string_to_event_location (&arg, current_language);
14794     }
14795
14796   create_breakpoint (get_current_arch (),
14797                      location.get (),
14798                      NULL, 0, arg, 1 /* parse arg */,
14799                      0 /* tempflag */,
14800                      bp_static_tracepoint /* type_wanted */,
14801                      0 /* Ignore count */,
14802                      pending_break_support,
14803                      ops,
14804                      from_tty,
14805                      1 /* enabled */,
14806                      0 /* internal */, 0);
14807 }
14808
14809 /* Set up a fake reader function that gets command lines from a linked
14810    list that was acquired during tracepoint uploading.  */
14811
14812 static struct uploaded_tp *this_utp;
14813 static int next_cmd;
14814
14815 static char *
14816 read_uploaded_action (void)
14817 {
14818   char *rslt;
14819
14820   VEC_iterate (char_ptr, this_utp->cmd_strings, next_cmd, rslt);
14821
14822   next_cmd++;
14823
14824   return rslt;
14825 }
14826
14827 /* Given information about a tracepoint as recorded on a target (which
14828    can be either a live system or a trace file), attempt to create an
14829    equivalent GDB tracepoint.  This is not a reliable process, since
14830    the target does not necessarily have all the information used when
14831    the tracepoint was originally defined.  */
14832   
14833 struct tracepoint *
14834 create_tracepoint_from_upload (struct uploaded_tp *utp)
14835 {
14836   const char *addr_str;
14837   char small_buf[100];
14838   struct tracepoint *tp;
14839
14840   if (utp->at_string)
14841     addr_str = utp->at_string;
14842   else
14843     {
14844       /* In the absence of a source location, fall back to raw
14845          address.  Since there is no way to confirm that the address
14846          means the same thing as when the trace was started, warn the
14847          user.  */
14848       warning (_("Uploaded tracepoint %d has no "
14849                  "source location, using raw address"),
14850                utp->number);
14851       xsnprintf (small_buf, sizeof (small_buf), "*%s", hex_string (utp->addr));
14852       addr_str = small_buf;
14853     }
14854
14855   /* There's not much we can do with a sequence of bytecodes.  */
14856   if (utp->cond && !utp->cond_string)
14857     warning (_("Uploaded tracepoint %d condition "
14858                "has no source form, ignoring it"),
14859              utp->number);
14860
14861   event_location_up location = string_to_event_location (&addr_str,
14862                                                          current_language);
14863   if (!create_breakpoint (get_current_arch (),
14864                           location.get (),
14865                           utp->cond_string, -1, addr_str,
14866                           0 /* parse cond/thread */,
14867                           0 /* tempflag */,
14868                           utp->type /* type_wanted */,
14869                           0 /* Ignore count */,
14870                           pending_break_support,
14871                           &tracepoint_breakpoint_ops,
14872                           0 /* from_tty */,
14873                           utp->enabled /* enabled */,
14874                           0 /* internal */,
14875                           CREATE_BREAKPOINT_FLAGS_INSERTED))
14876     return NULL;
14877
14878   /* Get the tracepoint we just created.  */
14879   tp = get_tracepoint (tracepoint_count);
14880   gdb_assert (tp != NULL);
14881
14882   if (utp->pass > 0)
14883     {
14884       xsnprintf (small_buf, sizeof (small_buf), "%d %d", utp->pass,
14885                  tp->number);
14886
14887       trace_pass_command (small_buf, 0);
14888     }
14889
14890   /* If we have uploaded versions of the original commands, set up a
14891      special-purpose "reader" function and call the usual command line
14892      reader, then pass the result to the breakpoint command-setting
14893      function.  */
14894   if (!VEC_empty (char_ptr, utp->cmd_strings))
14895     {
14896       command_line_up cmd_list;
14897
14898       this_utp = utp;
14899       next_cmd = 0;
14900
14901       cmd_list = read_command_lines_1 (read_uploaded_action, 1, NULL, NULL);
14902
14903       breakpoint_set_commands (tp, std::move (cmd_list));
14904     }
14905   else if (!VEC_empty (char_ptr, utp->actions)
14906            || !VEC_empty (char_ptr, utp->step_actions))
14907     warning (_("Uploaded tracepoint %d actions "
14908                "have no source form, ignoring them"),
14909              utp->number);
14910
14911   /* Copy any status information that might be available.  */
14912   tp->hit_count = utp->hit_count;
14913   tp->traceframe_usage = utp->traceframe_usage;
14914
14915   return tp;
14916 }
14917   
14918 /* Print information on tracepoint number TPNUM_EXP, or all if
14919    omitted.  */
14920
14921 static void
14922 info_tracepoints_command (char *args, int from_tty)
14923 {
14924   struct ui_out *uiout = current_uiout;
14925   int num_printed;
14926
14927   num_printed = breakpoint_1 (args, 0, is_tracepoint);
14928
14929   if (num_printed == 0)
14930     {
14931       if (args == NULL || *args == '\0')
14932         uiout->message ("No tracepoints.\n");
14933       else
14934         uiout->message ("No tracepoint matching '%s'.\n", args);
14935     }
14936
14937   default_collect_info ();
14938 }
14939
14940 /* The 'enable trace' command enables tracepoints.
14941    Not supported by all targets.  */
14942 static void
14943 enable_trace_command (char *args, int from_tty)
14944 {
14945   enable_command (args, from_tty);
14946 }
14947
14948 /* The 'disable trace' command disables tracepoints.
14949    Not supported by all targets.  */
14950 static void
14951 disable_trace_command (char *args, int from_tty)
14952 {
14953   disable_command (args, from_tty);
14954 }
14955
14956 /* Remove a tracepoint (or all if no argument).  */
14957 static void
14958 delete_trace_command (const char *arg, int from_tty)
14959 {
14960   struct breakpoint *b, *b_tmp;
14961
14962   dont_repeat ();
14963
14964   if (arg == 0)
14965     {
14966       int breaks_to_delete = 0;
14967
14968       /* Delete all breakpoints if no argument.
14969          Do not delete internal or call-dummy breakpoints, these
14970          have to be deleted with an explicit breakpoint number 
14971          argument.  */
14972       ALL_TRACEPOINTS (b)
14973         if (is_tracepoint (b) && user_breakpoint_p (b))
14974           {
14975             breaks_to_delete = 1;
14976             break;
14977           }
14978
14979       /* Ask user only if there are some breakpoints to delete.  */
14980       if (!from_tty
14981           || (breaks_to_delete && query (_("Delete all tracepoints? "))))
14982         {
14983           ALL_BREAKPOINTS_SAFE (b, b_tmp)
14984             if (is_tracepoint (b) && user_breakpoint_p (b))
14985               delete_breakpoint (b);
14986         }
14987     }
14988   else
14989     map_breakpoint_numbers
14990       (arg, [&] (breakpoint *b)
14991        {
14992          iterate_over_related_breakpoints (b, delete_breakpoint);
14993        });
14994 }
14995
14996 /* Helper function for trace_pass_command.  */
14997
14998 static void
14999 trace_pass_set_count (struct tracepoint *tp, int count, int from_tty)
15000 {
15001   tp->pass_count = count;
15002   observer_notify_breakpoint_modified (tp);
15003   if (from_tty)
15004     printf_filtered (_("Setting tracepoint %d's passcount to %d\n"),
15005                      tp->number, count);
15006 }
15007
15008 /* Set passcount for tracepoint.
15009
15010    First command argument is passcount, second is tracepoint number.
15011    If tracepoint number omitted, apply to most recently defined.
15012    Also accepts special argument "all".  */
15013
15014 static void
15015 trace_pass_command (const char *args, int from_tty)
15016 {
15017   struct tracepoint *t1;
15018   ULONGEST count;
15019
15020   if (args == 0 || *args == 0)
15021     error (_("passcount command requires an "
15022              "argument (count + optional TP num)"));
15023
15024   count = strtoulst (args, &args, 10);  /* Count comes first, then TP num.  */
15025
15026   args = skip_spaces (args);
15027   if (*args && strncasecmp (args, "all", 3) == 0)
15028     {
15029       struct breakpoint *b;
15030
15031       args += 3;                        /* Skip special argument "all".  */
15032       if (*args)
15033         error (_("Junk at end of arguments."));
15034
15035       ALL_TRACEPOINTS (b)
15036       {
15037         t1 = (struct tracepoint *) b;
15038         trace_pass_set_count (t1, count, from_tty);
15039       }
15040     }
15041   else if (*args == '\0')
15042     {
15043       t1 = get_tracepoint_by_number (&args, NULL);
15044       if (t1)
15045         trace_pass_set_count (t1, count, from_tty);
15046     }
15047   else
15048     {
15049       number_or_range_parser parser (args);
15050       while (!parser.finished ())
15051         {
15052           t1 = get_tracepoint_by_number (&args, &parser);
15053           if (t1)
15054             trace_pass_set_count (t1, count, from_tty);
15055         }
15056     }
15057 }
15058
15059 struct tracepoint *
15060 get_tracepoint (int num)
15061 {
15062   struct breakpoint *t;
15063
15064   ALL_TRACEPOINTS (t)
15065     if (t->number == num)
15066       return (struct tracepoint *) t;
15067
15068   return NULL;
15069 }
15070
15071 /* Find the tracepoint with the given target-side number (which may be
15072    different from the tracepoint number after disconnecting and
15073    reconnecting).  */
15074
15075 struct tracepoint *
15076 get_tracepoint_by_number_on_target (int num)
15077 {
15078   struct breakpoint *b;
15079
15080   ALL_TRACEPOINTS (b)
15081     {
15082       struct tracepoint *t = (struct tracepoint *) b;
15083
15084       if (t->number_on_target == num)
15085         return t;
15086     }
15087
15088   return NULL;
15089 }
15090
15091 /* Utility: parse a tracepoint number and look it up in the list.
15092    If STATE is not NULL, use, get_number_or_range_state and ignore ARG.
15093    If the argument is missing, the most recent tracepoint
15094    (tracepoint_count) is returned.  */
15095
15096 struct tracepoint *
15097 get_tracepoint_by_number (const char **arg,
15098                           number_or_range_parser *parser)
15099 {
15100   struct breakpoint *t;
15101   int tpnum;
15102   const char *instring = arg == NULL ? NULL : *arg;
15103
15104   if (parser != NULL)
15105     {
15106       gdb_assert (!parser->finished ());
15107       tpnum = parser->get_number ();
15108     }
15109   else if (arg == NULL || *arg == NULL || ! **arg)
15110     tpnum = tracepoint_count;
15111   else
15112     tpnum = get_number (arg);
15113
15114   if (tpnum <= 0)
15115     {
15116       if (instring && *instring)
15117         printf_filtered (_("bad tracepoint number at or near '%s'\n"), 
15118                          instring);
15119       else
15120         printf_filtered (_("No previous tracepoint\n"));
15121       return NULL;
15122     }
15123
15124   ALL_TRACEPOINTS (t)
15125     if (t->number == tpnum)
15126     {
15127       return (struct tracepoint *) t;
15128     }
15129
15130   printf_unfiltered ("No tracepoint number %d.\n", tpnum);
15131   return NULL;
15132 }
15133
15134 void
15135 print_recreate_thread (struct breakpoint *b, struct ui_file *fp)
15136 {
15137   if (b->thread != -1)
15138     fprintf_unfiltered (fp, " thread %d", b->thread);
15139
15140   if (b->task != 0)
15141     fprintf_unfiltered (fp, " task %d", b->task);
15142
15143   fprintf_unfiltered (fp, "\n");
15144 }
15145
15146 /* Save information on user settable breakpoints (watchpoints, etc) to
15147    a new script file named FILENAME.  If FILTER is non-NULL, call it
15148    on each breakpoint and only include the ones for which it returns
15149    non-zero.  */
15150
15151 static void
15152 save_breakpoints (const char *filename, int from_tty,
15153                   int (*filter) (const struct breakpoint *))
15154 {
15155   struct breakpoint *tp;
15156   int any = 0;
15157   int extra_trace_bits = 0;
15158
15159   if (filename == 0 || *filename == 0)
15160     error (_("Argument required (file name in which to save)"));
15161
15162   /* See if we have anything to save.  */
15163   ALL_BREAKPOINTS (tp)
15164   {
15165     /* Skip internal and momentary breakpoints.  */
15166     if (!user_breakpoint_p (tp))
15167       continue;
15168
15169     /* If we have a filter, only save the breakpoints it accepts.  */
15170     if (filter && !filter (tp))
15171       continue;
15172
15173     any = 1;
15174
15175     if (is_tracepoint (tp))
15176       {
15177         extra_trace_bits = 1;
15178
15179         /* We can stop searching.  */
15180         break;
15181       }
15182   }
15183
15184   if (!any)
15185     {
15186       warning (_("Nothing to save."));
15187       return;
15188     }
15189
15190   gdb::unique_xmalloc_ptr<char> expanded_filename (tilde_expand (filename));
15191
15192   stdio_file fp;
15193
15194   if (!fp.open (expanded_filename.get (), "w"))
15195     error (_("Unable to open file '%s' for saving (%s)"),
15196            expanded_filename.get (), safe_strerror (errno));
15197
15198   if (extra_trace_bits)
15199     save_trace_state_variables (&fp);
15200
15201   ALL_BREAKPOINTS (tp)
15202   {
15203     /* Skip internal and momentary breakpoints.  */
15204     if (!user_breakpoint_p (tp))
15205       continue;
15206
15207     /* If we have a filter, only save the breakpoints it accepts.  */
15208     if (filter && !filter (tp))
15209       continue;
15210
15211     tp->ops->print_recreate (tp, &fp);
15212
15213     /* Note, we can't rely on tp->number for anything, as we can't
15214        assume the recreated breakpoint numbers will match.  Use $bpnum
15215        instead.  */
15216
15217     if (tp->cond_string)
15218       fp.printf ("  condition $bpnum %s\n", tp->cond_string);
15219
15220     if (tp->ignore_count)
15221       fp.printf ("  ignore $bpnum %d\n", tp->ignore_count);
15222
15223     if (tp->type != bp_dprintf && tp->commands)
15224       {
15225         fp.puts ("  commands\n");
15226         
15227         current_uiout->redirect (&fp);
15228         TRY
15229           {
15230             print_command_lines (current_uiout, tp->commands.get (), 2);
15231           }
15232         CATCH (ex, RETURN_MASK_ALL)
15233           {
15234           current_uiout->redirect (NULL);
15235             throw_exception (ex);
15236           }
15237         END_CATCH
15238
15239         current_uiout->redirect (NULL);
15240         fp.puts ("  end\n");
15241       }
15242
15243     if (tp->enable_state == bp_disabled)
15244       fp.puts ("disable $bpnum\n");
15245
15246     /* If this is a multi-location breakpoint, check if the locations
15247        should be individually disabled.  Watchpoint locations are
15248        special, and not user visible.  */
15249     if (!is_watchpoint (tp) && tp->loc && tp->loc->next)
15250       {
15251         struct bp_location *loc;
15252         int n = 1;
15253
15254         for (loc = tp->loc; loc != NULL; loc = loc->next, n++)
15255           if (!loc->enabled)
15256             fp.printf ("disable $bpnum.%d\n", n);
15257       }
15258   }
15259
15260   if (extra_trace_bits && *default_collect)
15261     fp.printf ("set default-collect %s\n", default_collect);
15262
15263   if (from_tty)
15264     printf_filtered (_("Saved to file '%s'.\n"), expanded_filename.get ());
15265 }
15266
15267 /* The `save breakpoints' command.  */
15268
15269 static void
15270 save_breakpoints_command (const char *args, int from_tty)
15271 {
15272   save_breakpoints (args, from_tty, NULL);
15273 }
15274
15275 /* The `save tracepoints' command.  */
15276
15277 static void
15278 save_tracepoints_command (const char *args, int from_tty)
15279 {
15280   save_breakpoints (args, from_tty, is_tracepoint);
15281 }
15282
15283 /* Create a vector of all tracepoints.  */
15284
15285 VEC(breakpoint_p) *
15286 all_tracepoints (void)
15287 {
15288   VEC(breakpoint_p) *tp_vec = 0;
15289   struct breakpoint *tp;
15290
15291   ALL_TRACEPOINTS (tp)
15292   {
15293     VEC_safe_push (breakpoint_p, tp_vec, tp);
15294   }
15295
15296   return tp_vec;
15297 }
15298
15299 \f
15300 /* This help string is used to consolidate all the help string for specifying
15301    locations used by several commands.  */
15302
15303 #define LOCATION_HELP_STRING \
15304 "Linespecs are colon-separated lists of location parameters, such as\n\
15305 source filename, function name, label name, and line number.\n\
15306 Example: To specify the start of a label named \"the_top\" in the\n\
15307 function \"fact\" in the file \"factorial.c\", use\n\
15308 \"factorial.c:fact:the_top\".\n\
15309 \n\
15310 Address locations begin with \"*\" and specify an exact address in the\n\
15311 program.  Example: To specify the fourth byte past the start function\n\
15312 \"main\", use \"*main + 4\".\n\
15313 \n\
15314 Explicit locations are similar to linespecs but use an option/argument\n\
15315 syntax to specify location parameters.\n\
15316 Example: To specify the start of the label named \"the_top\" in the\n\
15317 function \"fact\" in the file \"factorial.c\", use \"-source factorial.c\n\
15318 -function fact -label the_top\".\n"
15319
15320 /* This help string is used for the break, hbreak, tbreak and thbreak
15321    commands.  It is defined as a macro to prevent duplication.
15322    COMMAND should be a string constant containing the name of the
15323    command.  */
15324
15325 #define BREAK_ARGS_HELP(command) \
15326 command" [PROBE_MODIFIER] [LOCATION] [thread THREADNUM] [if CONDITION]\n\
15327 PROBE_MODIFIER shall be present if the command is to be placed in a\n\
15328 probe point.  Accepted values are `-probe' (for a generic, automatically\n\
15329 guessed probe type), `-probe-stap' (for a SystemTap probe) or \n\
15330 `-probe-dtrace' (for a DTrace probe).\n\
15331 LOCATION may be a linespec, address, or explicit location as described\n\
15332 below.\n\
15333 \n\
15334 With no LOCATION, uses current execution address of the selected\n\
15335 stack frame.  This is useful for breaking on return to a stack frame.\n\
15336 \n\
15337 THREADNUM is the number from \"info threads\".\n\
15338 CONDITION is a boolean expression.\n\
15339 \n" LOCATION_HELP_STRING "\n\
15340 Multiple breakpoints at one place are permitted, and useful if their\n\
15341 conditions are different.\n\
15342 \n\
15343 Do \"help breakpoints\" for info on other commands dealing with breakpoints."
15344
15345 /* List of subcommands for "catch".  */
15346 static struct cmd_list_element *catch_cmdlist;
15347
15348 /* List of subcommands for "tcatch".  */
15349 static struct cmd_list_element *tcatch_cmdlist;
15350
15351 void
15352 add_catch_command (const char *name, const char *docstring,
15353                    cmd_sfunc_ftype *sfunc,
15354                    completer_ftype *completer,
15355                    void *user_data_catch,
15356                    void *user_data_tcatch)
15357 {
15358   struct cmd_list_element *command;
15359
15360   command = add_cmd (name, class_breakpoint, docstring,
15361                      &catch_cmdlist);
15362   set_cmd_sfunc (command, sfunc);
15363   set_cmd_context (command, user_data_catch);
15364   set_cmd_completer (command, completer);
15365
15366   command = add_cmd (name, class_breakpoint, docstring,
15367                      &tcatch_cmdlist);
15368   set_cmd_sfunc (command, sfunc);
15369   set_cmd_context (command, user_data_tcatch);
15370   set_cmd_completer (command, completer);
15371 }
15372
15373 static void
15374 save_command (const char *arg, int from_tty)
15375 {
15376   printf_unfiltered (_("\"save\" must be followed by "
15377                        "the name of a save subcommand.\n"));
15378   help_list (save_cmdlist, "save ", all_commands, gdb_stdout);
15379 }
15380
15381 struct breakpoint *
15382 iterate_over_breakpoints (int (*callback) (struct breakpoint *, void *),
15383                           void *data)
15384 {
15385   struct breakpoint *b, *b_tmp;
15386
15387   ALL_BREAKPOINTS_SAFE (b, b_tmp)
15388     {
15389       if ((*callback) (b, data))
15390         return b;
15391     }
15392
15393   return NULL;
15394 }
15395
15396 /* Zero if any of the breakpoint's locations could be a location where
15397    functions have been inlined, nonzero otherwise.  */
15398
15399 static int
15400 is_non_inline_function (struct breakpoint *b)
15401 {
15402   /* The shared library event breakpoint is set on the address of a
15403      non-inline function.  */
15404   if (b->type == bp_shlib_event)
15405     return 1;
15406
15407   return 0;
15408 }
15409
15410 /* Nonzero if the specified PC cannot be a location where functions
15411    have been inlined.  */
15412
15413 int
15414 pc_at_non_inline_function (const address_space *aspace, CORE_ADDR pc,
15415                            const struct target_waitstatus *ws)
15416 {
15417   struct breakpoint *b;
15418   struct bp_location *bl;
15419
15420   ALL_BREAKPOINTS (b)
15421     {
15422       if (!is_non_inline_function (b))
15423         continue;
15424
15425       for (bl = b->loc; bl != NULL; bl = bl->next)
15426         {
15427           if (!bl->shlib_disabled
15428               && bpstat_check_location (bl, aspace, pc, ws))
15429             return 1;
15430         }
15431     }
15432
15433   return 0;
15434 }
15435
15436 /* Remove any references to OBJFILE which is going to be freed.  */
15437
15438 void
15439 breakpoint_free_objfile (struct objfile *objfile)
15440 {
15441   struct bp_location **locp, *loc;
15442
15443   ALL_BP_LOCATIONS (loc, locp)
15444     if (loc->symtab != NULL && SYMTAB_OBJFILE (loc->symtab) == objfile)
15445       loc->symtab = NULL;
15446 }
15447
15448 void
15449 initialize_breakpoint_ops (void)
15450 {
15451   static int initialized = 0;
15452
15453   struct breakpoint_ops *ops;
15454
15455   if (initialized)
15456     return;
15457   initialized = 1;
15458
15459   /* The breakpoint_ops structure to be inherit by all kinds of
15460      breakpoints (real breakpoints, i.e., user "break" breakpoints,
15461      internal and momentary breakpoints, etc.).  */
15462   ops = &bkpt_base_breakpoint_ops;
15463   *ops = base_breakpoint_ops;
15464   ops->re_set = bkpt_re_set;
15465   ops->insert_location = bkpt_insert_location;
15466   ops->remove_location = bkpt_remove_location;
15467   ops->breakpoint_hit = bkpt_breakpoint_hit;
15468   ops->create_sals_from_location = bkpt_create_sals_from_location;
15469   ops->create_breakpoints_sal = bkpt_create_breakpoints_sal;
15470   ops->decode_location = bkpt_decode_location;
15471
15472   /* The breakpoint_ops structure to be used in regular breakpoints.  */
15473   ops = &bkpt_breakpoint_ops;
15474   *ops = bkpt_base_breakpoint_ops;
15475   ops->re_set = bkpt_re_set;
15476   ops->resources_needed = bkpt_resources_needed;
15477   ops->print_it = bkpt_print_it;
15478   ops->print_mention = bkpt_print_mention;
15479   ops->print_recreate = bkpt_print_recreate;
15480
15481   /* Ranged breakpoints.  */
15482   ops = &ranged_breakpoint_ops;
15483   *ops = bkpt_breakpoint_ops;
15484   ops->breakpoint_hit = breakpoint_hit_ranged_breakpoint;
15485   ops->resources_needed = resources_needed_ranged_breakpoint;
15486   ops->print_it = print_it_ranged_breakpoint;
15487   ops->print_one = print_one_ranged_breakpoint;
15488   ops->print_one_detail = print_one_detail_ranged_breakpoint;
15489   ops->print_mention = print_mention_ranged_breakpoint;
15490   ops->print_recreate = print_recreate_ranged_breakpoint;
15491
15492   /* Internal breakpoints.  */
15493   ops = &internal_breakpoint_ops;
15494   *ops = bkpt_base_breakpoint_ops;
15495   ops->re_set = internal_bkpt_re_set;
15496   ops->check_status = internal_bkpt_check_status;
15497   ops->print_it = internal_bkpt_print_it;
15498   ops->print_mention = internal_bkpt_print_mention;
15499
15500   /* Momentary breakpoints.  */
15501   ops = &momentary_breakpoint_ops;
15502   *ops = bkpt_base_breakpoint_ops;
15503   ops->re_set = momentary_bkpt_re_set;
15504   ops->check_status = momentary_bkpt_check_status;
15505   ops->print_it = momentary_bkpt_print_it;
15506   ops->print_mention = momentary_bkpt_print_mention;
15507
15508   /* Probe breakpoints.  */
15509   ops = &bkpt_probe_breakpoint_ops;
15510   *ops = bkpt_breakpoint_ops;
15511   ops->insert_location = bkpt_probe_insert_location;
15512   ops->remove_location = bkpt_probe_remove_location;
15513   ops->create_sals_from_location = bkpt_probe_create_sals_from_location;
15514   ops->decode_location = bkpt_probe_decode_location;
15515
15516   /* Watchpoints.  */
15517   ops = &watchpoint_breakpoint_ops;
15518   *ops = base_breakpoint_ops;
15519   ops->re_set = re_set_watchpoint;
15520   ops->insert_location = insert_watchpoint;
15521   ops->remove_location = remove_watchpoint;
15522   ops->breakpoint_hit = breakpoint_hit_watchpoint;
15523   ops->check_status = check_status_watchpoint;
15524   ops->resources_needed = resources_needed_watchpoint;
15525   ops->works_in_software_mode = works_in_software_mode_watchpoint;
15526   ops->print_it = print_it_watchpoint;
15527   ops->print_mention = print_mention_watchpoint;
15528   ops->print_recreate = print_recreate_watchpoint;
15529   ops->explains_signal = explains_signal_watchpoint;
15530
15531   /* Masked watchpoints.  */
15532   ops = &masked_watchpoint_breakpoint_ops;
15533   *ops = watchpoint_breakpoint_ops;
15534   ops->insert_location = insert_masked_watchpoint;
15535   ops->remove_location = remove_masked_watchpoint;
15536   ops->resources_needed = resources_needed_masked_watchpoint;
15537   ops->works_in_software_mode = works_in_software_mode_masked_watchpoint;
15538   ops->print_it = print_it_masked_watchpoint;
15539   ops->print_one_detail = print_one_detail_masked_watchpoint;
15540   ops->print_mention = print_mention_masked_watchpoint;
15541   ops->print_recreate = print_recreate_masked_watchpoint;
15542
15543   /* Tracepoints.  */
15544   ops = &tracepoint_breakpoint_ops;
15545   *ops = base_breakpoint_ops;
15546   ops->re_set = tracepoint_re_set;
15547   ops->breakpoint_hit = tracepoint_breakpoint_hit;
15548   ops->print_one_detail = tracepoint_print_one_detail;
15549   ops->print_mention = tracepoint_print_mention;
15550   ops->print_recreate = tracepoint_print_recreate;
15551   ops->create_sals_from_location = tracepoint_create_sals_from_location;
15552   ops->create_breakpoints_sal = tracepoint_create_breakpoints_sal;
15553   ops->decode_location = tracepoint_decode_location;
15554
15555   /* Probe tracepoints.  */
15556   ops = &tracepoint_probe_breakpoint_ops;
15557   *ops = tracepoint_breakpoint_ops;
15558   ops->create_sals_from_location = tracepoint_probe_create_sals_from_location;
15559   ops->decode_location = tracepoint_probe_decode_location;
15560
15561   /* Static tracepoints with marker (`-m').  */
15562   ops = &strace_marker_breakpoint_ops;
15563   *ops = tracepoint_breakpoint_ops;
15564   ops->create_sals_from_location = strace_marker_create_sals_from_location;
15565   ops->create_breakpoints_sal = strace_marker_create_breakpoints_sal;
15566   ops->decode_location = strace_marker_decode_location;
15567
15568   /* Fork catchpoints.  */
15569   ops = &catch_fork_breakpoint_ops;
15570   *ops = base_breakpoint_ops;
15571   ops->insert_location = insert_catch_fork;
15572   ops->remove_location = remove_catch_fork;
15573   ops->breakpoint_hit = breakpoint_hit_catch_fork;
15574   ops->print_it = print_it_catch_fork;
15575   ops->print_one = print_one_catch_fork;
15576   ops->print_mention = print_mention_catch_fork;
15577   ops->print_recreate = print_recreate_catch_fork;
15578
15579   /* Vfork catchpoints.  */
15580   ops = &catch_vfork_breakpoint_ops;
15581   *ops = base_breakpoint_ops;
15582   ops->insert_location = insert_catch_vfork;
15583   ops->remove_location = remove_catch_vfork;
15584   ops->breakpoint_hit = breakpoint_hit_catch_vfork;
15585   ops->print_it = print_it_catch_vfork;
15586   ops->print_one = print_one_catch_vfork;
15587   ops->print_mention = print_mention_catch_vfork;
15588   ops->print_recreate = print_recreate_catch_vfork;
15589
15590   /* Exec catchpoints.  */
15591   ops = &catch_exec_breakpoint_ops;
15592   *ops = base_breakpoint_ops;
15593   ops->insert_location = insert_catch_exec;
15594   ops->remove_location = remove_catch_exec;
15595   ops->breakpoint_hit = breakpoint_hit_catch_exec;
15596   ops->print_it = print_it_catch_exec;
15597   ops->print_one = print_one_catch_exec;
15598   ops->print_mention = print_mention_catch_exec;
15599   ops->print_recreate = print_recreate_catch_exec;
15600
15601   /* Solib-related catchpoints.  */
15602   ops = &catch_solib_breakpoint_ops;
15603   *ops = base_breakpoint_ops;
15604   ops->insert_location = insert_catch_solib;
15605   ops->remove_location = remove_catch_solib;
15606   ops->breakpoint_hit = breakpoint_hit_catch_solib;
15607   ops->check_status = check_status_catch_solib;
15608   ops->print_it = print_it_catch_solib;
15609   ops->print_one = print_one_catch_solib;
15610   ops->print_mention = print_mention_catch_solib;
15611   ops->print_recreate = print_recreate_catch_solib;
15612
15613   ops = &dprintf_breakpoint_ops;
15614   *ops = bkpt_base_breakpoint_ops;
15615   ops->re_set = dprintf_re_set;
15616   ops->resources_needed = bkpt_resources_needed;
15617   ops->print_it = bkpt_print_it;
15618   ops->print_mention = bkpt_print_mention;
15619   ops->print_recreate = dprintf_print_recreate;
15620   ops->after_condition_true = dprintf_after_condition_true;
15621   ops->breakpoint_hit = dprintf_breakpoint_hit;
15622 }
15623
15624 /* Chain containing all defined "enable breakpoint" subcommands.  */
15625
15626 static struct cmd_list_element *enablebreaklist = NULL;
15627
15628 void
15629 _initialize_breakpoint (void)
15630 {
15631   struct cmd_list_element *c;
15632
15633   initialize_breakpoint_ops ();
15634
15635   observer_attach_solib_unloaded (disable_breakpoints_in_unloaded_shlib);
15636   observer_attach_free_objfile (disable_breakpoints_in_freed_objfile);
15637   observer_attach_memory_changed (invalidate_bp_value_on_memory_change);
15638
15639   breakpoint_objfile_key
15640     = register_objfile_data_with_cleanup (NULL, free_breakpoint_objfile_data);
15641
15642   breakpoint_chain = 0;
15643   /* Don't bother to call set_breakpoint_count.  $bpnum isn't useful
15644      before a breakpoint is set.  */
15645   breakpoint_count = 0;
15646
15647   tracepoint_count = 0;
15648
15649   add_com ("ignore", class_breakpoint, ignore_command, _("\
15650 Set ignore-count of breakpoint number N to COUNT.\n\
15651 Usage is `ignore N COUNT'."));
15652
15653   add_com ("commands", class_breakpoint, commands_command, _("\
15654 Set commands to be executed when the given breakpoints are hit.\n\
15655 Give a space-separated breakpoint list as argument after \"commands\".\n\
15656 A list element can be a breakpoint number (e.g. `5') or a range of numbers\n\
15657 (e.g. `5-7').\n\
15658 With no argument, the targeted breakpoint is the last one set.\n\
15659 The commands themselves follow starting on the next line.\n\
15660 Type a line containing \"end\" to indicate the end of them.\n\
15661 Give \"silent\" as the first line to make the breakpoint silent;\n\
15662 then no output is printed when it is hit, except what the commands print."));
15663
15664   c = add_com ("condition", class_breakpoint, condition_command, _("\
15665 Specify breakpoint number N to break only if COND is true.\n\
15666 Usage is `condition N COND', where N is an integer and COND is an\n\
15667 expression to be evaluated whenever breakpoint N is reached."));
15668   set_cmd_completer (c, condition_completer);
15669
15670   c = add_com ("tbreak", class_breakpoint, tbreak_command, _("\
15671 Set a temporary breakpoint.\n\
15672 Like \"break\" except the breakpoint is only temporary,\n\
15673 so it will be deleted when hit.  Equivalent to \"break\" followed\n\
15674 by using \"enable delete\" on the breakpoint number.\n\
15675 \n"
15676 BREAK_ARGS_HELP ("tbreak")));
15677   set_cmd_completer (c, location_completer);
15678
15679   c = add_com ("hbreak", class_breakpoint, hbreak_command, _("\
15680 Set a hardware assisted breakpoint.\n\
15681 Like \"break\" except the breakpoint requires hardware support,\n\
15682 some target hardware may not have this support.\n\
15683 \n"
15684 BREAK_ARGS_HELP ("hbreak")));
15685   set_cmd_completer (c, location_completer);
15686
15687   c = add_com ("thbreak", class_breakpoint, thbreak_command, _("\
15688 Set a temporary hardware assisted breakpoint.\n\
15689 Like \"hbreak\" except the breakpoint is only temporary,\n\
15690 so it will be deleted when hit.\n\
15691 \n"
15692 BREAK_ARGS_HELP ("thbreak")));
15693   set_cmd_completer (c, location_completer);
15694
15695   add_prefix_cmd ("enable", class_breakpoint, enable_command, _("\
15696 Enable some breakpoints.\n\
15697 Give breakpoint numbers (separated by spaces) as arguments.\n\
15698 With no subcommand, breakpoints are enabled until you command otherwise.\n\
15699 This is used to cancel the effect of the \"disable\" command.\n\
15700 With a subcommand you can enable temporarily."),
15701                   &enablelist, "enable ", 1, &cmdlist);
15702
15703   add_com_alias ("en", "enable", class_breakpoint, 1);
15704
15705   add_prefix_cmd ("breakpoints", class_breakpoint, enable_command, _("\
15706 Enable some breakpoints.\n\
15707 Give breakpoint numbers (separated by spaces) as arguments.\n\
15708 This is used to cancel the effect of the \"disable\" command.\n\
15709 May be abbreviated to simply \"enable\".\n"),
15710                    &enablebreaklist, "enable breakpoints ", 1, &enablelist);
15711
15712   add_cmd ("once", no_class, enable_once_command, _("\
15713 Enable breakpoints for one hit.  Give breakpoint numbers.\n\
15714 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
15715            &enablebreaklist);
15716
15717   add_cmd ("delete", no_class, enable_delete_command, _("\
15718 Enable breakpoints and delete when hit.  Give breakpoint numbers.\n\
15719 If a breakpoint is hit while enabled in this fashion, it is deleted."),
15720            &enablebreaklist);
15721
15722   add_cmd ("count", no_class, enable_count_command, _("\
15723 Enable breakpoints for COUNT hits.  Give count and then breakpoint numbers.\n\
15724 If a breakpoint is hit while enabled in this fashion,\n\
15725 the count is decremented; when it reaches zero, the breakpoint is disabled."),
15726            &enablebreaklist);
15727
15728   add_cmd ("delete", no_class, enable_delete_command, _("\
15729 Enable breakpoints and delete when hit.  Give breakpoint numbers.\n\
15730 If a breakpoint is hit while enabled in this fashion, it is deleted."),
15731            &enablelist);
15732
15733   add_cmd ("once", no_class, enable_once_command, _("\
15734 Enable breakpoints for one hit.  Give breakpoint numbers.\n\
15735 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
15736            &enablelist);
15737
15738   add_cmd ("count", no_class, enable_count_command, _("\
15739 Enable breakpoints for COUNT hits.  Give count and then breakpoint numbers.\n\
15740 If a breakpoint is hit while enabled in this fashion,\n\
15741 the count is decremented; when it reaches zero, the breakpoint is disabled."),
15742            &enablelist);
15743
15744   add_prefix_cmd ("disable", class_breakpoint, disable_command, _("\
15745 Disable some breakpoints.\n\
15746 Arguments are breakpoint numbers with spaces in between.\n\
15747 To disable all breakpoints, give no argument.\n\
15748 A disabled breakpoint is not forgotten, but has no effect until re-enabled."),
15749                   &disablelist, "disable ", 1, &cmdlist);
15750   add_com_alias ("dis", "disable", class_breakpoint, 1);
15751   add_com_alias ("disa", "disable", class_breakpoint, 1);
15752
15753   add_cmd ("breakpoints", class_alias, disable_command, _("\
15754 Disable some breakpoints.\n\
15755 Arguments are breakpoint numbers with spaces in between.\n\
15756 To disable all breakpoints, give no argument.\n\
15757 A disabled breakpoint is not forgotten, but has no effect until re-enabled.\n\
15758 This command may be abbreviated \"disable\"."),
15759            &disablelist);
15760
15761   add_prefix_cmd ("delete", class_breakpoint, delete_command, _("\
15762 Delete some breakpoints or auto-display expressions.\n\
15763 Arguments are breakpoint numbers with spaces in between.\n\
15764 To delete all breakpoints, give no argument.\n\
15765 \n\
15766 Also a prefix command for deletion of other GDB objects.\n\
15767 The \"unset\" command is also an alias for \"delete\"."),
15768                   &deletelist, "delete ", 1, &cmdlist);
15769   add_com_alias ("d", "delete", class_breakpoint, 1);
15770   add_com_alias ("del", "delete", class_breakpoint, 1);
15771
15772   add_cmd ("breakpoints", class_alias, delete_command, _("\
15773 Delete some breakpoints or auto-display expressions.\n\
15774 Arguments are breakpoint numbers with spaces in between.\n\
15775 To delete all breakpoints, give no argument.\n\
15776 This command may be abbreviated \"delete\"."),
15777            &deletelist);
15778
15779   add_com ("clear", class_breakpoint, clear_command, _("\
15780 Clear breakpoint at specified location.\n\
15781 Argument may be a linespec, explicit, or address location as described below.\n\
15782 \n\
15783 With no argument, clears all breakpoints in the line that the selected frame\n\
15784 is executing in.\n"
15785 "\n" LOCATION_HELP_STRING "\n\
15786 See also the \"delete\" command which clears breakpoints by number."));
15787   add_com_alias ("cl", "clear", class_breakpoint, 1);
15788
15789   c = add_com ("break", class_breakpoint, break_command, _("\
15790 Set breakpoint at specified location.\n"
15791 BREAK_ARGS_HELP ("break")));
15792   set_cmd_completer (c, location_completer);
15793
15794   add_com_alias ("b", "break", class_run, 1);
15795   add_com_alias ("br", "break", class_run, 1);
15796   add_com_alias ("bre", "break", class_run, 1);
15797   add_com_alias ("brea", "break", class_run, 1);
15798
15799   if (dbx_commands)
15800     {
15801       add_abbrev_prefix_cmd ("stop", class_breakpoint, stop_command, _("\
15802 Break in function/address or break at a line in the current file."),
15803                              &stoplist, "stop ", 1, &cmdlist);
15804       add_cmd ("in", class_breakpoint, stopin_command,
15805                _("Break in function or address."), &stoplist);
15806       add_cmd ("at", class_breakpoint, stopat_command,
15807                _("Break at a line in the current file."), &stoplist);
15808       add_com ("status", class_info, info_breakpoints_command, _("\
15809 Status of user-settable breakpoints, or breakpoint number NUMBER.\n\
15810 The \"Type\" column indicates one of:\n\
15811 \tbreakpoint     - normal breakpoint\n\
15812 \twatchpoint     - watchpoint\n\
15813 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
15814 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
15815 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
15816 address and file/line number respectively.\n\
15817 \n\
15818 Convenience variable \"$_\" and default examine address for \"x\"\n\
15819 are set to the address of the last breakpoint listed unless the command\n\
15820 is prefixed with \"server \".\n\n\
15821 Convenience variable \"$bpnum\" contains the number of the last\n\
15822 breakpoint set."));
15823     }
15824
15825   add_info ("breakpoints", info_breakpoints_command, _("\
15826 Status of specified breakpoints (all user-settable breakpoints if no argument).\n\
15827 The \"Type\" column indicates one of:\n\
15828 \tbreakpoint     - normal breakpoint\n\
15829 \twatchpoint     - watchpoint\n\
15830 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
15831 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
15832 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
15833 address and file/line number respectively.\n\
15834 \n\
15835 Convenience variable \"$_\" and default examine address for \"x\"\n\
15836 are set to the address of the last breakpoint listed unless the command\n\
15837 is prefixed with \"server \".\n\n\
15838 Convenience variable \"$bpnum\" contains the number of the last\n\
15839 breakpoint set."));
15840
15841   add_info_alias ("b", "breakpoints", 1);
15842
15843   add_cmd ("breakpoints", class_maintenance, maintenance_info_breakpoints, _("\
15844 Status of all breakpoints, or breakpoint number NUMBER.\n\
15845 The \"Type\" column indicates one of:\n\
15846 \tbreakpoint     - normal breakpoint\n\
15847 \twatchpoint     - watchpoint\n\
15848 \tlongjmp        - internal breakpoint used to step through longjmp()\n\
15849 \tlongjmp resume - internal breakpoint at the target of longjmp()\n\
15850 \tuntil          - internal breakpoint used by the \"until\" command\n\
15851 \tfinish         - internal breakpoint used by the \"finish\" command\n\
15852 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
15853 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
15854 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
15855 address and file/line number respectively.\n\
15856 \n\
15857 Convenience variable \"$_\" and default examine address for \"x\"\n\
15858 are set to the address of the last breakpoint listed unless the command\n\
15859 is prefixed with \"server \".\n\n\
15860 Convenience variable \"$bpnum\" contains the number of the last\n\
15861 breakpoint set."),
15862            &maintenanceinfolist);
15863
15864   add_prefix_cmd ("catch", class_breakpoint, catch_command, _("\
15865 Set catchpoints to catch events."),
15866                   &catch_cmdlist, "catch ",
15867                   0/*allow-unknown*/, &cmdlist);
15868
15869   add_prefix_cmd ("tcatch", class_breakpoint, tcatch_command, _("\
15870 Set temporary catchpoints to catch events."),
15871                   &tcatch_cmdlist, "tcatch ",
15872                   0/*allow-unknown*/, &cmdlist);
15873
15874   add_catch_command ("fork", _("Catch calls to fork."),
15875                      catch_fork_command_1,
15876                      NULL,
15877                      (void *) (uintptr_t) catch_fork_permanent,
15878                      (void *) (uintptr_t) catch_fork_temporary);
15879   add_catch_command ("vfork", _("Catch calls to vfork."),
15880                      catch_fork_command_1,
15881                      NULL,
15882                      (void *) (uintptr_t) catch_vfork_permanent,
15883                      (void *) (uintptr_t) catch_vfork_temporary);
15884   add_catch_command ("exec", _("Catch calls to exec."),
15885                      catch_exec_command_1,
15886                      NULL,
15887                      CATCH_PERMANENT,
15888                      CATCH_TEMPORARY);
15889   add_catch_command ("load", _("Catch loads of shared libraries.\n\
15890 Usage: catch load [REGEX]\n\
15891 If REGEX is given, only stop for libraries matching the regular expression."),
15892                      catch_load_command_1,
15893                      NULL,
15894                      CATCH_PERMANENT,
15895                      CATCH_TEMPORARY);
15896   add_catch_command ("unload", _("Catch unloads of shared libraries.\n\
15897 Usage: catch unload [REGEX]\n\
15898 If REGEX is given, only stop for libraries matching the regular expression."),
15899                      catch_unload_command_1,
15900                      NULL,
15901                      CATCH_PERMANENT,
15902                      CATCH_TEMPORARY);
15903
15904   c = add_com ("watch", class_breakpoint, watch_command, _("\
15905 Set a watchpoint for an expression.\n\
15906 Usage: watch [-l|-location] EXPRESSION\n\
15907 A watchpoint stops execution of your program whenever the value of\n\
15908 an expression changes.\n\
15909 If -l or -location is given, this evaluates EXPRESSION and watches\n\
15910 the memory to which it refers."));
15911   set_cmd_completer (c, expression_completer);
15912
15913   c = add_com ("rwatch", class_breakpoint, rwatch_command, _("\
15914 Set a read watchpoint for an expression.\n\
15915 Usage: rwatch [-l|-location] EXPRESSION\n\
15916 A watchpoint stops execution of your program whenever the value of\n\
15917 an expression is read.\n\
15918 If -l or -location is given, this evaluates EXPRESSION and watches\n\
15919 the memory to which it refers."));
15920   set_cmd_completer (c, expression_completer);
15921
15922   c = add_com ("awatch", class_breakpoint, awatch_command, _("\
15923 Set a watchpoint for an expression.\n\
15924 Usage: awatch [-l|-location] EXPRESSION\n\
15925 A watchpoint stops execution of your program whenever the value of\n\
15926 an expression is either read or written.\n\
15927 If -l or -location is given, this evaluates EXPRESSION and watches\n\
15928 the memory to which it refers."));
15929   set_cmd_completer (c, expression_completer);
15930
15931   add_info ("watchpoints", info_watchpoints_command, _("\
15932 Status of specified watchpoints (all watchpoints if no argument)."));
15933
15934   /* XXX: cagney/2005-02-23: This should be a boolean, and should
15935      respond to changes - contrary to the description.  */
15936   add_setshow_zinteger_cmd ("can-use-hw-watchpoints", class_support,
15937                             &can_use_hw_watchpoints, _("\
15938 Set debugger's willingness to use watchpoint hardware."), _("\
15939 Show debugger's willingness to use watchpoint hardware."), _("\
15940 If zero, gdb will not use hardware for new watchpoints, even if\n\
15941 such is available.  (However, any hardware watchpoints that were\n\
15942 created before setting this to nonzero, will continue to use watchpoint\n\
15943 hardware.)"),
15944                             NULL,
15945                             show_can_use_hw_watchpoints,
15946                             &setlist, &showlist);
15947
15948   can_use_hw_watchpoints = 1;
15949
15950   /* Tracepoint manipulation commands.  */
15951
15952   c = add_com ("trace", class_breakpoint, trace_command, _("\
15953 Set a tracepoint at specified location.\n\
15954 \n"
15955 BREAK_ARGS_HELP ("trace") "\n\
15956 Do \"help tracepoints\" for info on other tracepoint commands."));
15957   set_cmd_completer (c, location_completer);
15958
15959   add_com_alias ("tp", "trace", class_alias, 0);
15960   add_com_alias ("tr", "trace", class_alias, 1);
15961   add_com_alias ("tra", "trace", class_alias, 1);
15962   add_com_alias ("trac", "trace", class_alias, 1);
15963
15964   c = add_com ("ftrace", class_breakpoint, ftrace_command, _("\
15965 Set a fast tracepoint at specified location.\n\
15966 \n"
15967 BREAK_ARGS_HELP ("ftrace") "\n\
15968 Do \"help tracepoints\" for info on other tracepoint commands."));
15969   set_cmd_completer (c, location_completer);
15970
15971   c = add_com ("strace", class_breakpoint, strace_command, _("\
15972 Set a static tracepoint at location or marker.\n\
15973 \n\
15974 strace [LOCATION] [if CONDITION]\n\
15975 LOCATION may be a linespec, explicit, or address location (described below) \n\
15976 or -m MARKER_ID.\n\n\
15977 If a marker id is specified, probe the marker with that name.  With\n\
15978 no LOCATION, uses current execution address of the selected stack frame.\n\
15979 Static tracepoints accept an extra collect action -- ``collect $_sdata''.\n\
15980 This collects arbitrary user data passed in the probe point call to the\n\
15981 tracing library.  You can inspect it when analyzing the trace buffer,\n\
15982 by printing the $_sdata variable like any other convenience variable.\n\
15983 \n\
15984 CONDITION is a boolean expression.\n\
15985 \n" LOCATION_HELP_STRING "\n\
15986 Multiple tracepoints at one place are permitted, and useful if their\n\
15987 conditions are different.\n\
15988 \n\
15989 Do \"help breakpoints\" for info on other commands dealing with breakpoints.\n\
15990 Do \"help tracepoints\" for info on other tracepoint commands."));
15991   set_cmd_completer (c, location_completer);
15992
15993   add_info ("tracepoints", info_tracepoints_command, _("\
15994 Status of specified tracepoints (all tracepoints if no argument).\n\
15995 Convenience variable \"$tpnum\" contains the number of the\n\
15996 last tracepoint set."));
15997
15998   add_info_alias ("tp", "tracepoints", 1);
15999
16000   add_cmd ("tracepoints", class_trace, delete_trace_command, _("\
16001 Delete specified tracepoints.\n\
16002 Arguments are tracepoint numbers, separated by spaces.\n\
16003 No argument means delete all tracepoints."),
16004            &deletelist);
16005   add_alias_cmd ("tr", "tracepoints", class_trace, 1, &deletelist);
16006
16007   c = add_cmd ("tracepoints", class_trace, disable_trace_command, _("\
16008 Disable specified tracepoints.\n\
16009 Arguments are tracepoint numbers, separated by spaces.\n\
16010 No argument means disable all tracepoints."),
16011            &disablelist);
16012   deprecate_cmd (c, "disable");
16013
16014   c = add_cmd ("tracepoints", class_trace, enable_trace_command, _("\
16015 Enable specified tracepoints.\n\
16016 Arguments are tracepoint numbers, separated by spaces.\n\
16017 No argument means enable all tracepoints."),
16018            &enablelist);
16019   deprecate_cmd (c, "enable");
16020
16021   add_com ("passcount", class_trace, trace_pass_command, _("\
16022 Set the passcount for a tracepoint.\n\
16023 The trace will end when the tracepoint has been passed 'count' times.\n\
16024 Usage: passcount COUNT TPNUM, where TPNUM may also be \"all\";\n\
16025 if TPNUM is omitted, passcount refers to the last tracepoint defined."));
16026
16027   add_prefix_cmd ("save", class_breakpoint, save_command,
16028                   _("Save breakpoint definitions as a script."),
16029                   &save_cmdlist, "save ",
16030                   0/*allow-unknown*/, &cmdlist);
16031
16032   c = add_cmd ("breakpoints", class_breakpoint, save_breakpoints_command, _("\
16033 Save current breakpoint definitions as a script.\n\
16034 This includes all types of breakpoints (breakpoints, watchpoints,\n\
16035 catchpoints, tracepoints).  Use the 'source' command in another debug\n\
16036 session to restore them."),
16037                &save_cmdlist);
16038   set_cmd_completer (c, filename_completer);
16039
16040   c = add_cmd ("tracepoints", class_trace, save_tracepoints_command, _("\
16041 Save current tracepoint definitions as a script.\n\
16042 Use the 'source' command in another debug session to restore them."),
16043                &save_cmdlist);
16044   set_cmd_completer (c, filename_completer);
16045
16046   c = add_com_alias ("save-tracepoints", "save tracepoints", class_trace, 0);
16047   deprecate_cmd (c, "save tracepoints");
16048
16049   add_prefix_cmd ("breakpoint", class_maintenance, set_breakpoint_cmd, _("\
16050 Breakpoint specific settings\n\
16051 Configure various breakpoint-specific variables such as\n\
16052 pending breakpoint behavior"),
16053                   &breakpoint_set_cmdlist, "set breakpoint ",
16054                   0/*allow-unknown*/, &setlist);
16055   add_prefix_cmd ("breakpoint", class_maintenance, show_breakpoint_cmd, _("\
16056 Breakpoint specific settings\n\
16057 Configure various breakpoint-specific variables such as\n\
16058 pending breakpoint behavior"),
16059                   &breakpoint_show_cmdlist, "show breakpoint ",
16060                   0/*allow-unknown*/, &showlist);
16061
16062   add_setshow_auto_boolean_cmd ("pending", no_class,
16063                                 &pending_break_support, _("\
16064 Set debugger's behavior regarding pending breakpoints."), _("\
16065 Show debugger's behavior regarding pending breakpoints."), _("\
16066 If on, an unrecognized breakpoint location will cause gdb to create a\n\
16067 pending breakpoint.  If off, an unrecognized breakpoint location results in\n\
16068 an error.  If auto, an unrecognized breakpoint location results in a\n\
16069 user-query to see if a pending breakpoint should be created."),
16070                                 NULL,
16071                                 show_pending_break_support,
16072                                 &breakpoint_set_cmdlist,
16073                                 &breakpoint_show_cmdlist);
16074
16075   pending_break_support = AUTO_BOOLEAN_AUTO;
16076
16077   add_setshow_boolean_cmd ("auto-hw", no_class,
16078                            &automatic_hardware_breakpoints, _("\
16079 Set automatic usage of hardware breakpoints."), _("\
16080 Show automatic usage of hardware breakpoints."), _("\
16081 If set, the debugger will automatically use hardware breakpoints for\n\
16082 breakpoints set with \"break\" but falling in read-only memory.  If not set,\n\
16083 a warning will be emitted for such breakpoints."),
16084                            NULL,
16085                            show_automatic_hardware_breakpoints,
16086                            &breakpoint_set_cmdlist,
16087                            &breakpoint_show_cmdlist);
16088
16089   add_setshow_boolean_cmd ("always-inserted", class_support,
16090                            &always_inserted_mode, _("\
16091 Set mode for inserting breakpoints."), _("\
16092 Show mode for inserting breakpoints."), _("\
16093 When this mode is on, breakpoints are inserted immediately as soon as\n\
16094 they're created, kept inserted even when execution stops, and removed\n\
16095 only when the user deletes them.  When this mode is off (the default),\n\
16096 breakpoints are inserted only when execution continues, and removed\n\
16097 when execution stops."),
16098                                 NULL,
16099                                 &show_always_inserted_mode,
16100                                 &breakpoint_set_cmdlist,
16101                                 &breakpoint_show_cmdlist);
16102
16103   add_setshow_enum_cmd ("condition-evaluation", class_breakpoint,
16104                         condition_evaluation_enums,
16105                         &condition_evaluation_mode_1, _("\
16106 Set mode of breakpoint condition evaluation."), _("\
16107 Show mode of breakpoint condition evaluation."), _("\
16108 When this is set to \"host\", breakpoint conditions will be\n\
16109 evaluated on the host's side by GDB.  When it is set to \"target\",\n\
16110 breakpoint conditions will be downloaded to the target (if the target\n\
16111 supports such feature) and conditions will be evaluated on the target's side.\n\
16112 If this is set to \"auto\" (default), this will be automatically set to\n\
16113 \"target\" if it supports condition evaluation, otherwise it will\n\
16114 be set to \"gdb\""),
16115                            &set_condition_evaluation_mode,
16116                            &show_condition_evaluation_mode,
16117                            &breakpoint_set_cmdlist,
16118                            &breakpoint_show_cmdlist);
16119
16120   add_com ("break-range", class_breakpoint, break_range_command, _("\
16121 Set a breakpoint for an address range.\n\
16122 break-range START-LOCATION, END-LOCATION\n\
16123 where START-LOCATION and END-LOCATION can be one of the following:\n\
16124   LINENUM, for that line in the current file,\n\
16125   FILE:LINENUM, for that line in that file,\n\
16126   +OFFSET, for that number of lines after the current line\n\
16127            or the start of the range\n\
16128   FUNCTION, for the first line in that function,\n\
16129   FILE:FUNCTION, to distinguish among like-named static functions.\n\
16130   *ADDRESS, for the instruction at that address.\n\
16131 \n\
16132 The breakpoint will stop execution of the inferior whenever it executes\n\
16133 an instruction at any address within the [START-LOCATION, END-LOCATION]\n\
16134 range (including START-LOCATION and END-LOCATION)."));
16135
16136   c = add_com ("dprintf", class_breakpoint, dprintf_command, _("\
16137 Set a dynamic printf at specified location.\n\
16138 dprintf location,format string,arg1,arg2,...\n\
16139 location may be a linespec, explicit, or address location.\n"
16140 "\n" LOCATION_HELP_STRING));
16141   set_cmd_completer (c, location_completer);
16142
16143   add_setshow_enum_cmd ("dprintf-style", class_support,
16144                         dprintf_style_enums, &dprintf_style, _("\
16145 Set the style of usage for dynamic printf."), _("\
16146 Show the style of usage for dynamic printf."), _("\
16147 This setting chooses how GDB will do a dynamic printf.\n\
16148 If the value is \"gdb\", then the printing is done by GDB to its own\n\
16149 console, as with the \"printf\" command.\n\
16150 If the value is \"call\", the print is done by calling a function in your\n\
16151 program; by default printf(), but you can choose a different function or\n\
16152 output stream by setting dprintf-function and dprintf-channel."),
16153                         update_dprintf_commands, NULL,
16154                         &setlist, &showlist);
16155
16156   dprintf_function = xstrdup ("printf");
16157   add_setshow_string_cmd ("dprintf-function", class_support,
16158                           &dprintf_function, _("\
16159 Set the function to use for dynamic printf"), _("\
16160 Show the function to use for dynamic printf"), NULL,
16161                           update_dprintf_commands, NULL,
16162                           &setlist, &showlist);
16163
16164   dprintf_channel = xstrdup ("");
16165   add_setshow_string_cmd ("dprintf-channel", class_support,
16166                           &dprintf_channel, _("\
16167 Set the channel to use for dynamic printf"), _("\
16168 Show the channel to use for dynamic printf"), NULL,
16169                           update_dprintf_commands, NULL,
16170                           &setlist, &showlist);
16171
16172   add_setshow_boolean_cmd ("disconnected-dprintf", no_class,
16173                            &disconnected_dprintf, _("\
16174 Set whether dprintf continues after GDB disconnects."), _("\
16175 Show whether dprintf continues after GDB disconnects."), _("\
16176 Use this to let dprintf commands continue to hit and produce output\n\
16177 even if GDB disconnects or detaches from the target."),
16178                            NULL,
16179                            NULL,
16180                            &setlist, &showlist);
16181
16182   add_com ("agent-printf", class_vars, agent_printf_command, _("\
16183 agent-printf \"printf format string\", arg1, arg2, arg3, ..., argn\n\
16184 (target agent only) This is useful for formatted output in user-defined commands."));
16185
16186   automatic_hardware_breakpoints = 1;
16187
16188   observer_attach_about_to_proceed (breakpoint_about_to_proceed);
16189   observer_attach_thread_exit (remove_threaded_breakpoints);
16190 }