Add myself as a write-after-approval GDB maintainer.
[external/binutils.git] / gdb / breakpoint.c
1 /* Everything about breakpoints, for GDB.
2
3    Copyright (C) 1986-2017 Free Software Foundation, Inc.
4
5    This file is part of GDB.
6
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
19
20 #include "defs.h"
21 #include "arch-utils.h"
22 #include <ctype.h>
23 #include "hashtab.h"
24 #include "symtab.h"
25 #include "frame.h"
26 #include "breakpoint.h"
27 #include "tracepoint.h"
28 #include "gdbtypes.h"
29 #include "expression.h"
30 #include "gdbcore.h"
31 #include "gdbcmd.h"
32 #include "value.h"
33 #include "command.h"
34 #include "inferior.h"
35 #include "infrun.h"
36 #include "gdbthread.h"
37 #include "target.h"
38 #include "language.h"
39 #include "gdb-demangle.h"
40 #include "filenames.h"
41 #include "annotate.h"
42 #include "symfile.h"
43 #include "objfiles.h"
44 #include "source.h"
45 #include "linespec.h"
46 #include "completer.h"
47 #include "gdb.h"
48 #include "ui-out.h"
49 #include "cli/cli-script.h"
50 #include "block.h"
51 #include "solib.h"
52 #include "solist.h"
53 #include "observer.h"
54 #include "memattr.h"
55 #include "ada-lang.h"
56 #include "top.h"
57 #include "valprint.h"
58 #include "jit.h"
59 #include "parser-defs.h"
60 #include "gdb_regex.h"
61 #include "probe.h"
62 #include "cli/cli-utils.h"
63 #include "continuations.h"
64 #include "stack.h"
65 #include "skip.h"
66 #include "ax-gdb.h"
67 #include "dummy-frame.h"
68 #include "interps.h"
69 #include "format.h"
70 #include "thread-fsm.h"
71 #include "tid-parse.h"
72
73 /* readline include files */
74 #include "readline/readline.h"
75 #include "readline/history.h"
76
77 /* readline defines this.  */
78 #undef savestring
79
80 #include "mi/mi-common.h"
81 #include "extension.h"
82 #include <algorithm>
83 #include "progspace-and-thread.h"
84
85 /* Enums for exception-handling support.  */
86 enum exception_event_kind
87 {
88   EX_EVENT_THROW,
89   EX_EVENT_RETHROW,
90   EX_EVENT_CATCH
91 };
92
93 /* Prototypes for local functions.  */
94
95 static void enable_delete_command (char *, int);
96
97 static void enable_once_command (char *, int);
98
99 static void enable_count_command (char *, int);
100
101 static void disable_command (char *, int);
102
103 static void enable_command (char *, int);
104
105 static void map_breakpoint_numbers (const char *,
106                                     void (*) (struct breakpoint *,
107                                               void *),
108                                     void *);
109
110 static void ignore_command (char *, int);
111
112 static int breakpoint_re_set_one (void *);
113
114 static void breakpoint_re_set_default (struct breakpoint *);
115
116 static void
117   create_sals_from_location_default (const struct event_location *location,
118                                      struct linespec_result *canonical,
119                                      enum bptype type_wanted);
120
121 static void create_breakpoints_sal_default (struct gdbarch *,
122                                             struct linespec_result *,
123                                             gdb::unique_xmalloc_ptr<char>,
124                                             gdb::unique_xmalloc_ptr<char>,
125                                             enum bptype,
126                                             enum bpdisp, int, int,
127                                             int,
128                                             const struct breakpoint_ops *,
129                                             int, int, int, unsigned);
130
131 static void decode_location_default (struct breakpoint *b,
132                                      const struct event_location *location,
133                                      struct program_space *search_pspace,
134                                      struct symtabs_and_lines *sals);
135
136 static void clear_command (char *, int);
137
138 static void catch_command (char *, int);
139
140 static int can_use_hardware_watchpoint (struct value *);
141
142 static void break_command_1 (char *, int, int);
143
144 static void mention (struct breakpoint *);
145
146 static struct breakpoint *set_raw_breakpoint_without_location (struct gdbarch *,
147                                                                enum bptype,
148                                                                const struct breakpoint_ops *);
149 static struct bp_location *add_location_to_breakpoint (struct breakpoint *,
150                                                        const struct symtab_and_line *);
151
152 /* This function is used in gdbtk sources and thus can not be made
153    static.  */
154 struct breakpoint *set_raw_breakpoint (struct gdbarch *gdbarch,
155                                        struct symtab_and_line,
156                                        enum bptype,
157                                        const struct breakpoint_ops *);
158
159 static struct breakpoint *
160   momentary_breakpoint_from_master (struct breakpoint *orig,
161                                     enum bptype type,
162                                     const struct breakpoint_ops *ops,
163                                     int loc_enabled);
164
165 static void breakpoint_adjustment_warning (CORE_ADDR, CORE_ADDR, int, int);
166
167 static CORE_ADDR adjust_breakpoint_address (struct gdbarch *gdbarch,
168                                             CORE_ADDR bpaddr,
169                                             enum bptype bptype);
170
171 static void describe_other_breakpoints (struct gdbarch *,
172                                         struct program_space *, CORE_ADDR,
173                                         struct obj_section *, int);
174
175 static int watchpoint_locations_match (struct bp_location *loc1,
176                                        struct bp_location *loc2);
177
178 static int breakpoint_location_address_match (struct bp_location *bl,
179                                               struct address_space *aspace,
180                                               CORE_ADDR addr);
181
182 static int breakpoint_location_address_range_overlap (struct bp_location *,
183                                                       struct address_space *,
184                                                       CORE_ADDR, int);
185
186 static void breakpoints_info (char *, int);
187
188 static void watchpoints_info (char *, int);
189
190 static int breakpoint_1 (char *, int, 
191                          int (*) (const struct breakpoint *));
192
193 static int breakpoint_cond_eval (void *);
194
195 static void cleanup_executing_breakpoints (void *);
196
197 static void commands_command (char *, int);
198
199 static void condition_command (char *, int);
200
201 static int remove_breakpoint (struct bp_location *);
202 static int remove_breakpoint_1 (struct bp_location *, enum remove_bp_reason);
203
204 static enum print_stop_action print_bp_stop_message (bpstat bs);
205
206 static int watchpoint_check (void *);
207
208 static void maintenance_info_breakpoints (char *, int);
209
210 static int hw_breakpoint_used_count (void);
211
212 static int hw_watchpoint_use_count (struct breakpoint *);
213
214 static int hw_watchpoint_used_count_others (struct breakpoint *except,
215                                             enum bptype type,
216                                             int *other_type_used);
217
218 static void hbreak_command (char *, int);
219
220 static void thbreak_command (char *, int);
221
222 static void enable_breakpoint_disp (struct breakpoint *, enum bpdisp,
223                                     int count);
224
225 static void stop_command (char *arg, int from_tty);
226
227 static void stopin_command (char *arg, int from_tty);
228
229 static void stopat_command (char *arg, int from_tty);
230
231 static void tcatch_command (char *arg, int from_tty);
232
233 static void free_bp_location (struct bp_location *loc);
234 static void incref_bp_location (struct bp_location *loc);
235 static void decref_bp_location (struct bp_location **loc);
236
237 static struct bp_location *allocate_bp_location (struct breakpoint *bpt);
238
239 /* update_global_location_list's modes of operation wrt to whether to
240    insert locations now.  */
241 enum ugll_insert_mode
242 {
243   /* Don't insert any breakpoint locations into the inferior, only
244      remove already-inserted locations that no longer should be
245      inserted.  Functions that delete a breakpoint or breakpoints
246      should specify this mode, so that deleting a breakpoint doesn't
247      have the side effect of inserting the locations of other
248      breakpoints that are marked not-inserted, but should_be_inserted
249      returns true on them.
250
251      This behavior is useful is situations close to tear-down -- e.g.,
252      after an exec, while the target still has execution, but
253      breakpoint shadows of the previous executable image should *NOT*
254      be restored to the new image; or before detaching, where the
255      target still has execution and wants to delete breakpoints from
256      GDB's lists, and all breakpoints had already been removed from
257      the inferior.  */
258   UGLL_DONT_INSERT,
259
260   /* May insert breakpoints iff breakpoints_should_be_inserted_now
261      claims breakpoints should be inserted now.  */
262   UGLL_MAY_INSERT,
263
264   /* Insert locations now, irrespective of
265      breakpoints_should_be_inserted_now.  E.g., say all threads are
266      stopped right now, and the user did "continue".  We need to
267      insert breakpoints _before_ resuming the target, but
268      UGLL_MAY_INSERT wouldn't insert them, because
269      breakpoints_should_be_inserted_now returns false at that point,
270      as no thread is running yet.  */
271   UGLL_INSERT
272 };
273
274 static void update_global_location_list (enum ugll_insert_mode);
275
276 static void update_global_location_list_nothrow (enum ugll_insert_mode);
277
278 static int is_hardware_watchpoint (const struct breakpoint *bpt);
279
280 static void insert_breakpoint_locations (void);
281
282 static void tracepoints_info (char *, int);
283
284 static void delete_trace_command (char *, int);
285
286 static void enable_trace_command (char *, int);
287
288 static void disable_trace_command (char *, int);
289
290 static void trace_pass_command (char *, int);
291
292 static void set_tracepoint_count (int num);
293
294 static int is_masked_watchpoint (const struct breakpoint *b);
295
296 static struct bp_location **get_first_locp_gte_addr (CORE_ADDR address);
297
298 /* Return 1 if B refers to a static tracepoint set by marker ("-m"), zero
299    otherwise.  */
300
301 static int strace_marker_p (struct breakpoint *b);
302
303 /* The breakpoint_ops structure to be inherited by all breakpoint_ops
304    that are implemented on top of software or hardware breakpoints
305    (user breakpoints, internal and momentary breakpoints, etc.).  */
306 static struct breakpoint_ops bkpt_base_breakpoint_ops;
307
308 /* Internal breakpoints class type.  */
309 static struct breakpoint_ops internal_breakpoint_ops;
310
311 /* Momentary breakpoints class type.  */
312 static struct breakpoint_ops momentary_breakpoint_ops;
313
314 /* The breakpoint_ops structure to be used in regular user created
315    breakpoints.  */
316 struct breakpoint_ops bkpt_breakpoint_ops;
317
318 /* Breakpoints set on probes.  */
319 static struct breakpoint_ops bkpt_probe_breakpoint_ops;
320
321 /* Dynamic printf class type.  */
322 struct breakpoint_ops dprintf_breakpoint_ops;
323
324 /* The style in which to perform a dynamic printf.  This is a user
325    option because different output options have different tradeoffs;
326    if GDB does the printing, there is better error handling if there
327    is a problem with any of the arguments, but using an inferior
328    function lets you have special-purpose printers and sending of
329    output to the same place as compiled-in print functions.  */
330
331 static const char dprintf_style_gdb[] = "gdb";
332 static const char dprintf_style_call[] = "call";
333 static const char dprintf_style_agent[] = "agent";
334 static const char *const dprintf_style_enums[] = {
335   dprintf_style_gdb,
336   dprintf_style_call,
337   dprintf_style_agent,
338   NULL
339 };
340 static const char *dprintf_style = dprintf_style_gdb;
341
342 /* The function to use for dynamic printf if the preferred style is to
343    call into the inferior.  The value is simply a string that is
344    copied into the command, so it can be anything that GDB can
345    evaluate to a callable address, not necessarily a function name.  */
346
347 static char *dprintf_function;
348
349 /* The channel to use for dynamic printf if the preferred style is to
350    call into the inferior; if a nonempty string, it will be passed to
351    the call as the first argument, with the format string as the
352    second.  As with the dprintf function, this can be anything that
353    GDB knows how to evaluate, so in addition to common choices like
354    "stderr", this could be an app-specific expression like
355    "mystreams[curlogger]".  */
356
357 static char *dprintf_channel;
358
359 /* True if dprintf commands should continue to operate even if GDB
360    has disconnected.  */
361 static int disconnected_dprintf = 1;
362
363 /* A reference-counted struct command_line.  This lets multiple
364    breakpoints share a single command list.  */
365 struct counted_command_line
366 {
367   /* The reference count.  */
368   int refc;
369
370   /* The command list.  */
371   struct command_line *commands;
372 };
373
374 struct command_line *
375 breakpoint_commands (struct breakpoint *b)
376 {
377   return b->commands ? b->commands->commands : NULL;
378 }
379
380 /* Flag indicating that a command has proceeded the inferior past the
381    current breakpoint.  */
382
383 static int breakpoint_proceeded;
384
385 const char *
386 bpdisp_text (enum bpdisp disp)
387 {
388   /* NOTE: the following values are a part of MI protocol and
389      represent values of 'disp' field returned when inferior stops at
390      a breakpoint.  */
391   static const char * const bpdisps[] = {"del", "dstp", "dis", "keep"};
392
393   return bpdisps[(int) disp];
394 }
395
396 /* Prototypes for exported functions.  */
397 /* If FALSE, gdb will not use hardware support for watchpoints, even
398    if such is available.  */
399 static int can_use_hw_watchpoints;
400
401 static void
402 show_can_use_hw_watchpoints (struct ui_file *file, int from_tty,
403                              struct cmd_list_element *c,
404                              const char *value)
405 {
406   fprintf_filtered (file,
407                     _("Debugger's willingness to use "
408                       "watchpoint hardware is %s.\n"),
409                     value);
410 }
411
412 /* If AUTO_BOOLEAN_FALSE, gdb will not attempt to create pending breakpoints.
413    If AUTO_BOOLEAN_TRUE, gdb will automatically create pending breakpoints
414    for unrecognized breakpoint locations.
415    If AUTO_BOOLEAN_AUTO, gdb will query when breakpoints are unrecognized.  */
416 static enum auto_boolean pending_break_support;
417 static void
418 show_pending_break_support (struct ui_file *file, int from_tty,
419                             struct cmd_list_element *c,
420                             const char *value)
421 {
422   fprintf_filtered (file,
423                     _("Debugger's behavior regarding "
424                       "pending breakpoints is %s.\n"),
425                     value);
426 }
427
428 /* If 1, gdb will automatically use hardware breakpoints for breakpoints
429    set with "break" but falling in read-only memory.
430    If 0, gdb will warn about such breakpoints, but won't automatically
431    use hardware breakpoints.  */
432 static int automatic_hardware_breakpoints;
433 static void
434 show_automatic_hardware_breakpoints (struct ui_file *file, int from_tty,
435                                      struct cmd_list_element *c,
436                                      const char *value)
437 {
438   fprintf_filtered (file,
439                     _("Automatic usage of hardware breakpoints is %s.\n"),
440                     value);
441 }
442
443 /* If on, GDB keeps breakpoints inserted even if the inferior is
444    stopped, and immediately inserts any new breakpoints as soon as
445    they're created.  If off (default), GDB keeps breakpoints off of
446    the target as long as possible.  That is, it delays inserting
447    breakpoints until the next resume, and removes them again when the
448    target fully stops.  This is a bit safer in case GDB crashes while
449    processing user input.  */
450 static int always_inserted_mode = 0;
451
452 static void
453 show_always_inserted_mode (struct ui_file *file, int from_tty,
454                      struct cmd_list_element *c, const char *value)
455 {
456   fprintf_filtered (file, _("Always inserted breakpoint mode is %s.\n"),
457                     value);
458 }
459
460 /* See breakpoint.h.  */
461
462 int
463 breakpoints_should_be_inserted_now (void)
464 {
465   if (gdbarch_has_global_breakpoints (target_gdbarch ()))
466     {
467       /* If breakpoints are global, they should be inserted even if no
468          thread under gdb's control is running, or even if there are
469          no threads under GDB's control yet.  */
470       return 1;
471     }
472   else if (target_has_execution)
473     {
474       struct thread_info *tp;
475
476       if (always_inserted_mode)
477         {
478           /* The user wants breakpoints inserted even if all threads
479              are stopped.  */
480           return 1;
481         }
482
483       if (threads_are_executing ())
484         return 1;
485
486       /* Don't remove breakpoints yet if, even though all threads are
487          stopped, we still have events to process.  */
488       ALL_NON_EXITED_THREADS (tp)
489         if (tp->resumed
490             && tp->suspend.waitstatus_pending_p)
491           return 1;
492     }
493   return 0;
494 }
495
496 static const char condition_evaluation_both[] = "host or target";
497
498 /* Modes for breakpoint condition evaluation.  */
499 static const char condition_evaluation_auto[] = "auto";
500 static const char condition_evaluation_host[] = "host";
501 static const char condition_evaluation_target[] = "target";
502 static const char *const condition_evaluation_enums[] = {
503   condition_evaluation_auto,
504   condition_evaluation_host,
505   condition_evaluation_target,
506   NULL
507 };
508
509 /* Global that holds the current mode for breakpoint condition evaluation.  */
510 static const char *condition_evaluation_mode_1 = condition_evaluation_auto;
511
512 /* Global that we use to display information to the user (gets its value from
513    condition_evaluation_mode_1.  */
514 static const char *condition_evaluation_mode = condition_evaluation_auto;
515
516 /* Translate a condition evaluation mode MODE into either "host"
517    or "target".  This is used mostly to translate from "auto" to the
518    real setting that is being used.  It returns the translated
519    evaluation mode.  */
520
521 static const char *
522 translate_condition_evaluation_mode (const char *mode)
523 {
524   if (mode == condition_evaluation_auto)
525     {
526       if (target_supports_evaluation_of_breakpoint_conditions ())
527         return condition_evaluation_target;
528       else
529         return condition_evaluation_host;
530     }
531   else
532     return mode;
533 }
534
535 /* Discovers what condition_evaluation_auto translates to.  */
536
537 static const char *
538 breakpoint_condition_evaluation_mode (void)
539 {
540   return translate_condition_evaluation_mode (condition_evaluation_mode);
541 }
542
543 /* Return true if GDB should evaluate breakpoint conditions or false
544    otherwise.  */
545
546 static int
547 gdb_evaluates_breakpoint_condition_p (void)
548 {
549   const char *mode = breakpoint_condition_evaluation_mode ();
550
551   return (mode == condition_evaluation_host);
552 }
553
554 void _initialize_breakpoint (void);
555
556 /* Are we executing breakpoint commands?  */
557 static int executing_breakpoint_commands;
558
559 /* Are overlay event breakpoints enabled? */
560 static int overlay_events_enabled;
561
562 /* See description in breakpoint.h. */
563 int target_exact_watchpoints = 0;
564
565 /* Walk the following statement or block through all breakpoints.
566    ALL_BREAKPOINTS_SAFE does so even if the statement deletes the
567    current breakpoint.  */
568
569 #define ALL_BREAKPOINTS(B)  for (B = breakpoint_chain; B; B = B->next)
570
571 #define ALL_BREAKPOINTS_SAFE(B,TMP)     \
572         for (B = breakpoint_chain;      \
573              B ? (TMP=B->next, 1): 0;   \
574              B = TMP)
575
576 /* Similar iterator for the low-level breakpoints.  SAFE variant is
577    not provided so update_global_location_list must not be called
578    while executing the block of ALL_BP_LOCATIONS.  */
579
580 #define ALL_BP_LOCATIONS(B,BP_TMP)                                      \
581         for (BP_TMP = bp_locations;                                     \
582              BP_TMP < bp_locations + bp_locations_count && (B = *BP_TMP);\
583              BP_TMP++)
584
585 /* Iterates through locations with address ADDRESS for the currently selected
586    program space.  BP_LOCP_TMP points to each object.  BP_LOCP_START points
587    to where the loop should start from.
588    If BP_LOCP_START is a NULL pointer, the macro automatically seeks the
589    appropriate location to start with.  */
590
591 #define ALL_BP_LOCATIONS_AT_ADDR(BP_LOCP_TMP, BP_LOCP_START, ADDRESS)   \
592         for (BP_LOCP_START = BP_LOCP_START == NULL ? get_first_locp_gte_addr (ADDRESS) : BP_LOCP_START, \
593              BP_LOCP_TMP = BP_LOCP_START;                               \
594              BP_LOCP_START                                              \
595              && (BP_LOCP_TMP < bp_locations + bp_locations_count        \
596              && (*BP_LOCP_TMP)->address == ADDRESS);                    \
597              BP_LOCP_TMP++)
598
599 /* Iterator for tracepoints only.  */
600
601 #define ALL_TRACEPOINTS(B)  \
602   for (B = breakpoint_chain; B; B = B->next)  \
603     if (is_tracepoint (B))
604
605 /* Chains of all breakpoints defined.  */
606
607 struct breakpoint *breakpoint_chain;
608
609 /* Array is sorted by bp_locations_compare - primarily by the ADDRESS.  */
610
611 static struct bp_location **bp_locations;
612
613 /* Number of elements of BP_LOCATIONS.  */
614
615 static unsigned bp_locations_count;
616
617 /* Maximum alignment offset between bp_target_info.PLACED_ADDRESS and
618    ADDRESS for the current elements of BP_LOCATIONS which get a valid
619    result from bp_location_has_shadow.  You can use it for roughly
620    limiting the subrange of BP_LOCATIONS to scan for shadow bytes for
621    an address you need to read.  */
622
623 static CORE_ADDR bp_locations_placed_address_before_address_max;
624
625 /* Maximum offset plus alignment between bp_target_info.PLACED_ADDRESS
626    + bp_target_info.SHADOW_LEN and ADDRESS for the current elements of
627    BP_LOCATIONS which get a valid result from bp_location_has_shadow.
628    You can use it for roughly limiting the subrange of BP_LOCATIONS to
629    scan for shadow bytes for an address you need to read.  */
630
631 static CORE_ADDR bp_locations_shadow_len_after_address_max;
632
633 /* The locations that no longer correspond to any breakpoint, unlinked
634    from the bp_locations array, but for which a hit may still be
635    reported by a target.  */
636 VEC(bp_location_p) *moribund_locations = NULL;
637
638 /* Number of last breakpoint made.  */
639
640 static int breakpoint_count;
641
642 /* The value of `breakpoint_count' before the last command that
643    created breakpoints.  If the last (break-like) command created more
644    than one breakpoint, then the difference between BREAKPOINT_COUNT
645    and PREV_BREAKPOINT_COUNT is more than one.  */
646 static int prev_breakpoint_count;
647
648 /* Number of last tracepoint made.  */
649
650 static int tracepoint_count;
651
652 static struct cmd_list_element *breakpoint_set_cmdlist;
653 static struct cmd_list_element *breakpoint_show_cmdlist;
654 struct cmd_list_element *save_cmdlist;
655
656 /* See declaration at breakpoint.h.  */
657
658 struct breakpoint *
659 breakpoint_find_if (int (*func) (struct breakpoint *b, void *d),
660                     void *user_data)
661 {
662   struct breakpoint *b = NULL;
663
664   ALL_BREAKPOINTS (b)
665     {
666       if (func (b, user_data) != 0)
667         break;
668     }
669
670   return b;
671 }
672
673 /* Return whether a breakpoint is an active enabled breakpoint.  */
674 static int
675 breakpoint_enabled (struct breakpoint *b)
676 {
677   return (b->enable_state == bp_enabled);
678 }
679
680 /* Set breakpoint count to NUM.  */
681
682 static void
683 set_breakpoint_count (int num)
684 {
685   prev_breakpoint_count = breakpoint_count;
686   breakpoint_count = num;
687   set_internalvar_integer (lookup_internalvar ("bpnum"), num);
688 }
689
690 /* Used by `start_rbreak_breakpoints' below, to record the current
691    breakpoint count before "rbreak" creates any breakpoint.  */
692 static int rbreak_start_breakpoint_count;
693
694 /* Called at the start an "rbreak" command to record the first
695    breakpoint made.  */
696
697 void
698 start_rbreak_breakpoints (void)
699 {
700   rbreak_start_breakpoint_count = breakpoint_count;
701 }
702
703 /* Called at the end of an "rbreak" command to record the last
704    breakpoint made.  */
705
706 void
707 end_rbreak_breakpoints (void)
708 {
709   prev_breakpoint_count = rbreak_start_breakpoint_count;
710 }
711
712 /* Used in run_command to zero the hit count when a new run starts.  */
713
714 void
715 clear_breakpoint_hit_counts (void)
716 {
717   struct breakpoint *b;
718
719   ALL_BREAKPOINTS (b)
720     b->hit_count = 0;
721 }
722
723 /* Allocate a new counted_command_line with reference count of 1.
724    The new structure owns COMMANDS.  */
725
726 static struct counted_command_line *
727 alloc_counted_command_line (struct command_line *commands)
728 {
729   struct counted_command_line *result = XNEW (struct counted_command_line);
730
731   result->refc = 1;
732   result->commands = commands;
733
734   return result;
735 }
736
737 /* Increment reference count.  This does nothing if CMD is NULL.  */
738
739 static void
740 incref_counted_command_line (struct counted_command_line *cmd)
741 {
742   if (cmd)
743     ++cmd->refc;
744 }
745
746 /* Decrement reference count.  If the reference count reaches 0,
747    destroy the counted_command_line.  Sets *CMDP to NULL.  This does
748    nothing if *CMDP is NULL.  */
749
750 static void
751 decref_counted_command_line (struct counted_command_line **cmdp)
752 {
753   if (*cmdp)
754     {
755       if (--(*cmdp)->refc == 0)
756         {
757           free_command_lines (&(*cmdp)->commands);
758           xfree (*cmdp);
759         }
760       *cmdp = NULL;
761     }
762 }
763
764 /* A cleanup function that calls decref_counted_command_line.  */
765
766 static void
767 do_cleanup_counted_command_line (void *arg)
768 {
769   decref_counted_command_line ((struct counted_command_line **) arg);
770 }
771
772 /* Create a cleanup that calls decref_counted_command_line on the
773    argument.  */
774
775 static struct cleanup *
776 make_cleanup_decref_counted_command_line (struct counted_command_line **cmdp)
777 {
778   return make_cleanup (do_cleanup_counted_command_line, cmdp);
779 }
780
781 \f
782 /* Return the breakpoint with the specified number, or NULL
783    if the number does not refer to an existing breakpoint.  */
784
785 struct breakpoint *
786 get_breakpoint (int num)
787 {
788   struct breakpoint *b;
789
790   ALL_BREAKPOINTS (b)
791     if (b->number == num)
792       return b;
793   
794   return NULL;
795 }
796
797 \f
798
799 /* Mark locations as "conditions have changed" in case the target supports
800    evaluating conditions on its side.  */
801
802 static void
803 mark_breakpoint_modified (struct breakpoint *b)
804 {
805   struct bp_location *loc;
806
807   /* This is only meaningful if the target is
808      evaluating conditions and if the user has
809      opted for condition evaluation on the target's
810      side.  */
811   if (gdb_evaluates_breakpoint_condition_p ()
812       || !target_supports_evaluation_of_breakpoint_conditions ())
813     return;
814
815   if (!is_breakpoint (b))
816     return;
817
818   for (loc = b->loc; loc; loc = loc->next)
819     loc->condition_changed = condition_modified;
820 }
821
822 /* Mark location as "conditions have changed" in case the target supports
823    evaluating conditions on its side.  */
824
825 static void
826 mark_breakpoint_location_modified (struct bp_location *loc)
827 {
828   /* This is only meaningful if the target is
829      evaluating conditions and if the user has
830      opted for condition evaluation on the target's
831      side.  */
832   if (gdb_evaluates_breakpoint_condition_p ()
833       || !target_supports_evaluation_of_breakpoint_conditions ())
834
835     return;
836
837   if (!is_breakpoint (loc->owner))
838     return;
839
840   loc->condition_changed = condition_modified;
841 }
842
843 /* Sets the condition-evaluation mode using the static global
844    condition_evaluation_mode.  */
845
846 static void
847 set_condition_evaluation_mode (char *args, int from_tty,
848                                struct cmd_list_element *c)
849 {
850   const char *old_mode, *new_mode;
851
852   if ((condition_evaluation_mode_1 == condition_evaluation_target)
853       && !target_supports_evaluation_of_breakpoint_conditions ())
854     {
855       condition_evaluation_mode_1 = condition_evaluation_mode;
856       warning (_("Target does not support breakpoint condition evaluation.\n"
857                  "Using host evaluation mode instead."));
858       return;
859     }
860
861   new_mode = translate_condition_evaluation_mode (condition_evaluation_mode_1);
862   old_mode = translate_condition_evaluation_mode (condition_evaluation_mode);
863
864   /* Flip the switch.  Flip it even if OLD_MODE == NEW_MODE as one of the
865      settings was "auto".  */
866   condition_evaluation_mode = condition_evaluation_mode_1;
867
868   /* Only update the mode if the user picked a different one.  */
869   if (new_mode != old_mode)
870     {
871       struct bp_location *loc, **loc_tmp;
872       /* If the user switched to a different evaluation mode, we
873          need to synch the changes with the target as follows:
874
875          "host" -> "target": Send all (valid) conditions to the target.
876          "target" -> "host": Remove all the conditions from the target.
877       */
878
879       if (new_mode == condition_evaluation_target)
880         {
881           /* Mark everything modified and synch conditions with the
882              target.  */
883           ALL_BP_LOCATIONS (loc, loc_tmp)
884             mark_breakpoint_location_modified (loc);
885         }
886       else
887         {
888           /* Manually mark non-duplicate locations to synch conditions
889              with the target.  We do this to remove all the conditions the
890              target knows about.  */
891           ALL_BP_LOCATIONS (loc, loc_tmp)
892             if (is_breakpoint (loc->owner) && loc->inserted)
893               loc->needs_update = 1;
894         }
895
896       /* Do the update.  */
897       update_global_location_list (UGLL_MAY_INSERT);
898     }
899
900   return;
901 }
902
903 /* Shows the current mode of breakpoint condition evaluation.  Explicitly shows
904    what "auto" is translating to.  */
905
906 static void
907 show_condition_evaluation_mode (struct ui_file *file, int from_tty,
908                                 struct cmd_list_element *c, const char *value)
909 {
910   if (condition_evaluation_mode == condition_evaluation_auto)
911     fprintf_filtered (file,
912                       _("Breakpoint condition evaluation "
913                         "mode is %s (currently %s).\n"),
914                       value,
915                       breakpoint_condition_evaluation_mode ());
916   else
917     fprintf_filtered (file, _("Breakpoint condition evaluation mode is %s.\n"),
918                       value);
919 }
920
921 /* A comparison function for bp_location AP and BP that is used by
922    bsearch.  This comparison function only cares about addresses, unlike
923    the more general bp_locations_compare function.  */
924
925 static int
926 bp_locations_compare_addrs (const void *ap, const void *bp)
927 {
928   const struct bp_location *a = *(const struct bp_location **) ap;
929   const struct bp_location *b = *(const struct bp_location **) bp;
930
931   if (a->address == b->address)
932     return 0;
933   else
934     return ((a->address > b->address) - (a->address < b->address));
935 }
936
937 /* Helper function to skip all bp_locations with addresses
938    less than ADDRESS.  It returns the first bp_location that
939    is greater than or equal to ADDRESS.  If none is found, just
940    return NULL.  */
941
942 static struct bp_location **
943 get_first_locp_gte_addr (CORE_ADDR address)
944 {
945   struct bp_location dummy_loc;
946   struct bp_location *dummy_locp = &dummy_loc;
947   struct bp_location **locp_found = NULL;
948
949   /* Initialize the dummy location's address field.  */
950   dummy_loc.address = address;
951
952   /* Find a close match to the first location at ADDRESS.  */
953   locp_found = ((struct bp_location **)
954                 bsearch (&dummy_locp, bp_locations, bp_locations_count,
955                          sizeof (struct bp_location **),
956                          bp_locations_compare_addrs));
957
958   /* Nothing was found, nothing left to do.  */
959   if (locp_found == NULL)
960     return NULL;
961
962   /* We may have found a location that is at ADDRESS but is not the first in the
963      location's list.  Go backwards (if possible) and locate the first one.  */
964   while ((locp_found - 1) >= bp_locations
965          && (*(locp_found - 1))->address == address)
966     locp_found--;
967
968   return locp_found;
969 }
970
971 void
972 set_breakpoint_condition (struct breakpoint *b, const char *exp,
973                           int from_tty)
974 {
975   xfree (b->cond_string);
976   b->cond_string = NULL;
977
978   if (is_watchpoint (b))
979     {
980       struct watchpoint *w = (struct watchpoint *) b;
981
982       w->cond_exp.reset ();
983     }
984   else
985     {
986       struct bp_location *loc;
987
988       for (loc = b->loc; loc; loc = loc->next)
989         {
990           loc->cond.reset ();
991
992           /* No need to free the condition agent expression
993              bytecode (if we have one).  We will handle this
994              when we go through update_global_location_list.  */
995         }
996     }
997
998   if (*exp == 0)
999     {
1000       if (from_tty)
1001         printf_filtered (_("Breakpoint %d now unconditional.\n"), b->number);
1002     }
1003   else
1004     {
1005       const char *arg = exp;
1006
1007       /* I don't know if it matters whether this is the string the user
1008          typed in or the decompiled expression.  */
1009       b->cond_string = xstrdup (arg);
1010       b->condition_not_parsed = 0;
1011
1012       if (is_watchpoint (b))
1013         {
1014           struct watchpoint *w = (struct watchpoint *) b;
1015
1016           innermost_block = NULL;
1017           arg = exp;
1018           w->cond_exp = parse_exp_1 (&arg, 0, 0, 0);
1019           if (*arg)
1020             error (_("Junk at end of expression"));
1021           w->cond_exp_valid_block = innermost_block;
1022         }
1023       else
1024         {
1025           struct bp_location *loc;
1026
1027           for (loc = b->loc; loc; loc = loc->next)
1028             {
1029               arg = exp;
1030               loc->cond =
1031                 parse_exp_1 (&arg, loc->address,
1032                              block_for_pc (loc->address), 0);
1033               if (*arg)
1034                 error (_("Junk at end of expression"));
1035             }
1036         }
1037     }
1038   mark_breakpoint_modified (b);
1039
1040   observer_notify_breakpoint_modified (b);
1041 }
1042
1043 /* Completion for the "condition" command.  */
1044
1045 static void
1046 condition_completer (struct cmd_list_element *cmd,
1047                      completion_tracker &tracker,
1048                      const char *text, const char *word)
1049 {
1050   const char *space;
1051
1052   text = skip_spaces_const (text);
1053   space = skip_to_space_const (text);
1054   if (*space == '\0')
1055     {
1056       int len;
1057       struct breakpoint *b;
1058       VEC (char_ptr) *result = NULL;
1059
1060       if (text[0] == '$')
1061         {
1062           /* We don't support completion of history indices.  */
1063           if (!isdigit (text[1]))
1064             complete_internalvar (tracker, &text[1]);
1065           return;
1066         }
1067
1068       /* We're completing the breakpoint number.  */
1069       len = strlen (text);
1070
1071       ALL_BREAKPOINTS (b)
1072         {
1073           char number[50];
1074
1075           xsnprintf (number, sizeof (number), "%d", b->number);
1076
1077           if (strncmp (number, text, len) == 0)
1078             {
1079               gdb::unique_xmalloc_ptr<char> copy (xstrdup (number));
1080               tracker.add_completion (std::move (copy));
1081             }
1082         }
1083
1084       return;
1085     }
1086
1087   /* We're completing the expression part.  */
1088   text = skip_spaces_const (space);
1089   expression_completer (cmd, tracker, text, word);
1090 }
1091
1092 /* condition N EXP -- set break condition of breakpoint N to EXP.  */
1093
1094 static void
1095 condition_command (char *arg, int from_tty)
1096 {
1097   struct breakpoint *b;
1098   char *p;
1099   int bnum;
1100
1101   if (arg == 0)
1102     error_no_arg (_("breakpoint number"));
1103
1104   p = arg;
1105   bnum = get_number (&p);
1106   if (bnum == 0)
1107     error (_("Bad breakpoint argument: '%s'"), arg);
1108
1109   ALL_BREAKPOINTS (b)
1110     if (b->number == bnum)
1111       {
1112         /* Check if this breakpoint has a "stop" method implemented in an
1113            extension language.  This method and conditions entered into GDB
1114            from the CLI are mutually exclusive.  */
1115         const struct extension_language_defn *extlang
1116           = get_breakpoint_cond_ext_lang (b, EXT_LANG_NONE);
1117
1118         if (extlang != NULL)
1119           {
1120             error (_("Only one stop condition allowed.  There is currently"
1121                      " a %s stop condition defined for this breakpoint."),
1122                    ext_lang_capitalized_name (extlang));
1123           }
1124         set_breakpoint_condition (b, p, from_tty);
1125
1126         if (is_breakpoint (b))
1127           update_global_location_list (UGLL_MAY_INSERT);
1128
1129         return;
1130       }
1131
1132   error (_("No breakpoint number %d."), bnum);
1133 }
1134
1135 /* Check that COMMAND do not contain commands that are suitable
1136    only for tracepoints and not suitable for ordinary breakpoints.
1137    Throw if any such commands is found.  */
1138
1139 static void
1140 check_no_tracepoint_commands (struct command_line *commands)
1141 {
1142   struct command_line *c;
1143
1144   for (c = commands; c; c = c->next)
1145     {
1146       int i;
1147
1148       if (c->control_type == while_stepping_control)
1149         error (_("The 'while-stepping' command can "
1150                  "only be used for tracepoints"));
1151
1152       for (i = 0; i < c->body_count; ++i)
1153         check_no_tracepoint_commands ((c->body_list)[i]);
1154
1155       /* Not that command parsing removes leading whitespace and comment
1156          lines and also empty lines.  So, we only need to check for
1157          command directly.  */
1158       if (strstr (c->line, "collect ") == c->line)
1159         error (_("The 'collect' command can only be used for tracepoints"));
1160
1161       if (strstr (c->line, "teval ") == c->line)
1162         error (_("The 'teval' command can only be used for tracepoints"));
1163     }
1164 }
1165
1166 struct longjmp_breakpoint : public breakpoint
1167 {
1168   ~longjmp_breakpoint () override;
1169 };
1170
1171 /* Encapsulate tests for different types of tracepoints.  */
1172
1173 static bool
1174 is_tracepoint_type (bptype type)
1175 {
1176   return (type == bp_tracepoint
1177           || type == bp_fast_tracepoint
1178           || type == bp_static_tracepoint);
1179 }
1180
1181 static bool
1182 is_longjmp_type (bptype type)
1183 {
1184   return type == bp_longjmp || type == bp_exception;
1185 }
1186
1187 int
1188 is_tracepoint (const struct breakpoint *b)
1189 {
1190   return is_tracepoint_type (b->type);
1191 }
1192
1193 /* Factory function to create an appropriate instance of breakpoint given
1194    TYPE.  */
1195
1196 static std::unique_ptr<breakpoint>
1197 new_breakpoint_from_type (bptype type)
1198 {
1199   breakpoint *b;
1200
1201   if (is_tracepoint_type (type))
1202     b = new tracepoint ();
1203   else if (is_longjmp_type (type))
1204     b = new longjmp_breakpoint ();
1205   else
1206     b = new breakpoint ();
1207
1208   return std::unique_ptr<breakpoint> (b);
1209 }
1210
1211 /* A helper function that validates that COMMANDS are valid for a
1212    breakpoint.  This function will throw an exception if a problem is
1213    found.  */
1214
1215 static void
1216 validate_commands_for_breakpoint (struct breakpoint *b,
1217                                   struct command_line *commands)
1218 {
1219   if (is_tracepoint (b))
1220     {
1221       struct tracepoint *t = (struct tracepoint *) b;
1222       struct command_line *c;
1223       struct command_line *while_stepping = 0;
1224
1225       /* Reset the while-stepping step count.  The previous commands
1226          might have included a while-stepping action, while the new
1227          ones might not.  */
1228       t->step_count = 0;
1229
1230       /* We need to verify that each top-level element of commands is
1231          valid for tracepoints, that there's at most one
1232          while-stepping element, and that the while-stepping's body
1233          has valid tracing commands excluding nested while-stepping.
1234          We also need to validate the tracepoint action line in the
1235          context of the tracepoint --- validate_actionline actually
1236          has side effects, like setting the tracepoint's
1237          while-stepping STEP_COUNT, in addition to checking if the
1238          collect/teval actions parse and make sense in the
1239          tracepoint's context.  */
1240       for (c = commands; c; c = c->next)
1241         {
1242           if (c->control_type == while_stepping_control)
1243             {
1244               if (b->type == bp_fast_tracepoint)
1245                 error (_("The 'while-stepping' command "
1246                          "cannot be used for fast tracepoint"));
1247               else if (b->type == bp_static_tracepoint)
1248                 error (_("The 'while-stepping' command "
1249                          "cannot be used for static tracepoint"));
1250
1251               if (while_stepping)
1252                 error (_("The 'while-stepping' command "
1253                          "can be used only once"));
1254               else
1255                 while_stepping = c;
1256             }
1257
1258           validate_actionline (c->line, b);
1259         }
1260       if (while_stepping)
1261         {
1262           struct command_line *c2;
1263
1264           gdb_assert (while_stepping->body_count == 1);
1265           c2 = while_stepping->body_list[0];
1266           for (; c2; c2 = c2->next)
1267             {
1268               if (c2->control_type == while_stepping_control)
1269                 error (_("The 'while-stepping' command cannot be nested"));
1270             }
1271         }
1272     }
1273   else
1274     {
1275       check_no_tracepoint_commands (commands);
1276     }
1277 }
1278
1279 /* Return a vector of all the static tracepoints set at ADDR.  The
1280    caller is responsible for releasing the vector.  */
1281
1282 VEC(breakpoint_p) *
1283 static_tracepoints_here (CORE_ADDR addr)
1284 {
1285   struct breakpoint *b;
1286   VEC(breakpoint_p) *found = 0;
1287   struct bp_location *loc;
1288
1289   ALL_BREAKPOINTS (b)
1290     if (b->type == bp_static_tracepoint)
1291       {
1292         for (loc = b->loc; loc; loc = loc->next)
1293           if (loc->address == addr)
1294             VEC_safe_push(breakpoint_p, found, b);
1295       }
1296
1297   return found;
1298 }
1299
1300 /* Set the command list of B to COMMANDS.  If breakpoint is tracepoint,
1301    validate that only allowed commands are included.  */
1302
1303 void
1304 breakpoint_set_commands (struct breakpoint *b, 
1305                          command_line_up &&commands)
1306 {
1307   validate_commands_for_breakpoint (b, commands.get ());
1308
1309   decref_counted_command_line (&b->commands);
1310   b->commands = alloc_counted_command_line (commands.release ());
1311   observer_notify_breakpoint_modified (b);
1312 }
1313
1314 /* Set the internal `silent' flag on the breakpoint.  Note that this
1315    is not the same as the "silent" that may appear in the breakpoint's
1316    commands.  */
1317
1318 void
1319 breakpoint_set_silent (struct breakpoint *b, int silent)
1320 {
1321   int old_silent = b->silent;
1322
1323   b->silent = silent;
1324   if (old_silent != silent)
1325     observer_notify_breakpoint_modified (b);
1326 }
1327
1328 /* Set the thread for this breakpoint.  If THREAD is -1, make the
1329    breakpoint work for any thread.  */
1330
1331 void
1332 breakpoint_set_thread (struct breakpoint *b, int thread)
1333 {
1334   int old_thread = b->thread;
1335
1336   b->thread = thread;
1337   if (old_thread != thread)
1338     observer_notify_breakpoint_modified (b);
1339 }
1340
1341 /* Set the task for this breakpoint.  If TASK is 0, make the
1342    breakpoint work for any task.  */
1343
1344 void
1345 breakpoint_set_task (struct breakpoint *b, int task)
1346 {
1347   int old_task = b->task;
1348
1349   b->task = task;
1350   if (old_task != task)
1351     observer_notify_breakpoint_modified (b);
1352 }
1353
1354 void
1355 check_tracepoint_command (char *line, void *closure)
1356 {
1357   struct breakpoint *b = (struct breakpoint *) closure;
1358
1359   validate_actionline (line, b);
1360 }
1361
1362 /* A structure used to pass information through
1363    map_breakpoint_numbers.  */
1364
1365 struct commands_info
1366 {
1367   /* True if the command was typed at a tty.  */
1368   int from_tty;
1369
1370   /* The breakpoint range spec.  */
1371   const char *arg;
1372
1373   /* Non-NULL if the body of the commands are being read from this
1374      already-parsed command.  */
1375   struct command_line *control;
1376
1377   /* The command lines read from the user, or NULL if they have not
1378      yet been read.  */
1379   struct counted_command_line *cmd;
1380 };
1381
1382 /* A callback for map_breakpoint_numbers that sets the commands for
1383    commands_command.  */
1384
1385 static void
1386 do_map_commands_command (struct breakpoint *b, void *data)
1387 {
1388   struct commands_info *info = (struct commands_info *) data;
1389
1390   if (info->cmd == NULL)
1391     {
1392       command_line_up l;
1393
1394       if (info->control != NULL)
1395         l = copy_command_lines (info->control->body_list[0]);
1396       else
1397         {
1398           struct cleanup *old_chain;
1399           char *str;
1400
1401           str = xstrprintf (_("Type commands for breakpoint(s) "
1402                               "%s, one per line."),
1403                             info->arg);
1404
1405           old_chain = make_cleanup (xfree, str);
1406
1407           l = read_command_lines (str,
1408                                   info->from_tty, 1,
1409                                   (is_tracepoint (b)
1410                                    ? check_tracepoint_command : 0),
1411                                   b);
1412
1413           do_cleanups (old_chain);
1414         }
1415
1416       info->cmd = alloc_counted_command_line (l.release ());
1417     }
1418
1419   /* If a breakpoint was on the list more than once, we don't need to
1420      do anything.  */
1421   if (b->commands != info->cmd)
1422     {
1423       validate_commands_for_breakpoint (b, info->cmd->commands);
1424       incref_counted_command_line (info->cmd);
1425       decref_counted_command_line (&b->commands);
1426       b->commands = info->cmd;
1427       observer_notify_breakpoint_modified (b);
1428     }
1429 }
1430
1431 static void
1432 commands_command_1 (const char *arg, int from_tty,
1433                     struct command_line *control)
1434 {
1435   struct cleanup *cleanups;
1436   struct commands_info info;
1437
1438   info.from_tty = from_tty;
1439   info.control = control;
1440   info.cmd = NULL;
1441   /* If we read command lines from the user, then `info' will hold an
1442      extra reference to the commands that we must clean up.  */
1443   cleanups = make_cleanup_decref_counted_command_line (&info.cmd);
1444
1445   std::string new_arg;
1446
1447   if (arg == NULL || !*arg)
1448     {
1449       if (breakpoint_count - prev_breakpoint_count > 1)
1450         new_arg = string_printf ("%d-%d", prev_breakpoint_count + 1,
1451                                  breakpoint_count);
1452       else if (breakpoint_count > 0)
1453         new_arg = string_printf ("%d", breakpoint_count);
1454     }
1455   else
1456     new_arg = arg;
1457
1458   info.arg = new_arg.c_str ();
1459
1460   map_breakpoint_numbers (info.arg, do_map_commands_command, &info);
1461
1462   if (info.cmd == NULL)
1463     error (_("No breakpoints specified."));
1464
1465   do_cleanups (cleanups);
1466 }
1467
1468 static void
1469 commands_command (char *arg, int from_tty)
1470 {
1471   commands_command_1 (arg, from_tty, NULL);
1472 }
1473
1474 /* Like commands_command, but instead of reading the commands from
1475    input stream, takes them from an already parsed command structure.
1476
1477    This is used by cli-script.c to DTRT with breakpoint commands
1478    that are part of if and while bodies.  */
1479 enum command_control_type
1480 commands_from_control_command (const char *arg, struct command_line *cmd)
1481 {
1482   commands_command_1 (arg, 0, cmd);
1483   return simple_control;
1484 }
1485
1486 /* Return non-zero if BL->TARGET_INFO contains valid information.  */
1487
1488 static int
1489 bp_location_has_shadow (struct bp_location *bl)
1490 {
1491   if (bl->loc_type != bp_loc_software_breakpoint)
1492     return 0;
1493   if (!bl->inserted)
1494     return 0;
1495   if (bl->target_info.shadow_len == 0)
1496     /* BL isn't valid, or doesn't shadow memory.  */
1497     return 0;
1498   return 1;
1499 }
1500
1501 /* Update BUF, which is LEN bytes read from the target address
1502    MEMADDR, by replacing a memory breakpoint with its shadowed
1503    contents.
1504
1505    If READBUF is not NULL, this buffer must not overlap with the of
1506    the breakpoint location's shadow_contents buffer.  Otherwise, a
1507    failed assertion internal error will be raised.  */
1508
1509 static void
1510 one_breakpoint_xfer_memory (gdb_byte *readbuf, gdb_byte *writebuf,
1511                             const gdb_byte *writebuf_org,
1512                             ULONGEST memaddr, LONGEST len,
1513                             struct bp_target_info *target_info,
1514                             struct gdbarch *gdbarch)
1515 {
1516   /* Now do full processing of the found relevant range of elements.  */
1517   CORE_ADDR bp_addr = 0;
1518   int bp_size = 0;
1519   int bptoffset = 0;
1520
1521   if (!breakpoint_address_match (target_info->placed_address_space, 0,
1522                                  current_program_space->aspace, 0))
1523     {
1524       /* The breakpoint is inserted in a different address space.  */
1525       return;
1526     }
1527
1528   /* Addresses and length of the part of the breakpoint that
1529      we need to copy.  */
1530   bp_addr = target_info->placed_address;
1531   bp_size = target_info->shadow_len;
1532
1533   if (bp_addr + bp_size <= memaddr)
1534     {
1535       /* The breakpoint is entirely before the chunk of memory we are
1536          reading.  */
1537       return;
1538     }
1539
1540   if (bp_addr >= memaddr + len)
1541     {
1542       /* The breakpoint is entirely after the chunk of memory we are
1543          reading.  */
1544       return;
1545     }
1546
1547   /* Offset within shadow_contents.  */
1548   if (bp_addr < memaddr)
1549     {
1550       /* Only copy the second part of the breakpoint.  */
1551       bp_size -= memaddr - bp_addr;
1552       bptoffset = memaddr - bp_addr;
1553       bp_addr = memaddr;
1554     }
1555
1556   if (bp_addr + bp_size > memaddr + len)
1557     {
1558       /* Only copy the first part of the breakpoint.  */
1559       bp_size -= (bp_addr + bp_size) - (memaddr + len);
1560     }
1561
1562   if (readbuf != NULL)
1563     {
1564       /* Verify that the readbuf buffer does not overlap with the
1565          shadow_contents buffer.  */
1566       gdb_assert (target_info->shadow_contents >= readbuf + len
1567                   || readbuf >= (target_info->shadow_contents
1568                                  + target_info->shadow_len));
1569
1570       /* Update the read buffer with this inserted breakpoint's
1571          shadow.  */
1572       memcpy (readbuf + bp_addr - memaddr,
1573               target_info->shadow_contents + bptoffset, bp_size);
1574     }
1575   else
1576     {
1577       const unsigned char *bp;
1578       CORE_ADDR addr = target_info->reqstd_address;
1579       int placed_size;
1580
1581       /* Update the shadow with what we want to write to memory.  */
1582       memcpy (target_info->shadow_contents + bptoffset,
1583               writebuf_org + bp_addr - memaddr, bp_size);
1584
1585       /* Determine appropriate breakpoint contents and size for this
1586          address.  */
1587       bp = gdbarch_breakpoint_from_pc (gdbarch, &addr, &placed_size);
1588
1589       /* Update the final write buffer with this inserted
1590          breakpoint's INSN.  */
1591       memcpy (writebuf + bp_addr - memaddr, bp + bptoffset, bp_size);
1592     }
1593 }
1594
1595 /* Update BUF, which is LEN bytes read from the target address MEMADDR,
1596    by replacing any memory breakpoints with their shadowed contents.
1597
1598    If READBUF is not NULL, this buffer must not overlap with any of
1599    the breakpoint location's shadow_contents buffers.  Otherwise,
1600    a failed assertion internal error will be raised.
1601
1602    The range of shadowed area by each bp_location is:
1603      bl->address - bp_locations_placed_address_before_address_max
1604      up to bl->address + bp_locations_shadow_len_after_address_max
1605    The range we were requested to resolve shadows for is:
1606      memaddr ... memaddr + len
1607    Thus the safe cutoff boundaries for performance optimization are
1608      memaddr + len <= (bl->address
1609                        - bp_locations_placed_address_before_address_max)
1610    and:
1611      bl->address + bp_locations_shadow_len_after_address_max <= memaddr  */
1612
1613 void
1614 breakpoint_xfer_memory (gdb_byte *readbuf, gdb_byte *writebuf,
1615                         const gdb_byte *writebuf_org,
1616                         ULONGEST memaddr, LONGEST len)
1617 {
1618   /* Left boundary, right boundary and median element of our binary
1619      search.  */
1620   unsigned bc_l, bc_r, bc;
1621
1622   /* Find BC_L which is a leftmost element which may affect BUF
1623      content.  It is safe to report lower value but a failure to
1624      report higher one.  */
1625
1626   bc_l = 0;
1627   bc_r = bp_locations_count;
1628   while (bc_l + 1 < bc_r)
1629     {
1630       struct bp_location *bl;
1631
1632       bc = (bc_l + bc_r) / 2;
1633       bl = bp_locations[bc];
1634
1635       /* Check first BL->ADDRESS will not overflow due to the added
1636          constant.  Then advance the left boundary only if we are sure
1637          the BC element can in no way affect the BUF content (MEMADDR
1638          to MEMADDR + LEN range).
1639
1640          Use the BP_LOCATIONS_SHADOW_LEN_AFTER_ADDRESS_MAX safety
1641          offset so that we cannot miss a breakpoint with its shadow
1642          range tail still reaching MEMADDR.  */
1643
1644       if ((bl->address + bp_locations_shadow_len_after_address_max
1645            >= bl->address)
1646           && (bl->address + bp_locations_shadow_len_after_address_max
1647               <= memaddr))
1648         bc_l = bc;
1649       else
1650         bc_r = bc;
1651     }
1652
1653   /* Due to the binary search above, we need to make sure we pick the
1654      first location that's at BC_L's address.  E.g., if there are
1655      multiple locations at the same address, BC_L may end up pointing
1656      at a duplicate location, and miss the "master"/"inserted"
1657      location.  Say, given locations L1, L2 and L3 at addresses A and
1658      B:
1659
1660       L1@A, L2@A, L3@B, ...
1661
1662      BC_L could end up pointing at location L2, while the "master"
1663      location could be L1.  Since the `loc->inserted' flag is only set
1664      on "master" locations, we'd forget to restore the shadow of L1
1665      and L2.  */
1666   while (bc_l > 0
1667          && bp_locations[bc_l]->address == bp_locations[bc_l - 1]->address)
1668     bc_l--;
1669
1670   /* Now do full processing of the found relevant range of elements.  */
1671
1672   for (bc = bc_l; bc < bp_locations_count; bc++)
1673   {
1674     struct bp_location *bl = bp_locations[bc];
1675
1676     /* bp_location array has BL->OWNER always non-NULL.  */
1677     if (bl->owner->type == bp_none)
1678       warning (_("reading through apparently deleted breakpoint #%d?"),
1679                bl->owner->number);
1680
1681     /* Performance optimization: any further element can no longer affect BUF
1682        content.  */
1683
1684     if (bl->address >= bp_locations_placed_address_before_address_max
1685         && memaddr + len <= (bl->address
1686                              - bp_locations_placed_address_before_address_max))
1687       break;
1688
1689     if (!bp_location_has_shadow (bl))
1690       continue;
1691
1692     one_breakpoint_xfer_memory (readbuf, writebuf, writebuf_org,
1693                                 memaddr, len, &bl->target_info, bl->gdbarch);
1694   }
1695 }
1696
1697 \f
1698
1699 /* Return true if BPT is either a software breakpoint or a hardware
1700    breakpoint.  */
1701
1702 int
1703 is_breakpoint (const struct breakpoint *bpt)
1704 {
1705   return (bpt->type == bp_breakpoint
1706           || bpt->type == bp_hardware_breakpoint
1707           || bpt->type == bp_dprintf);
1708 }
1709
1710 /* Return true if BPT is of any hardware watchpoint kind.  */
1711
1712 static int
1713 is_hardware_watchpoint (const struct breakpoint *bpt)
1714 {
1715   return (bpt->type == bp_hardware_watchpoint
1716           || bpt->type == bp_read_watchpoint
1717           || bpt->type == bp_access_watchpoint);
1718 }
1719
1720 /* Return true if BPT is of any watchpoint kind, hardware or
1721    software.  */
1722
1723 int
1724 is_watchpoint (const struct breakpoint *bpt)
1725 {
1726   return (is_hardware_watchpoint (bpt)
1727           || bpt->type == bp_watchpoint);
1728 }
1729
1730 /* Returns true if the current thread and its running state are safe
1731    to evaluate or update watchpoint B.  Watchpoints on local
1732    expressions need to be evaluated in the context of the thread that
1733    was current when the watchpoint was created, and, that thread needs
1734    to be stopped to be able to select the correct frame context.
1735    Watchpoints on global expressions can be evaluated on any thread,
1736    and in any state.  It is presently left to the target allowing
1737    memory accesses when threads are running.  */
1738
1739 static int
1740 watchpoint_in_thread_scope (struct watchpoint *b)
1741 {
1742   return (b->pspace == current_program_space
1743           && (ptid_equal (b->watchpoint_thread, null_ptid)
1744               || (ptid_equal (inferior_ptid, b->watchpoint_thread)
1745                   && !is_executing (inferior_ptid))));
1746 }
1747
1748 /* Set watchpoint B to disp_del_at_next_stop, even including its possible
1749    associated bp_watchpoint_scope breakpoint.  */
1750
1751 static void
1752 watchpoint_del_at_next_stop (struct watchpoint *w)
1753 {
1754   if (w->related_breakpoint != w)
1755     {
1756       gdb_assert (w->related_breakpoint->type == bp_watchpoint_scope);
1757       gdb_assert (w->related_breakpoint->related_breakpoint == w);
1758       w->related_breakpoint->disposition = disp_del_at_next_stop;
1759       w->related_breakpoint->related_breakpoint = w->related_breakpoint;
1760       w->related_breakpoint = w;
1761     }
1762   w->disposition = disp_del_at_next_stop;
1763 }
1764
1765 /* Extract a bitfield value from value VAL using the bit parameters contained in
1766    watchpoint W.  */
1767
1768 static struct value *
1769 extract_bitfield_from_watchpoint_value (struct watchpoint *w, struct value *val)
1770 {
1771   struct value *bit_val;
1772
1773   if (val == NULL)
1774     return NULL;
1775
1776   bit_val = allocate_value (value_type (val));
1777
1778   unpack_value_bitfield (bit_val,
1779                          w->val_bitpos,
1780                          w->val_bitsize,
1781                          value_contents_for_printing (val),
1782                          value_offset (val),
1783                          val);
1784
1785   return bit_val;
1786 }
1787
1788 /* Allocate a dummy location and add it to B, which must be a software
1789    watchpoint.  This is required because even if a software watchpoint
1790    is not watching any memory, bpstat_stop_status requires a location
1791    to be able to report stops.  */
1792
1793 static void
1794 software_watchpoint_add_no_memory_location (struct breakpoint *b,
1795                                             struct program_space *pspace)
1796 {
1797   gdb_assert (b->type == bp_watchpoint && b->loc == NULL);
1798
1799   b->loc = allocate_bp_location (b);
1800   b->loc->pspace = pspace;
1801   b->loc->address = -1;
1802   b->loc->length = -1;
1803 }
1804
1805 /* Returns true if B is a software watchpoint that is not watching any
1806    memory (e.g., "watch $pc").  */
1807
1808 static int
1809 is_no_memory_software_watchpoint (struct breakpoint *b)
1810 {
1811   return (b->type == bp_watchpoint
1812           && b->loc != NULL
1813           && b->loc->next == NULL
1814           && b->loc->address == -1
1815           && b->loc->length == -1);
1816 }
1817
1818 /* Assuming that B is a watchpoint:
1819    - Reparse watchpoint expression, if REPARSE is non-zero
1820    - Evaluate expression and store the result in B->val
1821    - Evaluate the condition if there is one, and store the result
1822      in b->loc->cond.
1823    - Update the list of values that must be watched in B->loc.
1824
1825    If the watchpoint disposition is disp_del_at_next_stop, then do
1826    nothing.  If this is local watchpoint that is out of scope, delete
1827    it.
1828
1829    Even with `set breakpoint always-inserted on' the watchpoints are
1830    removed + inserted on each stop here.  Normal breakpoints must
1831    never be removed because they might be missed by a running thread
1832    when debugging in non-stop mode.  On the other hand, hardware
1833    watchpoints (is_hardware_watchpoint; processed here) are specific
1834    to each LWP since they are stored in each LWP's hardware debug
1835    registers.  Therefore, such LWP must be stopped first in order to
1836    be able to modify its hardware watchpoints.
1837
1838    Hardware watchpoints must be reset exactly once after being
1839    presented to the user.  It cannot be done sooner, because it would
1840    reset the data used to present the watchpoint hit to the user.  And
1841    it must not be done later because it could display the same single
1842    watchpoint hit during multiple GDB stops.  Note that the latter is
1843    relevant only to the hardware watchpoint types bp_read_watchpoint
1844    and bp_access_watchpoint.  False hit by bp_hardware_watchpoint is
1845    not user-visible - its hit is suppressed if the memory content has
1846    not changed.
1847
1848    The following constraints influence the location where we can reset
1849    hardware watchpoints:
1850
1851    * target_stopped_by_watchpoint and target_stopped_data_address are
1852      called several times when GDB stops.
1853
1854    [linux] 
1855    * Multiple hardware watchpoints can be hit at the same time,
1856      causing GDB to stop.  GDB only presents one hardware watchpoint
1857      hit at a time as the reason for stopping, and all the other hits
1858      are presented later, one after the other, each time the user
1859      requests the execution to be resumed.  Execution is not resumed
1860      for the threads still having pending hit event stored in
1861      LWP_INFO->STATUS.  While the watchpoint is already removed from
1862      the inferior on the first stop the thread hit event is kept being
1863      reported from its cached value by linux_nat_stopped_data_address
1864      until the real thread resume happens after the watchpoint gets
1865      presented and thus its LWP_INFO->STATUS gets reset.
1866
1867    Therefore the hardware watchpoint hit can get safely reset on the
1868    watchpoint removal from inferior.  */
1869
1870 static void
1871 update_watchpoint (struct watchpoint *b, int reparse)
1872 {
1873   int within_current_scope;
1874   struct frame_id saved_frame_id;
1875   int frame_saved;
1876
1877   /* If this is a local watchpoint, we only want to check if the
1878      watchpoint frame is in scope if the current thread is the thread
1879      that was used to create the watchpoint.  */
1880   if (!watchpoint_in_thread_scope (b))
1881     return;
1882
1883   if (b->disposition == disp_del_at_next_stop)
1884     return;
1885  
1886   frame_saved = 0;
1887
1888   /* Determine if the watchpoint is within scope.  */
1889   if (b->exp_valid_block == NULL)
1890     within_current_scope = 1;
1891   else
1892     {
1893       struct frame_info *fi = get_current_frame ();
1894       struct gdbarch *frame_arch = get_frame_arch (fi);
1895       CORE_ADDR frame_pc = get_frame_pc (fi);
1896
1897       /* If we're at a point where the stack has been destroyed
1898          (e.g. in a function epilogue), unwinding may not work
1899          properly. Do not attempt to recreate locations at this
1900          point.  See similar comments in watchpoint_check.  */
1901       if (gdbarch_stack_frame_destroyed_p (frame_arch, frame_pc))
1902         return;
1903
1904       /* Save the current frame's ID so we can restore it after
1905          evaluating the watchpoint expression on its own frame.  */
1906       /* FIXME drow/2003-09-09: It would be nice if evaluate_expression
1907          took a frame parameter, so that we didn't have to change the
1908          selected frame.  */
1909       frame_saved = 1;
1910       saved_frame_id = get_frame_id (get_selected_frame (NULL));
1911
1912       fi = frame_find_by_id (b->watchpoint_frame);
1913       within_current_scope = (fi != NULL);
1914       if (within_current_scope)
1915         select_frame (fi);
1916     }
1917
1918   /* We don't free locations.  They are stored in the bp_location array
1919      and update_global_location_list will eventually delete them and
1920      remove breakpoints if needed.  */
1921   b->loc = NULL;
1922
1923   if (within_current_scope && reparse)
1924     {
1925       const char *s;
1926
1927       b->exp.reset ();
1928       s = b->exp_string_reparse ? b->exp_string_reparse : b->exp_string;
1929       b->exp = parse_exp_1 (&s, 0, b->exp_valid_block, 0);
1930       /* If the meaning of expression itself changed, the old value is
1931          no longer relevant.  We don't want to report a watchpoint hit
1932          to the user when the old value and the new value may actually
1933          be completely different objects.  */
1934       value_free (b->val);
1935       b->val = NULL;
1936       b->val_valid = 0;
1937
1938       /* Note that unlike with breakpoints, the watchpoint's condition
1939          expression is stored in the breakpoint object, not in the
1940          locations (re)created below.  */
1941       if (b->cond_string != NULL)
1942         {
1943           b->cond_exp.reset ();
1944
1945           s = b->cond_string;
1946           b->cond_exp = parse_exp_1 (&s, 0, b->cond_exp_valid_block, 0);
1947         }
1948     }
1949
1950   /* If we failed to parse the expression, for example because
1951      it refers to a global variable in a not-yet-loaded shared library,
1952      don't try to insert watchpoint.  We don't automatically delete
1953      such watchpoint, though, since failure to parse expression
1954      is different from out-of-scope watchpoint.  */
1955   if (!target_has_execution)
1956     {
1957       /* Without execution, memory can't change.  No use to try and
1958          set watchpoint locations.  The watchpoint will be reset when
1959          the target gains execution, through breakpoint_re_set.  */
1960       if (!can_use_hw_watchpoints)
1961         {
1962           if (b->ops->works_in_software_mode (b))
1963             b->type = bp_watchpoint;
1964           else
1965             error (_("Can't set read/access watchpoint when "
1966                      "hardware watchpoints are disabled."));
1967         }
1968     }
1969   else if (within_current_scope && b->exp)
1970     {
1971       int pc = 0;
1972       struct value *val_chain, *v, *result, *next;
1973       struct program_space *frame_pspace;
1974
1975       fetch_subexp_value (b->exp.get (), &pc, &v, &result, &val_chain, 0);
1976
1977       /* Avoid setting b->val if it's already set.  The meaning of
1978          b->val is 'the last value' user saw, and we should update
1979          it only if we reported that last value to user.  As it
1980          happens, the code that reports it updates b->val directly.
1981          We don't keep track of the memory value for masked
1982          watchpoints.  */
1983       if (!b->val_valid && !is_masked_watchpoint (b))
1984         {
1985           if (b->val_bitsize != 0)
1986             {
1987               v = extract_bitfield_from_watchpoint_value (b, v);
1988               if (v != NULL)
1989                 release_value (v);
1990             }
1991           b->val = v;
1992           b->val_valid = 1;
1993         }
1994
1995       frame_pspace = get_frame_program_space (get_selected_frame (NULL));
1996
1997       /* Look at each value on the value chain.  */
1998       for (v = val_chain; v; v = value_next (v))
1999         {
2000           /* If it's a memory location, and GDB actually needed
2001              its contents to evaluate the expression, then we
2002              must watch it.  If the first value returned is
2003              still lazy, that means an error occurred reading it;
2004              watch it anyway in case it becomes readable.  */
2005           if (VALUE_LVAL (v) == lval_memory
2006               && (v == val_chain || ! value_lazy (v)))
2007             {
2008               struct type *vtype = check_typedef (value_type (v));
2009
2010               /* We only watch structs and arrays if user asked
2011                  for it explicitly, never if they just happen to
2012                  appear in the middle of some value chain.  */
2013               if (v == result
2014                   || (TYPE_CODE (vtype) != TYPE_CODE_STRUCT
2015                       && TYPE_CODE (vtype) != TYPE_CODE_ARRAY))
2016                 {
2017                   CORE_ADDR addr;
2018                   enum target_hw_bp_type type;
2019                   struct bp_location *loc, **tmp;
2020                   int bitpos = 0, bitsize = 0;
2021
2022                   if (value_bitsize (v) != 0)
2023                     {
2024                       /* Extract the bit parameters out from the bitfield
2025                          sub-expression.  */
2026                       bitpos = value_bitpos (v);
2027                       bitsize = value_bitsize (v);
2028                     }
2029                   else if (v == result && b->val_bitsize != 0)
2030                     {
2031                      /* If VAL_BITSIZE != 0 then RESULT is actually a bitfield
2032                         lvalue whose bit parameters are saved in the fields
2033                         VAL_BITPOS and VAL_BITSIZE.  */
2034                       bitpos = b->val_bitpos;
2035                       bitsize = b->val_bitsize;
2036                     }
2037
2038                   addr = value_address (v);
2039                   if (bitsize != 0)
2040                     {
2041                       /* Skip the bytes that don't contain the bitfield.  */
2042                       addr += bitpos / 8;
2043                     }
2044
2045                   type = hw_write;
2046                   if (b->type == bp_read_watchpoint)
2047                     type = hw_read;
2048                   else if (b->type == bp_access_watchpoint)
2049                     type = hw_access;
2050
2051                   loc = allocate_bp_location (b);
2052                   for (tmp = &(b->loc); *tmp != NULL; tmp = &((*tmp)->next))
2053                     ;
2054                   *tmp = loc;
2055                   loc->gdbarch = get_type_arch (value_type (v));
2056
2057                   loc->pspace = frame_pspace;
2058                   loc->address = addr;
2059
2060                   if (bitsize != 0)
2061                     {
2062                       /* Just cover the bytes that make up the bitfield.  */
2063                       loc->length = ((bitpos % 8) + bitsize + 7) / 8;
2064                     }
2065                   else
2066                     loc->length = TYPE_LENGTH (value_type (v));
2067
2068                   loc->watchpoint_type = type;
2069                 }
2070             }
2071         }
2072
2073       /* Change the type of breakpoint between hardware assisted or
2074          an ordinary watchpoint depending on the hardware support
2075          and free hardware slots.  REPARSE is set when the inferior
2076          is started.  */
2077       if (reparse)
2078         {
2079           int reg_cnt;
2080           enum bp_loc_type loc_type;
2081           struct bp_location *bl;
2082
2083           reg_cnt = can_use_hardware_watchpoint (val_chain);
2084
2085           if (reg_cnt)
2086             {
2087               int i, target_resources_ok, other_type_used;
2088               enum bptype type;
2089
2090               /* Use an exact watchpoint when there's only one memory region to be
2091                  watched, and only one debug register is needed to watch it.  */
2092               b->exact = target_exact_watchpoints && reg_cnt == 1;
2093
2094               /* We need to determine how many resources are already
2095                  used for all other hardware watchpoints plus this one
2096                  to see if we still have enough resources to also fit
2097                  this watchpoint in as well.  */
2098
2099               /* If this is a software watchpoint, we try to turn it
2100                  to a hardware one -- count resources as if B was of
2101                  hardware watchpoint type.  */
2102               type = b->type;
2103               if (type == bp_watchpoint)
2104                 type = bp_hardware_watchpoint;
2105
2106               /* This watchpoint may or may not have been placed on
2107                  the list yet at this point (it won't be in the list
2108                  if we're trying to create it for the first time,
2109                  through watch_command), so always account for it
2110                  manually.  */
2111
2112               /* Count resources used by all watchpoints except B.  */
2113               i = hw_watchpoint_used_count_others (b, type, &other_type_used);
2114
2115               /* Add in the resources needed for B.  */
2116               i += hw_watchpoint_use_count (b);
2117
2118               target_resources_ok
2119                 = target_can_use_hardware_watchpoint (type, i, other_type_used);
2120               if (target_resources_ok <= 0)
2121                 {
2122                   int sw_mode = b->ops->works_in_software_mode (b);
2123
2124                   if (target_resources_ok == 0 && !sw_mode)
2125                     error (_("Target does not support this type of "
2126                              "hardware watchpoint."));
2127                   else if (target_resources_ok < 0 && !sw_mode)
2128                     error (_("There are not enough available hardware "
2129                              "resources for this watchpoint."));
2130
2131                   /* Downgrade to software watchpoint.  */
2132                   b->type = bp_watchpoint;
2133                 }
2134               else
2135                 {
2136                   /* If this was a software watchpoint, we've just
2137                      found we have enough resources to turn it to a
2138                      hardware watchpoint.  Otherwise, this is a
2139                      nop.  */
2140                   b->type = type;
2141                 }
2142             }
2143           else if (!b->ops->works_in_software_mode (b))
2144             {
2145               if (!can_use_hw_watchpoints)
2146                 error (_("Can't set read/access watchpoint when "
2147                          "hardware watchpoints are disabled."));
2148               else
2149                 error (_("Expression cannot be implemented with "
2150                          "read/access watchpoint."));
2151             }
2152           else
2153             b->type = bp_watchpoint;
2154
2155           loc_type = (b->type == bp_watchpoint? bp_loc_other
2156                       : bp_loc_hardware_watchpoint);
2157           for (bl = b->loc; bl; bl = bl->next)
2158             bl->loc_type = loc_type;
2159         }
2160
2161       for (v = val_chain; v; v = next)
2162         {
2163           next = value_next (v);
2164           if (v != b->val)
2165             value_free (v);
2166         }
2167
2168       /* If a software watchpoint is not watching any memory, then the
2169          above left it without any location set up.  But,
2170          bpstat_stop_status requires a location to be able to report
2171          stops, so make sure there's at least a dummy one.  */
2172       if (b->type == bp_watchpoint && b->loc == NULL)
2173         software_watchpoint_add_no_memory_location (b, frame_pspace);
2174     }
2175   else if (!within_current_scope)
2176     {
2177       printf_filtered (_("\
2178 Watchpoint %d deleted because the program has left the block\n\
2179 in which its expression is valid.\n"),
2180                        b->number);
2181       watchpoint_del_at_next_stop (b);
2182     }
2183
2184   /* Restore the selected frame.  */
2185   if (frame_saved)
2186     select_frame (frame_find_by_id (saved_frame_id));
2187 }
2188
2189
2190 /* Returns 1 iff breakpoint location should be
2191    inserted in the inferior.  We don't differentiate the type of BL's owner
2192    (breakpoint vs. tracepoint), although insert_location in tracepoint's
2193    breakpoint_ops is not defined, because in insert_bp_location,
2194    tracepoint's insert_location will not be called.  */
2195 static int
2196 should_be_inserted (struct bp_location *bl)
2197 {
2198   if (bl->owner == NULL || !breakpoint_enabled (bl->owner))
2199     return 0;
2200
2201   if (bl->owner->disposition == disp_del_at_next_stop)
2202     return 0;
2203
2204   if (!bl->enabled || bl->shlib_disabled || bl->duplicate)
2205     return 0;
2206
2207   if (user_breakpoint_p (bl->owner) && bl->pspace->executing_startup)
2208     return 0;
2209
2210   /* This is set for example, when we're attached to the parent of a
2211      vfork, and have detached from the child.  The child is running
2212      free, and we expect it to do an exec or exit, at which point the
2213      OS makes the parent schedulable again (and the target reports
2214      that the vfork is done).  Until the child is done with the shared
2215      memory region, do not insert breakpoints in the parent, otherwise
2216      the child could still trip on the parent's breakpoints.  Since
2217      the parent is blocked anyway, it won't miss any breakpoint.  */
2218   if (bl->pspace->breakpoints_not_allowed)
2219     return 0;
2220
2221   /* Don't insert a breakpoint if we're trying to step past its
2222      location, except if the breakpoint is a single-step breakpoint,
2223      and the breakpoint's thread is the thread which is stepping past
2224      a breakpoint.  */
2225   if ((bl->loc_type == bp_loc_software_breakpoint
2226        || bl->loc_type == bp_loc_hardware_breakpoint)
2227       && stepping_past_instruction_at (bl->pspace->aspace,
2228                                        bl->address)
2229       /* The single-step breakpoint may be inserted at the location
2230          we're trying to step if the instruction branches to itself.
2231          However, the instruction won't be executed at all and it may
2232          break the semantics of the instruction, for example, the
2233          instruction is a conditional branch or updates some flags.
2234          We can't fix it unless GDB is able to emulate the instruction
2235          or switch to displaced stepping.  */
2236       && !(bl->owner->type == bp_single_step
2237            && thread_is_stepping_over_breakpoint (bl->owner->thread)))
2238     {
2239       if (debug_infrun)
2240         {
2241           fprintf_unfiltered (gdb_stdlog,
2242                               "infrun: skipping breakpoint: "
2243                               "stepping past insn at: %s\n",
2244                               paddress (bl->gdbarch, bl->address));
2245         }
2246       return 0;
2247     }
2248
2249   /* Don't insert watchpoints if we're trying to step past the
2250      instruction that triggered one.  */
2251   if ((bl->loc_type == bp_loc_hardware_watchpoint)
2252       && stepping_past_nonsteppable_watchpoint ())
2253     {
2254       if (debug_infrun)
2255         {
2256           fprintf_unfiltered (gdb_stdlog,
2257                               "infrun: stepping past non-steppable watchpoint. "
2258                               "skipping watchpoint at %s:%d\n",
2259                               paddress (bl->gdbarch, bl->address),
2260                               bl->length);
2261         }
2262       return 0;
2263     }
2264
2265   return 1;
2266 }
2267
2268 /* Same as should_be_inserted but does the check assuming
2269    that the location is not duplicated.  */
2270
2271 static int
2272 unduplicated_should_be_inserted (struct bp_location *bl)
2273 {
2274   int result;
2275   const int save_duplicate = bl->duplicate;
2276
2277   bl->duplicate = 0;
2278   result = should_be_inserted (bl);
2279   bl->duplicate = save_duplicate;
2280   return result;
2281 }
2282
2283 /* Parses a conditional described by an expression COND into an
2284    agent expression bytecode suitable for evaluation
2285    by the bytecode interpreter.  Return NULL if there was
2286    any error during parsing.  */
2287
2288 static agent_expr_up
2289 parse_cond_to_aexpr (CORE_ADDR scope, struct expression *cond)
2290 {
2291   if (cond == NULL)
2292     return NULL;
2293
2294   agent_expr_up aexpr;
2295
2296   /* We don't want to stop processing, so catch any errors
2297      that may show up.  */
2298   TRY
2299     {
2300       aexpr = gen_eval_for_expr (scope, cond);
2301     }
2302
2303   CATCH (ex, RETURN_MASK_ERROR)
2304     {
2305       /* If we got here, it means the condition could not be parsed to a valid
2306          bytecode expression and thus can't be evaluated on the target's side.
2307          It's no use iterating through the conditions.  */
2308     }
2309   END_CATCH
2310
2311   /* We have a valid agent expression.  */
2312   return aexpr;
2313 }
2314
2315 /* Based on location BL, create a list of breakpoint conditions to be
2316    passed on to the target.  If we have duplicated locations with different
2317    conditions, we will add such conditions to the list.  The idea is that the
2318    target will evaluate the list of conditions and will only notify GDB when
2319    one of them is true.  */
2320
2321 static void
2322 build_target_condition_list (struct bp_location *bl)
2323 {
2324   struct bp_location **locp = NULL, **loc2p;
2325   int null_condition_or_parse_error = 0;
2326   int modified = bl->needs_update;
2327   struct bp_location *loc;
2328
2329   /* Release conditions left over from a previous insert.  */
2330   bl->target_info.conditions.clear ();
2331
2332   /* This is only meaningful if the target is
2333      evaluating conditions and if the user has
2334      opted for condition evaluation on the target's
2335      side.  */
2336   if (gdb_evaluates_breakpoint_condition_p ()
2337       || !target_supports_evaluation_of_breakpoint_conditions ())
2338     return;
2339
2340   /* Do a first pass to check for locations with no assigned
2341      conditions or conditions that fail to parse to a valid agent expression
2342      bytecode.  If any of these happen, then it's no use to send conditions
2343      to the target since this location will always trigger and generate a
2344      response back to GDB.  */
2345   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2346     {
2347       loc = (*loc2p);
2348       if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2349         {
2350           if (modified)
2351             {
2352               /* Re-parse the conditions since something changed.  In that
2353                  case we already freed the condition bytecodes (see
2354                  force_breakpoint_reinsertion).  We just
2355                  need to parse the condition to bytecodes again.  */
2356               loc->cond_bytecode = parse_cond_to_aexpr (bl->address,
2357                                                         loc->cond.get ());
2358             }
2359
2360           /* If we have a NULL bytecode expression, it means something
2361              went wrong or we have a null condition expression.  */
2362           if (!loc->cond_bytecode)
2363             {
2364               null_condition_or_parse_error = 1;
2365               break;
2366             }
2367         }
2368     }
2369
2370   /* If any of these happened, it means we will have to evaluate the conditions
2371      for the location's address on gdb's side.  It is no use keeping bytecodes
2372      for all the other duplicate locations, thus we free all of them here.
2373
2374      This is so we have a finer control over which locations' conditions are
2375      being evaluated by GDB or the remote stub.  */
2376   if (null_condition_or_parse_error)
2377     {
2378       ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2379         {
2380           loc = (*loc2p);
2381           if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2382             {
2383               /* Only go as far as the first NULL bytecode is
2384                  located.  */
2385               if (!loc->cond_bytecode)
2386                 return;
2387
2388               loc->cond_bytecode.reset ();
2389             }
2390         }
2391     }
2392
2393   /* No NULL conditions or failed bytecode generation.  Build a condition list
2394      for this location's address.  */
2395   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2396     {
2397       loc = (*loc2p);
2398       if (loc->cond
2399           && is_breakpoint (loc->owner)
2400           && loc->pspace->num == bl->pspace->num
2401           && loc->owner->enable_state == bp_enabled
2402           && loc->enabled)
2403         {
2404           /* Add the condition to the vector.  This will be used later
2405              to send the conditions to the target.  */
2406           bl->target_info.conditions.push_back (loc->cond_bytecode.get ());
2407         }
2408     }
2409
2410   return;
2411 }
2412
2413 /* Parses a command described by string CMD into an agent expression
2414    bytecode suitable for evaluation by the bytecode interpreter.
2415    Return NULL if there was any error during parsing.  */
2416
2417 static agent_expr_up
2418 parse_cmd_to_aexpr (CORE_ADDR scope, char *cmd)
2419 {
2420   struct cleanup *old_cleanups = 0;
2421   struct expression **argvec;
2422   const char *cmdrest;
2423   const char *format_start, *format_end;
2424   struct format_piece *fpieces;
2425   int nargs;
2426   struct gdbarch *gdbarch = get_current_arch ();
2427
2428   if (cmd == NULL)
2429     return NULL;
2430
2431   cmdrest = cmd;
2432
2433   if (*cmdrest == ',')
2434     ++cmdrest;
2435   cmdrest = skip_spaces_const (cmdrest);
2436
2437   if (*cmdrest++ != '"')
2438     error (_("No format string following the location"));
2439
2440   format_start = cmdrest;
2441
2442   fpieces = parse_format_string (&cmdrest);
2443
2444   old_cleanups = make_cleanup (free_format_pieces_cleanup, &fpieces);
2445
2446   format_end = cmdrest;
2447
2448   if (*cmdrest++ != '"')
2449     error (_("Bad format string, non-terminated '\"'."));
2450   
2451   cmdrest = skip_spaces_const (cmdrest);
2452
2453   if (!(*cmdrest == ',' || *cmdrest == '\0'))
2454     error (_("Invalid argument syntax"));
2455
2456   if (*cmdrest == ',')
2457     cmdrest++;
2458   cmdrest = skip_spaces_const (cmdrest);
2459
2460   /* For each argument, make an expression.  */
2461
2462   argvec = (struct expression **) alloca (strlen (cmd)
2463                                          * sizeof (struct expression *));
2464
2465   nargs = 0;
2466   while (*cmdrest != '\0')
2467     {
2468       const char *cmd1;
2469
2470       cmd1 = cmdrest;
2471       expression_up expr = parse_exp_1 (&cmd1, scope, block_for_pc (scope), 1);
2472       argvec[nargs++] = expr.release ();
2473       cmdrest = cmd1;
2474       if (*cmdrest == ',')
2475         ++cmdrest;
2476     }
2477
2478   agent_expr_up aexpr;
2479
2480   /* We don't want to stop processing, so catch any errors
2481      that may show up.  */
2482   TRY
2483     {
2484       aexpr = gen_printf (scope, gdbarch, 0, 0,
2485                           format_start, format_end - format_start,
2486                           fpieces, nargs, argvec);
2487     }
2488   CATCH (ex, RETURN_MASK_ERROR)
2489     {
2490       /* If we got here, it means the command could not be parsed to a valid
2491          bytecode expression and thus can't be evaluated on the target's side.
2492          It's no use iterating through the other commands.  */
2493     }
2494   END_CATCH
2495
2496   do_cleanups (old_cleanups);
2497
2498   /* We have a valid agent expression, return it.  */
2499   return aexpr;
2500 }
2501
2502 /* Based on location BL, create a list of breakpoint commands to be
2503    passed on to the target.  If we have duplicated locations with
2504    different commands, we will add any such to the list.  */
2505
2506 static void
2507 build_target_command_list (struct bp_location *bl)
2508 {
2509   struct bp_location **locp = NULL, **loc2p;
2510   int null_command_or_parse_error = 0;
2511   int modified = bl->needs_update;
2512   struct bp_location *loc;
2513
2514   /* Clear commands left over from a previous insert.  */
2515   bl->target_info.tcommands.clear ();
2516
2517   if (!target_can_run_breakpoint_commands ())
2518     return;
2519
2520   /* For now, limit to agent-style dprintf breakpoints.  */
2521   if (dprintf_style != dprintf_style_agent)
2522     return;
2523
2524   /* For now, if we have any duplicate location that isn't a dprintf,
2525      don't install the target-side commands, as that would make the
2526      breakpoint not be reported to the core, and we'd lose
2527      control.  */
2528   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2529     {
2530       loc = (*loc2p);
2531       if (is_breakpoint (loc->owner)
2532           && loc->pspace->num == bl->pspace->num
2533           && loc->owner->type != bp_dprintf)
2534         return;
2535     }
2536
2537   /* Do a first pass to check for locations with no assigned
2538      conditions or conditions that fail to parse to a valid agent expression
2539      bytecode.  If any of these happen, then it's no use to send conditions
2540      to the target since this location will always trigger and generate a
2541      response back to GDB.  */
2542   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2543     {
2544       loc = (*loc2p);
2545       if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2546         {
2547           if (modified)
2548             {
2549               /* Re-parse the commands since something changed.  In that
2550                  case we already freed the command bytecodes (see
2551                  force_breakpoint_reinsertion).  We just
2552                  need to parse the command to bytecodes again.  */
2553               loc->cmd_bytecode
2554                 = parse_cmd_to_aexpr (bl->address,
2555                                       loc->owner->extra_string);
2556             }
2557
2558           /* If we have a NULL bytecode expression, it means something
2559              went wrong or we have a null command expression.  */
2560           if (!loc->cmd_bytecode)
2561             {
2562               null_command_or_parse_error = 1;
2563               break;
2564             }
2565         }
2566     }
2567
2568   /* If anything failed, then we're not doing target-side commands,
2569      and so clean up.  */
2570   if (null_command_or_parse_error)
2571     {
2572       ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2573         {
2574           loc = (*loc2p);
2575           if (is_breakpoint (loc->owner)
2576               && loc->pspace->num == bl->pspace->num)
2577             {
2578               /* Only go as far as the first NULL bytecode is
2579                  located.  */
2580               if (loc->cmd_bytecode == NULL)
2581                 return;
2582
2583               loc->cmd_bytecode.reset ();
2584             }
2585         }
2586     }
2587
2588   /* No NULL commands or failed bytecode generation.  Build a command list
2589      for this location's address.  */
2590   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2591     {
2592       loc = (*loc2p);
2593       if (loc->owner->extra_string
2594           && is_breakpoint (loc->owner)
2595           && loc->pspace->num == bl->pspace->num
2596           && loc->owner->enable_state == bp_enabled
2597           && loc->enabled)
2598         {
2599           /* Add the command to the vector.  This will be used later
2600              to send the commands to the target.  */
2601           bl->target_info.tcommands.push_back (loc->cmd_bytecode.get ());
2602         }
2603     }
2604
2605   bl->target_info.persist = 0;
2606   /* Maybe flag this location as persistent.  */
2607   if (bl->owner->type == bp_dprintf && disconnected_dprintf)
2608     bl->target_info.persist = 1;
2609 }
2610
2611 /* Return the kind of breakpoint on address *ADDR.  Get the kind
2612    of breakpoint according to ADDR except single-step breakpoint.
2613    Get the kind of single-step breakpoint according to the current
2614    registers state.  */
2615
2616 static int
2617 breakpoint_kind (struct bp_location *bl, CORE_ADDR *addr)
2618 {
2619   if (bl->owner->type == bp_single_step)
2620     {
2621       struct thread_info *thr = find_thread_global_id (bl->owner->thread);
2622       struct regcache *regcache;
2623
2624       regcache = get_thread_regcache (thr->ptid);
2625
2626       return gdbarch_breakpoint_kind_from_current_state (bl->gdbarch,
2627                                                          regcache, addr);
2628     }
2629   else
2630     return gdbarch_breakpoint_kind_from_pc (bl->gdbarch, addr);
2631 }
2632
2633 /* Insert a low-level "breakpoint" of some type.  BL is the breakpoint
2634    location.  Any error messages are printed to TMP_ERROR_STREAM; and
2635    DISABLED_BREAKS, and HW_BREAKPOINT_ERROR are used to report problems.
2636    Returns 0 for success, 1 if the bp_location type is not supported or
2637    -1 for failure.
2638
2639    NOTE drow/2003-09-09: This routine could be broken down to an
2640    object-style method for each breakpoint or catchpoint type.  */
2641 static int
2642 insert_bp_location (struct bp_location *bl,
2643                     struct ui_file *tmp_error_stream,
2644                     int *disabled_breaks,
2645                     int *hw_breakpoint_error,
2646                     int *hw_bp_error_explained_already)
2647 {
2648   enum errors bp_err = GDB_NO_ERROR;
2649   const char *bp_err_message = NULL;
2650
2651   if (!should_be_inserted (bl) || (bl->inserted && !bl->needs_update))
2652     return 0;
2653
2654   /* Note we don't initialize bl->target_info, as that wipes out
2655      the breakpoint location's shadow_contents if the breakpoint
2656      is still inserted at that location.  This in turn breaks
2657      target_read_memory which depends on these buffers when
2658      a memory read is requested at the breakpoint location:
2659      Once the target_info has been wiped, we fail to see that
2660      we have a breakpoint inserted at that address and thus
2661      read the breakpoint instead of returning the data saved in
2662      the breakpoint location's shadow contents.  */
2663   bl->target_info.reqstd_address = bl->address;
2664   bl->target_info.placed_address_space = bl->pspace->aspace;
2665   bl->target_info.length = bl->length;
2666
2667   /* When working with target-side conditions, we must pass all the conditions
2668      for the same breakpoint address down to the target since GDB will not
2669      insert those locations.  With a list of breakpoint conditions, the target
2670      can decide when to stop and notify GDB.  */
2671
2672   if (is_breakpoint (bl->owner))
2673     {
2674       build_target_condition_list (bl);
2675       build_target_command_list (bl);
2676       /* Reset the modification marker.  */
2677       bl->needs_update = 0;
2678     }
2679
2680   if (bl->loc_type == bp_loc_software_breakpoint
2681       || bl->loc_type == bp_loc_hardware_breakpoint)
2682     {
2683       if (bl->owner->type != bp_hardware_breakpoint)
2684         {
2685           /* If the explicitly specified breakpoint type
2686              is not hardware breakpoint, check the memory map to see
2687              if the breakpoint address is in read only memory or not.
2688
2689              Two important cases are:
2690              - location type is not hardware breakpoint, memory
2691              is readonly.  We change the type of the location to
2692              hardware breakpoint.
2693              - location type is hardware breakpoint, memory is
2694              read-write.  This means we've previously made the
2695              location hardware one, but then the memory map changed,
2696              so we undo.
2697              
2698              When breakpoints are removed, remove_breakpoints will use
2699              location types we've just set here, the only possible
2700              problem is that memory map has changed during running
2701              program, but it's not going to work anyway with current
2702              gdb.  */
2703           struct mem_region *mr 
2704             = lookup_mem_region (bl->target_info.reqstd_address);
2705           
2706           if (mr)
2707             {
2708               if (automatic_hardware_breakpoints)
2709                 {
2710                   enum bp_loc_type new_type;
2711                   
2712                   if (mr->attrib.mode != MEM_RW)
2713                     new_type = bp_loc_hardware_breakpoint;
2714                   else 
2715                     new_type = bp_loc_software_breakpoint;
2716                   
2717                   if (new_type != bl->loc_type)
2718                     {
2719                       static int said = 0;
2720
2721                       bl->loc_type = new_type;
2722                       if (!said)
2723                         {
2724                           fprintf_filtered (gdb_stdout,
2725                                             _("Note: automatically using "
2726                                               "hardware breakpoints for "
2727                                               "read-only addresses.\n"));
2728                           said = 1;
2729                         }
2730                     }
2731                 }
2732               else if (bl->loc_type == bp_loc_software_breakpoint
2733                        && mr->attrib.mode != MEM_RW)
2734                 {
2735                   fprintf_unfiltered (tmp_error_stream,
2736                                       _("Cannot insert breakpoint %d.\n"
2737                                         "Cannot set software breakpoint "
2738                                         "at read-only address %s\n"),
2739                                       bl->owner->number,
2740                                       paddress (bl->gdbarch, bl->address));
2741                   return 1;
2742                 }
2743             }
2744         }
2745         
2746       /* First check to see if we have to handle an overlay.  */
2747       if (overlay_debugging == ovly_off
2748           || bl->section == NULL
2749           || !(section_is_overlay (bl->section)))
2750         {
2751           /* No overlay handling: just set the breakpoint.  */
2752           TRY
2753             {
2754               int val;
2755
2756               val = bl->owner->ops->insert_location (bl);
2757               if (val)
2758                 bp_err = GENERIC_ERROR;
2759             }
2760           CATCH (e, RETURN_MASK_ALL)
2761             {
2762               bp_err = e.error;
2763               bp_err_message = e.message;
2764             }
2765           END_CATCH
2766         }
2767       else
2768         {
2769           /* This breakpoint is in an overlay section.
2770              Shall we set a breakpoint at the LMA?  */
2771           if (!overlay_events_enabled)
2772             {
2773               /* Yes -- overlay event support is not active, 
2774                  so we must try to set a breakpoint at the LMA.
2775                  This will not work for a hardware breakpoint.  */
2776               if (bl->loc_type == bp_loc_hardware_breakpoint)
2777                 warning (_("hardware breakpoint %d not supported in overlay!"),
2778                          bl->owner->number);
2779               else
2780                 {
2781                   CORE_ADDR addr = overlay_unmapped_address (bl->address,
2782                                                              bl->section);
2783                   /* Set a software (trap) breakpoint at the LMA.  */
2784                   bl->overlay_target_info = bl->target_info;
2785                   bl->overlay_target_info.reqstd_address = addr;
2786
2787                   /* No overlay handling: just set the breakpoint.  */
2788                   TRY
2789                     {
2790                       int val;
2791
2792                       bl->overlay_target_info.kind
2793                         = breakpoint_kind (bl, &addr);
2794                       bl->overlay_target_info.placed_address = addr;
2795                       val = target_insert_breakpoint (bl->gdbarch,
2796                                                       &bl->overlay_target_info);
2797                       if (val)
2798                         bp_err = GENERIC_ERROR;
2799                     }
2800                   CATCH (e, RETURN_MASK_ALL)
2801                     {
2802                       bp_err = e.error;
2803                       bp_err_message = e.message;
2804                     }
2805                   END_CATCH
2806
2807                   if (bp_err != GDB_NO_ERROR)
2808                     fprintf_unfiltered (tmp_error_stream,
2809                                         "Overlay breakpoint %d "
2810                                         "failed: in ROM?\n",
2811                                         bl->owner->number);
2812                 }
2813             }
2814           /* Shall we set a breakpoint at the VMA? */
2815           if (section_is_mapped (bl->section))
2816             {
2817               /* Yes.  This overlay section is mapped into memory.  */
2818               TRY
2819                 {
2820                   int val;
2821
2822                   val = bl->owner->ops->insert_location (bl);
2823                   if (val)
2824                     bp_err = GENERIC_ERROR;
2825                 }
2826               CATCH (e, RETURN_MASK_ALL)
2827                 {
2828                   bp_err = e.error;
2829                   bp_err_message = e.message;
2830                 }
2831               END_CATCH
2832             }
2833           else
2834             {
2835               /* No.  This breakpoint will not be inserted.  
2836                  No error, but do not mark the bp as 'inserted'.  */
2837               return 0;
2838             }
2839         }
2840
2841       if (bp_err != GDB_NO_ERROR)
2842         {
2843           /* Can't set the breakpoint.  */
2844
2845           /* In some cases, we might not be able to insert a
2846              breakpoint in a shared library that has already been
2847              removed, but we have not yet processed the shlib unload
2848              event.  Unfortunately, some targets that implement
2849              breakpoint insertion themselves can't tell why the
2850              breakpoint insertion failed (e.g., the remote target
2851              doesn't define error codes), so we must treat generic
2852              errors as memory errors.  */
2853           if ((bp_err == GENERIC_ERROR || bp_err == MEMORY_ERROR)
2854               && bl->loc_type == bp_loc_software_breakpoint
2855               && (solib_name_from_address (bl->pspace, bl->address)
2856                   || shared_objfile_contains_address_p (bl->pspace,
2857                                                         bl->address)))
2858             {
2859               /* See also: disable_breakpoints_in_shlibs.  */
2860               bl->shlib_disabled = 1;
2861               observer_notify_breakpoint_modified (bl->owner);
2862               if (!*disabled_breaks)
2863                 {
2864                   fprintf_unfiltered (tmp_error_stream, 
2865                                       "Cannot insert breakpoint %d.\n", 
2866                                       bl->owner->number);
2867                   fprintf_unfiltered (tmp_error_stream, 
2868                                       "Temporarily disabling shared "
2869                                       "library breakpoints:\n");
2870                 }
2871               *disabled_breaks = 1;
2872               fprintf_unfiltered (tmp_error_stream,
2873                                   "breakpoint #%d\n", bl->owner->number);
2874               return 0;
2875             }
2876           else
2877             {
2878               if (bl->loc_type == bp_loc_hardware_breakpoint)
2879                 {
2880                   *hw_breakpoint_error = 1;
2881                   *hw_bp_error_explained_already = bp_err_message != NULL;
2882                   fprintf_unfiltered (tmp_error_stream,
2883                                       "Cannot insert hardware breakpoint %d%s",
2884                                       bl->owner->number, bp_err_message ? ":" : ".\n");
2885                   if (bp_err_message != NULL)
2886                     fprintf_unfiltered (tmp_error_stream, "%s.\n", bp_err_message);
2887                 }
2888               else
2889                 {
2890                   if (bp_err_message == NULL)
2891                     {
2892                       char *message
2893                         = memory_error_message (TARGET_XFER_E_IO,
2894                                                 bl->gdbarch, bl->address);
2895                       struct cleanup *old_chain = make_cleanup (xfree, message);
2896
2897                       fprintf_unfiltered (tmp_error_stream,
2898                                           "Cannot insert breakpoint %d.\n"
2899                                           "%s\n",
2900                                           bl->owner->number, message);
2901                       do_cleanups (old_chain);
2902                     }
2903                   else
2904                     {
2905                       fprintf_unfiltered (tmp_error_stream,
2906                                           "Cannot insert breakpoint %d: %s\n",
2907                                           bl->owner->number,
2908                                           bp_err_message);
2909                     }
2910                 }
2911               return 1;
2912
2913             }
2914         }
2915       else
2916         bl->inserted = 1;
2917
2918       return 0;
2919     }
2920
2921   else if (bl->loc_type == bp_loc_hardware_watchpoint
2922            /* NOTE drow/2003-09-08: This state only exists for removing
2923               watchpoints.  It's not clear that it's necessary...  */
2924            && bl->owner->disposition != disp_del_at_next_stop)
2925     {
2926       int val;
2927
2928       gdb_assert (bl->owner->ops != NULL
2929                   && bl->owner->ops->insert_location != NULL);
2930
2931       val = bl->owner->ops->insert_location (bl);
2932
2933       /* If trying to set a read-watchpoint, and it turns out it's not
2934          supported, try emulating one with an access watchpoint.  */
2935       if (val == 1 && bl->watchpoint_type == hw_read)
2936         {
2937           struct bp_location *loc, **loc_temp;
2938
2939           /* But don't try to insert it, if there's already another
2940              hw_access location that would be considered a duplicate
2941              of this one.  */
2942           ALL_BP_LOCATIONS (loc, loc_temp)
2943             if (loc != bl
2944                 && loc->watchpoint_type == hw_access
2945                 && watchpoint_locations_match (bl, loc))
2946               {
2947                 bl->duplicate = 1;
2948                 bl->inserted = 1;
2949                 bl->target_info = loc->target_info;
2950                 bl->watchpoint_type = hw_access;
2951                 val = 0;
2952                 break;
2953               }
2954
2955           if (val == 1)
2956             {
2957               bl->watchpoint_type = hw_access;
2958               val = bl->owner->ops->insert_location (bl);
2959
2960               if (val)
2961                 /* Back to the original value.  */
2962                 bl->watchpoint_type = hw_read;
2963             }
2964         }
2965
2966       bl->inserted = (val == 0);
2967     }
2968
2969   else if (bl->owner->type == bp_catchpoint)
2970     {
2971       int val;
2972
2973       gdb_assert (bl->owner->ops != NULL
2974                   && bl->owner->ops->insert_location != NULL);
2975
2976       val = bl->owner->ops->insert_location (bl);
2977       if (val)
2978         {
2979           bl->owner->enable_state = bp_disabled;
2980
2981           if (val == 1)
2982             warning (_("\
2983 Error inserting catchpoint %d: Your system does not support this type\n\
2984 of catchpoint."), bl->owner->number);
2985           else
2986             warning (_("Error inserting catchpoint %d."), bl->owner->number);
2987         }
2988
2989       bl->inserted = (val == 0);
2990
2991       /* We've already printed an error message if there was a problem
2992          inserting this catchpoint, and we've disabled the catchpoint,
2993          so just return success.  */
2994       return 0;
2995     }
2996
2997   return 0;
2998 }
2999
3000 /* This function is called when program space PSPACE is about to be
3001    deleted.  It takes care of updating breakpoints to not reference
3002    PSPACE anymore.  */
3003
3004 void
3005 breakpoint_program_space_exit (struct program_space *pspace)
3006 {
3007   struct breakpoint *b, *b_temp;
3008   struct bp_location *loc, **loc_temp;
3009
3010   /* Remove any breakpoint that was set through this program space.  */
3011   ALL_BREAKPOINTS_SAFE (b, b_temp)
3012     {
3013       if (b->pspace == pspace)
3014         delete_breakpoint (b);
3015     }
3016
3017   /* Breakpoints set through other program spaces could have locations
3018      bound to PSPACE as well.  Remove those.  */
3019   ALL_BP_LOCATIONS (loc, loc_temp)
3020     {
3021       struct bp_location *tmp;
3022
3023       if (loc->pspace == pspace)
3024         {
3025           /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
3026           if (loc->owner->loc == loc)
3027             loc->owner->loc = loc->next;
3028           else
3029             for (tmp = loc->owner->loc; tmp->next != NULL; tmp = tmp->next)
3030               if (tmp->next == loc)
3031                 {
3032                   tmp->next = loc->next;
3033                   break;
3034                 }
3035         }
3036     }
3037
3038   /* Now update the global location list to permanently delete the
3039      removed locations above.  */
3040   update_global_location_list (UGLL_DONT_INSERT);
3041 }
3042
3043 /* Make sure all breakpoints are inserted in inferior.
3044    Throws exception on any error.
3045    A breakpoint that is already inserted won't be inserted
3046    again, so calling this function twice is safe.  */
3047 void
3048 insert_breakpoints (void)
3049 {
3050   struct breakpoint *bpt;
3051
3052   ALL_BREAKPOINTS (bpt)
3053     if (is_hardware_watchpoint (bpt))
3054       {
3055         struct watchpoint *w = (struct watchpoint *) bpt;
3056
3057         update_watchpoint (w, 0 /* don't reparse.  */);
3058       }
3059
3060   /* Updating watchpoints creates new locations, so update the global
3061      location list.  Explicitly tell ugll to insert locations and
3062      ignore breakpoints_always_inserted_mode.  */
3063   update_global_location_list (UGLL_INSERT);
3064 }
3065
3066 /* Invoke CALLBACK for each of bp_location.  */
3067
3068 void
3069 iterate_over_bp_locations (walk_bp_location_callback callback)
3070 {
3071   struct bp_location *loc, **loc_tmp;
3072
3073   ALL_BP_LOCATIONS (loc, loc_tmp)
3074     {
3075       callback (loc, NULL);
3076     }
3077 }
3078
3079 /* This is used when we need to synch breakpoint conditions between GDB and the
3080    target.  It is the case with deleting and disabling of breakpoints when using
3081    always-inserted mode.  */
3082
3083 static void
3084 update_inserted_breakpoint_locations (void)
3085 {
3086   struct bp_location *bl, **blp_tmp;
3087   int error_flag = 0;
3088   int val = 0;
3089   int disabled_breaks = 0;
3090   int hw_breakpoint_error = 0;
3091   int hw_bp_details_reported = 0;
3092
3093   string_file tmp_error_stream;
3094
3095   /* Explicitly mark the warning -- this will only be printed if
3096      there was an error.  */
3097   tmp_error_stream.puts ("Warning:\n");
3098
3099   scoped_restore_current_pspace_and_thread restore_pspace_thread;
3100
3101   ALL_BP_LOCATIONS (bl, blp_tmp)
3102     {
3103       /* We only want to update software breakpoints and hardware
3104          breakpoints.  */
3105       if (!is_breakpoint (bl->owner))
3106         continue;
3107
3108       /* We only want to update locations that are already inserted
3109          and need updating.  This is to avoid unwanted insertion during
3110          deletion of breakpoints.  */
3111       if (!bl->inserted || (bl->inserted && !bl->needs_update))
3112         continue;
3113
3114       switch_to_program_space_and_thread (bl->pspace);
3115
3116       /* For targets that support global breakpoints, there's no need
3117          to select an inferior to insert breakpoint to.  In fact, even
3118          if we aren't attached to any process yet, we should still
3119          insert breakpoints.  */
3120       if (!gdbarch_has_global_breakpoints (target_gdbarch ())
3121           && ptid_equal (inferior_ptid, null_ptid))
3122         continue;
3123
3124       val = insert_bp_location (bl, &tmp_error_stream, &disabled_breaks,
3125                                     &hw_breakpoint_error, &hw_bp_details_reported);
3126       if (val)
3127         error_flag = val;
3128     }
3129
3130   if (error_flag)
3131     {
3132       target_terminal_ours_for_output ();
3133       error_stream (tmp_error_stream);
3134     }
3135 }
3136
3137 /* Used when starting or continuing the program.  */
3138
3139 static void
3140 insert_breakpoint_locations (void)
3141 {
3142   struct breakpoint *bpt;
3143   struct bp_location *bl, **blp_tmp;
3144   int error_flag = 0;
3145   int val = 0;
3146   int disabled_breaks = 0;
3147   int hw_breakpoint_error = 0;
3148   int hw_bp_error_explained_already = 0;
3149
3150   string_file tmp_error_stream;
3151
3152   /* Explicitly mark the warning -- this will only be printed if
3153      there was an error.  */
3154   tmp_error_stream.puts ("Warning:\n");
3155
3156   scoped_restore_current_pspace_and_thread restore_pspace_thread;
3157
3158   ALL_BP_LOCATIONS (bl, blp_tmp)
3159     {
3160       if (!should_be_inserted (bl) || (bl->inserted && !bl->needs_update))
3161         continue;
3162
3163       /* There is no point inserting thread-specific breakpoints if
3164          the thread no longer exists.  ALL_BP_LOCATIONS bp_location
3165          has BL->OWNER always non-NULL.  */
3166       if (bl->owner->thread != -1
3167           && !valid_global_thread_id (bl->owner->thread))
3168         continue;
3169
3170       switch_to_program_space_and_thread (bl->pspace);
3171
3172       /* For targets that support global breakpoints, there's no need
3173          to select an inferior to insert breakpoint to.  In fact, even
3174          if we aren't attached to any process yet, we should still
3175          insert breakpoints.  */
3176       if (!gdbarch_has_global_breakpoints (target_gdbarch ())
3177           && ptid_equal (inferior_ptid, null_ptid))
3178         continue;
3179
3180       val = insert_bp_location (bl, &tmp_error_stream, &disabled_breaks,
3181                                     &hw_breakpoint_error, &hw_bp_error_explained_already);
3182       if (val)
3183         error_flag = val;
3184     }
3185
3186   /* If we failed to insert all locations of a watchpoint, remove
3187      them, as half-inserted watchpoint is of limited use.  */
3188   ALL_BREAKPOINTS (bpt)  
3189     {
3190       int some_failed = 0;
3191       struct bp_location *loc;
3192
3193       if (!is_hardware_watchpoint (bpt))
3194         continue;
3195
3196       if (!breakpoint_enabled (bpt))
3197         continue;
3198
3199       if (bpt->disposition == disp_del_at_next_stop)
3200         continue;
3201       
3202       for (loc = bpt->loc; loc; loc = loc->next)
3203         if (!loc->inserted && should_be_inserted (loc))
3204           {
3205             some_failed = 1;
3206             break;
3207           }
3208       if (some_failed)
3209         {
3210           for (loc = bpt->loc; loc; loc = loc->next)
3211             if (loc->inserted)
3212               remove_breakpoint (loc);
3213
3214           hw_breakpoint_error = 1;
3215           tmp_error_stream.printf ("Could not insert "
3216                                    "hardware watchpoint %d.\n",
3217                                    bpt->number);
3218           error_flag = -1;
3219         }
3220     }
3221
3222   if (error_flag)
3223     {
3224       /* If a hardware breakpoint or watchpoint was inserted, add a
3225          message about possibly exhausted resources.  */
3226       if (hw_breakpoint_error && !hw_bp_error_explained_already)
3227         {
3228           tmp_error_stream.printf ("Could not insert hardware breakpoints:\n\
3229 You may have requested too many hardware breakpoints/watchpoints.\n");
3230         }
3231       target_terminal_ours_for_output ();
3232       error_stream (tmp_error_stream);
3233     }
3234 }
3235
3236 /* Used when the program stops.
3237    Returns zero if successful, or non-zero if there was a problem
3238    removing a breakpoint location.  */
3239
3240 int
3241 remove_breakpoints (void)
3242 {
3243   struct bp_location *bl, **blp_tmp;
3244   int val = 0;
3245
3246   ALL_BP_LOCATIONS (bl, blp_tmp)
3247   {
3248     if (bl->inserted && !is_tracepoint (bl->owner))
3249       val |= remove_breakpoint (bl);
3250   }
3251   return val;
3252 }
3253
3254 /* When a thread exits, remove breakpoints that are related to
3255    that thread.  */
3256
3257 static void
3258 remove_threaded_breakpoints (struct thread_info *tp, int silent)
3259 {
3260   struct breakpoint *b, *b_tmp;
3261
3262   ALL_BREAKPOINTS_SAFE (b, b_tmp)
3263     {
3264       if (b->thread == tp->global_num && user_breakpoint_p (b))
3265         {
3266           b->disposition = disp_del_at_next_stop;
3267
3268           printf_filtered (_("\
3269 Thread-specific breakpoint %d deleted - thread %s no longer in the thread list.\n"),
3270                            b->number, print_thread_id (tp));
3271
3272           /* Hide it from the user.  */
3273           b->number = 0;
3274        }
3275     }
3276 }
3277
3278 /* Remove breakpoints of process PID.  */
3279
3280 int
3281 remove_breakpoints_pid (int pid)
3282 {
3283   struct bp_location *bl, **blp_tmp;
3284   int val;
3285   struct inferior *inf = find_inferior_pid (pid);
3286
3287   ALL_BP_LOCATIONS (bl, blp_tmp)
3288   {
3289     if (bl->pspace != inf->pspace)
3290       continue;
3291
3292     if (bl->inserted && !bl->target_info.persist)
3293       {
3294         val = remove_breakpoint (bl);
3295         if (val != 0)
3296           return val;
3297       }
3298   }
3299   return 0;
3300 }
3301
3302 int
3303 reattach_breakpoints (int pid)
3304 {
3305   struct cleanup *old_chain;
3306   struct bp_location *bl, **blp_tmp;
3307   int val;
3308   int dummy1 = 0, dummy2 = 0, dummy3 = 0;
3309   struct inferior *inf;
3310   struct thread_info *tp;
3311
3312   tp = any_live_thread_of_process (pid);
3313   if (tp == NULL)
3314     return 1;
3315
3316   inf = find_inferior_pid (pid);
3317   old_chain = save_inferior_ptid ();
3318
3319   inferior_ptid = tp->ptid;
3320
3321   string_file tmp_error_stream;
3322
3323   ALL_BP_LOCATIONS (bl, blp_tmp)
3324   {
3325     if (bl->pspace != inf->pspace)
3326       continue;
3327
3328     if (bl->inserted)
3329       {
3330         bl->inserted = 0;
3331         val = insert_bp_location (bl, &tmp_error_stream, &dummy1, &dummy2, &dummy3);
3332         if (val != 0)
3333           {
3334             do_cleanups (old_chain);
3335             return val;
3336           }
3337       }
3338   }
3339   do_cleanups (old_chain);
3340   return 0;
3341 }
3342
3343 static int internal_breakpoint_number = -1;
3344
3345 /* Set the breakpoint number of B, depending on the value of INTERNAL.
3346    If INTERNAL is non-zero, the breakpoint number will be populated
3347    from internal_breakpoint_number and that variable decremented.
3348    Otherwise the breakpoint number will be populated from
3349    breakpoint_count and that value incremented.  Internal breakpoints
3350    do not set the internal var bpnum.  */
3351 static void
3352 set_breakpoint_number (int internal, struct breakpoint *b)
3353 {
3354   if (internal)
3355     b->number = internal_breakpoint_number--;
3356   else
3357     {
3358       set_breakpoint_count (breakpoint_count + 1);
3359       b->number = breakpoint_count;
3360     }
3361 }
3362
3363 static struct breakpoint *
3364 create_internal_breakpoint (struct gdbarch *gdbarch,
3365                             CORE_ADDR address, enum bptype type,
3366                             const struct breakpoint_ops *ops)
3367 {
3368   struct symtab_and_line sal;
3369   struct breakpoint *b;
3370
3371   init_sal (&sal);              /* Initialize to zeroes.  */
3372
3373   sal.pc = address;
3374   sal.section = find_pc_overlay (sal.pc);
3375   sal.pspace = current_program_space;
3376
3377   b = set_raw_breakpoint (gdbarch, sal, type, ops);
3378   b->number = internal_breakpoint_number--;
3379   b->disposition = disp_donttouch;
3380
3381   return b;
3382 }
3383
3384 static const char *const longjmp_names[] =
3385   {
3386     "longjmp", "_longjmp", "siglongjmp", "_siglongjmp"
3387   };
3388 #define NUM_LONGJMP_NAMES ARRAY_SIZE(longjmp_names)
3389
3390 /* Per-objfile data private to breakpoint.c.  */
3391 struct breakpoint_objfile_data
3392 {
3393   /* Minimal symbol for "_ovly_debug_event" (if any).  */
3394   struct bound_minimal_symbol overlay_msym;
3395
3396   /* Minimal symbol(s) for "longjmp", "siglongjmp", etc. (if any).  */
3397   struct bound_minimal_symbol longjmp_msym[NUM_LONGJMP_NAMES];
3398
3399   /* True if we have looked for longjmp probes.  */
3400   int longjmp_searched;
3401
3402   /* SystemTap probe points for longjmp (if any).  */
3403   VEC (probe_p) *longjmp_probes;
3404
3405   /* Minimal symbol for "std::terminate()" (if any).  */
3406   struct bound_minimal_symbol terminate_msym;
3407
3408   /* Minimal symbol for "_Unwind_DebugHook" (if any).  */
3409   struct bound_minimal_symbol exception_msym;
3410
3411   /* True if we have looked for exception probes.  */
3412   int exception_searched;
3413
3414   /* SystemTap probe points for unwinding (if any).  */
3415   VEC (probe_p) *exception_probes;
3416 };
3417
3418 static const struct objfile_data *breakpoint_objfile_key;
3419
3420 /* Minimal symbol not found sentinel.  */
3421 static struct minimal_symbol msym_not_found;
3422
3423 /* Returns TRUE if MSYM point to the "not found" sentinel.  */
3424
3425 static int
3426 msym_not_found_p (const struct minimal_symbol *msym)
3427 {
3428   return msym == &msym_not_found;
3429 }
3430
3431 /* Return per-objfile data needed by breakpoint.c.
3432    Allocate the data if necessary.  */
3433
3434 static struct breakpoint_objfile_data *
3435 get_breakpoint_objfile_data (struct objfile *objfile)
3436 {
3437   struct breakpoint_objfile_data *bp_objfile_data;
3438
3439   bp_objfile_data = ((struct breakpoint_objfile_data *)
3440                      objfile_data (objfile, breakpoint_objfile_key));
3441   if (bp_objfile_data == NULL)
3442     {
3443       bp_objfile_data =
3444         XOBNEW (&objfile->objfile_obstack, struct breakpoint_objfile_data);
3445
3446       memset (bp_objfile_data, 0, sizeof (*bp_objfile_data));
3447       set_objfile_data (objfile, breakpoint_objfile_key, bp_objfile_data);
3448     }
3449   return bp_objfile_data;
3450 }
3451
3452 static void
3453 free_breakpoint_probes (struct objfile *obj, void *data)
3454 {
3455   struct breakpoint_objfile_data *bp_objfile_data
3456     = (struct breakpoint_objfile_data *) data;
3457
3458   VEC_free (probe_p, bp_objfile_data->longjmp_probes);
3459   VEC_free (probe_p, bp_objfile_data->exception_probes);
3460 }
3461
3462 static void
3463 create_overlay_event_breakpoint (void)
3464 {
3465   struct objfile *objfile;
3466   const char *const func_name = "_ovly_debug_event";
3467
3468   ALL_OBJFILES (objfile)
3469     {
3470       struct breakpoint *b;
3471       struct breakpoint_objfile_data *bp_objfile_data;
3472       CORE_ADDR addr;
3473       struct explicit_location explicit_loc;
3474
3475       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3476
3477       if (msym_not_found_p (bp_objfile_data->overlay_msym.minsym))
3478         continue;
3479
3480       if (bp_objfile_data->overlay_msym.minsym == NULL)
3481         {
3482           struct bound_minimal_symbol m;
3483
3484           m = lookup_minimal_symbol_text (func_name, objfile);
3485           if (m.minsym == NULL)
3486             {
3487               /* Avoid future lookups in this objfile.  */
3488               bp_objfile_data->overlay_msym.minsym = &msym_not_found;
3489               continue;
3490             }
3491           bp_objfile_data->overlay_msym = m;
3492         }
3493
3494       addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->overlay_msym);
3495       b = create_internal_breakpoint (get_objfile_arch (objfile), addr,
3496                                       bp_overlay_event,
3497                                       &internal_breakpoint_ops);
3498       initialize_explicit_location (&explicit_loc);
3499       explicit_loc.function_name = ASTRDUP (func_name);
3500       b->location = new_explicit_location (&explicit_loc);
3501
3502       if (overlay_debugging == ovly_auto)
3503         {
3504           b->enable_state = bp_enabled;
3505           overlay_events_enabled = 1;
3506         }
3507       else
3508        {
3509          b->enable_state = bp_disabled;
3510          overlay_events_enabled = 0;
3511        }
3512     }
3513 }
3514
3515 static void
3516 create_longjmp_master_breakpoint (void)
3517 {
3518   struct program_space *pspace;
3519
3520   scoped_restore_current_program_space restore_pspace;
3521
3522   ALL_PSPACES (pspace)
3523   {
3524     struct objfile *objfile;
3525
3526     set_current_program_space (pspace);
3527
3528     ALL_OBJFILES (objfile)
3529     {
3530       int i;
3531       struct gdbarch *gdbarch;
3532       struct breakpoint_objfile_data *bp_objfile_data;
3533
3534       gdbarch = get_objfile_arch (objfile);
3535
3536       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3537
3538       if (!bp_objfile_data->longjmp_searched)
3539         {
3540           VEC (probe_p) *ret;
3541
3542           ret = find_probes_in_objfile (objfile, "libc", "longjmp");
3543           if (ret != NULL)
3544             {
3545               /* We are only interested in checking one element.  */
3546               struct probe *p = VEC_index (probe_p, ret, 0);
3547
3548               if (!can_evaluate_probe_arguments (p))
3549                 {
3550                   /* We cannot use the probe interface here, because it does
3551                      not know how to evaluate arguments.  */
3552                   VEC_free (probe_p, ret);
3553                   ret = NULL;
3554                 }
3555             }
3556           bp_objfile_data->longjmp_probes = ret;
3557           bp_objfile_data->longjmp_searched = 1;
3558         }
3559
3560       if (bp_objfile_data->longjmp_probes != NULL)
3561         {
3562           int i;
3563           struct probe *probe;
3564           struct gdbarch *gdbarch = get_objfile_arch (objfile);
3565
3566           for (i = 0;
3567                VEC_iterate (probe_p,
3568                             bp_objfile_data->longjmp_probes,
3569                             i, probe);
3570                ++i)
3571             {
3572               struct breakpoint *b;
3573
3574               b = create_internal_breakpoint (gdbarch,
3575                                               get_probe_address (probe,
3576                                                                  objfile),
3577                                               bp_longjmp_master,
3578                                               &internal_breakpoint_ops);
3579               b->location = new_probe_location ("-probe-stap libc:longjmp");
3580               b->enable_state = bp_disabled;
3581             }
3582
3583           continue;
3584         }
3585
3586       if (!gdbarch_get_longjmp_target_p (gdbarch))
3587         continue;
3588
3589       for (i = 0; i < NUM_LONGJMP_NAMES; i++)
3590         {
3591           struct breakpoint *b;
3592           const char *func_name;
3593           CORE_ADDR addr;
3594           struct explicit_location explicit_loc;
3595
3596           if (msym_not_found_p (bp_objfile_data->longjmp_msym[i].minsym))
3597             continue;
3598
3599           func_name = longjmp_names[i];
3600           if (bp_objfile_data->longjmp_msym[i].minsym == NULL)
3601             {
3602               struct bound_minimal_symbol m;
3603
3604               m = lookup_minimal_symbol_text (func_name, objfile);
3605               if (m.minsym == NULL)
3606                 {
3607                   /* Prevent future lookups in this objfile.  */
3608                   bp_objfile_data->longjmp_msym[i].minsym = &msym_not_found;
3609                   continue;
3610                 }
3611               bp_objfile_data->longjmp_msym[i] = m;
3612             }
3613
3614           addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->longjmp_msym[i]);
3615           b = create_internal_breakpoint (gdbarch, addr, bp_longjmp_master,
3616                                           &internal_breakpoint_ops);
3617           initialize_explicit_location (&explicit_loc);
3618           explicit_loc.function_name = ASTRDUP (func_name);
3619           b->location = new_explicit_location (&explicit_loc);
3620           b->enable_state = bp_disabled;
3621         }
3622     }
3623   }
3624 }
3625
3626 /* Create a master std::terminate breakpoint.  */
3627 static void
3628 create_std_terminate_master_breakpoint (void)
3629 {
3630   struct program_space *pspace;
3631   const char *const func_name = "std::terminate()";
3632
3633   scoped_restore_current_program_space restore_pspace;
3634
3635   ALL_PSPACES (pspace)
3636   {
3637     struct objfile *objfile;
3638     CORE_ADDR addr;
3639
3640     set_current_program_space (pspace);
3641
3642     ALL_OBJFILES (objfile)
3643     {
3644       struct breakpoint *b;
3645       struct breakpoint_objfile_data *bp_objfile_data;
3646       struct explicit_location explicit_loc;
3647
3648       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3649
3650       if (msym_not_found_p (bp_objfile_data->terminate_msym.minsym))
3651         continue;
3652
3653       if (bp_objfile_data->terminate_msym.minsym == NULL)
3654         {
3655           struct bound_minimal_symbol m;
3656
3657           m = lookup_minimal_symbol (func_name, NULL, objfile);
3658           if (m.minsym == NULL || (MSYMBOL_TYPE (m.minsym) != mst_text
3659                                    && MSYMBOL_TYPE (m.minsym) != mst_file_text))
3660             {
3661               /* Prevent future lookups in this objfile.  */
3662               bp_objfile_data->terminate_msym.minsym = &msym_not_found;
3663               continue;
3664             }
3665           bp_objfile_data->terminate_msym = m;
3666         }
3667
3668       addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->terminate_msym);
3669       b = create_internal_breakpoint (get_objfile_arch (objfile), addr,
3670                                       bp_std_terminate_master,
3671                                       &internal_breakpoint_ops);
3672       initialize_explicit_location (&explicit_loc);
3673       explicit_loc.function_name = ASTRDUP (func_name);
3674       b->location = new_explicit_location (&explicit_loc);
3675       b->enable_state = bp_disabled;
3676     }
3677   }
3678 }
3679
3680 /* Install a master breakpoint on the unwinder's debug hook.  */
3681
3682 static void
3683 create_exception_master_breakpoint (void)
3684 {
3685   struct objfile *objfile;
3686   const char *const func_name = "_Unwind_DebugHook";
3687
3688   ALL_OBJFILES (objfile)
3689     {
3690       struct breakpoint *b;
3691       struct gdbarch *gdbarch;
3692       struct breakpoint_objfile_data *bp_objfile_data;
3693       CORE_ADDR addr;
3694       struct explicit_location explicit_loc;
3695
3696       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3697
3698       /* We prefer the SystemTap probe point if it exists.  */
3699       if (!bp_objfile_data->exception_searched)
3700         {
3701           VEC (probe_p) *ret;
3702
3703           ret = find_probes_in_objfile (objfile, "libgcc", "unwind");
3704
3705           if (ret != NULL)
3706             {
3707               /* We are only interested in checking one element.  */
3708               struct probe *p = VEC_index (probe_p, ret, 0);
3709
3710               if (!can_evaluate_probe_arguments (p))
3711                 {
3712                   /* We cannot use the probe interface here, because it does
3713                      not know how to evaluate arguments.  */
3714                   VEC_free (probe_p, ret);
3715                   ret = NULL;
3716                 }
3717             }
3718           bp_objfile_data->exception_probes = ret;
3719           bp_objfile_data->exception_searched = 1;
3720         }
3721
3722       if (bp_objfile_data->exception_probes != NULL)
3723         {
3724           struct gdbarch *gdbarch = get_objfile_arch (objfile);
3725           int i;
3726           struct probe *probe;
3727
3728           for (i = 0;
3729                VEC_iterate (probe_p,
3730                             bp_objfile_data->exception_probes,
3731                             i, probe);
3732                ++i)
3733             {
3734               struct breakpoint *b;
3735
3736               b = create_internal_breakpoint (gdbarch,
3737                                               get_probe_address (probe,
3738                                                                  objfile),
3739                                               bp_exception_master,
3740                                               &internal_breakpoint_ops);
3741               b->location = new_probe_location ("-probe-stap libgcc:unwind");
3742               b->enable_state = bp_disabled;
3743             }
3744
3745           continue;
3746         }
3747
3748       /* Otherwise, try the hook function.  */
3749
3750       if (msym_not_found_p (bp_objfile_data->exception_msym.minsym))
3751         continue;
3752
3753       gdbarch = get_objfile_arch (objfile);
3754
3755       if (bp_objfile_data->exception_msym.minsym == NULL)
3756         {
3757           struct bound_minimal_symbol debug_hook;
3758
3759           debug_hook = lookup_minimal_symbol (func_name, NULL, objfile);
3760           if (debug_hook.minsym == NULL)
3761             {
3762               bp_objfile_data->exception_msym.minsym = &msym_not_found;
3763               continue;
3764             }
3765
3766           bp_objfile_data->exception_msym = debug_hook;
3767         }
3768
3769       addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->exception_msym);
3770       addr = gdbarch_convert_from_func_ptr_addr (gdbarch, addr,
3771                                                  &current_target);
3772       b = create_internal_breakpoint (gdbarch, addr, bp_exception_master,
3773                                       &internal_breakpoint_ops);
3774       initialize_explicit_location (&explicit_loc);
3775       explicit_loc.function_name = ASTRDUP (func_name);
3776       b->location = new_explicit_location (&explicit_loc);
3777       b->enable_state = bp_disabled;
3778     }
3779 }
3780
3781 /* Does B have a location spec?  */
3782
3783 static int
3784 breakpoint_event_location_empty_p (const struct breakpoint *b)
3785 {
3786   return b->location != NULL && event_location_empty_p (b->location.get ());
3787 }
3788
3789 void
3790 update_breakpoints_after_exec (void)
3791 {
3792   struct breakpoint *b, *b_tmp;
3793   struct bp_location *bploc, **bplocp_tmp;
3794
3795   /* We're about to delete breakpoints from GDB's lists.  If the
3796      INSERTED flag is true, GDB will try to lift the breakpoints by
3797      writing the breakpoints' "shadow contents" back into memory.  The
3798      "shadow contents" are NOT valid after an exec, so GDB should not
3799      do that.  Instead, the target is responsible from marking
3800      breakpoints out as soon as it detects an exec.  We don't do that
3801      here instead, because there may be other attempts to delete
3802      breakpoints after detecting an exec and before reaching here.  */
3803   ALL_BP_LOCATIONS (bploc, bplocp_tmp)
3804     if (bploc->pspace == current_program_space)
3805       gdb_assert (!bploc->inserted);
3806
3807   ALL_BREAKPOINTS_SAFE (b, b_tmp)
3808   {
3809     if (b->pspace != current_program_space)
3810       continue;
3811
3812     /* Solib breakpoints must be explicitly reset after an exec().  */
3813     if (b->type == bp_shlib_event)
3814       {
3815         delete_breakpoint (b);
3816         continue;
3817       }
3818
3819     /* JIT breakpoints must be explicitly reset after an exec().  */
3820     if (b->type == bp_jit_event)
3821       {
3822         delete_breakpoint (b);
3823         continue;
3824       }
3825
3826     /* Thread event breakpoints must be set anew after an exec(),
3827        as must overlay event and longjmp master breakpoints.  */
3828     if (b->type == bp_thread_event || b->type == bp_overlay_event
3829         || b->type == bp_longjmp_master || b->type == bp_std_terminate_master
3830         || b->type == bp_exception_master)
3831       {
3832         delete_breakpoint (b);
3833         continue;
3834       }
3835
3836     /* Step-resume breakpoints are meaningless after an exec().  */
3837     if (b->type == bp_step_resume || b->type == bp_hp_step_resume)
3838       {
3839         delete_breakpoint (b);
3840         continue;
3841       }
3842
3843     /* Just like single-step breakpoints.  */
3844     if (b->type == bp_single_step)
3845       {
3846         delete_breakpoint (b);
3847         continue;
3848       }
3849
3850     /* Longjmp and longjmp-resume breakpoints are also meaningless
3851        after an exec.  */
3852     if (b->type == bp_longjmp || b->type == bp_longjmp_resume
3853         || b->type == bp_longjmp_call_dummy
3854         || b->type == bp_exception || b->type == bp_exception_resume)
3855       {
3856         delete_breakpoint (b);
3857         continue;
3858       }
3859
3860     if (b->type == bp_catchpoint)
3861       {
3862         /* For now, none of the bp_catchpoint breakpoints need to
3863            do anything at this point.  In the future, if some of
3864            the catchpoints need to something, we will need to add
3865            a new method, and call this method from here.  */
3866         continue;
3867       }
3868
3869     /* bp_finish is a special case.  The only way we ought to be able
3870        to see one of these when an exec() has happened, is if the user
3871        caught a vfork, and then said "finish".  Ordinarily a finish just
3872        carries them to the call-site of the current callee, by setting
3873        a temporary bp there and resuming.  But in this case, the finish
3874        will carry them entirely through the vfork & exec.
3875
3876        We don't want to allow a bp_finish to remain inserted now.  But
3877        we can't safely delete it, 'cause finish_command has a handle to
3878        the bp on a bpstat, and will later want to delete it.  There's a
3879        chance (and I've seen it happen) that if we delete the bp_finish
3880        here, that its storage will get reused by the time finish_command
3881        gets 'round to deleting the "use to be a bp_finish" breakpoint.
3882        We really must allow finish_command to delete a bp_finish.
3883
3884        In the absence of a general solution for the "how do we know
3885        it's safe to delete something others may have handles to?"
3886        problem, what we'll do here is just uninsert the bp_finish, and
3887        let finish_command delete it.
3888
3889        (We know the bp_finish is "doomed" in the sense that it's
3890        momentary, and will be deleted as soon as finish_command sees
3891        the inferior stopped.  So it doesn't matter that the bp's
3892        address is probably bogus in the new a.out, unlike e.g., the
3893        solib breakpoints.)  */
3894
3895     if (b->type == bp_finish)
3896       {
3897         continue;
3898       }
3899
3900     /* Without a symbolic address, we have little hope of the
3901        pre-exec() address meaning the same thing in the post-exec()
3902        a.out.  */
3903     if (breakpoint_event_location_empty_p (b))
3904       {
3905         delete_breakpoint (b);
3906         continue;
3907       }
3908   }
3909 }
3910
3911 int
3912 detach_breakpoints (ptid_t ptid)
3913 {
3914   struct bp_location *bl, **blp_tmp;
3915   int val = 0;
3916   struct cleanup *old_chain = save_inferior_ptid ();
3917   struct inferior *inf = current_inferior ();
3918
3919   if (ptid_get_pid (ptid) == ptid_get_pid (inferior_ptid))
3920     error (_("Cannot detach breakpoints of inferior_ptid"));
3921
3922   /* Set inferior_ptid; remove_breakpoint_1 uses this global.  */
3923   inferior_ptid = ptid;
3924   ALL_BP_LOCATIONS (bl, blp_tmp)
3925   {
3926     if (bl->pspace != inf->pspace)
3927       continue;
3928
3929     /* This function must physically remove breakpoints locations
3930        from the specified ptid, without modifying the breakpoint
3931        package's state.  Locations of type bp_loc_other are only
3932        maintained at GDB side.  So, there is no need to remove
3933        these bp_loc_other locations.  Moreover, removing these
3934        would modify the breakpoint package's state.  */
3935     if (bl->loc_type == bp_loc_other)
3936       continue;
3937
3938     if (bl->inserted)
3939       val |= remove_breakpoint_1 (bl, DETACH_BREAKPOINT);
3940   }
3941
3942   do_cleanups (old_chain);
3943   return val;
3944 }
3945
3946 /* Remove the breakpoint location BL from the current address space.
3947    Note that this is used to detach breakpoints from a child fork.
3948    When we get here, the child isn't in the inferior list, and neither
3949    do we have objects to represent its address space --- we should
3950    *not* look at bl->pspace->aspace here.  */
3951
3952 static int
3953 remove_breakpoint_1 (struct bp_location *bl, enum remove_bp_reason reason)
3954 {
3955   int val;
3956
3957   /* BL is never in moribund_locations by our callers.  */
3958   gdb_assert (bl->owner != NULL);
3959
3960   /* The type of none suggests that owner is actually deleted.
3961      This should not ever happen.  */
3962   gdb_assert (bl->owner->type != bp_none);
3963
3964   if (bl->loc_type == bp_loc_software_breakpoint
3965       || bl->loc_type == bp_loc_hardware_breakpoint)
3966     {
3967       /* "Normal" instruction breakpoint: either the standard
3968          trap-instruction bp (bp_breakpoint), or a
3969          bp_hardware_breakpoint.  */
3970
3971       /* First check to see if we have to handle an overlay.  */
3972       if (overlay_debugging == ovly_off
3973           || bl->section == NULL
3974           || !(section_is_overlay (bl->section)))
3975         {
3976           /* No overlay handling: just remove the breakpoint.  */
3977
3978           /* If we're trying to uninsert a memory breakpoint that we
3979              know is set in a dynamic object that is marked
3980              shlib_disabled, then either the dynamic object was
3981              removed with "remove-symbol-file" or with
3982              "nosharedlibrary".  In the former case, we don't know
3983              whether another dynamic object might have loaded over the
3984              breakpoint's address -- the user might well let us know
3985              about it next with add-symbol-file (the whole point of
3986              add-symbol-file is letting the user manually maintain a
3987              list of dynamically loaded objects).  If we have the
3988              breakpoint's shadow memory, that is, this is a software
3989              breakpoint managed by GDB, check whether the breakpoint
3990              is still inserted in memory, to avoid overwriting wrong
3991              code with stale saved shadow contents.  Note that HW
3992              breakpoints don't have shadow memory, as they're
3993              implemented using a mechanism that is not dependent on
3994              being able to modify the target's memory, and as such
3995              they should always be removed.  */
3996           if (bl->shlib_disabled
3997               && bl->target_info.shadow_len != 0
3998               && !memory_validate_breakpoint (bl->gdbarch, &bl->target_info))
3999             val = 0;
4000           else
4001             val = bl->owner->ops->remove_location (bl, reason);
4002         }
4003       else
4004         {
4005           /* This breakpoint is in an overlay section.
4006              Did we set a breakpoint at the LMA?  */
4007           if (!overlay_events_enabled)
4008               {
4009                 /* Yes -- overlay event support is not active, so we
4010                    should have set a breakpoint at the LMA.  Remove it.  
4011                 */
4012                 /* Ignore any failures: if the LMA is in ROM, we will
4013                    have already warned when we failed to insert it.  */
4014                 if (bl->loc_type == bp_loc_hardware_breakpoint)
4015                   target_remove_hw_breakpoint (bl->gdbarch,
4016                                                &bl->overlay_target_info);
4017                 else
4018                   target_remove_breakpoint (bl->gdbarch,
4019                                             &bl->overlay_target_info,
4020                                             reason);
4021               }
4022           /* Did we set a breakpoint at the VMA? 
4023              If so, we will have marked the breakpoint 'inserted'.  */
4024           if (bl->inserted)
4025             {
4026               /* Yes -- remove it.  Previously we did not bother to
4027                  remove the breakpoint if the section had been
4028                  unmapped, but let's not rely on that being safe.  We
4029                  don't know what the overlay manager might do.  */
4030
4031               /* However, we should remove *software* breakpoints only
4032                  if the section is still mapped, or else we overwrite
4033                  wrong code with the saved shadow contents.  */
4034               if (bl->loc_type == bp_loc_hardware_breakpoint
4035                   || section_is_mapped (bl->section))
4036                 val = bl->owner->ops->remove_location (bl, reason);
4037               else
4038                 val = 0;
4039             }
4040           else
4041             {
4042               /* No -- not inserted, so no need to remove.  No error.  */
4043               val = 0;
4044             }
4045         }
4046
4047       /* In some cases, we might not be able to remove a breakpoint in
4048          a shared library that has already been removed, but we have
4049          not yet processed the shlib unload event.  Similarly for an
4050          unloaded add-symbol-file object - the user might not yet have
4051          had the chance to remove-symbol-file it.  shlib_disabled will
4052          be set if the library/object has already been removed, but
4053          the breakpoint hasn't been uninserted yet, e.g., after
4054          "nosharedlibrary" or "remove-symbol-file" with breakpoints
4055          always-inserted mode.  */
4056       if (val
4057           && (bl->loc_type == bp_loc_software_breakpoint
4058               && (bl->shlib_disabled
4059                   || solib_name_from_address (bl->pspace, bl->address)
4060                   || shared_objfile_contains_address_p (bl->pspace,
4061                                                         bl->address))))
4062         val = 0;
4063
4064       if (val)
4065         return val;
4066       bl->inserted = (reason == DETACH_BREAKPOINT);
4067     }
4068   else if (bl->loc_type == bp_loc_hardware_watchpoint)
4069     {
4070       gdb_assert (bl->owner->ops != NULL
4071                   && bl->owner->ops->remove_location != NULL);
4072
4073       bl->inserted = (reason == DETACH_BREAKPOINT);
4074       bl->owner->ops->remove_location (bl, reason);
4075
4076       /* Failure to remove any of the hardware watchpoints comes here.  */
4077       if (reason == REMOVE_BREAKPOINT && bl->inserted)
4078         warning (_("Could not remove hardware watchpoint %d."),
4079                  bl->owner->number);
4080     }
4081   else if (bl->owner->type == bp_catchpoint
4082            && breakpoint_enabled (bl->owner)
4083            && !bl->duplicate)
4084     {
4085       gdb_assert (bl->owner->ops != NULL
4086                   && bl->owner->ops->remove_location != NULL);
4087
4088       val = bl->owner->ops->remove_location (bl, reason);
4089       if (val)
4090         return val;
4091
4092       bl->inserted = (reason == DETACH_BREAKPOINT);
4093     }
4094
4095   return 0;
4096 }
4097
4098 static int
4099 remove_breakpoint (struct bp_location *bl)
4100 {
4101   /* BL is never in moribund_locations by our callers.  */
4102   gdb_assert (bl->owner != NULL);
4103
4104   /* The type of none suggests that owner is actually deleted.
4105      This should not ever happen.  */
4106   gdb_assert (bl->owner->type != bp_none);
4107
4108   scoped_restore_current_pspace_and_thread restore_pspace_thread;
4109
4110   switch_to_program_space_and_thread (bl->pspace);
4111
4112   return remove_breakpoint_1 (bl, REMOVE_BREAKPOINT);
4113 }
4114
4115 /* Clear the "inserted" flag in all breakpoints.  */
4116
4117 void
4118 mark_breakpoints_out (void)
4119 {
4120   struct bp_location *bl, **blp_tmp;
4121
4122   ALL_BP_LOCATIONS (bl, blp_tmp)
4123     if (bl->pspace == current_program_space)
4124       bl->inserted = 0;
4125 }
4126
4127 /* Clear the "inserted" flag in all breakpoints and delete any
4128    breakpoints which should go away between runs of the program.
4129
4130    Plus other such housekeeping that has to be done for breakpoints
4131    between runs.
4132
4133    Note: this function gets called at the end of a run (by
4134    generic_mourn_inferior) and when a run begins (by
4135    init_wait_for_inferior).  */
4136
4137
4138
4139 void
4140 breakpoint_init_inferior (enum inf_context context)
4141 {
4142   struct breakpoint *b, *b_tmp;
4143   struct bp_location *bl;
4144   int ix;
4145   struct program_space *pspace = current_program_space;
4146
4147   /* If breakpoint locations are shared across processes, then there's
4148      nothing to do.  */
4149   if (gdbarch_has_global_breakpoints (target_gdbarch ()))
4150     return;
4151
4152   mark_breakpoints_out ();
4153
4154   ALL_BREAKPOINTS_SAFE (b, b_tmp)
4155   {
4156     if (b->loc && b->loc->pspace != pspace)
4157       continue;
4158
4159     switch (b->type)
4160       {
4161       case bp_call_dummy:
4162       case bp_longjmp_call_dummy:
4163
4164         /* If the call dummy breakpoint is at the entry point it will
4165            cause problems when the inferior is rerun, so we better get
4166            rid of it.  */
4167
4168       case bp_watchpoint_scope:
4169
4170         /* Also get rid of scope breakpoints.  */
4171
4172       case bp_shlib_event:
4173
4174         /* Also remove solib event breakpoints.  Their addresses may
4175            have changed since the last time we ran the program.
4176            Actually we may now be debugging against different target;
4177            and so the solib backend that installed this breakpoint may
4178            not be used in by the target.  E.g.,
4179
4180            (gdb) file prog-linux
4181            (gdb) run               # native linux target
4182            ...
4183            (gdb) kill
4184            (gdb) file prog-win.exe
4185            (gdb) tar rem :9999     # remote Windows gdbserver.
4186         */
4187
4188       case bp_step_resume:
4189
4190         /* Also remove step-resume breakpoints.  */
4191
4192       case bp_single_step:
4193
4194         /* Also remove single-step breakpoints.  */
4195
4196         delete_breakpoint (b);
4197         break;
4198
4199       case bp_watchpoint:
4200       case bp_hardware_watchpoint:
4201       case bp_read_watchpoint:
4202       case bp_access_watchpoint:
4203         {
4204           struct watchpoint *w = (struct watchpoint *) b;
4205
4206           /* Likewise for watchpoints on local expressions.  */
4207           if (w->exp_valid_block != NULL)
4208             delete_breakpoint (b);
4209           else
4210             {
4211               /* Get rid of existing locations, which are no longer
4212                  valid.  New ones will be created in
4213                  update_watchpoint, when the inferior is restarted.
4214                  The next update_global_location_list call will
4215                  garbage collect them.  */
4216               b->loc = NULL;
4217
4218               if (context == inf_starting)
4219                 {
4220                   /* Reset val field to force reread of starting value in
4221                      insert_breakpoints.  */
4222                   if (w->val)
4223                     value_free (w->val);
4224                   w->val = NULL;
4225                   w->val_valid = 0;
4226                 }
4227             }
4228         }
4229         break;
4230       default:
4231         break;
4232       }
4233   }
4234
4235   /* Get rid of the moribund locations.  */
4236   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, bl); ++ix)
4237     decref_bp_location (&bl);
4238   VEC_free (bp_location_p, moribund_locations);
4239 }
4240
4241 /* These functions concern about actual breakpoints inserted in the
4242    target --- to e.g. check if we need to do decr_pc adjustment or if
4243    we need to hop over the bkpt --- so we check for address space
4244    match, not program space.  */
4245
4246 /* breakpoint_here_p (PC) returns non-zero if an enabled breakpoint
4247    exists at PC.  It returns ordinary_breakpoint_here if it's an
4248    ordinary breakpoint, or permanent_breakpoint_here if it's a
4249    permanent breakpoint.
4250    - When continuing from a location with an ordinary breakpoint, we
4251      actually single step once before calling insert_breakpoints.
4252    - When continuing from a location with a permanent breakpoint, we
4253      need to use the `SKIP_PERMANENT_BREAKPOINT' macro, provided by
4254      the target, to advance the PC past the breakpoint.  */
4255
4256 enum breakpoint_here
4257 breakpoint_here_p (struct address_space *aspace, CORE_ADDR pc)
4258 {
4259   struct bp_location *bl, **blp_tmp;
4260   int any_breakpoint_here = 0;
4261
4262   ALL_BP_LOCATIONS (bl, blp_tmp)
4263     {
4264       if (bl->loc_type != bp_loc_software_breakpoint
4265           && bl->loc_type != bp_loc_hardware_breakpoint)
4266         continue;
4267
4268       /* ALL_BP_LOCATIONS bp_location has BL->OWNER always non-NULL.  */
4269       if ((breakpoint_enabled (bl->owner)
4270            || bl->permanent)
4271           && breakpoint_location_address_match (bl, aspace, pc))
4272         {
4273           if (overlay_debugging 
4274               && section_is_overlay (bl->section)
4275               && !section_is_mapped (bl->section))
4276             continue;           /* unmapped overlay -- can't be a match */
4277           else if (bl->permanent)
4278             return permanent_breakpoint_here;
4279           else
4280             any_breakpoint_here = 1;
4281         }
4282     }
4283
4284   return any_breakpoint_here ? ordinary_breakpoint_here : no_breakpoint_here;
4285 }
4286
4287 /* See breakpoint.h.  */
4288
4289 int
4290 breakpoint_in_range_p (struct address_space *aspace,
4291                        CORE_ADDR addr, ULONGEST len)
4292 {
4293   struct bp_location *bl, **blp_tmp;
4294
4295   ALL_BP_LOCATIONS (bl, blp_tmp)
4296     {
4297       if (bl->loc_type != bp_loc_software_breakpoint
4298           && bl->loc_type != bp_loc_hardware_breakpoint)
4299         continue;
4300
4301       if ((breakpoint_enabled (bl->owner)
4302            || bl->permanent)
4303           && breakpoint_location_address_range_overlap (bl, aspace,
4304                                                         addr, len))
4305         {
4306           if (overlay_debugging
4307               && section_is_overlay (bl->section)
4308               && !section_is_mapped (bl->section))
4309             {
4310               /* Unmapped overlay -- can't be a match.  */
4311               continue;
4312             }
4313
4314           return 1;
4315         }
4316     }
4317
4318   return 0;
4319 }
4320
4321 /* Return true if there's a moribund breakpoint at PC.  */
4322
4323 int
4324 moribund_breakpoint_here_p (struct address_space *aspace, CORE_ADDR pc)
4325 {
4326   struct bp_location *loc;
4327   int ix;
4328
4329   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
4330     if (breakpoint_location_address_match (loc, aspace, pc))
4331       return 1;
4332
4333   return 0;
4334 }
4335
4336 /* Returns non-zero iff BL is inserted at PC, in address space
4337    ASPACE.  */
4338
4339 static int
4340 bp_location_inserted_here_p (struct bp_location *bl,
4341                              struct address_space *aspace, CORE_ADDR pc)
4342 {
4343   if (bl->inserted
4344       && breakpoint_address_match (bl->pspace->aspace, bl->address,
4345                                    aspace, pc))
4346     {
4347       if (overlay_debugging
4348           && section_is_overlay (bl->section)
4349           && !section_is_mapped (bl->section))
4350         return 0;               /* unmapped overlay -- can't be a match */
4351       else
4352         return 1;
4353     }
4354   return 0;
4355 }
4356
4357 /* Returns non-zero iff there's a breakpoint inserted at PC.  */
4358
4359 int
4360 breakpoint_inserted_here_p (struct address_space *aspace, CORE_ADDR pc)
4361 {
4362   struct bp_location **blp, **blp_tmp = NULL;
4363
4364   ALL_BP_LOCATIONS_AT_ADDR (blp, blp_tmp, pc)
4365     {
4366       struct bp_location *bl = *blp;
4367
4368       if (bl->loc_type != bp_loc_software_breakpoint
4369           && bl->loc_type != bp_loc_hardware_breakpoint)
4370         continue;
4371
4372       if (bp_location_inserted_here_p (bl, aspace, pc))
4373         return 1;
4374     }
4375   return 0;
4376 }
4377
4378 /* This function returns non-zero iff there is a software breakpoint
4379    inserted at PC.  */
4380
4381 int
4382 software_breakpoint_inserted_here_p (struct address_space *aspace,
4383                                      CORE_ADDR pc)
4384 {
4385   struct bp_location **blp, **blp_tmp = NULL;
4386
4387   ALL_BP_LOCATIONS_AT_ADDR (blp, blp_tmp, pc)
4388     {
4389       struct bp_location *bl = *blp;
4390
4391       if (bl->loc_type != bp_loc_software_breakpoint)
4392         continue;
4393
4394       if (bp_location_inserted_here_p (bl, aspace, pc))
4395         return 1;
4396     }
4397
4398   return 0;
4399 }
4400
4401 /* See breakpoint.h.  */
4402
4403 int
4404 hardware_breakpoint_inserted_here_p (struct address_space *aspace,
4405                                      CORE_ADDR pc)
4406 {
4407   struct bp_location **blp, **blp_tmp = NULL;
4408
4409   ALL_BP_LOCATIONS_AT_ADDR (blp, blp_tmp, pc)
4410     {
4411       struct bp_location *bl = *blp;
4412
4413       if (bl->loc_type != bp_loc_hardware_breakpoint)
4414         continue;
4415
4416       if (bp_location_inserted_here_p (bl, aspace, pc))
4417         return 1;
4418     }
4419
4420   return 0;
4421 }
4422
4423 int
4424 hardware_watchpoint_inserted_in_range (struct address_space *aspace,
4425                                        CORE_ADDR addr, ULONGEST len)
4426 {
4427   struct breakpoint *bpt;
4428
4429   ALL_BREAKPOINTS (bpt)
4430     {
4431       struct bp_location *loc;
4432
4433       if (bpt->type != bp_hardware_watchpoint
4434           && bpt->type != bp_access_watchpoint)
4435         continue;
4436
4437       if (!breakpoint_enabled (bpt))
4438         continue;
4439
4440       for (loc = bpt->loc; loc; loc = loc->next)
4441         if (loc->pspace->aspace == aspace && loc->inserted)
4442           {
4443             CORE_ADDR l, h;
4444
4445             /* Check for intersection.  */
4446             l = std::max<CORE_ADDR> (loc->address, addr);
4447             h = std::min<CORE_ADDR> (loc->address + loc->length, addr + len);
4448             if (l < h)
4449               return 1;
4450           }
4451     }
4452   return 0;
4453 }
4454 \f
4455
4456 /* bpstat stuff.  External routines' interfaces are documented
4457    in breakpoint.h.  */
4458
4459 int
4460 is_catchpoint (struct breakpoint *ep)
4461 {
4462   return (ep->type == bp_catchpoint);
4463 }
4464
4465 /* Frees any storage that is part of a bpstat.  Does not walk the
4466    'next' chain.  */
4467
4468 static void
4469 bpstat_free (bpstat bs)
4470 {
4471   if (bs->old_val != NULL)
4472     value_free (bs->old_val);
4473   decref_counted_command_line (&bs->commands);
4474   decref_bp_location (&bs->bp_location_at);
4475   xfree (bs);
4476 }
4477
4478 /* Clear a bpstat so that it says we are not at any breakpoint.
4479    Also free any storage that is part of a bpstat.  */
4480
4481 void
4482 bpstat_clear (bpstat *bsp)
4483 {
4484   bpstat p;
4485   bpstat q;
4486
4487   if (bsp == 0)
4488     return;
4489   p = *bsp;
4490   while (p != NULL)
4491     {
4492       q = p->next;
4493       bpstat_free (p);
4494       p = q;
4495     }
4496   *bsp = NULL;
4497 }
4498
4499 /* Return a copy of a bpstat.  Like "bs1 = bs2" but all storage that
4500    is part of the bpstat is copied as well.  */
4501
4502 bpstat
4503 bpstat_copy (bpstat bs)
4504 {
4505   bpstat p = NULL;
4506   bpstat tmp;
4507   bpstat retval = NULL;
4508
4509   if (bs == NULL)
4510     return bs;
4511
4512   for (; bs != NULL; bs = bs->next)
4513     {
4514       tmp = (bpstat) xmalloc (sizeof (*tmp));
4515       memcpy (tmp, bs, sizeof (*tmp));
4516       incref_counted_command_line (tmp->commands);
4517       incref_bp_location (tmp->bp_location_at);
4518       if (bs->old_val != NULL)
4519         {
4520           tmp->old_val = value_copy (bs->old_val);
4521           release_value (tmp->old_val);
4522         }
4523
4524       if (p == NULL)
4525         /* This is the first thing in the chain.  */
4526         retval = tmp;
4527       else
4528         p->next = tmp;
4529       p = tmp;
4530     }
4531   p->next = NULL;
4532   return retval;
4533 }
4534
4535 /* Find the bpstat associated with this breakpoint.  */
4536
4537 bpstat
4538 bpstat_find_breakpoint (bpstat bsp, struct breakpoint *breakpoint)
4539 {
4540   if (bsp == NULL)
4541     return NULL;
4542
4543   for (; bsp != NULL; bsp = bsp->next)
4544     {
4545       if (bsp->breakpoint_at == breakpoint)
4546         return bsp;
4547     }
4548   return NULL;
4549 }
4550
4551 /* See breakpoint.h.  */
4552
4553 int
4554 bpstat_explains_signal (bpstat bsp, enum gdb_signal sig)
4555 {
4556   for (; bsp != NULL; bsp = bsp->next)
4557     {
4558       if (bsp->breakpoint_at == NULL)
4559         {
4560           /* A moribund location can never explain a signal other than
4561              GDB_SIGNAL_TRAP.  */
4562           if (sig == GDB_SIGNAL_TRAP)
4563             return 1;
4564         }
4565       else
4566         {
4567           if (bsp->breakpoint_at->ops->explains_signal (bsp->breakpoint_at,
4568                                                         sig))
4569             return 1;
4570         }
4571     }
4572
4573   return 0;
4574 }
4575
4576 /* Put in *NUM the breakpoint number of the first breakpoint we are
4577    stopped at.  *BSP upon return is a bpstat which points to the
4578    remaining breakpoints stopped at (but which is not guaranteed to be
4579    good for anything but further calls to bpstat_num).
4580
4581    Return 0 if passed a bpstat which does not indicate any breakpoints.
4582    Return -1 if stopped at a breakpoint that has been deleted since
4583    we set it.
4584    Return 1 otherwise.  */
4585
4586 int
4587 bpstat_num (bpstat *bsp, int *num)
4588 {
4589   struct breakpoint *b;
4590
4591   if ((*bsp) == NULL)
4592     return 0;                   /* No more breakpoint values */
4593
4594   /* We assume we'll never have several bpstats that correspond to a
4595      single breakpoint -- otherwise, this function might return the
4596      same number more than once and this will look ugly.  */
4597   b = (*bsp)->breakpoint_at;
4598   *bsp = (*bsp)->next;
4599   if (b == NULL)
4600     return -1;                  /* breakpoint that's been deleted since */
4601
4602   *num = b->number;             /* We have its number */
4603   return 1;
4604 }
4605
4606 /* See breakpoint.h.  */
4607
4608 void
4609 bpstat_clear_actions (void)
4610 {
4611   struct thread_info *tp;
4612   bpstat bs;
4613
4614   if (ptid_equal (inferior_ptid, null_ptid))
4615     return;
4616
4617   tp = find_thread_ptid (inferior_ptid);
4618   if (tp == NULL)
4619     return;
4620
4621   for (bs = tp->control.stop_bpstat; bs != NULL; bs = bs->next)
4622     {
4623       decref_counted_command_line (&bs->commands);
4624
4625       if (bs->old_val != NULL)
4626         {
4627           value_free (bs->old_val);
4628           bs->old_val = NULL;
4629         }
4630     }
4631 }
4632
4633 /* Called when a command is about to proceed the inferior.  */
4634
4635 static void
4636 breakpoint_about_to_proceed (void)
4637 {
4638   if (!ptid_equal (inferior_ptid, null_ptid))
4639     {
4640       struct thread_info *tp = inferior_thread ();
4641
4642       /* Allow inferior function calls in breakpoint commands to not
4643          interrupt the command list.  When the call finishes
4644          successfully, the inferior will be standing at the same
4645          breakpoint as if nothing happened.  */
4646       if (tp->control.in_infcall)
4647         return;
4648     }
4649
4650   breakpoint_proceeded = 1;
4651 }
4652
4653 /* Stub for cleaning up our state if we error-out of a breakpoint
4654    command.  */
4655 static void
4656 cleanup_executing_breakpoints (void *ignore)
4657 {
4658   executing_breakpoint_commands = 0;
4659 }
4660
4661 /* Return non-zero iff CMD as the first line of a command sequence is `silent'
4662    or its equivalent.  */
4663
4664 static int
4665 command_line_is_silent (struct command_line *cmd)
4666 {
4667   return cmd && (strcmp ("silent", cmd->line) == 0);
4668 }
4669
4670 /* Execute all the commands associated with all the breakpoints at
4671    this location.  Any of these commands could cause the process to
4672    proceed beyond this point, etc.  We look out for such changes by
4673    checking the global "breakpoint_proceeded" after each command.
4674
4675    Returns true if a breakpoint command resumed the inferior.  In that
4676    case, it is the caller's responsibility to recall it again with the
4677    bpstat of the current thread.  */
4678
4679 static int
4680 bpstat_do_actions_1 (bpstat *bsp)
4681 {
4682   bpstat bs;
4683   struct cleanup *old_chain;
4684   int again = 0;
4685
4686   /* Avoid endless recursion if a `source' command is contained
4687      in bs->commands.  */
4688   if (executing_breakpoint_commands)
4689     return 0;
4690
4691   executing_breakpoint_commands = 1;
4692   old_chain = make_cleanup (cleanup_executing_breakpoints, 0);
4693
4694   scoped_restore preventer = prevent_dont_repeat ();
4695
4696   /* This pointer will iterate over the list of bpstat's.  */
4697   bs = *bsp;
4698
4699   breakpoint_proceeded = 0;
4700   for (; bs != NULL; bs = bs->next)
4701     {
4702       struct counted_command_line *ccmd;
4703       struct command_line *cmd;
4704       struct cleanup *this_cmd_tree_chain;
4705
4706       /* Take ownership of the BSP's command tree, if it has one.
4707
4708          The command tree could legitimately contain commands like
4709          'step' and 'next', which call clear_proceed_status, which
4710          frees stop_bpstat's command tree.  To make sure this doesn't
4711          free the tree we're executing out from under us, we need to
4712          take ownership of the tree ourselves.  Since a given bpstat's
4713          commands are only executed once, we don't need to copy it; we
4714          can clear the pointer in the bpstat, and make sure we free
4715          the tree when we're done.  */
4716       ccmd = bs->commands;
4717       bs->commands = NULL;
4718       this_cmd_tree_chain = make_cleanup_decref_counted_command_line (&ccmd);
4719       cmd = ccmd ? ccmd->commands : NULL;
4720       if (command_line_is_silent (cmd))
4721         {
4722           /* The action has been already done by bpstat_stop_status.  */
4723           cmd = cmd->next;
4724         }
4725
4726       while (cmd != NULL)
4727         {
4728           execute_control_command (cmd);
4729
4730           if (breakpoint_proceeded)
4731             break;
4732           else
4733             cmd = cmd->next;
4734         }
4735
4736       /* We can free this command tree now.  */
4737       do_cleanups (this_cmd_tree_chain);
4738
4739       if (breakpoint_proceeded)
4740         {
4741           if (current_ui->async)
4742             /* If we are in async mode, then the target might be still
4743                running, not stopped at any breakpoint, so nothing for
4744                us to do here -- just return to the event loop.  */
4745             ;
4746           else
4747             /* In sync mode, when execute_control_command returns
4748                we're already standing on the next breakpoint.
4749                Breakpoint commands for that stop were not run, since
4750                execute_command does not run breakpoint commands --
4751                only command_line_handler does, but that one is not
4752                involved in execution of breakpoint commands.  So, we
4753                can now execute breakpoint commands.  It should be
4754                noted that making execute_command do bpstat actions is
4755                not an option -- in this case we'll have recursive
4756                invocation of bpstat for each breakpoint with a
4757                command, and can easily blow up GDB stack.  Instead, we
4758                return true, which will trigger the caller to recall us
4759                with the new stop_bpstat.  */
4760             again = 1;
4761           break;
4762         }
4763     }
4764   do_cleanups (old_chain);
4765   return again;
4766 }
4767
4768 void
4769 bpstat_do_actions (void)
4770 {
4771   struct cleanup *cleanup_if_error = make_bpstat_clear_actions_cleanup ();
4772
4773   /* Do any commands attached to breakpoint we are stopped at.  */
4774   while (!ptid_equal (inferior_ptid, null_ptid)
4775          && target_has_execution
4776          && !is_exited (inferior_ptid)
4777          && !is_executing (inferior_ptid))
4778     /* Since in sync mode, bpstat_do_actions may resume the inferior,
4779        and only return when it is stopped at the next breakpoint, we
4780        keep doing breakpoint actions until it returns false to
4781        indicate the inferior was not resumed.  */
4782     if (!bpstat_do_actions_1 (&inferior_thread ()->control.stop_bpstat))
4783       break;
4784
4785   discard_cleanups (cleanup_if_error);
4786 }
4787
4788 /* Print out the (old or new) value associated with a watchpoint.  */
4789
4790 static void
4791 watchpoint_value_print (struct value *val, struct ui_file *stream)
4792 {
4793   if (val == NULL)
4794     fprintf_unfiltered (stream, _("<unreadable>"));
4795   else
4796     {
4797       struct value_print_options opts;
4798       get_user_print_options (&opts);
4799       value_print (val, stream, &opts);
4800     }
4801 }
4802
4803 /* Print the "Thread ID hit" part of "Thread ID hit Breakpoint N" if
4804    debugging multiple threads.  */
4805
4806 void
4807 maybe_print_thread_hit_breakpoint (struct ui_out *uiout)
4808 {
4809   if (uiout->is_mi_like_p ())
4810     return;
4811
4812   uiout->text ("\n");
4813
4814   if (show_thread_that_caused_stop ())
4815     {
4816       const char *name;
4817       struct thread_info *thr = inferior_thread ();
4818
4819       uiout->text ("Thread ");
4820       uiout->field_fmt ("thread-id", "%s", print_thread_id (thr));
4821
4822       name = thr->name != NULL ? thr->name : target_thread_name (thr);
4823       if (name != NULL)
4824         {
4825           uiout->text (" \"");
4826           uiout->field_fmt ("name", "%s", name);
4827           uiout->text ("\"");
4828         }
4829
4830       uiout->text (" hit ");
4831     }
4832 }
4833
4834 /* Generic routine for printing messages indicating why we
4835    stopped.  The behavior of this function depends on the value
4836    'print_it' in the bpstat structure.  Under some circumstances we
4837    may decide not to print anything here and delegate the task to
4838    normal_stop().  */
4839
4840 static enum print_stop_action
4841 print_bp_stop_message (bpstat bs)
4842 {
4843   switch (bs->print_it)
4844     {
4845     case print_it_noop:
4846       /* Nothing should be printed for this bpstat entry.  */
4847       return PRINT_UNKNOWN;
4848       break;
4849
4850     case print_it_done:
4851       /* We still want to print the frame, but we already printed the
4852          relevant messages.  */
4853       return PRINT_SRC_AND_LOC;
4854       break;
4855
4856     case print_it_normal:
4857       {
4858         struct breakpoint *b = bs->breakpoint_at;
4859
4860         /* bs->breakpoint_at can be NULL if it was a momentary breakpoint
4861            which has since been deleted.  */
4862         if (b == NULL)
4863           return PRINT_UNKNOWN;
4864
4865         /* Normal case.  Call the breakpoint's print_it method.  */
4866         return b->ops->print_it (bs);
4867       }
4868       break;
4869
4870     default:
4871       internal_error (__FILE__, __LINE__,
4872                       _("print_bp_stop_message: unrecognized enum value"));
4873       break;
4874     }
4875 }
4876
4877 /* A helper function that prints a shared library stopped event.  */
4878
4879 static void
4880 print_solib_event (int is_catchpoint)
4881 {
4882   int any_deleted
4883     = !VEC_empty (char_ptr, current_program_space->deleted_solibs);
4884   int any_added
4885     = !VEC_empty (so_list_ptr, current_program_space->added_solibs);
4886
4887   if (!is_catchpoint)
4888     {
4889       if (any_added || any_deleted)
4890         current_uiout->text (_("Stopped due to shared library event:\n"));
4891       else
4892         current_uiout->text (_("Stopped due to shared library event (no "
4893                                "libraries added or removed)\n"));
4894     }
4895
4896   if (current_uiout->is_mi_like_p ())
4897     current_uiout->field_string ("reason",
4898                                  async_reason_lookup (EXEC_ASYNC_SOLIB_EVENT));
4899
4900   if (any_deleted)
4901     {
4902       char *name;
4903       int ix;
4904
4905       current_uiout->text (_("  Inferior unloaded "));
4906       ui_out_emit_list list_emitter (current_uiout, "removed");
4907       for (ix = 0;
4908            VEC_iterate (char_ptr, current_program_space->deleted_solibs,
4909                         ix, name);
4910            ++ix)
4911         {
4912           if (ix > 0)
4913             current_uiout->text ("    ");
4914           current_uiout->field_string ("library", name);
4915           current_uiout->text ("\n");
4916         }
4917     }
4918
4919   if (any_added)
4920     {
4921       struct so_list *iter;
4922       int ix;
4923
4924       current_uiout->text (_("  Inferior loaded "));
4925       ui_out_emit_list list_emitter (current_uiout, "added");
4926       for (ix = 0;
4927            VEC_iterate (so_list_ptr, current_program_space->added_solibs,
4928                         ix, iter);
4929            ++ix)
4930         {
4931           if (ix > 0)
4932             current_uiout->text ("    ");
4933           current_uiout->field_string ("library", iter->so_name);
4934           current_uiout->text ("\n");
4935         }
4936     }
4937 }
4938
4939 /* Print a message indicating what happened.  This is called from
4940    normal_stop().  The input to this routine is the head of the bpstat
4941    list - a list of the eventpoints that caused this stop.  KIND is
4942    the target_waitkind for the stopping event.  This
4943    routine calls the generic print routine for printing a message
4944    about reasons for stopping.  This will print (for example) the
4945    "Breakpoint n," part of the output.  The return value of this
4946    routine is one of:
4947
4948    PRINT_UNKNOWN: Means we printed nothing.
4949    PRINT_SRC_AND_LOC: Means we printed something, and expect subsequent
4950    code to print the location.  An example is 
4951    "Breakpoint 1, " which should be followed by
4952    the location.
4953    PRINT_SRC_ONLY: Means we printed something, but there is no need
4954    to also print the location part of the message.
4955    An example is the catch/throw messages, which
4956    don't require a location appended to the end.
4957    PRINT_NOTHING: We have done some printing and we don't need any 
4958    further info to be printed.  */
4959
4960 enum print_stop_action
4961 bpstat_print (bpstat bs, int kind)
4962 {
4963   enum print_stop_action val;
4964
4965   /* Maybe another breakpoint in the chain caused us to stop.
4966      (Currently all watchpoints go on the bpstat whether hit or not.
4967      That probably could (should) be changed, provided care is taken
4968      with respect to bpstat_explains_signal).  */
4969   for (; bs; bs = bs->next)
4970     {
4971       val = print_bp_stop_message (bs);
4972       if (val == PRINT_SRC_ONLY 
4973           || val == PRINT_SRC_AND_LOC 
4974           || val == PRINT_NOTHING)
4975         return val;
4976     }
4977
4978   /* If we had hit a shared library event breakpoint,
4979      print_bp_stop_message would print out this message.  If we hit an
4980      OS-level shared library event, do the same thing.  */
4981   if (kind == TARGET_WAITKIND_LOADED)
4982     {
4983       print_solib_event (0);
4984       return PRINT_NOTHING;
4985     }
4986
4987   /* We reached the end of the chain, or we got a null BS to start
4988      with and nothing was printed.  */
4989   return PRINT_UNKNOWN;
4990 }
4991
4992 /* Evaluate the expression EXP and return 1 if value is zero.
4993    This returns the inverse of the condition because it is called
4994    from catch_errors which returns 0 if an exception happened, and if an
4995    exception happens we want execution to stop.
4996    The argument is a "struct expression *" that has been cast to a
4997    "void *" to make it pass through catch_errors.  */
4998
4999 static int
5000 breakpoint_cond_eval (void *exp)
5001 {
5002   struct value *mark = value_mark ();
5003   int i = !value_true (evaluate_expression ((struct expression *) exp));
5004
5005   value_free_to_mark (mark);
5006   return i;
5007 }
5008
5009 /* Allocate a new bpstat.  Link it to the FIFO list by BS_LINK_POINTER.  */
5010
5011 static bpstat
5012 bpstat_alloc (struct bp_location *bl, bpstat **bs_link_pointer)
5013 {
5014   bpstat bs;
5015
5016   bs = (bpstat) xmalloc (sizeof (*bs));
5017   bs->next = NULL;
5018   **bs_link_pointer = bs;
5019   *bs_link_pointer = &bs->next;
5020   bs->breakpoint_at = bl->owner;
5021   bs->bp_location_at = bl;
5022   incref_bp_location (bl);
5023   /* If the condition is false, etc., don't do the commands.  */
5024   bs->commands = NULL;
5025   bs->old_val = NULL;
5026   bs->print_it = print_it_normal;
5027   return bs;
5028 }
5029 \f
5030 /* The target has stopped with waitstatus WS.  Check if any hardware
5031    watchpoints have triggered, according to the target.  */
5032
5033 int
5034 watchpoints_triggered (struct target_waitstatus *ws)
5035 {
5036   int stopped_by_watchpoint = target_stopped_by_watchpoint ();
5037   CORE_ADDR addr;
5038   struct breakpoint *b;
5039
5040   if (!stopped_by_watchpoint)
5041     {
5042       /* We were not stopped by a watchpoint.  Mark all watchpoints
5043          as not triggered.  */
5044       ALL_BREAKPOINTS (b)
5045         if (is_hardware_watchpoint (b))
5046           {
5047             struct watchpoint *w = (struct watchpoint *) b;
5048
5049             w->watchpoint_triggered = watch_triggered_no;
5050           }
5051
5052       return 0;
5053     }
5054
5055   if (!target_stopped_data_address (&current_target, &addr))
5056     {
5057       /* We were stopped by a watchpoint, but we don't know where.
5058          Mark all watchpoints as unknown.  */
5059       ALL_BREAKPOINTS (b)
5060         if (is_hardware_watchpoint (b))
5061           {
5062             struct watchpoint *w = (struct watchpoint *) b;
5063
5064             w->watchpoint_triggered = watch_triggered_unknown;
5065           }
5066
5067       return 1;
5068     }
5069
5070   /* The target could report the data address.  Mark watchpoints
5071      affected by this data address as triggered, and all others as not
5072      triggered.  */
5073
5074   ALL_BREAKPOINTS (b)
5075     if (is_hardware_watchpoint (b))
5076       {
5077         struct watchpoint *w = (struct watchpoint *) b;
5078         struct bp_location *loc;
5079
5080         w->watchpoint_triggered = watch_triggered_no;
5081         for (loc = b->loc; loc; loc = loc->next)
5082           {
5083             if (is_masked_watchpoint (b))
5084               {
5085                 CORE_ADDR newaddr = addr & w->hw_wp_mask;
5086                 CORE_ADDR start = loc->address & w->hw_wp_mask;
5087
5088                 if (newaddr == start)
5089                   {
5090                     w->watchpoint_triggered = watch_triggered_yes;
5091                     break;
5092                   }
5093               }
5094             /* Exact match not required.  Within range is sufficient.  */
5095             else if (target_watchpoint_addr_within_range (&current_target,
5096                                                          addr, loc->address,
5097                                                          loc->length))
5098               {
5099                 w->watchpoint_triggered = watch_triggered_yes;
5100                 break;
5101               }
5102           }
5103       }
5104
5105   return 1;
5106 }
5107
5108 /* Possible return values for watchpoint_check (this can't be an enum
5109    because of check_errors).  */
5110 /* The watchpoint has been deleted.  */
5111 #define WP_DELETED 1
5112 /* The value has changed.  */
5113 #define WP_VALUE_CHANGED 2
5114 /* The value has not changed.  */
5115 #define WP_VALUE_NOT_CHANGED 3
5116 /* Ignore this watchpoint, no matter if the value changed or not.  */
5117 #define WP_IGNORE 4
5118
5119 #define BP_TEMPFLAG 1
5120 #define BP_HARDWAREFLAG 2
5121
5122 /* Evaluate watchpoint condition expression and check if its value
5123    changed.
5124
5125    P should be a pointer to struct bpstat, but is defined as a void *
5126    in order for this function to be usable with catch_errors.  */
5127
5128 static int
5129 watchpoint_check (void *p)
5130 {
5131   bpstat bs = (bpstat) p;
5132   struct watchpoint *b;
5133   struct frame_info *fr;
5134   int within_current_scope;
5135
5136   /* BS is built from an existing struct breakpoint.  */
5137   gdb_assert (bs->breakpoint_at != NULL);
5138   b = (struct watchpoint *) bs->breakpoint_at;
5139
5140   /* If this is a local watchpoint, we only want to check if the
5141      watchpoint frame is in scope if the current thread is the thread
5142      that was used to create the watchpoint.  */
5143   if (!watchpoint_in_thread_scope (b))
5144     return WP_IGNORE;
5145
5146   if (b->exp_valid_block == NULL)
5147     within_current_scope = 1;
5148   else
5149     {
5150       struct frame_info *frame = get_current_frame ();
5151       struct gdbarch *frame_arch = get_frame_arch (frame);
5152       CORE_ADDR frame_pc = get_frame_pc (frame);
5153
5154       /* stack_frame_destroyed_p() returns a non-zero value if we're
5155          still in the function but the stack frame has already been
5156          invalidated.  Since we can't rely on the values of local
5157          variables after the stack has been destroyed, we are treating
5158          the watchpoint in that state as `not changed' without further
5159          checking.  Don't mark watchpoints as changed if the current
5160          frame is in an epilogue - even if they are in some other
5161          frame, our view of the stack is likely to be wrong and
5162          frame_find_by_id could error out.  */
5163       if (gdbarch_stack_frame_destroyed_p (frame_arch, frame_pc))
5164         return WP_IGNORE;
5165
5166       fr = frame_find_by_id (b->watchpoint_frame);
5167       within_current_scope = (fr != NULL);
5168
5169       /* If we've gotten confused in the unwinder, we might have
5170          returned a frame that can't describe this variable.  */
5171       if (within_current_scope)
5172         {
5173           struct symbol *function;
5174
5175           function = get_frame_function (fr);
5176           if (function == NULL
5177               || !contained_in (b->exp_valid_block,
5178                                 SYMBOL_BLOCK_VALUE (function)))
5179             within_current_scope = 0;
5180         }
5181
5182       if (within_current_scope)
5183         /* If we end up stopping, the current frame will get selected
5184            in normal_stop.  So this call to select_frame won't affect
5185            the user.  */
5186         select_frame (fr);
5187     }
5188
5189   if (within_current_scope)
5190     {
5191       /* We use value_{,free_to_}mark because it could be a *long*
5192          time before we return to the command level and call
5193          free_all_values.  We can't call free_all_values because we
5194          might be in the middle of evaluating a function call.  */
5195
5196       int pc = 0;
5197       struct value *mark;
5198       struct value *new_val;
5199
5200       if (is_masked_watchpoint (b))
5201         /* Since we don't know the exact trigger address (from
5202            stopped_data_address), just tell the user we've triggered
5203            a mask watchpoint.  */
5204         return WP_VALUE_CHANGED;
5205
5206       mark = value_mark ();
5207       fetch_subexp_value (b->exp.get (), &pc, &new_val, NULL, NULL, 0);
5208
5209       if (b->val_bitsize != 0)
5210         new_val = extract_bitfield_from_watchpoint_value (b, new_val);
5211
5212       /* We use value_equal_contents instead of value_equal because
5213          the latter coerces an array to a pointer, thus comparing just
5214          the address of the array instead of its contents.  This is
5215          not what we want.  */
5216       if ((b->val != NULL) != (new_val != NULL)
5217           || (b->val != NULL && !value_equal_contents (b->val, new_val)))
5218         {
5219           if (new_val != NULL)
5220             {
5221               release_value (new_val);
5222               value_free_to_mark (mark);
5223             }
5224           bs->old_val = b->val;
5225           b->val = new_val;
5226           b->val_valid = 1;
5227           return WP_VALUE_CHANGED;
5228         }
5229       else
5230         {
5231           /* Nothing changed.  */
5232           value_free_to_mark (mark);
5233           return WP_VALUE_NOT_CHANGED;
5234         }
5235     }
5236   else
5237     {
5238       /* This seems like the only logical thing to do because
5239          if we temporarily ignored the watchpoint, then when
5240          we reenter the block in which it is valid it contains
5241          garbage (in the case of a function, it may have two
5242          garbage values, one before and one after the prologue).
5243          So we can't even detect the first assignment to it and
5244          watch after that (since the garbage may or may not equal
5245          the first value assigned).  */
5246       /* We print all the stop information in
5247          breakpoint_ops->print_it, but in this case, by the time we
5248          call breakpoint_ops->print_it this bp will be deleted
5249          already.  So we have no choice but print the information
5250          here.  */
5251
5252       SWITCH_THRU_ALL_UIS ()
5253         {
5254           struct ui_out *uiout = current_uiout;
5255
5256           if (uiout->is_mi_like_p ())
5257             uiout->field_string
5258               ("reason", async_reason_lookup (EXEC_ASYNC_WATCHPOINT_SCOPE));
5259           uiout->text ("\nWatchpoint ");
5260           uiout->field_int ("wpnum", b->number);
5261           uiout->text (" deleted because the program has left the block in\n"
5262                        "which its expression is valid.\n");
5263         }
5264
5265       /* Make sure the watchpoint's commands aren't executed.  */
5266       decref_counted_command_line (&b->commands);
5267       watchpoint_del_at_next_stop (b);
5268
5269       return WP_DELETED;
5270     }
5271 }
5272
5273 /* Return true if it looks like target has stopped due to hitting
5274    breakpoint location BL.  This function does not check if we should
5275    stop, only if BL explains the stop.  */
5276
5277 static int
5278 bpstat_check_location (const struct bp_location *bl,
5279                        struct address_space *aspace, CORE_ADDR bp_addr,
5280                        const struct target_waitstatus *ws)
5281 {
5282   struct breakpoint *b = bl->owner;
5283
5284   /* BL is from an existing breakpoint.  */
5285   gdb_assert (b != NULL);
5286
5287   return b->ops->breakpoint_hit (bl, aspace, bp_addr, ws);
5288 }
5289
5290 /* Determine if the watched values have actually changed, and we
5291    should stop.  If not, set BS->stop to 0.  */
5292
5293 static void
5294 bpstat_check_watchpoint (bpstat bs)
5295 {
5296   const struct bp_location *bl;
5297   struct watchpoint *b;
5298
5299   /* BS is built for existing struct breakpoint.  */
5300   bl = bs->bp_location_at;
5301   gdb_assert (bl != NULL);
5302   b = (struct watchpoint *) bs->breakpoint_at;
5303   gdb_assert (b != NULL);
5304
5305     {
5306       int must_check_value = 0;
5307       
5308       if (b->type == bp_watchpoint)
5309         /* For a software watchpoint, we must always check the
5310            watched value.  */
5311         must_check_value = 1;
5312       else if (b->watchpoint_triggered == watch_triggered_yes)
5313         /* We have a hardware watchpoint (read, write, or access)
5314            and the target earlier reported an address watched by
5315            this watchpoint.  */
5316         must_check_value = 1;
5317       else if (b->watchpoint_triggered == watch_triggered_unknown
5318                && b->type == bp_hardware_watchpoint)
5319         /* We were stopped by a hardware watchpoint, but the target could
5320            not report the data address.  We must check the watchpoint's
5321            value.  Access and read watchpoints are out of luck; without
5322            a data address, we can't figure it out.  */
5323         must_check_value = 1;
5324
5325       if (must_check_value)
5326         {
5327           char *message
5328             = xstrprintf ("Error evaluating expression for watchpoint %d\n",
5329                           b->number);
5330           struct cleanup *cleanups = make_cleanup (xfree, message);
5331           int e = catch_errors (watchpoint_check, bs, message,
5332                                 RETURN_MASK_ALL);
5333           do_cleanups (cleanups);
5334           switch (e)
5335             {
5336             case WP_DELETED:
5337               /* We've already printed what needs to be printed.  */
5338               bs->print_it = print_it_done;
5339               /* Stop.  */
5340               break;
5341             case WP_IGNORE:
5342               bs->print_it = print_it_noop;
5343               bs->stop = 0;
5344               break;
5345             case WP_VALUE_CHANGED:
5346               if (b->type == bp_read_watchpoint)
5347                 {
5348                   /* There are two cases to consider here:
5349
5350                      1. We're watching the triggered memory for reads.
5351                      In that case, trust the target, and always report
5352                      the watchpoint hit to the user.  Even though
5353                      reads don't cause value changes, the value may
5354                      have changed since the last time it was read, and
5355                      since we're not trapping writes, we will not see
5356                      those, and as such we should ignore our notion of
5357                      old value.
5358
5359                      2. We're watching the triggered memory for both
5360                      reads and writes.  There are two ways this may
5361                      happen:
5362
5363                      2.1. This is a target that can't break on data
5364                      reads only, but can break on accesses (reads or
5365                      writes), such as e.g., x86.  We detect this case
5366                      at the time we try to insert read watchpoints.
5367
5368                      2.2. Otherwise, the target supports read
5369                      watchpoints, but, the user set an access or write
5370                      watchpoint watching the same memory as this read
5371                      watchpoint.
5372
5373                      If we're watching memory writes as well as reads,
5374                      ignore watchpoint hits when we find that the
5375                      value hasn't changed, as reads don't cause
5376                      changes.  This still gives false positives when
5377                      the program writes the same value to memory as
5378                      what there was already in memory (we will confuse
5379                      it for a read), but it's much better than
5380                      nothing.  */
5381
5382                   int other_write_watchpoint = 0;
5383
5384                   if (bl->watchpoint_type == hw_read)
5385                     {
5386                       struct breakpoint *other_b;
5387
5388                       ALL_BREAKPOINTS (other_b)
5389                         if (other_b->type == bp_hardware_watchpoint
5390                             || other_b->type == bp_access_watchpoint)
5391                           {
5392                             struct watchpoint *other_w =
5393                               (struct watchpoint *) other_b;
5394
5395                             if (other_w->watchpoint_triggered
5396                                 == watch_triggered_yes)
5397                               {
5398                                 other_write_watchpoint = 1;
5399                                 break;
5400                               }
5401                           }
5402                     }
5403
5404                   if (other_write_watchpoint
5405                       || bl->watchpoint_type == hw_access)
5406                     {
5407                       /* We're watching the same memory for writes,
5408                          and the value changed since the last time we
5409                          updated it, so this trap must be for a write.
5410                          Ignore it.  */
5411                       bs->print_it = print_it_noop;
5412                       bs->stop = 0;
5413                     }
5414                 }
5415               break;
5416             case WP_VALUE_NOT_CHANGED:
5417               if (b->type == bp_hardware_watchpoint
5418                   || b->type == bp_watchpoint)
5419                 {
5420                   /* Don't stop: write watchpoints shouldn't fire if
5421                      the value hasn't changed.  */
5422                   bs->print_it = print_it_noop;
5423                   bs->stop = 0;
5424                 }
5425               /* Stop.  */
5426               break;
5427             default:
5428               /* Can't happen.  */
5429             case 0:
5430               /* Error from catch_errors.  */
5431               {
5432                 SWITCH_THRU_ALL_UIS ()
5433                   {
5434                     printf_filtered (_("Watchpoint %d deleted.\n"),
5435                                      b->number);
5436                   }
5437                 watchpoint_del_at_next_stop (b);
5438                 /* We've already printed what needs to be printed.  */
5439                 bs->print_it = print_it_done;
5440               }
5441               break;
5442             }
5443         }
5444       else      /* must_check_value == 0 */
5445         {
5446           /* This is a case where some watchpoint(s) triggered, but
5447              not at the address of this watchpoint, or else no
5448              watchpoint triggered after all.  So don't print
5449              anything for this watchpoint.  */
5450           bs->print_it = print_it_noop;
5451           bs->stop = 0;
5452         }
5453     }
5454 }
5455
5456 /* For breakpoints that are currently marked as telling gdb to stop,
5457    check conditions (condition proper, frame, thread and ignore count)
5458    of breakpoint referred to by BS.  If we should not stop for this
5459    breakpoint, set BS->stop to 0.  */
5460
5461 static void
5462 bpstat_check_breakpoint_conditions (bpstat bs, ptid_t ptid)
5463 {
5464   const struct bp_location *bl;
5465   struct breakpoint *b;
5466   int value_is_zero = 0;
5467   struct expression *cond;
5468
5469   gdb_assert (bs->stop);
5470
5471   /* BS is built for existing struct breakpoint.  */
5472   bl = bs->bp_location_at;
5473   gdb_assert (bl != NULL);
5474   b = bs->breakpoint_at;
5475   gdb_assert (b != NULL);
5476
5477   /* Even if the target evaluated the condition on its end and notified GDB, we
5478      need to do so again since GDB does not know if we stopped due to a
5479      breakpoint or a single step breakpoint.  */
5480
5481   if (frame_id_p (b->frame_id)
5482       && !frame_id_eq (b->frame_id, get_stack_frame_id (get_current_frame ())))
5483     {
5484       bs->stop = 0;
5485       return;
5486     }
5487
5488   /* If this is a thread/task-specific breakpoint, don't waste cpu
5489      evaluating the condition if this isn't the specified
5490      thread/task.  */
5491   if ((b->thread != -1 && b->thread != ptid_to_global_thread_id (ptid))
5492       || (b->task != 0 && b->task != ada_get_task_number (ptid)))
5493
5494     {
5495       bs->stop = 0;
5496       return;
5497     }
5498
5499   /* Evaluate extension language breakpoints that have a "stop" method
5500      implemented.  */
5501   bs->stop = breakpoint_ext_lang_cond_says_stop (b);
5502
5503   if (is_watchpoint (b))
5504     {
5505       struct watchpoint *w = (struct watchpoint *) b;
5506
5507       cond = w->cond_exp.get ();
5508     }
5509   else
5510     cond = bl->cond.get ();
5511
5512   if (cond && b->disposition != disp_del_at_next_stop)
5513     {
5514       int within_current_scope = 1;
5515       struct watchpoint * w;
5516
5517       /* We use value_mark and value_free_to_mark because it could
5518          be a long time before we return to the command level and
5519          call free_all_values.  We can't call free_all_values
5520          because we might be in the middle of evaluating a
5521          function call.  */
5522       struct value *mark = value_mark ();
5523
5524       if (is_watchpoint (b))
5525         w = (struct watchpoint *) b;
5526       else
5527         w = NULL;
5528
5529       /* Need to select the frame, with all that implies so that
5530          the conditions will have the right context.  Because we
5531          use the frame, we will not see an inlined function's
5532          variables when we arrive at a breakpoint at the start
5533          of the inlined function; the current frame will be the
5534          call site.  */
5535       if (w == NULL || w->cond_exp_valid_block == NULL)
5536         select_frame (get_current_frame ());
5537       else
5538         {
5539           struct frame_info *frame;
5540
5541           /* For local watchpoint expressions, which particular
5542              instance of a local is being watched matters, so we
5543              keep track of the frame to evaluate the expression
5544              in.  To evaluate the condition however, it doesn't
5545              really matter which instantiation of the function
5546              where the condition makes sense triggers the
5547              watchpoint.  This allows an expression like "watch
5548              global if q > 10" set in `func', catch writes to
5549              global on all threads that call `func', or catch
5550              writes on all recursive calls of `func' by a single
5551              thread.  We simply always evaluate the condition in
5552              the innermost frame that's executing where it makes
5553              sense to evaluate the condition.  It seems
5554              intuitive.  */
5555           frame = block_innermost_frame (w->cond_exp_valid_block);
5556           if (frame != NULL)
5557             select_frame (frame);
5558           else
5559             within_current_scope = 0;
5560         }
5561       if (within_current_scope)
5562         value_is_zero
5563           = catch_errors (breakpoint_cond_eval, cond,
5564                           "Error in testing breakpoint condition:\n",
5565                           RETURN_MASK_ALL);
5566       else
5567         {
5568           warning (_("Watchpoint condition cannot be tested "
5569                      "in the current scope"));
5570           /* If we failed to set the right context for this
5571              watchpoint, unconditionally report it.  */
5572           value_is_zero = 0;
5573         }
5574       /* FIXME-someday, should give breakpoint #.  */
5575       value_free_to_mark (mark);
5576     }
5577
5578   if (cond && value_is_zero)
5579     {
5580       bs->stop = 0;
5581     }
5582   else if (b->ignore_count > 0)
5583     {
5584       b->ignore_count--;
5585       bs->stop = 0;
5586       /* Increase the hit count even though we don't stop.  */
5587       ++(b->hit_count);
5588       observer_notify_breakpoint_modified (b);
5589     }   
5590 }
5591
5592 /* Returns true if we need to track moribund locations of LOC's type
5593    on the current target.  */
5594
5595 static int
5596 need_moribund_for_location_type (struct bp_location *loc)
5597 {
5598   return ((loc->loc_type == bp_loc_software_breakpoint
5599            && !target_supports_stopped_by_sw_breakpoint ())
5600           || (loc->loc_type == bp_loc_hardware_breakpoint
5601               && !target_supports_stopped_by_hw_breakpoint ()));
5602 }
5603
5604
5605 /* Get a bpstat associated with having just stopped at address
5606    BP_ADDR in thread PTID.
5607
5608    Determine whether we stopped at a breakpoint, etc, or whether we
5609    don't understand this stop.  Result is a chain of bpstat's such
5610    that:
5611
5612    if we don't understand the stop, the result is a null pointer.
5613
5614    if we understand why we stopped, the result is not null.
5615
5616    Each element of the chain refers to a particular breakpoint or
5617    watchpoint at which we have stopped.  (We may have stopped for
5618    several reasons concurrently.)
5619
5620    Each element of the chain has valid next, breakpoint_at,
5621    commands, FIXME??? fields.  */
5622
5623 bpstat
5624 bpstat_stop_status (struct address_space *aspace,
5625                     CORE_ADDR bp_addr, ptid_t ptid,
5626                     const struct target_waitstatus *ws)
5627 {
5628   struct breakpoint *b = NULL;
5629   struct bp_location *bl;
5630   struct bp_location *loc;
5631   /* First item of allocated bpstat's.  */
5632   bpstat bs_head = NULL, *bs_link = &bs_head;
5633   /* Pointer to the last thing in the chain currently.  */
5634   bpstat bs;
5635   int ix;
5636   int need_remove_insert;
5637   int removed_any;
5638
5639   /* First, build the bpstat chain with locations that explain a
5640      target stop, while being careful to not set the target running,
5641      as that may invalidate locations (in particular watchpoint
5642      locations are recreated).  Resuming will happen here with
5643      breakpoint conditions or watchpoint expressions that include
5644      inferior function calls.  */
5645
5646   ALL_BREAKPOINTS (b)
5647     {
5648       if (!breakpoint_enabled (b))
5649         continue;
5650
5651       for (bl = b->loc; bl != NULL; bl = bl->next)
5652         {
5653           /* For hardware watchpoints, we look only at the first
5654              location.  The watchpoint_check function will work on the
5655              entire expression, not the individual locations.  For
5656              read watchpoints, the watchpoints_triggered function has
5657              checked all locations already.  */
5658           if (b->type == bp_hardware_watchpoint && bl != b->loc)
5659             break;
5660
5661           if (!bl->enabled || bl->shlib_disabled)
5662             continue;
5663
5664           if (!bpstat_check_location (bl, aspace, bp_addr, ws))
5665             continue;
5666
5667           /* Come here if it's a watchpoint, or if the break address
5668              matches.  */
5669
5670           bs = bpstat_alloc (bl, &bs_link);     /* Alloc a bpstat to
5671                                                    explain stop.  */
5672
5673           /* Assume we stop.  Should we find a watchpoint that is not
5674              actually triggered, or if the condition of the breakpoint
5675              evaluates as false, we'll reset 'stop' to 0.  */
5676           bs->stop = 1;
5677           bs->print = 1;
5678
5679           /* If this is a scope breakpoint, mark the associated
5680              watchpoint as triggered so that we will handle the
5681              out-of-scope event.  We'll get to the watchpoint next
5682              iteration.  */
5683           if (b->type == bp_watchpoint_scope && b->related_breakpoint != b)
5684             {
5685               struct watchpoint *w = (struct watchpoint *) b->related_breakpoint;
5686
5687               w->watchpoint_triggered = watch_triggered_yes;
5688             }
5689         }
5690     }
5691
5692   /* Check if a moribund breakpoint explains the stop.  */
5693   if (!target_supports_stopped_by_sw_breakpoint ()
5694       || !target_supports_stopped_by_hw_breakpoint ())
5695     {
5696       for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
5697         {
5698           if (breakpoint_location_address_match (loc, aspace, bp_addr)
5699               && need_moribund_for_location_type (loc))
5700             {
5701               bs = bpstat_alloc (loc, &bs_link);
5702               /* For hits of moribund locations, we should just proceed.  */
5703               bs->stop = 0;
5704               bs->print = 0;
5705               bs->print_it = print_it_noop;
5706             }
5707         }
5708     }
5709
5710   /* A bit of special processing for shlib breakpoints.  We need to
5711      process solib loading here, so that the lists of loaded and
5712      unloaded libraries are correct before we handle "catch load" and
5713      "catch unload".  */
5714   for (bs = bs_head; bs != NULL; bs = bs->next)
5715     {
5716       if (bs->breakpoint_at && bs->breakpoint_at->type == bp_shlib_event)
5717         {
5718           handle_solib_event ();
5719           break;
5720         }
5721     }
5722
5723   /* Now go through the locations that caused the target to stop, and
5724      check whether we're interested in reporting this stop to higher
5725      layers, or whether we should resume the target transparently.  */
5726
5727   removed_any = 0;
5728
5729   for (bs = bs_head; bs != NULL; bs = bs->next)
5730     {
5731       if (!bs->stop)
5732         continue;
5733
5734       b = bs->breakpoint_at;
5735       b->ops->check_status (bs);
5736       if (bs->stop)
5737         {
5738           bpstat_check_breakpoint_conditions (bs, ptid);
5739
5740           if (bs->stop)
5741             {
5742               ++(b->hit_count);
5743               observer_notify_breakpoint_modified (b);
5744
5745               /* We will stop here.  */
5746               if (b->disposition == disp_disable)
5747                 {
5748                   --(b->enable_count);
5749                   if (b->enable_count <= 0)
5750                     b->enable_state = bp_disabled;
5751                   removed_any = 1;
5752                 }
5753               if (b->silent)
5754                 bs->print = 0;
5755               bs->commands = b->commands;
5756               incref_counted_command_line (bs->commands);
5757               if (command_line_is_silent (bs->commands
5758                                           ? bs->commands->commands : NULL))
5759                 bs->print = 0;
5760
5761               b->ops->after_condition_true (bs);
5762             }
5763
5764         }
5765
5766       /* Print nothing for this entry if we don't stop or don't
5767          print.  */
5768       if (!bs->stop || !bs->print)
5769         bs->print_it = print_it_noop;
5770     }
5771
5772   /* If we aren't stopping, the value of some hardware watchpoint may
5773      not have changed, but the intermediate memory locations we are
5774      watching may have.  Don't bother if we're stopping; this will get
5775      done later.  */
5776   need_remove_insert = 0;
5777   if (! bpstat_causes_stop (bs_head))
5778     for (bs = bs_head; bs != NULL; bs = bs->next)
5779       if (!bs->stop
5780           && bs->breakpoint_at
5781           && is_hardware_watchpoint (bs->breakpoint_at))
5782         {
5783           struct watchpoint *w = (struct watchpoint *) bs->breakpoint_at;
5784
5785           update_watchpoint (w, 0 /* don't reparse.  */);
5786           need_remove_insert = 1;
5787         }
5788
5789   if (need_remove_insert)
5790     update_global_location_list (UGLL_MAY_INSERT);
5791   else if (removed_any)
5792     update_global_location_list (UGLL_DONT_INSERT);
5793
5794   return bs_head;
5795 }
5796
5797 static void
5798 handle_jit_event (void)
5799 {
5800   struct frame_info *frame;
5801   struct gdbarch *gdbarch;
5802
5803   if (debug_infrun)
5804     fprintf_unfiltered (gdb_stdlog, "handling bp_jit_event\n");
5805
5806   /* Switch terminal for any messages produced by
5807      breakpoint_re_set.  */
5808   target_terminal_ours_for_output ();
5809
5810   frame = get_current_frame ();
5811   gdbarch = get_frame_arch (frame);
5812
5813   jit_event_handler (gdbarch);
5814
5815   target_terminal_inferior ();
5816 }
5817
5818 /* Prepare WHAT final decision for infrun.  */
5819
5820 /* Decide what infrun needs to do with this bpstat.  */
5821
5822 struct bpstat_what
5823 bpstat_what (bpstat bs_head)
5824 {
5825   struct bpstat_what retval;
5826   bpstat bs;
5827
5828   retval.main_action = BPSTAT_WHAT_KEEP_CHECKING;
5829   retval.call_dummy = STOP_NONE;
5830   retval.is_longjmp = 0;
5831
5832   for (bs = bs_head; bs != NULL; bs = bs->next)
5833     {
5834       /* Extract this BS's action.  After processing each BS, we check
5835          if its action overrides all we've seem so far.  */
5836       enum bpstat_what_main_action this_action = BPSTAT_WHAT_KEEP_CHECKING;
5837       enum bptype bptype;
5838
5839       if (bs->breakpoint_at == NULL)
5840         {
5841           /* I suspect this can happen if it was a momentary
5842              breakpoint which has since been deleted.  */
5843           bptype = bp_none;
5844         }
5845       else
5846         bptype = bs->breakpoint_at->type;
5847
5848       switch (bptype)
5849         {
5850         case bp_none:
5851           break;
5852         case bp_breakpoint:
5853         case bp_hardware_breakpoint:
5854         case bp_single_step:
5855         case bp_until:
5856         case bp_finish:
5857         case bp_shlib_event:
5858           if (bs->stop)
5859             {
5860               if (bs->print)
5861                 this_action = BPSTAT_WHAT_STOP_NOISY;
5862               else
5863                 this_action = BPSTAT_WHAT_STOP_SILENT;
5864             }
5865           else
5866             this_action = BPSTAT_WHAT_SINGLE;
5867           break;
5868         case bp_watchpoint:
5869         case bp_hardware_watchpoint:
5870         case bp_read_watchpoint:
5871         case bp_access_watchpoint:
5872           if (bs->stop)
5873             {
5874               if (bs->print)
5875                 this_action = BPSTAT_WHAT_STOP_NOISY;
5876               else
5877                 this_action = BPSTAT_WHAT_STOP_SILENT;
5878             }
5879           else
5880             {
5881               /* There was a watchpoint, but we're not stopping.
5882                  This requires no further action.  */
5883             }
5884           break;
5885         case bp_longjmp:
5886         case bp_longjmp_call_dummy:
5887         case bp_exception:
5888           if (bs->stop)
5889             {
5890               this_action = BPSTAT_WHAT_SET_LONGJMP_RESUME;
5891               retval.is_longjmp = bptype != bp_exception;
5892             }
5893           else
5894             this_action = BPSTAT_WHAT_SINGLE;
5895           break;
5896         case bp_longjmp_resume:
5897         case bp_exception_resume:
5898           if (bs->stop)
5899             {
5900               this_action = BPSTAT_WHAT_CLEAR_LONGJMP_RESUME;
5901               retval.is_longjmp = bptype == bp_longjmp_resume;
5902             }
5903           else
5904             this_action = BPSTAT_WHAT_SINGLE;
5905           break;
5906         case bp_step_resume:
5907           if (bs->stop)
5908             this_action = BPSTAT_WHAT_STEP_RESUME;
5909           else
5910             {
5911               /* It is for the wrong frame.  */
5912               this_action = BPSTAT_WHAT_SINGLE;
5913             }
5914           break;
5915         case bp_hp_step_resume:
5916           if (bs->stop)
5917             this_action = BPSTAT_WHAT_HP_STEP_RESUME;
5918           else
5919             {
5920               /* It is for the wrong frame.  */
5921               this_action = BPSTAT_WHAT_SINGLE;
5922             }
5923           break;
5924         case bp_watchpoint_scope:
5925         case bp_thread_event:
5926         case bp_overlay_event:
5927         case bp_longjmp_master:
5928         case bp_std_terminate_master:
5929         case bp_exception_master:
5930           this_action = BPSTAT_WHAT_SINGLE;
5931           break;
5932         case bp_catchpoint:
5933           if (bs->stop)
5934             {
5935               if (bs->print)
5936                 this_action = BPSTAT_WHAT_STOP_NOISY;
5937               else
5938                 this_action = BPSTAT_WHAT_STOP_SILENT;
5939             }
5940           else
5941             {
5942               /* There was a catchpoint, but we're not stopping.
5943                  This requires no further action.  */
5944             }
5945           break;
5946         case bp_jit_event:
5947           this_action = BPSTAT_WHAT_SINGLE;
5948           break;
5949         case bp_call_dummy:
5950           /* Make sure the action is stop (silent or noisy),
5951              so infrun.c pops the dummy frame.  */
5952           retval.call_dummy = STOP_STACK_DUMMY;
5953           this_action = BPSTAT_WHAT_STOP_SILENT;
5954           break;
5955         case bp_std_terminate:
5956           /* Make sure the action is stop (silent or noisy),
5957              so infrun.c pops the dummy frame.  */
5958           retval.call_dummy = STOP_STD_TERMINATE;
5959           this_action = BPSTAT_WHAT_STOP_SILENT;
5960           break;
5961         case bp_tracepoint:
5962         case bp_fast_tracepoint:
5963         case bp_static_tracepoint:
5964           /* Tracepoint hits should not be reported back to GDB, and
5965              if one got through somehow, it should have been filtered
5966              out already.  */
5967           internal_error (__FILE__, __LINE__,
5968                           _("bpstat_what: tracepoint encountered"));
5969           break;
5970         case bp_gnu_ifunc_resolver:
5971           /* Step over it (and insert bp_gnu_ifunc_resolver_return).  */
5972           this_action = BPSTAT_WHAT_SINGLE;
5973           break;
5974         case bp_gnu_ifunc_resolver_return:
5975           /* The breakpoint will be removed, execution will restart from the
5976              PC of the former breakpoint.  */
5977           this_action = BPSTAT_WHAT_KEEP_CHECKING;
5978           break;
5979
5980         case bp_dprintf:
5981           if (bs->stop)
5982             this_action = BPSTAT_WHAT_STOP_SILENT;
5983           else
5984             this_action = BPSTAT_WHAT_SINGLE;
5985           break;
5986
5987         default:
5988           internal_error (__FILE__, __LINE__,
5989                           _("bpstat_what: unhandled bptype %d"), (int) bptype);
5990         }
5991
5992       retval.main_action = std::max (retval.main_action, this_action);
5993     }
5994
5995   return retval;
5996 }
5997
5998 void
5999 bpstat_run_callbacks (bpstat bs_head)
6000 {
6001   bpstat bs;
6002
6003   for (bs = bs_head; bs != NULL; bs = bs->next)
6004     {
6005       struct breakpoint *b = bs->breakpoint_at;
6006
6007       if (b == NULL)
6008         continue;
6009       switch (b->type)
6010         {
6011         case bp_jit_event:
6012           handle_jit_event ();
6013           break;
6014         case bp_gnu_ifunc_resolver:
6015           gnu_ifunc_resolver_stop (b);
6016           break;
6017         case bp_gnu_ifunc_resolver_return:
6018           gnu_ifunc_resolver_return_stop (b);
6019           break;
6020         }
6021     }
6022 }
6023
6024 /* Nonzero if we should step constantly (e.g. watchpoints on machines
6025    without hardware support).  This isn't related to a specific bpstat,
6026    just to things like whether watchpoints are set.  */
6027
6028 int
6029 bpstat_should_step (void)
6030 {
6031   struct breakpoint *b;
6032
6033   ALL_BREAKPOINTS (b)
6034     if (breakpoint_enabled (b) && b->type == bp_watchpoint && b->loc != NULL)
6035       return 1;
6036   return 0;
6037 }
6038
6039 int
6040 bpstat_causes_stop (bpstat bs)
6041 {
6042   for (; bs != NULL; bs = bs->next)
6043     if (bs->stop)
6044       return 1;
6045
6046   return 0;
6047 }
6048
6049 \f
6050
6051 /* Compute a string of spaces suitable to indent the next line
6052    so it starts at the position corresponding to the table column
6053    named COL_NAME in the currently active table of UIOUT.  */
6054
6055 static char *
6056 wrap_indent_at_field (struct ui_out *uiout, const char *col_name)
6057 {
6058   static char wrap_indent[80];
6059   int i, total_width, width, align;
6060   const char *text;
6061
6062   total_width = 0;
6063   for (i = 1; uiout->query_table_field (i, &width, &align, &text); i++)
6064     {
6065       if (strcmp (text, col_name) == 0)
6066         {
6067           gdb_assert (total_width < sizeof wrap_indent);
6068           memset (wrap_indent, ' ', total_width);
6069           wrap_indent[total_width] = 0;
6070
6071           return wrap_indent;
6072         }
6073
6074       total_width += width + 1;
6075     }
6076
6077   return NULL;
6078 }
6079
6080 /* Determine if the locations of this breakpoint will have their conditions
6081    evaluated by the target, host or a mix of both.  Returns the following:
6082
6083     "host": Host evals condition.
6084     "host or target": Host or Target evals condition.
6085     "target": Target evals condition.
6086 */
6087
6088 static const char *
6089 bp_condition_evaluator (struct breakpoint *b)
6090 {
6091   struct bp_location *bl;
6092   char host_evals = 0;
6093   char target_evals = 0;
6094
6095   if (!b)
6096     return NULL;
6097
6098   if (!is_breakpoint (b))
6099     return NULL;
6100
6101   if (gdb_evaluates_breakpoint_condition_p ()
6102       || !target_supports_evaluation_of_breakpoint_conditions ())
6103     return condition_evaluation_host;
6104
6105   for (bl = b->loc; bl; bl = bl->next)
6106     {
6107       if (bl->cond_bytecode)
6108         target_evals++;
6109       else
6110         host_evals++;
6111     }
6112
6113   if (host_evals && target_evals)
6114     return condition_evaluation_both;
6115   else if (target_evals)
6116     return condition_evaluation_target;
6117   else
6118     return condition_evaluation_host;
6119 }
6120
6121 /* Determine the breakpoint location's condition evaluator.  This is
6122    similar to bp_condition_evaluator, but for locations.  */
6123
6124 static const char *
6125 bp_location_condition_evaluator (struct bp_location *bl)
6126 {
6127   if (bl && !is_breakpoint (bl->owner))
6128     return NULL;
6129
6130   if (gdb_evaluates_breakpoint_condition_p ()
6131       || !target_supports_evaluation_of_breakpoint_conditions ())
6132     return condition_evaluation_host;
6133
6134   if (bl && bl->cond_bytecode)
6135     return condition_evaluation_target;
6136   else
6137     return condition_evaluation_host;
6138 }
6139
6140 /* Print the LOC location out of the list of B->LOC locations.  */
6141
6142 static void
6143 print_breakpoint_location (struct breakpoint *b,
6144                            struct bp_location *loc)
6145 {
6146   struct ui_out *uiout = current_uiout;
6147
6148   scoped_restore_current_program_space restore_pspace;
6149
6150   if (loc != NULL && loc->shlib_disabled)
6151     loc = NULL;
6152
6153   if (loc != NULL)
6154     set_current_program_space (loc->pspace);
6155
6156   if (b->display_canonical)
6157     uiout->field_string ("what", event_location_to_string (b->location.get ()));
6158   else if (loc && loc->symtab)
6159     {
6160       struct symbol *sym 
6161         = find_pc_sect_function (loc->address, loc->section);
6162       if (sym)
6163         {
6164           uiout->text ("in ");
6165           uiout->field_string ("func", SYMBOL_PRINT_NAME (sym));
6166           uiout->text (" ");
6167           uiout->wrap_hint (wrap_indent_at_field (uiout, "what"));
6168           uiout->text ("at ");
6169         }
6170       uiout->field_string ("file",
6171                            symtab_to_filename_for_display (loc->symtab));
6172       uiout->text (":");
6173
6174       if (uiout->is_mi_like_p ())
6175         uiout->field_string ("fullname", symtab_to_fullname (loc->symtab));
6176       
6177       uiout->field_int ("line", loc->line_number);
6178     }
6179   else if (loc)
6180     {
6181       string_file stb;
6182
6183       print_address_symbolic (loc->gdbarch, loc->address, &stb,
6184                               demangle, "");
6185       uiout->field_stream ("at", stb);
6186     }
6187   else
6188     {
6189       uiout->field_string ("pending",
6190                            event_location_to_string (b->location.get ()));
6191       /* If extra_string is available, it could be holding a condition
6192          or dprintf arguments.  In either case, make sure it is printed,
6193          too, but only for non-MI streams.  */
6194       if (!uiout->is_mi_like_p () && b->extra_string != NULL)
6195         {
6196           if (b->type == bp_dprintf)
6197             uiout->text (",");
6198           else
6199             uiout->text (" ");
6200           uiout->text (b->extra_string);
6201         }
6202     }
6203
6204   if (loc && is_breakpoint (b)
6205       && breakpoint_condition_evaluation_mode () == condition_evaluation_target
6206       && bp_condition_evaluator (b) == condition_evaluation_both)
6207     {
6208       uiout->text (" (");
6209       uiout->field_string ("evaluated-by",
6210                            bp_location_condition_evaluator (loc));
6211       uiout->text (")");
6212     }
6213 }
6214
6215 static const char *
6216 bptype_string (enum bptype type)
6217 {
6218   struct ep_type_description
6219     {
6220       enum bptype type;
6221       const char *description;
6222     };
6223   static struct ep_type_description bptypes[] =
6224   {
6225     {bp_none, "?deleted?"},
6226     {bp_breakpoint, "breakpoint"},
6227     {bp_hardware_breakpoint, "hw breakpoint"},
6228     {bp_single_step, "sw single-step"},
6229     {bp_until, "until"},
6230     {bp_finish, "finish"},
6231     {bp_watchpoint, "watchpoint"},
6232     {bp_hardware_watchpoint, "hw watchpoint"},
6233     {bp_read_watchpoint, "read watchpoint"},
6234     {bp_access_watchpoint, "acc watchpoint"},
6235     {bp_longjmp, "longjmp"},
6236     {bp_longjmp_resume, "longjmp resume"},
6237     {bp_longjmp_call_dummy, "longjmp for call dummy"},
6238     {bp_exception, "exception"},
6239     {bp_exception_resume, "exception resume"},
6240     {bp_step_resume, "step resume"},
6241     {bp_hp_step_resume, "high-priority step resume"},
6242     {bp_watchpoint_scope, "watchpoint scope"},
6243     {bp_call_dummy, "call dummy"},
6244     {bp_std_terminate, "std::terminate"},
6245     {bp_shlib_event, "shlib events"},
6246     {bp_thread_event, "thread events"},
6247     {bp_overlay_event, "overlay events"},
6248     {bp_longjmp_master, "longjmp master"},
6249     {bp_std_terminate_master, "std::terminate master"},
6250     {bp_exception_master, "exception master"},
6251     {bp_catchpoint, "catchpoint"},
6252     {bp_tracepoint, "tracepoint"},
6253     {bp_fast_tracepoint, "fast tracepoint"},
6254     {bp_static_tracepoint, "static tracepoint"},
6255     {bp_dprintf, "dprintf"},
6256     {bp_jit_event, "jit events"},
6257     {bp_gnu_ifunc_resolver, "STT_GNU_IFUNC resolver"},
6258     {bp_gnu_ifunc_resolver_return, "STT_GNU_IFUNC resolver return"},
6259   };
6260
6261   if (((int) type >= (sizeof (bptypes) / sizeof (bptypes[0])))
6262       || ((int) type != bptypes[(int) type].type))
6263     internal_error (__FILE__, __LINE__,
6264                     _("bptypes table does not describe type #%d."),
6265                     (int) type);
6266
6267   return bptypes[(int) type].description;
6268 }
6269
6270 /* For MI, output a field named 'thread-groups' with a list as the value.
6271    For CLI, prefix the list with the string 'inf'. */
6272
6273 static void
6274 output_thread_groups (struct ui_out *uiout,
6275                       const char *field_name,
6276                       VEC(int) *inf_num,
6277                       int mi_only)
6278 {
6279   int is_mi = uiout->is_mi_like_p ();
6280   int inf;
6281   int i;
6282
6283   /* For backward compatibility, don't display inferiors in CLI unless
6284      there are several.  Always display them for MI. */
6285   if (!is_mi && mi_only)
6286     return;
6287
6288   ui_out_emit_list list_emitter (uiout, field_name);
6289
6290   for (i = 0; VEC_iterate (int, inf_num, i, inf); ++i)
6291     {
6292       if (is_mi)
6293         {
6294           char mi_group[10];
6295
6296           xsnprintf (mi_group, sizeof (mi_group), "i%d", inf);
6297           uiout->field_string (NULL, mi_group);
6298         }
6299       else
6300         {
6301           if (i == 0)
6302             uiout->text (" inf ");
6303           else
6304             uiout->text (", ");
6305         
6306           uiout->text (plongest (inf));
6307         }
6308     }
6309 }
6310
6311 /* Print B to gdb_stdout.  */
6312
6313 static void
6314 print_one_breakpoint_location (struct breakpoint *b,
6315                                struct bp_location *loc,
6316                                int loc_number,
6317                                struct bp_location **last_loc,
6318                                int allflag)
6319 {
6320   struct command_line *l;
6321   static char bpenables[] = "nynny";
6322
6323   struct ui_out *uiout = current_uiout;
6324   int header_of_multiple = 0;
6325   int part_of_multiple = (loc != NULL);
6326   struct value_print_options opts;
6327
6328   get_user_print_options (&opts);
6329
6330   gdb_assert (!loc || loc_number != 0);
6331   /* See comment in print_one_breakpoint concerning treatment of
6332      breakpoints with single disabled location.  */
6333   if (loc == NULL 
6334       && (b->loc != NULL 
6335           && (b->loc->next != NULL || !b->loc->enabled)))
6336     header_of_multiple = 1;
6337   if (loc == NULL)
6338     loc = b->loc;
6339
6340   annotate_record ();
6341
6342   /* 1 */
6343   annotate_field (0);
6344   if (part_of_multiple)
6345     {
6346       char *formatted;
6347       formatted = xstrprintf ("%d.%d", b->number, loc_number);
6348       uiout->field_string ("number", formatted);
6349       xfree (formatted);
6350     }
6351   else
6352     {
6353       uiout->field_int ("number", b->number);
6354     }
6355
6356   /* 2 */
6357   annotate_field (1);
6358   if (part_of_multiple)
6359     uiout->field_skip ("type");
6360   else
6361     uiout->field_string ("type", bptype_string (b->type));
6362
6363   /* 3 */
6364   annotate_field (2);
6365   if (part_of_multiple)
6366     uiout->field_skip ("disp");
6367   else
6368     uiout->field_string ("disp", bpdisp_text (b->disposition));
6369
6370
6371   /* 4 */
6372   annotate_field (3);
6373   if (part_of_multiple)
6374     uiout->field_string ("enabled", loc->enabled ? "y" : "n");
6375   else
6376     uiout->field_fmt ("enabled", "%c", bpenables[(int) b->enable_state]);
6377   uiout->spaces (2);
6378
6379   
6380   /* 5 and 6 */
6381   if (b->ops != NULL && b->ops->print_one != NULL)
6382     {
6383       /* Although the print_one can possibly print all locations,
6384          calling it here is not likely to get any nice result.  So,
6385          make sure there's just one location.  */
6386       gdb_assert (b->loc == NULL || b->loc->next == NULL);
6387       b->ops->print_one (b, last_loc);
6388     }
6389   else
6390     switch (b->type)
6391       {
6392       case bp_none:
6393         internal_error (__FILE__, __LINE__,
6394                         _("print_one_breakpoint: bp_none encountered\n"));
6395         break;
6396
6397       case bp_watchpoint:
6398       case bp_hardware_watchpoint:
6399       case bp_read_watchpoint:
6400       case bp_access_watchpoint:
6401         {
6402           struct watchpoint *w = (struct watchpoint *) b;
6403
6404           /* Field 4, the address, is omitted (which makes the columns
6405              not line up too nicely with the headers, but the effect
6406              is relatively readable).  */
6407           if (opts.addressprint)
6408             uiout->field_skip ("addr");
6409           annotate_field (5);
6410           uiout->field_string ("what", w->exp_string);
6411         }
6412         break;
6413
6414       case bp_breakpoint:
6415       case bp_hardware_breakpoint:
6416       case bp_single_step:
6417       case bp_until:
6418       case bp_finish:
6419       case bp_longjmp:
6420       case bp_longjmp_resume:
6421       case bp_longjmp_call_dummy:
6422       case bp_exception:
6423       case bp_exception_resume:
6424       case bp_step_resume:
6425       case bp_hp_step_resume:
6426       case bp_watchpoint_scope:
6427       case bp_call_dummy:
6428       case bp_std_terminate:
6429       case bp_shlib_event:
6430       case bp_thread_event:
6431       case bp_overlay_event:
6432       case bp_longjmp_master:
6433       case bp_std_terminate_master:
6434       case bp_exception_master:
6435       case bp_tracepoint:
6436       case bp_fast_tracepoint:
6437       case bp_static_tracepoint:
6438       case bp_dprintf:
6439       case bp_jit_event:
6440       case bp_gnu_ifunc_resolver:
6441       case bp_gnu_ifunc_resolver_return:
6442         if (opts.addressprint)
6443           {
6444             annotate_field (4);
6445             if (header_of_multiple)
6446               uiout->field_string ("addr", "<MULTIPLE>");
6447             else if (b->loc == NULL || loc->shlib_disabled)
6448               uiout->field_string ("addr", "<PENDING>");
6449             else
6450               uiout->field_core_addr ("addr",
6451                                       loc->gdbarch, loc->address);
6452           }
6453         annotate_field (5);
6454         if (!header_of_multiple)
6455           print_breakpoint_location (b, loc);
6456         if (b->loc)
6457           *last_loc = b->loc;
6458         break;
6459       }
6460
6461
6462   if (loc != NULL && !header_of_multiple)
6463     {
6464       struct inferior *inf;
6465       VEC(int) *inf_num = NULL;
6466       int mi_only = 1;
6467
6468       ALL_INFERIORS (inf)
6469         {
6470           if (inf->pspace == loc->pspace)
6471             VEC_safe_push (int, inf_num, inf->num);
6472         }
6473
6474         /* For backward compatibility, don't display inferiors in CLI unless
6475            there are several.  Always display for MI. */
6476         if (allflag
6477             || (!gdbarch_has_global_breakpoints (target_gdbarch ())
6478                 && (number_of_program_spaces () > 1
6479                     || number_of_inferiors () > 1)
6480                 /* LOC is for existing B, it cannot be in
6481                    moribund_locations and thus having NULL OWNER.  */
6482                 && loc->owner->type != bp_catchpoint))
6483         mi_only = 0;
6484       output_thread_groups (uiout, "thread-groups", inf_num, mi_only);
6485       VEC_free (int, inf_num);
6486     }
6487
6488   if (!part_of_multiple)
6489     {
6490       if (b->thread != -1)
6491         {
6492           /* FIXME: This seems to be redundant and lost here; see the
6493              "stop only in" line a little further down.  */
6494           uiout->text (" thread ");
6495           uiout->field_int ("thread", b->thread);
6496         }
6497       else if (b->task != 0)
6498         {
6499           uiout->text (" task ");
6500           uiout->field_int ("task", b->task);
6501         }
6502     }
6503
6504   uiout->text ("\n");
6505
6506   if (!part_of_multiple)
6507     b->ops->print_one_detail (b, uiout);
6508
6509   if (part_of_multiple && frame_id_p (b->frame_id))
6510     {
6511       annotate_field (6);
6512       uiout->text ("\tstop only in stack frame at ");
6513       /* FIXME: cagney/2002-12-01: Shouldn't be poking around inside
6514          the frame ID.  */
6515       uiout->field_core_addr ("frame",
6516                               b->gdbarch, b->frame_id.stack_addr);
6517       uiout->text ("\n");
6518     }
6519   
6520   if (!part_of_multiple && b->cond_string)
6521     {
6522       annotate_field (7);
6523       if (is_tracepoint (b))
6524         uiout->text ("\ttrace only if ");
6525       else
6526         uiout->text ("\tstop only if ");
6527       uiout->field_string ("cond", b->cond_string);
6528
6529       /* Print whether the target is doing the breakpoint's condition
6530          evaluation.  If GDB is doing the evaluation, don't print anything.  */
6531       if (is_breakpoint (b)
6532           && breakpoint_condition_evaluation_mode ()
6533           == condition_evaluation_target)
6534         {
6535           uiout->text (" (");
6536           uiout->field_string ("evaluated-by",
6537                                bp_condition_evaluator (b));
6538           uiout->text (" evals)");
6539         }
6540       uiout->text ("\n");
6541     }
6542
6543   if (!part_of_multiple && b->thread != -1)
6544     {
6545       /* FIXME should make an annotation for this.  */
6546       uiout->text ("\tstop only in thread ");
6547       if (uiout->is_mi_like_p ())
6548         uiout->field_int ("thread", b->thread);
6549       else
6550         {
6551           struct thread_info *thr = find_thread_global_id (b->thread);
6552
6553           uiout->field_string ("thread", print_thread_id (thr));
6554         }
6555       uiout->text ("\n");
6556     }
6557   
6558   if (!part_of_multiple)
6559     {
6560       if (b->hit_count)
6561         {
6562           /* FIXME should make an annotation for this.  */
6563           if (is_catchpoint (b))
6564             uiout->text ("\tcatchpoint");
6565           else if (is_tracepoint (b))
6566             uiout->text ("\ttracepoint");
6567           else
6568             uiout->text ("\tbreakpoint");
6569           uiout->text (" already hit ");
6570           uiout->field_int ("times", b->hit_count);
6571           if (b->hit_count == 1)
6572             uiout->text (" time\n");
6573           else
6574             uiout->text (" times\n");
6575         }
6576       else
6577         {
6578           /* Output the count also if it is zero, but only if this is mi.  */
6579           if (uiout->is_mi_like_p ())
6580             uiout->field_int ("times", b->hit_count);
6581         }
6582     }
6583
6584   if (!part_of_multiple && b->ignore_count)
6585     {
6586       annotate_field (8);
6587       uiout->text ("\tignore next ");
6588       uiout->field_int ("ignore", b->ignore_count);
6589       uiout->text (" hits\n");
6590     }
6591
6592   /* Note that an enable count of 1 corresponds to "enable once"
6593      behavior, which is reported by the combination of enablement and
6594      disposition, so we don't need to mention it here.  */
6595   if (!part_of_multiple && b->enable_count > 1)
6596     {
6597       annotate_field (8);
6598       uiout->text ("\tdisable after ");
6599       /* Tweak the wording to clarify that ignore and enable counts
6600          are distinct, and have additive effect.  */
6601       if (b->ignore_count)
6602         uiout->text ("additional ");
6603       else
6604         uiout->text ("next ");
6605       uiout->field_int ("enable", b->enable_count);
6606       uiout->text (" hits\n");
6607     }
6608
6609   if (!part_of_multiple && is_tracepoint (b))
6610     {
6611       struct tracepoint *tp = (struct tracepoint *) b;
6612
6613       if (tp->traceframe_usage)
6614         {
6615           uiout->text ("\ttrace buffer usage ");
6616           uiout->field_int ("traceframe-usage", tp->traceframe_usage);
6617           uiout->text (" bytes\n");
6618         }
6619     }
6620
6621   l = b->commands ? b->commands->commands : NULL;
6622   if (!part_of_multiple && l)
6623     {
6624       annotate_field (9);
6625       ui_out_emit_tuple tuple_emitter (uiout, "script");
6626       print_command_lines (uiout, l, 4);
6627     }
6628
6629   if (is_tracepoint (b))
6630     {
6631       struct tracepoint *t = (struct tracepoint *) b;
6632
6633       if (!part_of_multiple && t->pass_count)
6634         {
6635           annotate_field (10);
6636           uiout->text ("\tpass count ");
6637           uiout->field_int ("pass", t->pass_count);
6638           uiout->text (" \n");
6639         }
6640
6641       /* Don't display it when tracepoint or tracepoint location is
6642          pending.   */
6643       if (!header_of_multiple && loc != NULL && !loc->shlib_disabled)
6644         {
6645           annotate_field (11);
6646
6647           if (uiout->is_mi_like_p ())
6648             uiout->field_string ("installed",
6649                                  loc->inserted ? "y" : "n");
6650           else
6651             {
6652               if (loc->inserted)
6653                 uiout->text ("\t");
6654               else
6655                 uiout->text ("\tnot ");
6656               uiout->text ("installed on target\n");
6657             }
6658         }
6659     }
6660
6661   if (uiout->is_mi_like_p () && !part_of_multiple)
6662     {
6663       if (is_watchpoint (b))
6664         {
6665           struct watchpoint *w = (struct watchpoint *) b;
6666
6667           uiout->field_string ("original-location", w->exp_string);
6668         }
6669       else if (b->location != NULL
6670                && event_location_to_string (b->location.get ()) != NULL)
6671         uiout->field_string ("original-location",
6672                              event_location_to_string (b->location.get ()));
6673     }
6674 }
6675
6676 static void
6677 print_one_breakpoint (struct breakpoint *b,
6678                       struct bp_location **last_loc, 
6679                       int allflag)
6680 {
6681   struct ui_out *uiout = current_uiout;
6682
6683   {
6684     ui_out_emit_tuple tuple_emitter (uiout, "bkpt");
6685
6686     print_one_breakpoint_location (b, NULL, 0, last_loc, allflag);
6687   }
6688
6689   /* If this breakpoint has custom print function,
6690      it's already printed.  Otherwise, print individual
6691      locations, if any.  */
6692   if (b->ops == NULL || b->ops->print_one == NULL)
6693     {
6694       /* If breakpoint has a single location that is disabled, we
6695          print it as if it had several locations, since otherwise it's
6696          hard to represent "breakpoint enabled, location disabled"
6697          situation.
6698
6699          Note that while hardware watchpoints have several locations
6700          internally, that's not a property exposed to user.  */
6701       if (b->loc 
6702           && !is_hardware_watchpoint (b)
6703           && (b->loc->next || !b->loc->enabled))
6704         {
6705           struct bp_location *loc;
6706           int n = 1;
6707
6708           for (loc = b->loc; loc; loc = loc->next, ++n)
6709             {
6710               ui_out_emit_tuple tuple_emitter (uiout, NULL);
6711               print_one_breakpoint_location (b, loc, n, last_loc, allflag);
6712             }
6713         }
6714     }
6715 }
6716
6717 static int
6718 breakpoint_address_bits (struct breakpoint *b)
6719 {
6720   int print_address_bits = 0;
6721   struct bp_location *loc;
6722
6723   /* Software watchpoints that aren't watching memory don't have an
6724      address to print.  */
6725   if (is_no_memory_software_watchpoint (b))
6726     return 0;
6727
6728   for (loc = b->loc; loc; loc = loc->next)
6729     {
6730       int addr_bit;
6731
6732       addr_bit = gdbarch_addr_bit (loc->gdbarch);
6733       if (addr_bit > print_address_bits)
6734         print_address_bits = addr_bit;
6735     }
6736
6737   return print_address_bits;
6738 }
6739
6740 struct captured_breakpoint_query_args
6741   {
6742     int bnum;
6743   };
6744
6745 static int
6746 do_captured_breakpoint_query (struct ui_out *uiout, void *data)
6747 {
6748   struct captured_breakpoint_query_args *args
6749     = (struct captured_breakpoint_query_args *) data;
6750   struct breakpoint *b;
6751   struct bp_location *dummy_loc = NULL;
6752
6753   ALL_BREAKPOINTS (b)
6754     {
6755       if (args->bnum == b->number)
6756         {
6757           print_one_breakpoint (b, &dummy_loc, 0);
6758           return GDB_RC_OK;
6759         }
6760     }
6761   return GDB_RC_NONE;
6762 }
6763
6764 enum gdb_rc
6765 gdb_breakpoint_query (struct ui_out *uiout, int bnum, 
6766                       char **error_message)
6767 {
6768   struct captured_breakpoint_query_args args;
6769
6770   args.bnum = bnum;
6771   /* For the moment we don't trust print_one_breakpoint() to not throw
6772      an error.  */
6773   if (catch_exceptions_with_msg (uiout, do_captured_breakpoint_query, &args,
6774                                  error_message, RETURN_MASK_ALL) < 0)
6775     return GDB_RC_FAIL;
6776   else
6777     return GDB_RC_OK;
6778 }
6779
6780 /* Return true if this breakpoint was set by the user, false if it is
6781    internal or momentary.  */
6782
6783 int
6784 user_breakpoint_p (struct breakpoint *b)
6785 {
6786   return b->number > 0;
6787 }
6788
6789 /* See breakpoint.h.  */
6790
6791 int
6792 pending_breakpoint_p (struct breakpoint *b)
6793 {
6794   return b->loc == NULL;
6795 }
6796
6797 /* Print information on user settable breakpoint (watchpoint, etc)
6798    number BNUM.  If BNUM is -1 print all user-settable breakpoints.
6799    If ALLFLAG is non-zero, include non-user-settable breakpoints.  If
6800    FILTER is non-NULL, call it on each breakpoint and only include the
6801    ones for which it returns non-zero.  Return the total number of
6802    breakpoints listed.  */
6803
6804 static int
6805 breakpoint_1 (char *args, int allflag, 
6806               int (*filter) (const struct breakpoint *))
6807 {
6808   struct breakpoint *b;
6809   struct bp_location *last_loc = NULL;
6810   int nr_printable_breakpoints;
6811   struct value_print_options opts;
6812   int print_address_bits = 0;
6813   int print_type_col_width = 14;
6814   struct ui_out *uiout = current_uiout;
6815
6816   get_user_print_options (&opts);
6817
6818   /* Compute the number of rows in the table, as well as the size
6819      required for address fields.  */
6820   nr_printable_breakpoints = 0;
6821   ALL_BREAKPOINTS (b)
6822     {
6823       /* If we have a filter, only list the breakpoints it accepts.  */
6824       if (filter && !filter (b))
6825         continue;
6826
6827       /* If we have an "args" string, it is a list of breakpoints to 
6828          accept.  Skip the others.  */
6829       if (args != NULL && *args != '\0')
6830         {
6831           if (allflag && parse_and_eval_long (args) != b->number)
6832             continue;
6833           if (!allflag && !number_is_in_list (args, b->number))
6834             continue;
6835         }
6836
6837       if (allflag || user_breakpoint_p (b))
6838         {
6839           int addr_bit, type_len;
6840
6841           addr_bit = breakpoint_address_bits (b);
6842           if (addr_bit > print_address_bits)
6843             print_address_bits = addr_bit;
6844
6845           type_len = strlen (bptype_string (b->type));
6846           if (type_len > print_type_col_width)
6847             print_type_col_width = type_len;
6848
6849           nr_printable_breakpoints++;
6850         }
6851     }
6852
6853   {
6854     ui_out_emit_table table_emitter (uiout,
6855                                      opts.addressprint ? 6 : 5,
6856                                      nr_printable_breakpoints,
6857                                      "BreakpointTable");
6858
6859     if (nr_printable_breakpoints > 0)
6860       annotate_breakpoints_headers ();
6861     if (nr_printable_breakpoints > 0)
6862       annotate_field (0);
6863     uiout->table_header (7, ui_left, "number", "Num"); /* 1 */
6864     if (nr_printable_breakpoints > 0)
6865       annotate_field (1);
6866     uiout->table_header (print_type_col_width, ui_left, "type", "Type"); /* 2 */
6867     if (nr_printable_breakpoints > 0)
6868       annotate_field (2);
6869     uiout->table_header (4, ui_left, "disp", "Disp"); /* 3 */
6870     if (nr_printable_breakpoints > 0)
6871       annotate_field (3);
6872     uiout->table_header (3, ui_left, "enabled", "Enb"); /* 4 */
6873     if (opts.addressprint)
6874       {
6875         if (nr_printable_breakpoints > 0)
6876           annotate_field (4);
6877         if (print_address_bits <= 32)
6878           uiout->table_header (10, ui_left, "addr", "Address"); /* 5 */
6879         else
6880           uiout->table_header (18, ui_left, "addr", "Address"); /* 5 */
6881       }
6882     if (nr_printable_breakpoints > 0)
6883       annotate_field (5);
6884     uiout->table_header (40, ui_noalign, "what", "What"); /* 6 */
6885     uiout->table_body ();
6886     if (nr_printable_breakpoints > 0)
6887       annotate_breakpoints_table ();
6888
6889     ALL_BREAKPOINTS (b)
6890       {
6891         QUIT;
6892         /* If we have a filter, only list the breakpoints it accepts.  */
6893         if (filter && !filter (b))
6894           continue;
6895
6896         /* If we have an "args" string, it is a list of breakpoints to 
6897            accept.  Skip the others.  */
6898
6899         if (args != NULL && *args != '\0')
6900           {
6901             if (allflag)        /* maintenance info breakpoint */
6902               {
6903                 if (parse_and_eval_long (args) != b->number)
6904                   continue;
6905               }
6906             else                /* all others */
6907               {
6908                 if (!number_is_in_list (args, b->number))
6909                   continue;
6910               }
6911           }
6912         /* We only print out user settable breakpoints unless the
6913            allflag is set.  */
6914         if (allflag || user_breakpoint_p (b))
6915           print_one_breakpoint (b, &last_loc, allflag);
6916       }
6917   }
6918
6919   if (nr_printable_breakpoints == 0)
6920     {
6921       /* If there's a filter, let the caller decide how to report
6922          empty list.  */
6923       if (!filter)
6924         {
6925           if (args == NULL || *args == '\0')
6926             uiout->message ("No breakpoints or watchpoints.\n");
6927           else
6928             uiout->message ("No breakpoint or watchpoint matching '%s'.\n",
6929                             args);
6930         }
6931     }
6932   else
6933     {
6934       if (last_loc && !server_command)
6935         set_next_address (last_loc->gdbarch, last_loc->address);
6936     }
6937
6938   /* FIXME?  Should this be moved up so that it is only called when
6939      there have been breakpoints? */
6940   annotate_breakpoints_table_end ();
6941
6942   return nr_printable_breakpoints;
6943 }
6944
6945 /* Display the value of default-collect in a way that is generally
6946    compatible with the breakpoint list.  */
6947
6948 static void
6949 default_collect_info (void)
6950 {
6951   struct ui_out *uiout = current_uiout;
6952
6953   /* If it has no value (which is frequently the case), say nothing; a
6954      message like "No default-collect." gets in user's face when it's
6955      not wanted.  */
6956   if (!*default_collect)
6957     return;
6958
6959   /* The following phrase lines up nicely with per-tracepoint collect
6960      actions.  */
6961   uiout->text ("default collect ");
6962   uiout->field_string ("default-collect", default_collect);
6963   uiout->text (" \n");
6964 }
6965   
6966 static void
6967 breakpoints_info (char *args, int from_tty)
6968 {
6969   breakpoint_1 (args, 0, NULL);
6970
6971   default_collect_info ();
6972 }
6973
6974 static void
6975 watchpoints_info (char *args, int from_tty)
6976 {
6977   int num_printed = breakpoint_1 (args, 0, is_watchpoint);
6978   struct ui_out *uiout = current_uiout;
6979
6980   if (num_printed == 0)
6981     {
6982       if (args == NULL || *args == '\0')
6983         uiout->message ("No watchpoints.\n");
6984       else
6985         uiout->message ("No watchpoint matching '%s'.\n", args);
6986     }
6987 }
6988
6989 static void
6990 maintenance_info_breakpoints (char *args, int from_tty)
6991 {
6992   breakpoint_1 (args, 1, NULL);
6993
6994   default_collect_info ();
6995 }
6996
6997 static int
6998 breakpoint_has_pc (struct breakpoint *b,
6999                    struct program_space *pspace,
7000                    CORE_ADDR pc, struct obj_section *section)
7001 {
7002   struct bp_location *bl = b->loc;
7003
7004   for (; bl; bl = bl->next)
7005     {
7006       if (bl->pspace == pspace
7007           && bl->address == pc
7008           && (!overlay_debugging || bl->section == section))
7009         return 1;         
7010     }
7011   return 0;
7012 }
7013
7014 /* Print a message describing any user-breakpoints set at PC.  This
7015    concerns with logical breakpoints, so we match program spaces, not
7016    address spaces.  */
7017
7018 static void
7019 describe_other_breakpoints (struct gdbarch *gdbarch,
7020                             struct program_space *pspace, CORE_ADDR pc,
7021                             struct obj_section *section, int thread)
7022 {
7023   int others = 0;
7024   struct breakpoint *b;
7025
7026   ALL_BREAKPOINTS (b)
7027     others += (user_breakpoint_p (b)
7028                && breakpoint_has_pc (b, pspace, pc, section));
7029   if (others > 0)
7030     {
7031       if (others == 1)
7032         printf_filtered (_("Note: breakpoint "));
7033       else /* if (others == ???) */
7034         printf_filtered (_("Note: breakpoints "));
7035       ALL_BREAKPOINTS (b)
7036         if (user_breakpoint_p (b) && breakpoint_has_pc (b, pspace, pc, section))
7037           {
7038             others--;
7039             printf_filtered ("%d", b->number);
7040             if (b->thread == -1 && thread != -1)
7041               printf_filtered (" (all threads)");
7042             else if (b->thread != -1)
7043               printf_filtered (" (thread %d)", b->thread);
7044             printf_filtered ("%s%s ",
7045                              ((b->enable_state == bp_disabled
7046                                || b->enable_state == bp_call_disabled)
7047                               ? " (disabled)"
7048                               : ""),
7049                              (others > 1) ? "," 
7050                              : ((others == 1) ? " and" : ""));
7051           }
7052       printf_filtered (_("also set at pc "));
7053       fputs_filtered (paddress (gdbarch, pc), gdb_stdout);
7054       printf_filtered (".\n");
7055     }
7056 }
7057 \f
7058
7059 /* Return true iff it is meaningful to use the address member of
7060    BPT locations.  For some breakpoint types, the locations' address members
7061    are irrelevant and it makes no sense to attempt to compare them to other
7062    addresses (or use them for any other purpose either).
7063
7064    More specifically, each of the following breakpoint types will
7065    always have a zero valued location address and we don't want to mark
7066    breakpoints of any of these types to be a duplicate of an actual
7067    breakpoint location at address zero:
7068
7069       bp_watchpoint
7070       bp_catchpoint
7071
7072 */
7073
7074 static int
7075 breakpoint_address_is_meaningful (struct breakpoint *bpt)
7076 {
7077   enum bptype type = bpt->type;
7078
7079   return (type != bp_watchpoint && type != bp_catchpoint);
7080 }
7081
7082 /* Assuming LOC1 and LOC2's owners are hardware watchpoints, returns
7083    true if LOC1 and LOC2 represent the same watchpoint location.  */
7084
7085 static int
7086 watchpoint_locations_match (struct bp_location *loc1, 
7087                             struct bp_location *loc2)
7088 {
7089   struct watchpoint *w1 = (struct watchpoint *) loc1->owner;
7090   struct watchpoint *w2 = (struct watchpoint *) loc2->owner;
7091
7092   /* Both of them must exist.  */
7093   gdb_assert (w1 != NULL);
7094   gdb_assert (w2 != NULL);
7095
7096   /* If the target can evaluate the condition expression in hardware,
7097      then we we need to insert both watchpoints even if they are at
7098      the same place.  Otherwise the watchpoint will only trigger when
7099      the condition of whichever watchpoint was inserted evaluates to
7100      true, not giving a chance for GDB to check the condition of the
7101      other watchpoint.  */
7102   if ((w1->cond_exp
7103        && target_can_accel_watchpoint_condition (loc1->address, 
7104                                                  loc1->length,
7105                                                  loc1->watchpoint_type,
7106                                                  w1->cond_exp.get ()))
7107       || (w2->cond_exp
7108           && target_can_accel_watchpoint_condition (loc2->address, 
7109                                                     loc2->length,
7110                                                     loc2->watchpoint_type,
7111                                                     w2->cond_exp.get ())))
7112     return 0;
7113
7114   /* Note that this checks the owner's type, not the location's.  In
7115      case the target does not support read watchpoints, but does
7116      support access watchpoints, we'll have bp_read_watchpoint
7117      watchpoints with hw_access locations.  Those should be considered
7118      duplicates of hw_read locations.  The hw_read locations will
7119      become hw_access locations later.  */
7120   return (loc1->owner->type == loc2->owner->type
7121           && loc1->pspace->aspace == loc2->pspace->aspace
7122           && loc1->address == loc2->address
7123           && loc1->length == loc2->length);
7124 }
7125
7126 /* See breakpoint.h.  */
7127
7128 int
7129 breakpoint_address_match (struct address_space *aspace1, CORE_ADDR addr1,
7130                           struct address_space *aspace2, CORE_ADDR addr2)
7131 {
7132   return ((gdbarch_has_global_breakpoints (target_gdbarch ())
7133            || aspace1 == aspace2)
7134           && addr1 == addr2);
7135 }
7136
7137 /* Returns true if {ASPACE2,ADDR2} falls within the range determined by
7138    {ASPACE1,ADDR1,LEN1}.  In most targets, this can only be true if ASPACE1
7139    matches ASPACE2.  On targets that have global breakpoints, the address
7140    space doesn't really matter.  */
7141
7142 static int
7143 breakpoint_address_match_range (struct address_space *aspace1, CORE_ADDR addr1,
7144                                 int len1, struct address_space *aspace2,
7145                                 CORE_ADDR addr2)
7146 {
7147   return ((gdbarch_has_global_breakpoints (target_gdbarch ())
7148            || aspace1 == aspace2)
7149           && addr2 >= addr1 && addr2 < addr1 + len1);
7150 }
7151
7152 /* Returns true if {ASPACE,ADDR} matches the breakpoint BL.  BL may be
7153    a ranged breakpoint.  In most targets, a match happens only if ASPACE
7154    matches the breakpoint's address space.  On targets that have global
7155    breakpoints, the address space doesn't really matter.  */
7156
7157 static int
7158 breakpoint_location_address_match (struct bp_location *bl,
7159                                    struct address_space *aspace,
7160                                    CORE_ADDR addr)
7161 {
7162   return (breakpoint_address_match (bl->pspace->aspace, bl->address,
7163                                     aspace, addr)
7164           || (bl->length
7165               && breakpoint_address_match_range (bl->pspace->aspace,
7166                                                  bl->address, bl->length,
7167                                                  aspace, addr)));
7168 }
7169
7170 /* Returns true if the [ADDR,ADDR+LEN) range in ASPACE overlaps
7171    breakpoint BL.  BL may be a ranged breakpoint.  In most targets, a
7172    match happens only if ASPACE matches the breakpoint's address
7173    space.  On targets that have global breakpoints, the address space
7174    doesn't really matter.  */
7175
7176 static int
7177 breakpoint_location_address_range_overlap (struct bp_location *bl,
7178                                            struct address_space *aspace,
7179                                            CORE_ADDR addr, int len)
7180 {
7181   if (gdbarch_has_global_breakpoints (target_gdbarch ())
7182       || bl->pspace->aspace == aspace)
7183     {
7184       int bl_len = bl->length != 0 ? bl->length : 1;
7185
7186       if (mem_ranges_overlap (addr, len, bl->address, bl_len))
7187         return 1;
7188     }
7189   return 0;
7190 }
7191
7192 /* If LOC1 and LOC2's owners are not tracepoints, returns false directly.
7193    Then, if LOC1 and LOC2 represent the same tracepoint location, returns
7194    true, otherwise returns false.  */
7195
7196 static int
7197 tracepoint_locations_match (struct bp_location *loc1,
7198                             struct bp_location *loc2)
7199 {
7200   if (is_tracepoint (loc1->owner) && is_tracepoint (loc2->owner))
7201     /* Since tracepoint locations are never duplicated with others', tracepoint
7202        locations at the same address of different tracepoints are regarded as
7203        different locations.  */
7204     return (loc1->address == loc2->address && loc1->owner == loc2->owner);
7205   else
7206     return 0;
7207 }
7208
7209 /* Assuming LOC1 and LOC2's types' have meaningful target addresses
7210    (breakpoint_address_is_meaningful), returns true if LOC1 and LOC2
7211    represent the same location.  */
7212
7213 static int
7214 breakpoint_locations_match (struct bp_location *loc1, 
7215                             struct bp_location *loc2)
7216 {
7217   int hw_point1, hw_point2;
7218
7219   /* Both of them must not be in moribund_locations.  */
7220   gdb_assert (loc1->owner != NULL);
7221   gdb_assert (loc2->owner != NULL);
7222
7223   hw_point1 = is_hardware_watchpoint (loc1->owner);
7224   hw_point2 = is_hardware_watchpoint (loc2->owner);
7225
7226   if (hw_point1 != hw_point2)
7227     return 0;
7228   else if (hw_point1)
7229     return watchpoint_locations_match (loc1, loc2);
7230   else if (is_tracepoint (loc1->owner) || is_tracepoint (loc2->owner))
7231     return tracepoint_locations_match (loc1, loc2);
7232   else
7233     /* We compare bp_location.length in order to cover ranged breakpoints.  */
7234     return (breakpoint_address_match (loc1->pspace->aspace, loc1->address,
7235                                      loc2->pspace->aspace, loc2->address)
7236             && loc1->length == loc2->length);
7237 }
7238
7239 static void
7240 breakpoint_adjustment_warning (CORE_ADDR from_addr, CORE_ADDR to_addr,
7241                                int bnum, int have_bnum)
7242 {
7243   /* The longest string possibly returned by hex_string_custom
7244      is 50 chars.  These must be at least that big for safety.  */
7245   char astr1[64];
7246   char astr2[64];
7247
7248   strcpy (astr1, hex_string_custom ((unsigned long) from_addr, 8));
7249   strcpy (astr2, hex_string_custom ((unsigned long) to_addr, 8));
7250   if (have_bnum)
7251     warning (_("Breakpoint %d address previously adjusted from %s to %s."),
7252              bnum, astr1, astr2);
7253   else
7254     warning (_("Breakpoint address adjusted from %s to %s."), astr1, astr2);
7255 }
7256
7257 /* Adjust a breakpoint's address to account for architectural
7258    constraints on breakpoint placement.  Return the adjusted address.
7259    Note: Very few targets require this kind of adjustment.  For most
7260    targets, this function is simply the identity function.  */
7261
7262 static CORE_ADDR
7263 adjust_breakpoint_address (struct gdbarch *gdbarch,
7264                            CORE_ADDR bpaddr, enum bptype bptype)
7265 {
7266   if (!gdbarch_adjust_breakpoint_address_p (gdbarch))
7267     {
7268       /* Very few targets need any kind of breakpoint adjustment.  */
7269       return bpaddr;
7270     }
7271   else if (bptype == bp_watchpoint
7272            || bptype == bp_hardware_watchpoint
7273            || bptype == bp_read_watchpoint
7274            || bptype == bp_access_watchpoint
7275            || bptype == bp_catchpoint)
7276     {
7277       /* Watchpoints and the various bp_catch_* eventpoints should not
7278          have their addresses modified.  */
7279       return bpaddr;
7280     }
7281   else if (bptype == bp_single_step)
7282     {
7283       /* Single-step breakpoints should not have their addresses
7284          modified.  If there's any architectural constrain that
7285          applies to this address, then it should have already been
7286          taken into account when the breakpoint was created in the
7287          first place.  If we didn't do this, stepping through e.g.,
7288          Thumb-2 IT blocks would break.  */
7289       return bpaddr;
7290     }
7291   else
7292     {
7293       CORE_ADDR adjusted_bpaddr;
7294
7295       /* Some targets have architectural constraints on the placement
7296          of breakpoint instructions.  Obtain the adjusted address.  */
7297       adjusted_bpaddr = gdbarch_adjust_breakpoint_address (gdbarch, bpaddr);
7298
7299       /* An adjusted breakpoint address can significantly alter
7300          a user's expectations.  Print a warning if an adjustment
7301          is required.  */
7302       if (adjusted_bpaddr != bpaddr)
7303         breakpoint_adjustment_warning (bpaddr, adjusted_bpaddr, 0, 0);
7304
7305       return adjusted_bpaddr;
7306     }
7307 }
7308
7309 bp_location::bp_location (const bp_location_ops *ops, breakpoint *owner)
7310 {
7311   bp_location *loc = this;
7312
7313   gdb_assert (ops != NULL);
7314
7315   loc->ops = ops;
7316   loc->owner = owner;
7317   loc->cond_bytecode = NULL;
7318   loc->shlib_disabled = 0;
7319   loc->enabled = 1;
7320
7321   switch (owner->type)
7322     {
7323     case bp_breakpoint:
7324     case bp_single_step:
7325     case bp_until:
7326     case bp_finish:
7327     case bp_longjmp:
7328     case bp_longjmp_resume:
7329     case bp_longjmp_call_dummy:
7330     case bp_exception:
7331     case bp_exception_resume:
7332     case bp_step_resume:
7333     case bp_hp_step_resume:
7334     case bp_watchpoint_scope:
7335     case bp_call_dummy:
7336     case bp_std_terminate:
7337     case bp_shlib_event:
7338     case bp_thread_event:
7339     case bp_overlay_event:
7340     case bp_jit_event:
7341     case bp_longjmp_master:
7342     case bp_std_terminate_master:
7343     case bp_exception_master:
7344     case bp_gnu_ifunc_resolver:
7345     case bp_gnu_ifunc_resolver_return:
7346     case bp_dprintf:
7347       loc->loc_type = bp_loc_software_breakpoint;
7348       mark_breakpoint_location_modified (loc);
7349       break;
7350     case bp_hardware_breakpoint:
7351       loc->loc_type = bp_loc_hardware_breakpoint;
7352       mark_breakpoint_location_modified (loc);
7353       break;
7354     case bp_hardware_watchpoint:
7355     case bp_read_watchpoint:
7356     case bp_access_watchpoint:
7357       loc->loc_type = bp_loc_hardware_watchpoint;
7358       break;
7359     case bp_watchpoint:
7360     case bp_catchpoint:
7361     case bp_tracepoint:
7362     case bp_fast_tracepoint:
7363     case bp_static_tracepoint:
7364       loc->loc_type = bp_loc_other;
7365       break;
7366     default:
7367       internal_error (__FILE__, __LINE__, _("unknown breakpoint type"));
7368     }
7369
7370   loc->refc = 1;
7371 }
7372
7373 /* Allocate a struct bp_location.  */
7374
7375 static struct bp_location *
7376 allocate_bp_location (struct breakpoint *bpt)
7377 {
7378   return bpt->ops->allocate_location (bpt);
7379 }
7380
7381 static void
7382 free_bp_location (struct bp_location *loc)
7383 {
7384   loc->ops->dtor (loc);
7385   delete loc;
7386 }
7387
7388 /* Increment reference count.  */
7389
7390 static void
7391 incref_bp_location (struct bp_location *bl)
7392 {
7393   ++bl->refc;
7394 }
7395
7396 /* Decrement reference count.  If the reference count reaches 0,
7397    destroy the bp_location.  Sets *BLP to NULL.  */
7398
7399 static void
7400 decref_bp_location (struct bp_location **blp)
7401 {
7402   gdb_assert ((*blp)->refc > 0);
7403
7404   if (--(*blp)->refc == 0)
7405     free_bp_location (*blp);
7406   *blp = NULL;
7407 }
7408
7409 /* Add breakpoint B at the end of the global breakpoint chain.  */
7410
7411 static void
7412 add_to_breakpoint_chain (struct breakpoint *b)
7413 {
7414   struct breakpoint *b1;
7415
7416   /* Add this breakpoint to the end of the chain so that a list of
7417      breakpoints will come out in order of increasing numbers.  */
7418
7419   b1 = breakpoint_chain;
7420   if (b1 == 0)
7421     breakpoint_chain = b;
7422   else
7423     {
7424       while (b1->next)
7425         b1 = b1->next;
7426       b1->next = b;
7427     }
7428 }
7429
7430 /* Initializes breakpoint B with type BPTYPE and no locations yet.  */
7431
7432 static void
7433 init_raw_breakpoint_without_location (struct breakpoint *b,
7434                                       struct gdbarch *gdbarch,
7435                                       enum bptype bptype,
7436                                       const struct breakpoint_ops *ops)
7437 {
7438   gdb_assert (ops != NULL);
7439
7440   b->ops = ops;
7441   b->type = bptype;
7442   b->gdbarch = gdbarch;
7443   b->language = current_language->la_language;
7444   b->input_radix = input_radix;
7445   b->related_breakpoint = b;
7446 }
7447
7448 /* Helper to set_raw_breakpoint below.  Creates a breakpoint
7449    that has type BPTYPE and has no locations as yet.  */
7450
7451 static struct breakpoint *
7452 set_raw_breakpoint_without_location (struct gdbarch *gdbarch,
7453                                      enum bptype bptype,
7454                                      const struct breakpoint_ops *ops)
7455 {
7456   std::unique_ptr<breakpoint> b = new_breakpoint_from_type (bptype);
7457
7458   init_raw_breakpoint_without_location (b.get (), gdbarch, bptype, ops);
7459   add_to_breakpoint_chain (b.get ());
7460
7461   return b.release ();
7462 }
7463
7464 /* Initialize loc->function_name.  EXPLICIT_LOC says no indirect function
7465    resolutions should be made as the user specified the location explicitly
7466    enough.  */
7467
7468 static void
7469 set_breakpoint_location_function (struct bp_location *loc, int explicit_loc)
7470 {
7471   gdb_assert (loc->owner != NULL);
7472
7473   if (loc->owner->type == bp_breakpoint
7474       || loc->owner->type == bp_hardware_breakpoint
7475       || is_tracepoint (loc->owner))
7476     {
7477       int is_gnu_ifunc;
7478       const char *function_name;
7479       CORE_ADDR func_addr;
7480
7481       find_pc_partial_function_gnu_ifunc (loc->address, &function_name,
7482                                           &func_addr, NULL, &is_gnu_ifunc);
7483
7484       if (is_gnu_ifunc && !explicit_loc)
7485         {
7486           struct breakpoint *b = loc->owner;
7487
7488           gdb_assert (loc->pspace == current_program_space);
7489           if (gnu_ifunc_resolve_name (function_name,
7490                                       &loc->requested_address))
7491             {
7492               /* Recalculate ADDRESS based on new REQUESTED_ADDRESS.  */
7493               loc->address = adjust_breakpoint_address (loc->gdbarch,
7494                                                         loc->requested_address,
7495                                                         b->type);
7496             }
7497           else if (b->type == bp_breakpoint && b->loc == loc
7498                    && loc->next == NULL && b->related_breakpoint == b)
7499             {
7500               /* Create only the whole new breakpoint of this type but do not
7501                  mess more complicated breakpoints with multiple locations.  */
7502               b->type = bp_gnu_ifunc_resolver;
7503               /* Remember the resolver's address for use by the return
7504                  breakpoint.  */
7505               loc->related_address = func_addr;
7506             }
7507         }
7508
7509       if (function_name)
7510         loc->function_name = xstrdup (function_name);
7511     }
7512 }
7513
7514 /* Attempt to determine architecture of location identified by SAL.  */
7515 struct gdbarch *
7516 get_sal_arch (struct symtab_and_line sal)
7517 {
7518   if (sal.section)
7519     return get_objfile_arch (sal.section->objfile);
7520   if (sal.symtab)
7521     return get_objfile_arch (SYMTAB_OBJFILE (sal.symtab));
7522
7523   return NULL;
7524 }
7525
7526 /* Low level routine for partially initializing a breakpoint of type
7527    BPTYPE.  The newly created breakpoint's address, section, source
7528    file name, and line number are provided by SAL.
7529
7530    It is expected that the caller will complete the initialization of
7531    the newly created breakpoint struct as well as output any status
7532    information regarding the creation of a new breakpoint.  */
7533
7534 static void
7535 init_raw_breakpoint (struct breakpoint *b, struct gdbarch *gdbarch,
7536                      struct symtab_and_line sal, enum bptype bptype,
7537                      const struct breakpoint_ops *ops)
7538 {
7539   init_raw_breakpoint_without_location (b, gdbarch, bptype, ops);
7540
7541   add_location_to_breakpoint (b, &sal);
7542
7543   if (bptype != bp_catchpoint)
7544     gdb_assert (sal.pspace != NULL);
7545
7546   /* Store the program space that was used to set the breakpoint,
7547      except for ordinary breakpoints, which are independent of the
7548      program space.  */
7549   if (bptype != bp_breakpoint && bptype != bp_hardware_breakpoint)
7550     b->pspace = sal.pspace;
7551 }
7552
7553 /* set_raw_breakpoint is a low level routine for allocating and
7554    partially initializing a breakpoint of type BPTYPE.  The newly
7555    created breakpoint's address, section, source file name, and line
7556    number are provided by SAL.  The newly created and partially
7557    initialized breakpoint is added to the breakpoint chain and
7558    is also returned as the value of this function.
7559
7560    It is expected that the caller will complete the initialization of
7561    the newly created breakpoint struct as well as output any status
7562    information regarding the creation of a new breakpoint.  In
7563    particular, set_raw_breakpoint does NOT set the breakpoint
7564    number!  Care should be taken to not allow an error to occur
7565    prior to completing the initialization of the breakpoint.  If this
7566    should happen, a bogus breakpoint will be left on the chain.  */
7567
7568 struct breakpoint *
7569 set_raw_breakpoint (struct gdbarch *gdbarch,
7570                     struct symtab_and_line sal, enum bptype bptype,
7571                     const struct breakpoint_ops *ops)
7572 {
7573   std::unique_ptr<breakpoint> b = new_breakpoint_from_type (bptype);
7574
7575   init_raw_breakpoint (b.get (), gdbarch, sal, bptype, ops);
7576   add_to_breakpoint_chain (b.get ());
7577
7578   return b.release ();
7579 }
7580
7581 /* Call this routine when stepping and nexting to enable a breakpoint
7582    if we do a longjmp() or 'throw' in TP.  FRAME is the frame which
7583    initiated the operation.  */
7584
7585 void
7586 set_longjmp_breakpoint (struct thread_info *tp, struct frame_id frame)
7587 {
7588   struct breakpoint *b, *b_tmp;
7589   int thread = tp->global_num;
7590
7591   /* To avoid having to rescan all objfile symbols at every step,
7592      we maintain a list of continually-inserted but always disabled
7593      longjmp "master" breakpoints.  Here, we simply create momentary
7594      clones of those and enable them for the requested thread.  */
7595   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7596     if (b->pspace == current_program_space
7597         && (b->type == bp_longjmp_master
7598             || b->type == bp_exception_master))
7599       {
7600         enum bptype type = b->type == bp_longjmp_master ? bp_longjmp : bp_exception;
7601         struct breakpoint *clone;
7602
7603         /* longjmp_breakpoint_ops ensures INITIATING_FRAME is cleared again
7604            after their removal.  */
7605         clone = momentary_breakpoint_from_master (b, type,
7606                                                   &momentary_breakpoint_ops, 1);
7607         clone->thread = thread;
7608       }
7609
7610   tp->initiating_frame = frame;
7611 }
7612
7613 /* Delete all longjmp breakpoints from THREAD.  */
7614 void
7615 delete_longjmp_breakpoint (int thread)
7616 {
7617   struct breakpoint *b, *b_tmp;
7618
7619   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7620     if (b->type == bp_longjmp || b->type == bp_exception)
7621       {
7622         if (b->thread == thread)
7623           delete_breakpoint (b);
7624       }
7625 }
7626
7627 void
7628 delete_longjmp_breakpoint_at_next_stop (int thread)
7629 {
7630   struct breakpoint *b, *b_tmp;
7631
7632   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7633     if (b->type == bp_longjmp || b->type == bp_exception)
7634       {
7635         if (b->thread == thread)
7636           b->disposition = disp_del_at_next_stop;
7637       }
7638 }
7639
7640 /* Place breakpoints of type bp_longjmp_call_dummy to catch longjmp for
7641    INFERIOR_PTID thread.  Chain them all by RELATED_BREAKPOINT and return
7642    pointer to any of them.  Return NULL if this system cannot place longjmp
7643    breakpoints.  */
7644
7645 struct breakpoint *
7646 set_longjmp_breakpoint_for_call_dummy (void)
7647 {
7648   struct breakpoint *b, *retval = NULL;
7649
7650   ALL_BREAKPOINTS (b)
7651     if (b->pspace == current_program_space && b->type == bp_longjmp_master)
7652       {
7653         struct breakpoint *new_b;
7654
7655         new_b = momentary_breakpoint_from_master (b, bp_longjmp_call_dummy,
7656                                                   &momentary_breakpoint_ops,
7657                                                   1);
7658         new_b->thread = ptid_to_global_thread_id (inferior_ptid);
7659
7660         /* Link NEW_B into the chain of RETVAL breakpoints.  */
7661
7662         gdb_assert (new_b->related_breakpoint == new_b);
7663         if (retval == NULL)
7664           retval = new_b;
7665         new_b->related_breakpoint = retval;
7666         while (retval->related_breakpoint != new_b->related_breakpoint)
7667           retval = retval->related_breakpoint;
7668         retval->related_breakpoint = new_b;
7669       }
7670
7671   return retval;
7672 }
7673
7674 /* Verify all existing dummy frames and their associated breakpoints for
7675    TP.  Remove those which can no longer be found in the current frame
7676    stack.
7677
7678    You should call this function only at places where it is safe to currently
7679    unwind the whole stack.  Failed stack unwind would discard live dummy
7680    frames.  */
7681
7682 void
7683 check_longjmp_breakpoint_for_call_dummy (struct thread_info *tp)
7684 {
7685   struct breakpoint *b, *b_tmp;
7686
7687   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7688     if (b->type == bp_longjmp_call_dummy && b->thread == tp->global_num)
7689       {
7690         struct breakpoint *dummy_b = b->related_breakpoint;
7691
7692         while (dummy_b != b && dummy_b->type != bp_call_dummy)
7693           dummy_b = dummy_b->related_breakpoint;
7694         if (dummy_b->type != bp_call_dummy
7695             || frame_find_by_id (dummy_b->frame_id) != NULL)
7696           continue;
7697         
7698         dummy_frame_discard (dummy_b->frame_id, tp->ptid);
7699
7700         while (b->related_breakpoint != b)
7701           {
7702             if (b_tmp == b->related_breakpoint)
7703               b_tmp = b->related_breakpoint->next;
7704             delete_breakpoint (b->related_breakpoint);
7705           }
7706         delete_breakpoint (b);
7707       }
7708 }
7709
7710 void
7711 enable_overlay_breakpoints (void)
7712 {
7713   struct breakpoint *b;
7714
7715   ALL_BREAKPOINTS (b)
7716     if (b->type == bp_overlay_event)
7717     {
7718       b->enable_state = bp_enabled;
7719       update_global_location_list (UGLL_MAY_INSERT);
7720       overlay_events_enabled = 1;
7721     }
7722 }
7723
7724 void
7725 disable_overlay_breakpoints (void)
7726 {
7727   struct breakpoint *b;
7728
7729   ALL_BREAKPOINTS (b)
7730     if (b->type == bp_overlay_event)
7731     {
7732       b->enable_state = bp_disabled;
7733       update_global_location_list (UGLL_DONT_INSERT);
7734       overlay_events_enabled = 0;
7735     }
7736 }
7737
7738 /* Set an active std::terminate breakpoint for each std::terminate
7739    master breakpoint.  */
7740 void
7741 set_std_terminate_breakpoint (void)
7742 {
7743   struct breakpoint *b, *b_tmp;
7744
7745   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7746     if (b->pspace == current_program_space
7747         && b->type == bp_std_terminate_master)
7748       {
7749         momentary_breakpoint_from_master (b, bp_std_terminate,
7750                                           &momentary_breakpoint_ops, 1);
7751       }
7752 }
7753
7754 /* Delete all the std::terminate breakpoints.  */
7755 void
7756 delete_std_terminate_breakpoint (void)
7757 {
7758   struct breakpoint *b, *b_tmp;
7759
7760   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7761     if (b->type == bp_std_terminate)
7762       delete_breakpoint (b);
7763 }
7764
7765 struct breakpoint *
7766 create_thread_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7767 {
7768   struct breakpoint *b;
7769
7770   b = create_internal_breakpoint (gdbarch, address, bp_thread_event,
7771                                   &internal_breakpoint_ops);
7772
7773   b->enable_state = bp_enabled;
7774   /* location has to be used or breakpoint_re_set will delete me.  */
7775   b->location = new_address_location (b->loc->address, NULL, 0);
7776
7777   update_global_location_list_nothrow (UGLL_MAY_INSERT);
7778
7779   return b;
7780 }
7781
7782 struct lang_and_radix
7783   {
7784     enum language lang;
7785     int radix;
7786   };
7787
7788 /* Create a breakpoint for JIT code registration and unregistration.  */
7789
7790 struct breakpoint *
7791 create_jit_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7792 {
7793   return create_internal_breakpoint (gdbarch, address, bp_jit_event,
7794                                      &internal_breakpoint_ops);
7795 }
7796
7797 /* Remove JIT code registration and unregistration breakpoint(s).  */
7798
7799 void
7800 remove_jit_event_breakpoints (void)
7801 {
7802   struct breakpoint *b, *b_tmp;
7803
7804   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7805     if (b->type == bp_jit_event
7806         && b->loc->pspace == current_program_space)
7807       delete_breakpoint (b);
7808 }
7809
7810 void
7811 remove_solib_event_breakpoints (void)
7812 {
7813   struct breakpoint *b, *b_tmp;
7814
7815   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7816     if (b->type == bp_shlib_event
7817         && b->loc->pspace == current_program_space)
7818       delete_breakpoint (b);
7819 }
7820
7821 /* See breakpoint.h.  */
7822
7823 void
7824 remove_solib_event_breakpoints_at_next_stop (void)
7825 {
7826   struct breakpoint *b, *b_tmp;
7827
7828   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7829     if (b->type == bp_shlib_event
7830         && b->loc->pspace == current_program_space)
7831       b->disposition = disp_del_at_next_stop;
7832 }
7833
7834 /* Helper for create_solib_event_breakpoint /
7835    create_and_insert_solib_event_breakpoint.  Allows specifying which
7836    INSERT_MODE to pass through to update_global_location_list.  */
7837
7838 static struct breakpoint *
7839 create_solib_event_breakpoint_1 (struct gdbarch *gdbarch, CORE_ADDR address,
7840                                  enum ugll_insert_mode insert_mode)
7841 {
7842   struct breakpoint *b;
7843
7844   b = create_internal_breakpoint (gdbarch, address, bp_shlib_event,
7845                                   &internal_breakpoint_ops);
7846   update_global_location_list_nothrow (insert_mode);
7847   return b;
7848 }
7849
7850 struct breakpoint *
7851 create_solib_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7852 {
7853   return create_solib_event_breakpoint_1 (gdbarch, address, UGLL_MAY_INSERT);
7854 }
7855
7856 /* See breakpoint.h.  */
7857
7858 struct breakpoint *
7859 create_and_insert_solib_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7860 {
7861   struct breakpoint *b;
7862
7863   /* Explicitly tell update_global_location_list to insert
7864      locations.  */
7865   b = create_solib_event_breakpoint_1 (gdbarch, address, UGLL_INSERT);
7866   if (!b->loc->inserted)
7867     {
7868       delete_breakpoint (b);
7869       return NULL;
7870     }
7871   return b;
7872 }
7873
7874 /* Disable any breakpoints that are on code in shared libraries.  Only
7875    apply to enabled breakpoints, disabled ones can just stay disabled.  */
7876
7877 void
7878 disable_breakpoints_in_shlibs (void)
7879 {
7880   struct bp_location *loc, **locp_tmp;
7881
7882   ALL_BP_LOCATIONS (loc, locp_tmp)
7883   {
7884     /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
7885     struct breakpoint *b = loc->owner;
7886
7887     /* We apply the check to all breakpoints, including disabled for
7888        those with loc->duplicate set.  This is so that when breakpoint
7889        becomes enabled, or the duplicate is removed, gdb will try to
7890        insert all breakpoints.  If we don't set shlib_disabled here,
7891        we'll try to insert those breakpoints and fail.  */
7892     if (((b->type == bp_breakpoint)
7893          || (b->type == bp_jit_event)
7894          || (b->type == bp_hardware_breakpoint)
7895          || (is_tracepoint (b)))
7896         && loc->pspace == current_program_space
7897         && !loc->shlib_disabled
7898         && solib_name_from_address (loc->pspace, loc->address)
7899         )
7900       {
7901         loc->shlib_disabled = 1;
7902       }
7903   }
7904 }
7905
7906 /* Disable any breakpoints and tracepoints that are in SOLIB upon
7907    notification of unloaded_shlib.  Only apply to enabled breakpoints,
7908    disabled ones can just stay disabled.  */
7909
7910 static void
7911 disable_breakpoints_in_unloaded_shlib (struct so_list *solib)
7912 {
7913   struct bp_location *loc, **locp_tmp;
7914   int disabled_shlib_breaks = 0;
7915
7916   ALL_BP_LOCATIONS (loc, locp_tmp)
7917   {
7918     /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
7919     struct breakpoint *b = loc->owner;
7920
7921     if (solib->pspace == loc->pspace
7922         && !loc->shlib_disabled
7923         && (((b->type == bp_breakpoint
7924               || b->type == bp_jit_event
7925               || b->type == bp_hardware_breakpoint)
7926              && (loc->loc_type == bp_loc_hardware_breakpoint
7927                  || loc->loc_type == bp_loc_software_breakpoint))
7928             || is_tracepoint (b))
7929         && solib_contains_address_p (solib, loc->address))
7930       {
7931         loc->shlib_disabled = 1;
7932         /* At this point, we cannot rely on remove_breakpoint
7933            succeeding so we must mark the breakpoint as not inserted
7934            to prevent future errors occurring in remove_breakpoints.  */
7935         loc->inserted = 0;
7936
7937         /* This may cause duplicate notifications for the same breakpoint.  */
7938         observer_notify_breakpoint_modified (b);
7939
7940         if (!disabled_shlib_breaks)
7941           {
7942             target_terminal_ours_for_output ();
7943             warning (_("Temporarily disabling breakpoints "
7944                        "for unloaded shared library \"%s\""),
7945                      solib->so_name);
7946           }
7947         disabled_shlib_breaks = 1;
7948       }
7949   }
7950 }
7951
7952 /* Disable any breakpoints and tracepoints in OBJFILE upon
7953    notification of free_objfile.  Only apply to enabled breakpoints,
7954    disabled ones can just stay disabled.  */
7955
7956 static void
7957 disable_breakpoints_in_freed_objfile (struct objfile *objfile)
7958 {
7959   struct breakpoint *b;
7960
7961   if (objfile == NULL)
7962     return;
7963
7964   /* OBJF_SHARED|OBJF_USERLOADED objfiles are dynamic modules manually
7965      managed by the user with add-symbol-file/remove-symbol-file.
7966      Similarly to how breakpoints in shared libraries are handled in
7967      response to "nosharedlibrary", mark breakpoints in such modules
7968      shlib_disabled so they end up uninserted on the next global
7969      location list update.  Shared libraries not loaded by the user
7970      aren't handled here -- they're already handled in
7971      disable_breakpoints_in_unloaded_shlib, called by solib.c's
7972      solib_unloaded observer.  We skip objfiles that are not
7973      OBJF_SHARED as those aren't considered dynamic objects (e.g. the
7974      main objfile).  */
7975   if ((objfile->flags & OBJF_SHARED) == 0
7976       || (objfile->flags & OBJF_USERLOADED) == 0)
7977     return;
7978
7979   ALL_BREAKPOINTS (b)
7980     {
7981       struct bp_location *loc;
7982       int bp_modified = 0;
7983
7984       if (!is_breakpoint (b) && !is_tracepoint (b))
7985         continue;
7986
7987       for (loc = b->loc; loc != NULL; loc = loc->next)
7988         {
7989           CORE_ADDR loc_addr = loc->address;
7990
7991           if (loc->loc_type != bp_loc_hardware_breakpoint
7992               && loc->loc_type != bp_loc_software_breakpoint)
7993             continue;
7994
7995           if (loc->shlib_disabled != 0)
7996             continue;
7997
7998           if (objfile->pspace != loc->pspace)
7999             continue;
8000
8001           if (loc->loc_type != bp_loc_hardware_breakpoint
8002               && loc->loc_type != bp_loc_software_breakpoint)
8003             continue;
8004
8005           if (is_addr_in_objfile (loc_addr, objfile))
8006             {
8007               loc->shlib_disabled = 1;
8008               /* At this point, we don't know whether the object was
8009                  unmapped from the inferior or not, so leave the
8010                  inserted flag alone.  We'll handle failure to
8011                  uninsert quietly, in case the object was indeed
8012                  unmapped.  */
8013
8014               mark_breakpoint_location_modified (loc);
8015
8016               bp_modified = 1;
8017             }
8018         }
8019
8020       if (bp_modified)
8021         observer_notify_breakpoint_modified (b);
8022     }
8023 }
8024
8025 /* FORK & VFORK catchpoints.  */
8026
8027 /* An instance of this type is used to represent a fork or vfork
8028    catchpoint.  A breakpoint is really of this type iff its ops pointer points
8029    to CATCH_FORK_BREAKPOINT_OPS.  */
8030
8031 struct fork_catchpoint : public breakpoint
8032 {
8033   /* Process id of a child process whose forking triggered this
8034      catchpoint.  This field is only valid immediately after this
8035      catchpoint has triggered.  */
8036   ptid_t forked_inferior_pid;
8037 };
8038
8039 /* Implement the "insert" breakpoint_ops method for fork
8040    catchpoints.  */
8041
8042 static int
8043 insert_catch_fork (struct bp_location *bl)
8044 {
8045   return target_insert_fork_catchpoint (ptid_get_pid (inferior_ptid));
8046 }
8047
8048 /* Implement the "remove" breakpoint_ops method for fork
8049    catchpoints.  */
8050
8051 static int
8052 remove_catch_fork (struct bp_location *bl, enum remove_bp_reason reason)
8053 {
8054   return target_remove_fork_catchpoint (ptid_get_pid (inferior_ptid));
8055 }
8056
8057 /* Implement the "breakpoint_hit" breakpoint_ops method for fork
8058    catchpoints.  */
8059
8060 static int
8061 breakpoint_hit_catch_fork (const struct bp_location *bl,
8062                            struct address_space *aspace, CORE_ADDR bp_addr,
8063                            const struct target_waitstatus *ws)
8064 {
8065   struct fork_catchpoint *c = (struct fork_catchpoint *) bl->owner;
8066
8067   if (ws->kind != TARGET_WAITKIND_FORKED)
8068     return 0;
8069
8070   c->forked_inferior_pid = ws->value.related_pid;
8071   return 1;
8072 }
8073
8074 /* Implement the "print_it" breakpoint_ops method for fork
8075    catchpoints.  */
8076
8077 static enum print_stop_action
8078 print_it_catch_fork (bpstat bs)
8079 {
8080   struct ui_out *uiout = current_uiout;
8081   struct breakpoint *b = bs->breakpoint_at;
8082   struct fork_catchpoint *c = (struct fork_catchpoint *) bs->breakpoint_at;
8083
8084   annotate_catchpoint (b->number);
8085   maybe_print_thread_hit_breakpoint (uiout);
8086   if (b->disposition == disp_del)
8087     uiout->text ("Temporary catchpoint ");
8088   else
8089     uiout->text ("Catchpoint ");
8090   if (uiout->is_mi_like_p ())
8091     {
8092       uiout->field_string ("reason", async_reason_lookup (EXEC_ASYNC_FORK));
8093       uiout->field_string ("disp", bpdisp_text (b->disposition));
8094     }
8095   uiout->field_int ("bkptno", b->number);
8096   uiout->text (" (forked process ");
8097   uiout->field_int ("newpid", ptid_get_pid (c->forked_inferior_pid));
8098   uiout->text ("), ");
8099   return PRINT_SRC_AND_LOC;
8100 }
8101
8102 /* Implement the "print_one" breakpoint_ops method for fork
8103    catchpoints.  */
8104
8105 static void
8106 print_one_catch_fork (struct breakpoint *b, struct bp_location **last_loc)
8107 {
8108   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
8109   struct value_print_options opts;
8110   struct ui_out *uiout = current_uiout;
8111
8112   get_user_print_options (&opts);
8113
8114   /* Field 4, the address, is omitted (which makes the columns not
8115      line up too nicely with the headers, but the effect is relatively
8116      readable).  */
8117   if (opts.addressprint)
8118     uiout->field_skip ("addr");
8119   annotate_field (5);
8120   uiout->text ("fork");
8121   if (!ptid_equal (c->forked_inferior_pid, null_ptid))
8122     {
8123       uiout->text (", process ");
8124       uiout->field_int ("what", ptid_get_pid (c->forked_inferior_pid));
8125       uiout->spaces (1);
8126     }
8127
8128   if (uiout->is_mi_like_p ())
8129     uiout->field_string ("catch-type", "fork");
8130 }
8131
8132 /* Implement the "print_mention" breakpoint_ops method for fork
8133    catchpoints.  */
8134
8135 static void
8136 print_mention_catch_fork (struct breakpoint *b)
8137 {
8138   printf_filtered (_("Catchpoint %d (fork)"), b->number);
8139 }
8140
8141 /* Implement the "print_recreate" breakpoint_ops method for fork
8142    catchpoints.  */
8143
8144 static void
8145 print_recreate_catch_fork (struct breakpoint *b, struct ui_file *fp)
8146 {
8147   fprintf_unfiltered (fp, "catch fork");
8148   print_recreate_thread (b, fp);
8149 }
8150
8151 /* The breakpoint_ops structure to be used in fork catchpoints.  */
8152
8153 static struct breakpoint_ops catch_fork_breakpoint_ops;
8154
8155 /* Implement the "insert" breakpoint_ops method for vfork
8156    catchpoints.  */
8157
8158 static int
8159 insert_catch_vfork (struct bp_location *bl)
8160 {
8161   return target_insert_vfork_catchpoint (ptid_get_pid (inferior_ptid));
8162 }
8163
8164 /* Implement the "remove" breakpoint_ops method for vfork
8165    catchpoints.  */
8166
8167 static int
8168 remove_catch_vfork (struct bp_location *bl, enum remove_bp_reason reason)
8169 {
8170   return target_remove_vfork_catchpoint (ptid_get_pid (inferior_ptid));
8171 }
8172
8173 /* Implement the "breakpoint_hit" breakpoint_ops method for vfork
8174    catchpoints.  */
8175
8176 static int
8177 breakpoint_hit_catch_vfork (const struct bp_location *bl,
8178                             struct address_space *aspace, CORE_ADDR bp_addr,
8179                             const struct target_waitstatus *ws)
8180 {
8181   struct fork_catchpoint *c = (struct fork_catchpoint *) bl->owner;
8182
8183   if (ws->kind != TARGET_WAITKIND_VFORKED)
8184     return 0;
8185
8186   c->forked_inferior_pid = ws->value.related_pid;
8187   return 1;
8188 }
8189
8190 /* Implement the "print_it" breakpoint_ops method for vfork
8191    catchpoints.  */
8192
8193 static enum print_stop_action
8194 print_it_catch_vfork (bpstat bs)
8195 {
8196   struct ui_out *uiout = current_uiout;
8197   struct breakpoint *b = bs->breakpoint_at;
8198   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
8199
8200   annotate_catchpoint (b->number);
8201   maybe_print_thread_hit_breakpoint (uiout);
8202   if (b->disposition == disp_del)
8203     uiout->text ("Temporary catchpoint ");
8204   else
8205     uiout->text ("Catchpoint ");
8206   if (uiout->is_mi_like_p ())
8207     {
8208       uiout->field_string ("reason", async_reason_lookup (EXEC_ASYNC_VFORK));
8209       uiout->field_string ("disp", bpdisp_text (b->disposition));
8210     }
8211   uiout->field_int ("bkptno", b->number);
8212   uiout->text (" (vforked process ");
8213   uiout->field_int ("newpid", ptid_get_pid (c->forked_inferior_pid));
8214   uiout->text ("), ");
8215   return PRINT_SRC_AND_LOC;
8216 }
8217
8218 /* Implement the "print_one" breakpoint_ops method for vfork
8219    catchpoints.  */
8220
8221 static void
8222 print_one_catch_vfork (struct breakpoint *b, struct bp_location **last_loc)
8223 {
8224   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
8225   struct value_print_options opts;
8226   struct ui_out *uiout = current_uiout;
8227
8228   get_user_print_options (&opts);
8229   /* Field 4, the address, is omitted (which makes the columns not
8230      line up too nicely with the headers, but the effect is relatively
8231      readable).  */
8232   if (opts.addressprint)
8233     uiout->field_skip ("addr");
8234   annotate_field (5);
8235   uiout->text ("vfork");
8236   if (!ptid_equal (c->forked_inferior_pid, null_ptid))
8237     {
8238       uiout->text (", process ");
8239       uiout->field_int ("what", ptid_get_pid (c->forked_inferior_pid));
8240       uiout->spaces (1);
8241     }
8242
8243   if (uiout->is_mi_like_p ())
8244     uiout->field_string ("catch-type", "vfork");
8245 }
8246
8247 /* Implement the "print_mention" breakpoint_ops method for vfork
8248    catchpoints.  */
8249
8250 static void
8251 print_mention_catch_vfork (struct breakpoint *b)
8252 {
8253   printf_filtered (_("Catchpoint %d (vfork)"), b->number);
8254 }
8255
8256 /* Implement the "print_recreate" breakpoint_ops method for vfork
8257    catchpoints.  */
8258
8259 static void
8260 print_recreate_catch_vfork (struct breakpoint *b, struct ui_file *fp)
8261 {
8262   fprintf_unfiltered (fp, "catch vfork");
8263   print_recreate_thread (b, fp);
8264 }
8265
8266 /* The breakpoint_ops structure to be used in vfork catchpoints.  */
8267
8268 static struct breakpoint_ops catch_vfork_breakpoint_ops;
8269
8270 /* An instance of this type is used to represent an solib catchpoint.
8271    A breakpoint is really of this type iff its ops pointer points to
8272    CATCH_SOLIB_BREAKPOINT_OPS.  */
8273
8274 struct solib_catchpoint : public breakpoint
8275 {
8276   ~solib_catchpoint () override;
8277
8278   /* True for "catch load", false for "catch unload".  */
8279   unsigned char is_load;
8280
8281   /* Regular expression to match, if any.  COMPILED is only valid when
8282      REGEX is non-NULL.  */
8283   char *regex;
8284   std::unique_ptr<compiled_regex> compiled;
8285 };
8286
8287 solib_catchpoint::~solib_catchpoint ()
8288 {
8289   xfree (this->regex);
8290 }
8291
8292 static int
8293 insert_catch_solib (struct bp_location *ignore)
8294 {
8295   return 0;
8296 }
8297
8298 static int
8299 remove_catch_solib (struct bp_location *ignore, enum remove_bp_reason reason)
8300 {
8301   return 0;
8302 }
8303
8304 static int
8305 breakpoint_hit_catch_solib (const struct bp_location *bl,
8306                             struct address_space *aspace,
8307                             CORE_ADDR bp_addr,
8308                             const struct target_waitstatus *ws)
8309 {
8310   struct solib_catchpoint *self = (struct solib_catchpoint *) bl->owner;
8311   struct breakpoint *other;
8312
8313   if (ws->kind == TARGET_WAITKIND_LOADED)
8314     return 1;
8315
8316   ALL_BREAKPOINTS (other)
8317   {
8318     struct bp_location *other_bl;
8319
8320     if (other == bl->owner)
8321       continue;
8322
8323     if (other->type != bp_shlib_event)
8324       continue;
8325
8326     if (self->pspace != NULL && other->pspace != self->pspace)
8327       continue;
8328
8329     for (other_bl = other->loc; other_bl != NULL; other_bl = other_bl->next)
8330       {
8331         if (other->ops->breakpoint_hit (other_bl, aspace, bp_addr, ws))
8332           return 1;
8333       }
8334   }
8335
8336   return 0;
8337 }
8338
8339 static void
8340 check_status_catch_solib (struct bpstats *bs)
8341 {
8342   struct solib_catchpoint *self
8343     = (struct solib_catchpoint *) bs->breakpoint_at;
8344   int ix;
8345
8346   if (self->is_load)
8347     {
8348       struct so_list *iter;
8349
8350       for (ix = 0;
8351            VEC_iterate (so_list_ptr, current_program_space->added_solibs,
8352                         ix, iter);
8353            ++ix)
8354         {
8355           if (!self->regex
8356               || self->compiled->exec (iter->so_name, 0, NULL, 0) == 0)
8357             return;
8358         }
8359     }
8360   else
8361     {
8362       char *iter;
8363
8364       for (ix = 0;
8365            VEC_iterate (char_ptr, current_program_space->deleted_solibs,
8366                         ix, iter);
8367            ++ix)
8368         {
8369           if (!self->regex
8370               || self->compiled->exec (iter, 0, NULL, 0) == 0)
8371             return;
8372         }
8373     }
8374
8375   bs->stop = 0;
8376   bs->print_it = print_it_noop;
8377 }
8378
8379 static enum print_stop_action
8380 print_it_catch_solib (bpstat bs)
8381 {
8382   struct breakpoint *b = bs->breakpoint_at;
8383   struct ui_out *uiout = current_uiout;
8384
8385   annotate_catchpoint (b->number);
8386   maybe_print_thread_hit_breakpoint (uiout);
8387   if (b->disposition == disp_del)
8388     uiout->text ("Temporary catchpoint ");
8389   else
8390     uiout->text ("Catchpoint ");
8391   uiout->field_int ("bkptno", b->number);
8392   uiout->text ("\n");
8393   if (uiout->is_mi_like_p ())
8394     uiout->field_string ("disp", bpdisp_text (b->disposition));
8395   print_solib_event (1);
8396   return PRINT_SRC_AND_LOC;
8397 }
8398
8399 static void
8400 print_one_catch_solib (struct breakpoint *b, struct bp_location **locs)
8401 {
8402   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8403   struct value_print_options opts;
8404   struct ui_out *uiout = current_uiout;
8405   char *msg;
8406
8407   get_user_print_options (&opts);
8408   /* Field 4, the address, is omitted (which makes the columns not
8409      line up too nicely with the headers, but the effect is relatively
8410      readable).  */
8411   if (opts.addressprint)
8412     {
8413       annotate_field (4);
8414       uiout->field_skip ("addr");
8415     }
8416
8417   annotate_field (5);
8418   if (self->is_load)
8419     {
8420       if (self->regex)
8421         msg = xstrprintf (_("load of library matching %s"), self->regex);
8422       else
8423         msg = xstrdup (_("load of library"));
8424     }
8425   else
8426     {
8427       if (self->regex)
8428         msg = xstrprintf (_("unload of library matching %s"), self->regex);
8429       else
8430         msg = xstrdup (_("unload of library"));
8431     }
8432   uiout->field_string ("what", msg);
8433   xfree (msg);
8434
8435   if (uiout->is_mi_like_p ())
8436     uiout->field_string ("catch-type", self->is_load ? "load" : "unload");
8437 }
8438
8439 static void
8440 print_mention_catch_solib (struct breakpoint *b)
8441 {
8442   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8443
8444   printf_filtered (_("Catchpoint %d (%s)"), b->number,
8445                    self->is_load ? "load" : "unload");
8446 }
8447
8448 static void
8449 print_recreate_catch_solib (struct breakpoint *b, struct ui_file *fp)
8450 {
8451   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8452
8453   fprintf_unfiltered (fp, "%s %s",
8454                       b->disposition == disp_del ? "tcatch" : "catch",
8455                       self->is_load ? "load" : "unload");
8456   if (self->regex)
8457     fprintf_unfiltered (fp, " %s", self->regex);
8458   fprintf_unfiltered (fp, "\n");
8459 }
8460
8461 static struct breakpoint_ops catch_solib_breakpoint_ops;
8462
8463 /* Shared helper function (MI and CLI) for creating and installing
8464    a shared object event catchpoint.  If IS_LOAD is non-zero then
8465    the events to be caught are load events, otherwise they are
8466    unload events.  If IS_TEMP is non-zero the catchpoint is a
8467    temporary one.  If ENABLED is non-zero the catchpoint is
8468    created in an enabled state.  */
8469
8470 void
8471 add_solib_catchpoint (const char *arg, int is_load, int is_temp, int enabled)
8472 {
8473   struct solib_catchpoint *c;
8474   struct gdbarch *gdbarch = get_current_arch ();
8475   struct cleanup *cleanup;
8476
8477   if (!arg)
8478     arg = "";
8479   arg = skip_spaces_const (arg);
8480
8481   c = new solib_catchpoint ();
8482   cleanup = make_cleanup (xfree, c);
8483
8484   if (*arg != '\0')
8485     {
8486       c->compiled.reset (new compiled_regex (arg, REG_NOSUB,
8487                                              _("Invalid regexp")));
8488       c->regex = xstrdup (arg);
8489     }
8490
8491   c->is_load = is_load;
8492   init_catchpoint (c, gdbarch, is_temp, NULL,
8493                    &catch_solib_breakpoint_ops);
8494
8495   c->enable_state = enabled ? bp_enabled : bp_disabled;
8496
8497   discard_cleanups (cleanup);
8498   install_breakpoint (0, c, 1);
8499 }
8500
8501 /* A helper function that does all the work for "catch load" and
8502    "catch unload".  */
8503
8504 static void
8505 catch_load_or_unload (char *arg, int from_tty, int is_load,
8506                       struct cmd_list_element *command)
8507 {
8508   int tempflag;
8509   const int enabled = 1;
8510
8511   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
8512
8513   add_solib_catchpoint (arg, is_load, tempflag, enabled);
8514 }
8515
8516 static void
8517 catch_load_command_1 (char *arg, int from_tty,
8518                       struct cmd_list_element *command)
8519 {
8520   catch_load_or_unload (arg, from_tty, 1, command);
8521 }
8522
8523 static void
8524 catch_unload_command_1 (char *arg, int from_tty,
8525                         struct cmd_list_element *command)
8526 {
8527   catch_load_or_unload (arg, from_tty, 0, command);
8528 }
8529
8530 /* Initialize a new breakpoint of the bp_catchpoint kind.  If TEMPFLAG
8531    is non-zero, then make the breakpoint temporary.  If COND_STRING is
8532    not NULL, then store it in the breakpoint.  OPS, if not NULL, is
8533    the breakpoint_ops structure associated to the catchpoint.  */
8534
8535 void
8536 init_catchpoint (struct breakpoint *b,
8537                  struct gdbarch *gdbarch, int tempflag,
8538                  const char *cond_string,
8539                  const struct breakpoint_ops *ops)
8540 {
8541   struct symtab_and_line sal;
8542
8543   init_sal (&sal);
8544   sal.pspace = current_program_space;
8545
8546   init_raw_breakpoint (b, gdbarch, sal, bp_catchpoint, ops);
8547
8548   b->cond_string = (cond_string == NULL) ? NULL : xstrdup (cond_string);
8549   b->disposition = tempflag ? disp_del : disp_donttouch;
8550 }
8551
8552 void
8553 install_breakpoint (int internal, struct breakpoint *b, int update_gll)
8554 {
8555   add_to_breakpoint_chain (b);
8556   set_breakpoint_number (internal, b);
8557   if (is_tracepoint (b))
8558     set_tracepoint_count (breakpoint_count);
8559   if (!internal)
8560     mention (b);
8561   observer_notify_breakpoint_created (b);
8562
8563   if (update_gll)
8564     update_global_location_list (UGLL_MAY_INSERT);
8565 }
8566
8567 static void
8568 create_fork_vfork_event_catchpoint (struct gdbarch *gdbarch,
8569                                     int tempflag, const char *cond_string,
8570                                     const struct breakpoint_ops *ops)
8571 {
8572   struct fork_catchpoint *c = new fork_catchpoint ();
8573
8574   init_catchpoint (c, gdbarch, tempflag, cond_string, ops);
8575
8576   c->forked_inferior_pid = null_ptid;
8577
8578   install_breakpoint (0, c, 1);
8579 }
8580
8581 /* Exec catchpoints.  */
8582
8583 /* An instance of this type is used to represent an exec catchpoint.
8584    A breakpoint is really of this type iff its ops pointer points to
8585    CATCH_EXEC_BREAKPOINT_OPS.  */
8586
8587 struct exec_catchpoint : public breakpoint
8588 {
8589   ~exec_catchpoint () override;
8590
8591   /* Filename of a program whose exec triggered this catchpoint.
8592      This field is only valid immediately after this catchpoint has
8593      triggered.  */
8594   char *exec_pathname;
8595 };
8596
8597 /* Exec catchpoint destructor.  */
8598
8599 exec_catchpoint::~exec_catchpoint ()
8600 {
8601   xfree (this->exec_pathname);
8602 }
8603
8604 static int
8605 insert_catch_exec (struct bp_location *bl)
8606 {
8607   return target_insert_exec_catchpoint (ptid_get_pid (inferior_ptid));
8608 }
8609
8610 static int
8611 remove_catch_exec (struct bp_location *bl, enum remove_bp_reason reason)
8612 {
8613   return target_remove_exec_catchpoint (ptid_get_pid (inferior_ptid));
8614 }
8615
8616 static int
8617 breakpoint_hit_catch_exec (const struct bp_location *bl,
8618                            struct address_space *aspace, CORE_ADDR bp_addr,
8619                            const struct target_waitstatus *ws)
8620 {
8621   struct exec_catchpoint *c = (struct exec_catchpoint *) bl->owner;
8622
8623   if (ws->kind != TARGET_WAITKIND_EXECD)
8624     return 0;
8625
8626   c->exec_pathname = xstrdup (ws->value.execd_pathname);
8627   return 1;
8628 }
8629
8630 static enum print_stop_action
8631 print_it_catch_exec (bpstat bs)
8632 {
8633   struct ui_out *uiout = current_uiout;
8634   struct breakpoint *b = bs->breakpoint_at;
8635   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
8636
8637   annotate_catchpoint (b->number);
8638   maybe_print_thread_hit_breakpoint (uiout);
8639   if (b->disposition == disp_del)
8640     uiout->text ("Temporary catchpoint ");
8641   else
8642     uiout->text ("Catchpoint ");
8643   if (uiout->is_mi_like_p ())
8644     {
8645       uiout->field_string ("reason", async_reason_lookup (EXEC_ASYNC_EXEC));
8646       uiout->field_string ("disp", bpdisp_text (b->disposition));
8647     }
8648   uiout->field_int ("bkptno", b->number);
8649   uiout->text (" (exec'd ");
8650   uiout->field_string ("new-exec", c->exec_pathname);
8651   uiout->text ("), ");
8652
8653   return PRINT_SRC_AND_LOC;
8654 }
8655
8656 static void
8657 print_one_catch_exec (struct breakpoint *b, struct bp_location **last_loc)
8658 {
8659   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
8660   struct value_print_options opts;
8661   struct ui_out *uiout = current_uiout;
8662
8663   get_user_print_options (&opts);
8664
8665   /* Field 4, the address, is omitted (which makes the columns
8666      not line up too nicely with the headers, but the effect
8667      is relatively readable).  */
8668   if (opts.addressprint)
8669     uiout->field_skip ("addr");
8670   annotate_field (5);
8671   uiout->text ("exec");
8672   if (c->exec_pathname != NULL)
8673     {
8674       uiout->text (", program \"");
8675       uiout->field_string ("what", c->exec_pathname);
8676       uiout->text ("\" ");
8677     }
8678
8679   if (uiout->is_mi_like_p ())
8680     uiout->field_string ("catch-type", "exec");
8681 }
8682
8683 static void
8684 print_mention_catch_exec (struct breakpoint *b)
8685 {
8686   printf_filtered (_("Catchpoint %d (exec)"), b->number);
8687 }
8688
8689 /* Implement the "print_recreate" breakpoint_ops method for exec
8690    catchpoints.  */
8691
8692 static void
8693 print_recreate_catch_exec (struct breakpoint *b, struct ui_file *fp)
8694 {
8695   fprintf_unfiltered (fp, "catch exec");
8696   print_recreate_thread (b, fp);
8697 }
8698
8699 static struct breakpoint_ops catch_exec_breakpoint_ops;
8700
8701 static int
8702 hw_breakpoint_used_count (void)
8703 {
8704   int i = 0;
8705   struct breakpoint *b;
8706   struct bp_location *bl;
8707
8708   ALL_BREAKPOINTS (b)
8709   {
8710     if (b->type == bp_hardware_breakpoint && breakpoint_enabled (b))
8711       for (bl = b->loc; bl; bl = bl->next)
8712         {
8713           /* Special types of hardware breakpoints may use more than
8714              one register.  */
8715           i += b->ops->resources_needed (bl);
8716         }
8717   }
8718
8719   return i;
8720 }
8721
8722 /* Returns the resources B would use if it were a hardware
8723    watchpoint.  */
8724
8725 static int
8726 hw_watchpoint_use_count (struct breakpoint *b)
8727 {
8728   int i = 0;
8729   struct bp_location *bl;
8730
8731   if (!breakpoint_enabled (b))
8732     return 0;
8733
8734   for (bl = b->loc; bl; bl = bl->next)
8735     {
8736       /* Special types of hardware watchpoints may use more than
8737          one register.  */
8738       i += b->ops->resources_needed (bl);
8739     }
8740
8741   return i;
8742 }
8743
8744 /* Returns the sum the used resources of all hardware watchpoints of
8745    type TYPE in the breakpoints list.  Also returns in OTHER_TYPE_USED
8746    the sum of the used resources of all hardware watchpoints of other
8747    types _not_ TYPE.  */
8748
8749 static int
8750 hw_watchpoint_used_count_others (struct breakpoint *except,
8751                                  enum bptype type, int *other_type_used)
8752 {
8753   int i = 0;
8754   struct breakpoint *b;
8755
8756   *other_type_used = 0;
8757   ALL_BREAKPOINTS (b)
8758     {
8759       if (b == except)
8760         continue;
8761       if (!breakpoint_enabled (b))
8762         continue;
8763
8764       if (b->type == type)
8765         i += hw_watchpoint_use_count (b);
8766       else if (is_hardware_watchpoint (b))
8767         *other_type_used = 1;
8768     }
8769
8770   return i;
8771 }
8772
8773 void
8774 disable_watchpoints_before_interactive_call_start (void)
8775 {
8776   struct breakpoint *b;
8777
8778   ALL_BREAKPOINTS (b)
8779   {
8780     if (is_watchpoint (b) && breakpoint_enabled (b))
8781       {
8782         b->enable_state = bp_call_disabled;
8783         update_global_location_list (UGLL_DONT_INSERT);
8784       }
8785   }
8786 }
8787
8788 void
8789 enable_watchpoints_after_interactive_call_stop (void)
8790 {
8791   struct breakpoint *b;
8792
8793   ALL_BREAKPOINTS (b)
8794   {
8795     if (is_watchpoint (b) && b->enable_state == bp_call_disabled)
8796       {
8797         b->enable_state = bp_enabled;
8798         update_global_location_list (UGLL_MAY_INSERT);
8799       }
8800   }
8801 }
8802
8803 void
8804 disable_breakpoints_before_startup (void)
8805 {
8806   current_program_space->executing_startup = 1;
8807   update_global_location_list (UGLL_DONT_INSERT);
8808 }
8809
8810 void
8811 enable_breakpoints_after_startup (void)
8812 {
8813   current_program_space->executing_startup = 0;
8814   breakpoint_re_set ();
8815 }
8816
8817 /* Create a new single-step breakpoint for thread THREAD, with no
8818    locations.  */
8819
8820 static struct breakpoint *
8821 new_single_step_breakpoint (int thread, struct gdbarch *gdbarch)
8822 {
8823   struct breakpoint *b = new breakpoint ();
8824
8825   init_raw_breakpoint_without_location (b, gdbarch, bp_single_step,
8826                                         &momentary_breakpoint_ops);
8827
8828   b->disposition = disp_donttouch;
8829   b->frame_id = null_frame_id;
8830
8831   b->thread = thread;
8832   gdb_assert (b->thread != 0);
8833
8834   add_to_breakpoint_chain (b);
8835
8836   return b;
8837 }
8838
8839 /* Set a momentary breakpoint of type TYPE at address specified by
8840    SAL.  If FRAME_ID is valid, the breakpoint is restricted to that
8841    frame.  */
8842
8843 struct breakpoint *
8844 set_momentary_breakpoint (struct gdbarch *gdbarch, struct symtab_and_line sal,
8845                           struct frame_id frame_id, enum bptype type)
8846 {
8847   struct breakpoint *b;
8848
8849   /* If FRAME_ID is valid, it should be a real frame, not an inlined or
8850      tail-called one.  */
8851   gdb_assert (!frame_id_artificial_p (frame_id));
8852
8853   b = set_raw_breakpoint (gdbarch, sal, type, &momentary_breakpoint_ops);
8854   b->enable_state = bp_enabled;
8855   b->disposition = disp_donttouch;
8856   b->frame_id = frame_id;
8857
8858   /* If we're debugging a multi-threaded program, then we want
8859      momentary breakpoints to be active in only a single thread of
8860      control.  */
8861   if (in_thread_list (inferior_ptid))
8862     b->thread = ptid_to_global_thread_id (inferior_ptid);
8863
8864   update_global_location_list_nothrow (UGLL_MAY_INSERT);
8865
8866   return b;
8867 }
8868
8869 /* Make a momentary breakpoint based on the master breakpoint ORIG.
8870    The new breakpoint will have type TYPE, use OPS as its
8871    breakpoint_ops, and will set enabled to LOC_ENABLED.  */
8872
8873 static struct breakpoint *
8874 momentary_breakpoint_from_master (struct breakpoint *orig,
8875                                   enum bptype type,
8876                                   const struct breakpoint_ops *ops,
8877                                   int loc_enabled)
8878 {
8879   struct breakpoint *copy;
8880
8881   copy = set_raw_breakpoint_without_location (orig->gdbarch, type, ops);
8882   copy->loc = allocate_bp_location (copy);
8883   set_breakpoint_location_function (copy->loc, 1);
8884
8885   copy->loc->gdbarch = orig->loc->gdbarch;
8886   copy->loc->requested_address = orig->loc->requested_address;
8887   copy->loc->address = orig->loc->address;
8888   copy->loc->section = orig->loc->section;
8889   copy->loc->pspace = orig->loc->pspace;
8890   copy->loc->probe = orig->loc->probe;
8891   copy->loc->line_number = orig->loc->line_number;
8892   copy->loc->symtab = orig->loc->symtab;
8893   copy->loc->enabled = loc_enabled;
8894   copy->frame_id = orig->frame_id;
8895   copy->thread = orig->thread;
8896   copy->pspace = orig->pspace;
8897
8898   copy->enable_state = bp_enabled;
8899   copy->disposition = disp_donttouch;
8900   copy->number = internal_breakpoint_number--;
8901
8902   update_global_location_list_nothrow (UGLL_DONT_INSERT);
8903   return copy;
8904 }
8905
8906 /* Make a deep copy of momentary breakpoint ORIG.  Returns NULL if
8907    ORIG is NULL.  */
8908
8909 struct breakpoint *
8910 clone_momentary_breakpoint (struct breakpoint *orig)
8911 {
8912   /* If there's nothing to clone, then return nothing.  */
8913   if (orig == NULL)
8914     return NULL;
8915
8916   return momentary_breakpoint_from_master (orig, orig->type, orig->ops, 0);
8917 }
8918
8919 struct breakpoint *
8920 set_momentary_breakpoint_at_pc (struct gdbarch *gdbarch, CORE_ADDR pc,
8921                                 enum bptype type)
8922 {
8923   struct symtab_and_line sal;
8924
8925   sal = find_pc_line (pc, 0);
8926   sal.pc = pc;
8927   sal.section = find_pc_overlay (pc);
8928   sal.explicit_pc = 1;
8929
8930   return set_momentary_breakpoint (gdbarch, sal, null_frame_id, type);
8931 }
8932 \f
8933
8934 /* Tell the user we have just set a breakpoint B.  */
8935
8936 static void
8937 mention (struct breakpoint *b)
8938 {
8939   b->ops->print_mention (b);
8940   if (current_uiout->is_mi_like_p ())
8941     return;
8942   printf_filtered ("\n");
8943 }
8944 \f
8945
8946 static int bp_loc_is_permanent (struct bp_location *loc);
8947
8948 static struct bp_location *
8949 add_location_to_breakpoint (struct breakpoint *b,
8950                             const struct symtab_and_line *sal)
8951 {
8952   struct bp_location *loc, **tmp;
8953   CORE_ADDR adjusted_address;
8954   struct gdbarch *loc_gdbarch = get_sal_arch (*sal);
8955
8956   if (loc_gdbarch == NULL)
8957     loc_gdbarch = b->gdbarch;
8958
8959   /* Adjust the breakpoint's address prior to allocating a location.
8960      Once we call allocate_bp_location(), that mostly uninitialized
8961      location will be placed on the location chain.  Adjustment of the
8962      breakpoint may cause target_read_memory() to be called and we do
8963      not want its scan of the location chain to find a breakpoint and
8964      location that's only been partially initialized.  */
8965   adjusted_address = adjust_breakpoint_address (loc_gdbarch,
8966                                                 sal->pc, b->type);
8967
8968   /* Sort the locations by their ADDRESS.  */
8969   loc = allocate_bp_location (b);
8970   for (tmp = &(b->loc); *tmp != NULL && (*tmp)->address <= adjusted_address;
8971        tmp = &((*tmp)->next))
8972     ;
8973   loc->next = *tmp;
8974   *tmp = loc;
8975
8976   loc->requested_address = sal->pc;
8977   loc->address = adjusted_address;
8978   loc->pspace = sal->pspace;
8979   loc->probe.probe = sal->probe;
8980   loc->probe.objfile = sal->objfile;
8981   gdb_assert (loc->pspace != NULL);
8982   loc->section = sal->section;
8983   loc->gdbarch = loc_gdbarch;
8984   loc->line_number = sal->line;
8985   loc->symtab = sal->symtab;
8986
8987   set_breakpoint_location_function (loc,
8988                                     sal->explicit_pc || sal->explicit_line);
8989
8990   /* While by definition, permanent breakpoints are already present in the
8991      code, we don't mark the location as inserted.  Normally one would expect
8992      that GDB could rely on that breakpoint instruction to stop the program,
8993      thus removing the need to insert its own breakpoint, except that executing
8994      the breakpoint instruction can kill the target instead of reporting a
8995      SIGTRAP.  E.g., on SPARC, when interrupts are disabled, executing the
8996      instruction resets the CPU, so QEMU 2.0.0 for SPARC correspondingly dies
8997      with "Trap 0x02 while interrupts disabled, Error state".  Letting the
8998      breakpoint be inserted normally results in QEMU knowing about the GDB
8999      breakpoint, and thus trap before the breakpoint instruction is executed.
9000      (If GDB later needs to continue execution past the permanent breakpoint,
9001      it manually increments the PC, thus avoiding executing the breakpoint
9002      instruction.)  */
9003   if (bp_loc_is_permanent (loc))
9004     loc->permanent = 1;
9005
9006   return loc;
9007 }
9008 \f
9009
9010 /* See breakpoint.h.  */
9011
9012 int
9013 program_breakpoint_here_p (struct gdbarch *gdbarch, CORE_ADDR address)
9014 {
9015   int len;
9016   CORE_ADDR addr;
9017   const gdb_byte *bpoint;
9018   gdb_byte *target_mem;
9019   struct cleanup *cleanup;
9020   int retval = 0;
9021
9022   addr = address;
9023   bpoint = gdbarch_breakpoint_from_pc (gdbarch, &addr, &len);
9024
9025   /* Software breakpoints unsupported?  */
9026   if (bpoint == NULL)
9027     return 0;
9028
9029   target_mem = (gdb_byte *) alloca (len);
9030
9031   /* Enable the automatic memory restoration from breakpoints while
9032      we read the memory.  Otherwise we could say about our temporary
9033      breakpoints they are permanent.  */
9034   cleanup = make_show_memory_breakpoints_cleanup (0);
9035
9036   if (target_read_memory (address, target_mem, len) == 0
9037       && memcmp (target_mem, bpoint, len) == 0)
9038     retval = 1;
9039
9040   do_cleanups (cleanup);
9041
9042   return retval;
9043 }
9044
9045 /* Return 1 if LOC is pointing to a permanent breakpoint,
9046    return 0 otherwise.  */
9047
9048 static int
9049 bp_loc_is_permanent (struct bp_location *loc)
9050 {
9051   gdb_assert (loc != NULL);
9052
9053   /* If we have a catchpoint or a watchpoint, just return 0.  We should not
9054      attempt to read from the addresses the locations of these breakpoint types
9055      point to.  program_breakpoint_here_p, below, will attempt to read
9056      memory.  */
9057   if (!breakpoint_address_is_meaningful (loc->owner))
9058     return 0;
9059
9060   scoped_restore_current_pspace_and_thread restore_pspace_thread;
9061   switch_to_program_space_and_thread (loc->pspace);
9062   return program_breakpoint_here_p (loc->gdbarch, loc->address);
9063 }
9064
9065 /* Build a command list for the dprintf corresponding to the current
9066    settings of the dprintf style options.  */
9067
9068 static void
9069 update_dprintf_command_list (struct breakpoint *b)
9070 {
9071   char *dprintf_args = b->extra_string;
9072   char *printf_line = NULL;
9073
9074   if (!dprintf_args)
9075     return;
9076
9077   dprintf_args = skip_spaces (dprintf_args);
9078
9079   /* Allow a comma, as it may have terminated a location, but don't
9080      insist on it.  */
9081   if (*dprintf_args == ',')
9082     ++dprintf_args;
9083   dprintf_args = skip_spaces (dprintf_args);
9084
9085   if (*dprintf_args != '"')
9086     error (_("Bad format string, missing '\"'."));
9087
9088   if (strcmp (dprintf_style, dprintf_style_gdb) == 0)
9089     printf_line = xstrprintf ("printf %s", dprintf_args);
9090   else if (strcmp (dprintf_style, dprintf_style_call) == 0)
9091     {
9092       if (!dprintf_function)
9093         error (_("No function supplied for dprintf call"));
9094
9095       if (dprintf_channel && strlen (dprintf_channel) > 0)
9096         printf_line = xstrprintf ("call (void) %s (%s,%s)",
9097                                   dprintf_function,
9098                                   dprintf_channel,
9099                                   dprintf_args);
9100       else
9101         printf_line = xstrprintf ("call (void) %s (%s)",
9102                                   dprintf_function,
9103                                   dprintf_args);
9104     }
9105   else if (strcmp (dprintf_style, dprintf_style_agent) == 0)
9106     {
9107       if (target_can_run_breakpoint_commands ())
9108         printf_line = xstrprintf ("agent-printf %s", dprintf_args);
9109       else
9110         {
9111           warning (_("Target cannot run dprintf commands, falling back to GDB printf"));
9112           printf_line = xstrprintf ("printf %s", dprintf_args);
9113         }
9114     }
9115   else
9116     internal_error (__FILE__, __LINE__,
9117                     _("Invalid dprintf style."));
9118
9119   gdb_assert (printf_line != NULL);
9120   /* Manufacture a printf sequence.  */
9121   {
9122     struct command_line *printf_cmd_line = XNEW (struct command_line);
9123
9124     printf_cmd_line->control_type = simple_control;
9125     printf_cmd_line->body_count = 0;
9126     printf_cmd_line->body_list = NULL;
9127     printf_cmd_line->next = NULL;
9128     printf_cmd_line->line = printf_line;
9129
9130     breakpoint_set_commands (b, command_line_up (printf_cmd_line));
9131   }
9132 }
9133
9134 /* Update all dprintf commands, making their command lists reflect
9135    current style settings.  */
9136
9137 static void
9138 update_dprintf_commands (char *args, int from_tty,
9139                          struct cmd_list_element *c)
9140 {
9141   struct breakpoint *b;
9142
9143   ALL_BREAKPOINTS (b)
9144     {
9145       if (b->type == bp_dprintf)
9146         update_dprintf_command_list (b);
9147     }
9148 }
9149
9150 /* Create a breakpoint with SAL as location.  Use LOCATION
9151    as a description of the location, and COND_STRING
9152    as condition expression.  If LOCATION is NULL then create an
9153    "address location" from the address in the SAL.  */
9154
9155 static void
9156 init_breakpoint_sal (struct breakpoint *b, struct gdbarch *gdbarch,
9157                      struct symtabs_and_lines sals,
9158                      event_location_up &&location,
9159                      gdb::unique_xmalloc_ptr<char> filter,
9160                      gdb::unique_xmalloc_ptr<char> cond_string,
9161                      gdb::unique_xmalloc_ptr<char> extra_string,
9162                      enum bptype type, enum bpdisp disposition,
9163                      int thread, int task, int ignore_count,
9164                      const struct breakpoint_ops *ops, int from_tty,
9165                      int enabled, int internal, unsigned flags,
9166                      int display_canonical)
9167 {
9168   int i;
9169
9170   if (type == bp_hardware_breakpoint)
9171     {
9172       int target_resources_ok;
9173
9174       i = hw_breakpoint_used_count ();
9175       target_resources_ok =
9176         target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
9177                                             i + 1, 0);
9178       if (target_resources_ok == 0)
9179         error (_("No hardware breakpoint support in the target."));
9180       else if (target_resources_ok < 0)
9181         error (_("Hardware breakpoints used exceeds limit."));
9182     }
9183
9184   gdb_assert (sals.nelts > 0);
9185
9186   for (i = 0; i < sals.nelts; ++i)
9187     {
9188       struct symtab_and_line sal = sals.sals[i];
9189       struct bp_location *loc;
9190
9191       if (from_tty)
9192         {
9193           struct gdbarch *loc_gdbarch = get_sal_arch (sal);
9194           if (!loc_gdbarch)
9195             loc_gdbarch = gdbarch;
9196
9197           describe_other_breakpoints (loc_gdbarch,
9198                                       sal.pspace, sal.pc, sal.section, thread);
9199         }
9200
9201       if (i == 0)
9202         {
9203           init_raw_breakpoint (b, gdbarch, sal, type, ops);
9204           b->thread = thread;
9205           b->task = task;
9206
9207           b->cond_string = cond_string.release ();
9208           b->extra_string = extra_string.release ();
9209           b->ignore_count = ignore_count;
9210           b->enable_state = enabled ? bp_enabled : bp_disabled;
9211           b->disposition = disposition;
9212
9213           if ((flags & CREATE_BREAKPOINT_FLAGS_INSERTED) != 0)
9214             b->loc->inserted = 1;
9215
9216           if (type == bp_static_tracepoint)
9217             {
9218               struct tracepoint *t = (struct tracepoint *) b;
9219               struct static_tracepoint_marker marker;
9220
9221               if (strace_marker_p (b))
9222                 {
9223                   /* We already know the marker exists, otherwise, we
9224                      wouldn't see a sal for it.  */
9225                   const char *p
9226                     = &event_location_to_string (b->location.get ())[3];
9227                   const char *endp;
9228                   char *marker_str;
9229
9230                   p = skip_spaces_const (p);
9231
9232                   endp = skip_to_space_const (p);
9233
9234                   marker_str = savestring (p, endp - p);
9235                   t->static_trace_marker_id = marker_str;
9236
9237                   printf_filtered (_("Probed static tracepoint "
9238                                      "marker \"%s\"\n"),
9239                                    t->static_trace_marker_id);
9240                 }
9241               else if (target_static_tracepoint_marker_at (sal.pc, &marker))
9242                 {
9243                   t->static_trace_marker_id = xstrdup (marker.str_id);
9244                   release_static_tracepoint_marker (&marker);
9245
9246                   printf_filtered (_("Probed static tracepoint "
9247                                      "marker \"%s\"\n"),
9248                                    t->static_trace_marker_id);
9249                 }
9250               else
9251                 warning (_("Couldn't determine the static "
9252                            "tracepoint marker to probe"));
9253             }
9254
9255           loc = b->loc;
9256         }
9257       else
9258         {
9259           loc = add_location_to_breakpoint (b, &sal);
9260           if ((flags & CREATE_BREAKPOINT_FLAGS_INSERTED) != 0)
9261             loc->inserted = 1;
9262         }
9263
9264       if (b->cond_string)
9265         {
9266           const char *arg = b->cond_string;
9267
9268           loc->cond = parse_exp_1 (&arg, loc->address,
9269                                    block_for_pc (loc->address), 0);
9270           if (*arg)
9271               error (_("Garbage '%s' follows condition"), arg);
9272         }
9273
9274       /* Dynamic printf requires and uses additional arguments on the
9275          command line, otherwise it's an error.  */
9276       if (type == bp_dprintf)
9277         {
9278           if (b->extra_string)
9279             update_dprintf_command_list (b);
9280           else
9281             error (_("Format string required"));
9282         }
9283       else if (b->extra_string)
9284         error (_("Garbage '%s' at end of command"), b->extra_string);
9285     }
9286
9287   b->display_canonical = display_canonical;
9288   if (location != NULL)
9289     b->location = std::move (location);
9290   else
9291     b->location = new_address_location (b->loc->address, NULL, 0);
9292   b->filter = filter.release ();
9293 }
9294
9295 static void
9296 create_breakpoint_sal (struct gdbarch *gdbarch,
9297                        struct symtabs_and_lines sals,
9298                        event_location_up &&location,
9299                        gdb::unique_xmalloc_ptr<char> filter,
9300                        gdb::unique_xmalloc_ptr<char> cond_string,
9301                        gdb::unique_xmalloc_ptr<char> extra_string,
9302                        enum bptype type, enum bpdisp disposition,
9303                        int thread, int task, int ignore_count,
9304                        const struct breakpoint_ops *ops, int from_tty,
9305                        int enabled, int internal, unsigned flags,
9306                        int display_canonical)
9307 {
9308   std::unique_ptr<breakpoint> b = new_breakpoint_from_type (type);
9309
9310   init_breakpoint_sal (b.get (), gdbarch,
9311                        sals, std::move (location),
9312                        std::move (filter),
9313                        std::move (cond_string),
9314                        std::move (extra_string),
9315                        type, disposition,
9316                        thread, task, ignore_count,
9317                        ops, from_tty,
9318                        enabled, internal, flags,
9319                        display_canonical);
9320
9321   install_breakpoint (internal, b.release (), 0);
9322 }
9323
9324 /* Add SALS.nelts breakpoints to the breakpoint table.  For each
9325    SALS.sal[i] breakpoint, include the corresponding ADDR_STRING[i]
9326    value.  COND_STRING, if not NULL, specified the condition to be
9327    used for all breakpoints.  Essentially the only case where
9328    SALS.nelts is not 1 is when we set a breakpoint on an overloaded
9329    function.  In that case, it's still not possible to specify
9330    separate conditions for different overloaded functions, so
9331    we take just a single condition string.
9332    
9333    NOTE: If the function succeeds, the caller is expected to cleanup
9334    the arrays ADDR_STRING, COND_STRING, and SALS (but not the
9335    array contents).  If the function fails (error() is called), the
9336    caller is expected to cleanups both the ADDR_STRING, COND_STRING,
9337    COND and SALS arrays and each of those arrays contents.  */
9338
9339 static void
9340 create_breakpoints_sal (struct gdbarch *gdbarch,
9341                         struct linespec_result *canonical,
9342                         gdb::unique_xmalloc_ptr<char> cond_string,
9343                         gdb::unique_xmalloc_ptr<char> extra_string,
9344                         enum bptype type, enum bpdisp disposition,
9345                         int thread, int task, int ignore_count,
9346                         const struct breakpoint_ops *ops, int from_tty,
9347                         int enabled, int internal, unsigned flags)
9348 {
9349   int i;
9350   struct linespec_sals *lsal;
9351
9352   if (canonical->pre_expanded)
9353     gdb_assert (VEC_length (linespec_sals, canonical->sals) == 1);
9354
9355   for (i = 0; VEC_iterate (linespec_sals, canonical->sals, i, lsal); ++i)
9356     {
9357       /* Note that 'location' can be NULL in the case of a plain
9358          'break', without arguments.  */
9359       event_location_up location
9360         = (canonical->location != NULL
9361            ? copy_event_location (canonical->location.get ()) : NULL);
9362       gdb::unique_xmalloc_ptr<char> filter_string
9363         (lsal->canonical != NULL ? xstrdup (lsal->canonical) : NULL);
9364
9365       create_breakpoint_sal (gdbarch, lsal->sals,
9366                              std::move (location),
9367                              std::move (filter_string),
9368                              std::move (cond_string),
9369                              std::move (extra_string),
9370                              type, disposition,
9371                              thread, task, ignore_count, ops,
9372                              from_tty, enabled, internal, flags,
9373                              canonical->special_display);
9374     }
9375 }
9376
9377 /* Parse LOCATION which is assumed to be a SAL specification possibly
9378    followed by conditionals.  On return, SALS contains an array of SAL
9379    addresses found.  LOCATION points to the end of the SAL (for
9380    linespec locations).
9381
9382    The array and the line spec strings are allocated on the heap, it is
9383    the caller's responsibility to free them.  */
9384
9385 static void
9386 parse_breakpoint_sals (const struct event_location *location,
9387                        struct linespec_result *canonical)
9388 {
9389   struct symtab_and_line cursal;
9390
9391   if (event_location_type (location) == LINESPEC_LOCATION)
9392     {
9393       const char *address = get_linespec_location (location);
9394
9395       if (address == NULL)
9396         {
9397           /* The last displayed codepoint, if it's valid, is our default
9398              breakpoint address.  */
9399           if (last_displayed_sal_is_valid ())
9400             {
9401               struct linespec_sals lsal;
9402               struct symtab_and_line sal;
9403               CORE_ADDR pc;
9404
9405               init_sal (&sal);          /* Initialize to zeroes.  */
9406               lsal.sals.sals = XNEW (struct symtab_and_line);
9407
9408               /* Set sal's pspace, pc, symtab, and line to the values
9409                  corresponding to the last call to print_frame_info.
9410                  Be sure to reinitialize LINE with NOTCURRENT == 0
9411                  as the breakpoint line number is inappropriate otherwise.
9412                  find_pc_line would adjust PC, re-set it back.  */
9413               get_last_displayed_sal (&sal);
9414               pc = sal.pc;
9415               sal = find_pc_line (pc, 0);
9416
9417               /* "break" without arguments is equivalent to "break *PC"
9418                  where PC is the last displayed codepoint's address.  So
9419                  make sure to set sal.explicit_pc to prevent GDB from
9420                  trying to expand the list of sals to include all other
9421                  instances with the same symtab and line.  */
9422               sal.pc = pc;
9423               sal.explicit_pc = 1;
9424
9425               lsal.sals.sals[0] = sal;
9426               lsal.sals.nelts = 1;
9427               lsal.canonical = NULL;
9428
9429               VEC_safe_push (linespec_sals, canonical->sals, &lsal);
9430               return;
9431             }
9432           else
9433             error (_("No default breakpoint address now."));
9434         }
9435     }
9436
9437   /* Force almost all breakpoints to be in terms of the
9438      current_source_symtab (which is decode_line_1's default).
9439      This should produce the results we want almost all of the
9440      time while leaving default_breakpoint_* alone.
9441
9442      ObjC: However, don't match an Objective-C method name which
9443      may have a '+' or '-' succeeded by a '['.  */
9444   cursal = get_current_source_symtab_and_line ();
9445   if (last_displayed_sal_is_valid ())
9446     {
9447       const char *address = NULL;
9448
9449       if (event_location_type (location) == LINESPEC_LOCATION)
9450         address = get_linespec_location (location);
9451
9452       if (!cursal.symtab
9453           || (address != NULL
9454               && strchr ("+-", address[0]) != NULL
9455               && address[1] != '['))
9456         {
9457           decode_line_full (location, DECODE_LINE_FUNFIRSTLINE, NULL,
9458                             get_last_displayed_symtab (),
9459                             get_last_displayed_line (),
9460                             canonical, NULL, NULL);
9461           return;
9462         }
9463     }
9464
9465   decode_line_full (location, DECODE_LINE_FUNFIRSTLINE, NULL,
9466                     cursal.symtab, cursal.line, canonical, NULL, NULL);
9467 }
9468
9469
9470 /* Convert each SAL into a real PC.  Verify that the PC can be
9471    inserted as a breakpoint.  If it can't throw an error.  */
9472
9473 static void
9474 breakpoint_sals_to_pc (struct symtabs_and_lines *sals)
9475 {    
9476   int i;
9477
9478   for (i = 0; i < sals->nelts; i++)
9479     resolve_sal_pc (&sals->sals[i]);
9480 }
9481
9482 /* Fast tracepoints may have restrictions on valid locations.  For
9483    instance, a fast tracepoint using a jump instead of a trap will
9484    likely have to overwrite more bytes than a trap would, and so can
9485    only be placed where the instruction is longer than the jump, or a
9486    multi-instruction sequence does not have a jump into the middle of
9487    it, etc.  */
9488
9489 static void
9490 check_fast_tracepoint_sals (struct gdbarch *gdbarch,
9491                             struct symtabs_and_lines *sals)
9492 {
9493   int i, rslt;
9494   struct symtab_and_line *sal;
9495   char *msg;
9496   struct cleanup *old_chain;
9497
9498   for (i = 0; i < sals->nelts; i++)
9499     {
9500       struct gdbarch *sarch;
9501
9502       sal = &sals->sals[i];
9503
9504       sarch = get_sal_arch (*sal);
9505       /* We fall back to GDBARCH if there is no architecture
9506          associated with SAL.  */
9507       if (sarch == NULL)
9508         sarch = gdbarch;
9509       rslt = gdbarch_fast_tracepoint_valid_at (sarch, sal->pc, &msg);
9510       old_chain = make_cleanup (xfree, msg);
9511
9512       if (!rslt)
9513         error (_("May not have a fast tracepoint at %s%s"),
9514                paddress (sarch, sal->pc), (msg ? msg : ""));
9515
9516       do_cleanups (old_chain);
9517     }
9518 }
9519
9520 /* Given TOK, a string specification of condition and thread, as
9521    accepted by the 'break' command, extract the condition
9522    string and thread number and set *COND_STRING and *THREAD.
9523    PC identifies the context at which the condition should be parsed.
9524    If no condition is found, *COND_STRING is set to NULL.
9525    If no thread is found, *THREAD is set to -1.  */
9526
9527 static void
9528 find_condition_and_thread (const char *tok, CORE_ADDR pc,
9529                            char **cond_string, int *thread, int *task,
9530                            char **rest)
9531 {
9532   *cond_string = NULL;
9533   *thread = -1;
9534   *task = 0;
9535   *rest = NULL;
9536
9537   while (tok && *tok)
9538     {
9539       const char *end_tok;
9540       int toklen;
9541       const char *cond_start = NULL;
9542       const char *cond_end = NULL;
9543
9544       tok = skip_spaces_const (tok);
9545
9546       if ((*tok == '"' || *tok == ',') && rest)
9547         {
9548           *rest = savestring (tok, strlen (tok));
9549           return;
9550         }
9551
9552       end_tok = skip_to_space_const (tok);
9553
9554       toklen = end_tok - tok;
9555
9556       if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
9557         {
9558           tok = cond_start = end_tok + 1;
9559           parse_exp_1 (&tok, pc, block_for_pc (pc), 0);
9560           cond_end = tok;
9561           *cond_string = savestring (cond_start, cond_end - cond_start);
9562         }
9563       else if (toklen >= 1 && strncmp (tok, "thread", toklen) == 0)
9564         {
9565           const char *tmptok;
9566           struct thread_info *thr;
9567
9568           tok = end_tok + 1;
9569           thr = parse_thread_id (tok, &tmptok);
9570           if (tok == tmptok)
9571             error (_("Junk after thread keyword."));
9572           *thread = thr->global_num;
9573           tok = tmptok;
9574         }
9575       else if (toklen >= 1 && strncmp (tok, "task", toklen) == 0)
9576         {
9577           char *tmptok;
9578
9579           tok = end_tok + 1;
9580           *task = strtol (tok, &tmptok, 0);
9581           if (tok == tmptok)
9582             error (_("Junk after task keyword."));
9583           if (!valid_task_id (*task))
9584             error (_("Unknown task %d."), *task);
9585           tok = tmptok;
9586         }
9587       else if (rest)
9588         {
9589           *rest = savestring (tok, strlen (tok));
9590           return;
9591         }
9592       else
9593         error (_("Junk at end of arguments."));
9594     }
9595 }
9596
9597 /* Decode a static tracepoint marker spec.  */
9598
9599 static struct symtabs_and_lines
9600 decode_static_tracepoint_spec (const char **arg_p)
9601 {
9602   VEC(static_tracepoint_marker_p) *markers = NULL;
9603   struct symtabs_and_lines sals;
9604   struct cleanup *old_chain;
9605   const char *p = &(*arg_p)[3];
9606   const char *endp;
9607   char *marker_str;
9608   int i;
9609
9610   p = skip_spaces_const (p);
9611
9612   endp = skip_to_space_const (p);
9613
9614   marker_str = savestring (p, endp - p);
9615   old_chain = make_cleanup (xfree, marker_str);
9616
9617   markers = target_static_tracepoint_markers_by_strid (marker_str);
9618   if (VEC_empty(static_tracepoint_marker_p, markers))
9619     error (_("No known static tracepoint marker named %s"), marker_str);
9620
9621   sals.nelts = VEC_length(static_tracepoint_marker_p, markers);
9622   sals.sals = XNEWVEC (struct symtab_and_line, sals.nelts);
9623
9624   for (i = 0; i < sals.nelts; i++)
9625     {
9626       struct static_tracepoint_marker *marker;
9627
9628       marker = VEC_index (static_tracepoint_marker_p, markers, i);
9629
9630       init_sal (&sals.sals[i]);
9631
9632       sals.sals[i] = find_pc_line (marker->address, 0);
9633       sals.sals[i].pc = marker->address;
9634
9635       release_static_tracepoint_marker (marker);
9636     }
9637
9638   do_cleanups (old_chain);
9639
9640   *arg_p = endp;
9641   return sals;
9642 }
9643
9644 /* See breakpoint.h.  */
9645
9646 int
9647 create_breakpoint (struct gdbarch *gdbarch,
9648                    const struct event_location *location,
9649                    const char *cond_string,
9650                    int thread, const char *extra_string,
9651                    int parse_extra,
9652                    int tempflag, enum bptype type_wanted,
9653                    int ignore_count,
9654                    enum auto_boolean pending_break_support,
9655                    const struct breakpoint_ops *ops,
9656                    int from_tty, int enabled, int internal,
9657                    unsigned flags)
9658 {
9659   struct linespec_result canonical;
9660   struct cleanup *bkpt_chain = NULL;
9661   int pending = 0;
9662   int task = 0;
9663   int prev_bkpt_count = breakpoint_count;
9664
9665   gdb_assert (ops != NULL);
9666
9667   /* If extra_string isn't useful, set it to NULL.  */
9668   if (extra_string != NULL && *extra_string == '\0')
9669     extra_string = NULL;
9670
9671   TRY
9672     {
9673       ops->create_sals_from_location (location, &canonical, type_wanted);
9674     }
9675   CATCH (e, RETURN_MASK_ERROR)
9676     {
9677       /* If caller is interested in rc value from parse, set
9678          value.  */
9679       if (e.error == NOT_FOUND_ERROR)
9680         {
9681           /* If pending breakpoint support is turned off, throw
9682              error.  */
9683
9684           if (pending_break_support == AUTO_BOOLEAN_FALSE)
9685             throw_exception (e);
9686
9687           exception_print (gdb_stderr, e);
9688
9689           /* If pending breakpoint support is auto query and the user
9690              selects no, then simply return the error code.  */
9691           if (pending_break_support == AUTO_BOOLEAN_AUTO
9692               && !nquery (_("Make %s pending on future shared library load? "),
9693                           bptype_string (type_wanted)))
9694             return 0;
9695
9696           /* At this point, either the user was queried about setting
9697              a pending breakpoint and selected yes, or pending
9698              breakpoint behavior is on and thus a pending breakpoint
9699              is defaulted on behalf of the user.  */
9700           pending = 1;
9701         }
9702       else
9703         throw_exception (e);
9704     }
9705   END_CATCH
9706
9707   if (!pending && VEC_empty (linespec_sals, canonical.sals))
9708     return 0;
9709
9710   /* ----------------------------- SNIP -----------------------------
9711      Anything added to the cleanup chain beyond this point is assumed
9712      to be part of a breakpoint.  If the breakpoint create succeeds
9713      then the memory is not reclaimed.  */
9714   bkpt_chain = make_cleanup (null_cleanup, 0);
9715
9716   /* Resolve all line numbers to PC's and verify that the addresses
9717      are ok for the target.  */
9718   if (!pending)
9719     {
9720       int ix;
9721       struct linespec_sals *iter;
9722
9723       for (ix = 0; VEC_iterate (linespec_sals, canonical.sals, ix, iter); ++ix)
9724         breakpoint_sals_to_pc (&iter->sals);
9725     }
9726
9727   /* Fast tracepoints may have additional restrictions on location.  */
9728   if (!pending && type_wanted == bp_fast_tracepoint)
9729     {
9730       int ix;
9731       struct linespec_sals *iter;
9732
9733       for (ix = 0; VEC_iterate (linespec_sals, canonical.sals, ix, iter); ++ix)
9734         check_fast_tracepoint_sals (gdbarch, &iter->sals);
9735     }
9736
9737   /* Verify that condition can be parsed, before setting any
9738      breakpoints.  Allocate a separate condition expression for each
9739      breakpoint.  */
9740   if (!pending)
9741     {
9742       gdb::unique_xmalloc_ptr<char> cond_string_copy;
9743       gdb::unique_xmalloc_ptr<char> extra_string_copy;
9744
9745       if (parse_extra)
9746         {
9747           char *rest;
9748           char *cond;
9749           struct linespec_sals *lsal;
9750
9751           lsal = VEC_index (linespec_sals, canonical.sals, 0);
9752
9753           /* Here we only parse 'arg' to separate condition
9754              from thread number, so parsing in context of first
9755              sal is OK.  When setting the breakpoint we'll
9756              re-parse it in context of each sal.  */
9757
9758           find_condition_and_thread (extra_string, lsal->sals.sals[0].pc,
9759                                      &cond, &thread, &task, &rest);
9760           cond_string_copy.reset (cond);
9761           extra_string_copy.reset (rest);
9762         }
9763       else
9764         {
9765           if (type_wanted != bp_dprintf
9766               && extra_string != NULL && *extra_string != '\0')
9767                 error (_("Garbage '%s' at end of location"), extra_string);
9768
9769           /* Create a private copy of condition string.  */
9770           if (cond_string)
9771             cond_string_copy.reset (xstrdup (cond_string));
9772           /* Create a private copy of any extra string.  */
9773           if (extra_string)
9774             extra_string_copy.reset (xstrdup (extra_string));
9775         }
9776
9777       ops->create_breakpoints_sal (gdbarch, &canonical,
9778                                    std::move (cond_string_copy),
9779                                    std::move (extra_string_copy),
9780                                    type_wanted,
9781                                    tempflag ? disp_del : disp_donttouch,
9782                                    thread, task, ignore_count, ops,
9783                                    from_tty, enabled, internal, flags);
9784     }
9785   else
9786     {
9787       std::unique_ptr <breakpoint> b = new_breakpoint_from_type (type_wanted);
9788
9789       init_raw_breakpoint_without_location (b.get (), gdbarch, type_wanted, ops);
9790       b->location = copy_event_location (location);
9791
9792       if (parse_extra)
9793         b->cond_string = NULL;
9794       else
9795         {
9796           /* Create a private copy of condition string.  */
9797           b->cond_string = cond_string != NULL ? xstrdup (cond_string) : NULL;
9798           b->thread = thread;
9799         }
9800
9801       /* Create a private copy of any extra string.  */
9802       b->extra_string = extra_string != NULL ? xstrdup (extra_string) : NULL;
9803       b->ignore_count = ignore_count;
9804       b->disposition = tempflag ? disp_del : disp_donttouch;
9805       b->condition_not_parsed = 1;
9806       b->enable_state = enabled ? bp_enabled : bp_disabled;
9807       if ((type_wanted != bp_breakpoint
9808            && type_wanted != bp_hardware_breakpoint) || thread != -1)
9809         b->pspace = current_program_space;
9810
9811       install_breakpoint (internal, b.release (), 0);
9812     }
9813   
9814   if (VEC_length (linespec_sals, canonical.sals) > 1)
9815     {
9816       warning (_("Multiple breakpoints were set.\nUse the "
9817                  "\"delete\" command to delete unwanted breakpoints."));
9818       prev_breakpoint_count = prev_bkpt_count;
9819     }
9820
9821   /* That's it.  Discard the cleanups for data inserted into the
9822      breakpoint.  */
9823   discard_cleanups (bkpt_chain);
9824
9825   /* error call may happen here - have BKPT_CHAIN already discarded.  */
9826   update_global_location_list (UGLL_MAY_INSERT);
9827
9828   return 1;
9829 }
9830
9831 /* Set a breakpoint.
9832    ARG is a string describing breakpoint address,
9833    condition, and thread.
9834    FLAG specifies if a breakpoint is hardware on,
9835    and if breakpoint is temporary, using BP_HARDWARE_FLAG
9836    and BP_TEMPFLAG.  */
9837
9838 static void
9839 break_command_1 (char *arg, int flag, int from_tty)
9840 {
9841   int tempflag = flag & BP_TEMPFLAG;
9842   enum bptype type_wanted = (flag & BP_HARDWAREFLAG
9843                              ? bp_hardware_breakpoint
9844                              : bp_breakpoint);
9845   struct breakpoint_ops *ops;
9846
9847   event_location_up location = string_to_event_location (&arg, current_language);
9848
9849   /* Matching breakpoints on probes.  */
9850   if (location != NULL
9851       && event_location_type (location.get ()) == PROBE_LOCATION)
9852     ops = &bkpt_probe_breakpoint_ops;
9853   else
9854     ops = &bkpt_breakpoint_ops;
9855
9856   create_breakpoint (get_current_arch (),
9857                      location.get (),
9858                      NULL, 0, arg, 1 /* parse arg */,
9859                      tempflag, type_wanted,
9860                      0 /* Ignore count */,
9861                      pending_break_support,
9862                      ops,
9863                      from_tty,
9864                      1 /* enabled */,
9865                      0 /* internal */,
9866                      0);
9867 }
9868
9869 /* Helper function for break_command_1 and disassemble_command.  */
9870
9871 void
9872 resolve_sal_pc (struct symtab_and_line *sal)
9873 {
9874   CORE_ADDR pc;
9875
9876   if (sal->pc == 0 && sal->symtab != NULL)
9877     {
9878       if (!find_line_pc (sal->symtab, sal->line, &pc))
9879         error (_("No line %d in file \"%s\"."),
9880                sal->line, symtab_to_filename_for_display (sal->symtab));
9881       sal->pc = pc;
9882
9883       /* If this SAL corresponds to a breakpoint inserted using a line
9884          number, then skip the function prologue if necessary.  */
9885       if (sal->explicit_line)
9886         skip_prologue_sal (sal);
9887     }
9888
9889   if (sal->section == 0 && sal->symtab != NULL)
9890     {
9891       const struct blockvector *bv;
9892       const struct block *b;
9893       struct symbol *sym;
9894
9895       bv = blockvector_for_pc_sect (sal->pc, 0, &b,
9896                                     SYMTAB_COMPUNIT (sal->symtab));
9897       if (bv != NULL)
9898         {
9899           sym = block_linkage_function (b);
9900           if (sym != NULL)
9901             {
9902               fixup_symbol_section (sym, SYMTAB_OBJFILE (sal->symtab));
9903               sal->section = SYMBOL_OBJ_SECTION (SYMTAB_OBJFILE (sal->symtab),
9904                                                  sym);
9905             }
9906           else
9907             {
9908               /* It really is worthwhile to have the section, so we'll
9909                  just have to look harder. This case can be executed
9910                  if we have line numbers but no functions (as can
9911                  happen in assembly source).  */
9912
9913               scoped_restore_current_pspace_and_thread restore_pspace_thread;
9914               switch_to_program_space_and_thread (sal->pspace);
9915
9916               bound_minimal_symbol msym = lookup_minimal_symbol_by_pc (sal->pc);
9917               if (msym.minsym)
9918                 sal->section = MSYMBOL_OBJ_SECTION (msym.objfile, msym.minsym);
9919             }
9920         }
9921     }
9922 }
9923
9924 void
9925 break_command (char *arg, int from_tty)
9926 {
9927   break_command_1 (arg, 0, from_tty);
9928 }
9929
9930 void
9931 tbreak_command (char *arg, int from_tty)
9932 {
9933   break_command_1 (arg, BP_TEMPFLAG, from_tty);
9934 }
9935
9936 static void
9937 hbreak_command (char *arg, int from_tty)
9938 {
9939   break_command_1 (arg, BP_HARDWAREFLAG, from_tty);
9940 }
9941
9942 static void
9943 thbreak_command (char *arg, int from_tty)
9944 {
9945   break_command_1 (arg, (BP_TEMPFLAG | BP_HARDWAREFLAG), from_tty);
9946 }
9947
9948 static void
9949 stop_command (char *arg, int from_tty)
9950 {
9951   printf_filtered (_("Specify the type of breakpoint to set.\n\
9952 Usage: stop in <function | address>\n\
9953        stop at <line>\n"));
9954 }
9955
9956 static void
9957 stopin_command (char *arg, int from_tty)
9958 {
9959   int badInput = 0;
9960
9961   if (arg == (char *) NULL)
9962     badInput = 1;
9963   else if (*arg != '*')
9964     {
9965       char *argptr = arg;
9966       int hasColon = 0;
9967
9968       /* Look for a ':'.  If this is a line number specification, then
9969          say it is bad, otherwise, it should be an address or
9970          function/method name.  */
9971       while (*argptr && !hasColon)
9972         {
9973           hasColon = (*argptr == ':');
9974           argptr++;
9975         }
9976
9977       if (hasColon)
9978         badInput = (*argptr != ':');    /* Not a class::method */
9979       else
9980         badInput = isdigit (*arg);      /* a simple line number */
9981     }
9982
9983   if (badInput)
9984     printf_filtered (_("Usage: stop in <function | address>\n"));
9985   else
9986     break_command_1 (arg, 0, from_tty);
9987 }
9988
9989 static void
9990 stopat_command (char *arg, int from_tty)
9991 {
9992   int badInput = 0;
9993
9994   if (arg == (char *) NULL || *arg == '*')      /* no line number */
9995     badInput = 1;
9996   else
9997     {
9998       char *argptr = arg;
9999       int hasColon = 0;
10000
10001       /* Look for a ':'.  If there is a '::' then get out, otherwise
10002          it is probably a line number.  */
10003       while (*argptr && !hasColon)
10004         {
10005           hasColon = (*argptr == ':');
10006           argptr++;
10007         }
10008
10009       if (hasColon)
10010         badInput = (*argptr == ':');    /* we have class::method */
10011       else
10012         badInput = !isdigit (*arg);     /* not a line number */
10013     }
10014
10015   if (badInput)
10016     printf_filtered (_("Usage: stop at <line>\n"));
10017   else
10018     break_command_1 (arg, 0, from_tty);
10019 }
10020
10021 /* The dynamic printf command is mostly like a regular breakpoint, but
10022    with a prewired command list consisting of a single output command,
10023    built from extra arguments supplied on the dprintf command
10024    line.  */
10025
10026 static void
10027 dprintf_command (char *arg, int from_tty)
10028 {
10029   event_location_up location = string_to_event_location (&arg, current_language);
10030
10031   /* If non-NULL, ARG should have been advanced past the location;
10032      the next character must be ','.  */
10033   if (arg != NULL)
10034     {
10035       if (arg[0] != ',' || arg[1] == '\0')
10036         error (_("Format string required"));
10037       else
10038         {
10039           /* Skip the comma.  */
10040           ++arg;
10041         }
10042     }
10043
10044   create_breakpoint (get_current_arch (),
10045                      location.get (),
10046                      NULL, 0, arg, 1 /* parse arg */,
10047                      0, bp_dprintf,
10048                      0 /* Ignore count */,
10049                      pending_break_support,
10050                      &dprintf_breakpoint_ops,
10051                      from_tty,
10052                      1 /* enabled */,
10053                      0 /* internal */,
10054                      0);
10055 }
10056
10057 static void
10058 agent_printf_command (char *arg, int from_tty)
10059 {
10060   error (_("May only run agent-printf on the target"));
10061 }
10062
10063 /* Implement the "breakpoint_hit" breakpoint_ops method for
10064    ranged breakpoints.  */
10065
10066 static int
10067 breakpoint_hit_ranged_breakpoint (const struct bp_location *bl,
10068                                   struct address_space *aspace,
10069                                   CORE_ADDR bp_addr,
10070                                   const struct target_waitstatus *ws)
10071 {
10072   if (ws->kind != TARGET_WAITKIND_STOPPED
10073       || ws->value.sig != GDB_SIGNAL_TRAP)
10074     return 0;
10075
10076   return breakpoint_address_match_range (bl->pspace->aspace, bl->address,
10077                                          bl->length, aspace, bp_addr);
10078 }
10079
10080 /* Implement the "resources_needed" breakpoint_ops method for
10081    ranged breakpoints.  */
10082
10083 static int
10084 resources_needed_ranged_breakpoint (const struct bp_location *bl)
10085 {
10086   return target_ranged_break_num_registers ();
10087 }
10088
10089 /* Implement the "print_it" breakpoint_ops method for
10090    ranged breakpoints.  */
10091
10092 static enum print_stop_action
10093 print_it_ranged_breakpoint (bpstat bs)
10094 {
10095   struct breakpoint *b = bs->breakpoint_at;
10096   struct bp_location *bl = b->loc;
10097   struct ui_out *uiout = current_uiout;
10098
10099   gdb_assert (b->type == bp_hardware_breakpoint);
10100
10101   /* Ranged breakpoints have only one location.  */
10102   gdb_assert (bl && bl->next == NULL);
10103
10104   annotate_breakpoint (b->number);
10105
10106   maybe_print_thread_hit_breakpoint (uiout);
10107
10108   if (b->disposition == disp_del)
10109     uiout->text ("Temporary ranged breakpoint ");
10110   else
10111     uiout->text ("Ranged breakpoint ");
10112   if (uiout->is_mi_like_p ())
10113     {
10114       uiout->field_string ("reason",
10115                       async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
10116       uiout->field_string ("disp", bpdisp_text (b->disposition));
10117     }
10118   uiout->field_int ("bkptno", b->number);
10119   uiout->text (", ");
10120
10121   return PRINT_SRC_AND_LOC;
10122 }
10123
10124 /* Implement the "print_one" breakpoint_ops method for
10125    ranged breakpoints.  */
10126
10127 static void
10128 print_one_ranged_breakpoint (struct breakpoint *b,
10129                              struct bp_location **last_loc)
10130 {
10131   struct bp_location *bl = b->loc;
10132   struct value_print_options opts;
10133   struct ui_out *uiout = current_uiout;
10134
10135   /* Ranged breakpoints have only one location.  */
10136   gdb_assert (bl && bl->next == NULL);
10137
10138   get_user_print_options (&opts);
10139
10140   if (opts.addressprint)
10141     /* We don't print the address range here, it will be printed later
10142        by print_one_detail_ranged_breakpoint.  */
10143     uiout->field_skip ("addr");
10144   annotate_field (5);
10145   print_breakpoint_location (b, bl);
10146   *last_loc = bl;
10147 }
10148
10149 /* Implement the "print_one_detail" breakpoint_ops method for
10150    ranged breakpoints.  */
10151
10152 static void
10153 print_one_detail_ranged_breakpoint (const struct breakpoint *b,
10154                                     struct ui_out *uiout)
10155 {
10156   CORE_ADDR address_start, address_end;
10157   struct bp_location *bl = b->loc;
10158   string_file stb;
10159
10160   gdb_assert (bl);
10161
10162   address_start = bl->address;
10163   address_end = address_start + bl->length - 1;
10164
10165   uiout->text ("\taddress range: ");
10166   stb.printf ("[%s, %s]",
10167               print_core_address (bl->gdbarch, address_start),
10168               print_core_address (bl->gdbarch, address_end));
10169   uiout->field_stream ("addr", stb);
10170   uiout->text ("\n");
10171 }
10172
10173 /* Implement the "print_mention" breakpoint_ops method for
10174    ranged breakpoints.  */
10175
10176 static void
10177 print_mention_ranged_breakpoint (struct breakpoint *b)
10178 {
10179   struct bp_location *bl = b->loc;
10180   struct ui_out *uiout = current_uiout;
10181
10182   gdb_assert (bl);
10183   gdb_assert (b->type == bp_hardware_breakpoint);
10184
10185   if (uiout->is_mi_like_p ())
10186     return;
10187
10188   printf_filtered (_("Hardware assisted ranged breakpoint %d from %s to %s."),
10189                    b->number, paddress (bl->gdbarch, bl->address),
10190                    paddress (bl->gdbarch, bl->address + bl->length - 1));
10191 }
10192
10193 /* Implement the "print_recreate" breakpoint_ops method for
10194    ranged breakpoints.  */
10195
10196 static void
10197 print_recreate_ranged_breakpoint (struct breakpoint *b, struct ui_file *fp)
10198 {
10199   fprintf_unfiltered (fp, "break-range %s, %s",
10200                       event_location_to_string (b->location.get ()),
10201                       event_location_to_string (b->location_range_end.get ()));
10202   print_recreate_thread (b, fp);
10203 }
10204
10205 /* The breakpoint_ops structure to be used in ranged breakpoints.  */
10206
10207 static struct breakpoint_ops ranged_breakpoint_ops;
10208
10209 /* Find the address where the end of the breakpoint range should be
10210    placed, given the SAL of the end of the range.  This is so that if
10211    the user provides a line number, the end of the range is set to the
10212    last instruction of the given line.  */
10213
10214 static CORE_ADDR
10215 find_breakpoint_range_end (struct symtab_and_line sal)
10216 {
10217   CORE_ADDR end;
10218
10219   /* If the user provided a PC value, use it.  Otherwise,
10220      find the address of the end of the given location.  */
10221   if (sal.explicit_pc)
10222     end = sal.pc;
10223   else
10224     {
10225       int ret;
10226       CORE_ADDR start;
10227
10228       ret = find_line_pc_range (sal, &start, &end);
10229       if (!ret)
10230         error (_("Could not find location of the end of the range."));
10231
10232       /* find_line_pc_range returns the start of the next line.  */
10233       end--;
10234     }
10235
10236   return end;
10237 }
10238
10239 /* Implement the "break-range" CLI command.  */
10240
10241 static void
10242 break_range_command (char *arg, int from_tty)
10243 {
10244   char *arg_start, *addr_string_start;
10245   struct linespec_result canonical_start, canonical_end;
10246   int bp_count, can_use_bp, length;
10247   CORE_ADDR end;
10248   struct breakpoint *b;
10249   struct symtab_and_line sal_start, sal_end;
10250   struct cleanup *cleanup_bkpt;
10251   struct linespec_sals *lsal_start, *lsal_end;
10252
10253   /* We don't support software ranged breakpoints.  */
10254   if (target_ranged_break_num_registers () < 0)
10255     error (_("This target does not support hardware ranged breakpoints."));
10256
10257   bp_count = hw_breakpoint_used_count ();
10258   bp_count += target_ranged_break_num_registers ();
10259   can_use_bp = target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
10260                                                    bp_count, 0);
10261   if (can_use_bp < 0)
10262     error (_("Hardware breakpoints used exceeds limit."));
10263
10264   arg = skip_spaces (arg);
10265   if (arg == NULL || arg[0] == '\0')
10266     error(_("No address range specified."));
10267
10268   arg_start = arg;
10269   event_location_up start_location = string_to_event_location (&arg,
10270                                                                current_language);
10271   parse_breakpoint_sals (start_location.get (), &canonical_start);
10272
10273   if (arg[0] != ',')
10274     error (_("Too few arguments."));
10275   else if (VEC_empty (linespec_sals, canonical_start.sals))
10276     error (_("Could not find location of the beginning of the range."));
10277
10278   lsal_start = VEC_index (linespec_sals, canonical_start.sals, 0);
10279
10280   if (VEC_length (linespec_sals, canonical_start.sals) > 1
10281       || lsal_start->sals.nelts != 1)
10282     error (_("Cannot create a ranged breakpoint with multiple locations."));
10283
10284   sal_start = lsal_start->sals.sals[0];
10285   addr_string_start = savestring (arg_start, arg - arg_start);
10286   cleanup_bkpt = make_cleanup (xfree, addr_string_start);
10287
10288   arg++;        /* Skip the comma.  */
10289   arg = skip_spaces (arg);
10290
10291   /* Parse the end location.  */
10292
10293   arg_start = arg;
10294
10295   /* We call decode_line_full directly here instead of using
10296      parse_breakpoint_sals because we need to specify the start location's
10297      symtab and line as the default symtab and line for the end of the
10298      range.  This makes it possible to have ranges like "foo.c:27, +14",
10299      where +14 means 14 lines from the start location.  */
10300   event_location_up end_location = string_to_event_location (&arg,
10301                                                              current_language);
10302   decode_line_full (end_location.get (), DECODE_LINE_FUNFIRSTLINE, NULL,
10303                     sal_start.symtab, sal_start.line,
10304                     &canonical_end, NULL, NULL);
10305
10306   if (VEC_empty (linespec_sals, canonical_end.sals))
10307     error (_("Could not find location of the end of the range."));
10308
10309   lsal_end = VEC_index (linespec_sals, canonical_end.sals, 0);
10310   if (VEC_length (linespec_sals, canonical_end.sals) > 1
10311       || lsal_end->sals.nelts != 1)
10312     error (_("Cannot create a ranged breakpoint with multiple locations."));
10313
10314   sal_end = lsal_end->sals.sals[0];
10315
10316   end = find_breakpoint_range_end (sal_end);
10317   if (sal_start.pc > end)
10318     error (_("Invalid address range, end precedes start."));
10319
10320   length = end - sal_start.pc + 1;
10321   if (length < 0)
10322     /* Length overflowed.  */
10323     error (_("Address range too large."));
10324   else if (length == 1)
10325     {
10326       /* This range is simple enough to be handled by
10327          the `hbreak' command.  */
10328       hbreak_command (addr_string_start, 1);
10329
10330       do_cleanups (cleanup_bkpt);
10331
10332       return;
10333     }
10334
10335   /* Now set up the breakpoint.  */
10336   b = set_raw_breakpoint (get_current_arch (), sal_start,
10337                           bp_hardware_breakpoint, &ranged_breakpoint_ops);
10338   set_breakpoint_count (breakpoint_count + 1);
10339   b->number = breakpoint_count;
10340   b->disposition = disp_donttouch;
10341   b->location = std::move (start_location);
10342   b->location_range_end = std::move (end_location);
10343   b->loc->length = length;
10344
10345   do_cleanups (cleanup_bkpt);
10346
10347   mention (b);
10348   observer_notify_breakpoint_created (b);
10349   update_global_location_list (UGLL_MAY_INSERT);
10350 }
10351
10352 /*  Return non-zero if EXP is verified as constant.  Returned zero
10353     means EXP is variable.  Also the constant detection may fail for
10354     some constant expressions and in such case still falsely return
10355     zero.  */
10356
10357 static int
10358 watchpoint_exp_is_const (const struct expression *exp)
10359 {
10360   int i = exp->nelts;
10361
10362   while (i > 0)
10363     {
10364       int oplenp, argsp;
10365
10366       /* We are only interested in the descriptor of each element.  */
10367       operator_length (exp, i, &oplenp, &argsp);
10368       i -= oplenp;
10369
10370       switch (exp->elts[i].opcode)
10371         {
10372         case BINOP_ADD:
10373         case BINOP_SUB:
10374         case BINOP_MUL:
10375         case BINOP_DIV:
10376         case BINOP_REM:
10377         case BINOP_MOD:
10378         case BINOP_LSH:
10379         case BINOP_RSH:
10380         case BINOP_LOGICAL_AND:
10381         case BINOP_LOGICAL_OR:
10382         case BINOP_BITWISE_AND:
10383         case BINOP_BITWISE_IOR:
10384         case BINOP_BITWISE_XOR:
10385         case BINOP_EQUAL:
10386         case BINOP_NOTEQUAL:
10387         case BINOP_LESS:
10388         case BINOP_GTR:
10389         case BINOP_LEQ:
10390         case BINOP_GEQ:
10391         case BINOP_REPEAT:
10392         case BINOP_COMMA:
10393         case BINOP_EXP:
10394         case BINOP_MIN:
10395         case BINOP_MAX:
10396         case BINOP_INTDIV:
10397         case BINOP_CONCAT:
10398         case TERNOP_COND:
10399         case TERNOP_SLICE:
10400
10401         case OP_LONG:
10402         case OP_DOUBLE:
10403         case OP_DECFLOAT:
10404         case OP_LAST:
10405         case OP_COMPLEX:
10406         case OP_STRING:
10407         case OP_ARRAY:
10408         case OP_TYPE:
10409         case OP_TYPEOF:
10410         case OP_DECLTYPE:
10411         case OP_TYPEID:
10412         case OP_NAME:
10413         case OP_OBJC_NSSTRING:
10414
10415         case UNOP_NEG:
10416         case UNOP_LOGICAL_NOT:
10417         case UNOP_COMPLEMENT:
10418         case UNOP_ADDR:
10419         case UNOP_HIGH:
10420         case UNOP_CAST:
10421
10422         case UNOP_CAST_TYPE:
10423         case UNOP_REINTERPRET_CAST:
10424         case UNOP_DYNAMIC_CAST:
10425           /* Unary, binary and ternary operators: We have to check
10426              their operands.  If they are constant, then so is the
10427              result of that operation.  For instance, if A and B are
10428              determined to be constants, then so is "A + B".
10429
10430              UNOP_IND is one exception to the rule above, because the
10431              value of *ADDR is not necessarily a constant, even when
10432              ADDR is.  */
10433           break;
10434
10435         case OP_VAR_VALUE:
10436           /* Check whether the associated symbol is a constant.
10437
10438              We use SYMBOL_CLASS rather than TYPE_CONST because it's
10439              possible that a buggy compiler could mark a variable as
10440              constant even when it is not, and TYPE_CONST would return
10441              true in this case, while SYMBOL_CLASS wouldn't.
10442
10443              We also have to check for function symbols because they
10444              are always constant.  */
10445           {
10446             struct symbol *s = exp->elts[i + 2].symbol;
10447
10448             if (SYMBOL_CLASS (s) != LOC_BLOCK
10449                 && SYMBOL_CLASS (s) != LOC_CONST
10450                 && SYMBOL_CLASS (s) != LOC_CONST_BYTES)
10451               return 0;
10452             break;
10453           }
10454
10455         /* The default action is to return 0 because we are using
10456            the optimistic approach here: If we don't know something,
10457            then it is not a constant.  */
10458         default:
10459           return 0;
10460         }
10461     }
10462
10463   return 1;
10464 }
10465
10466 /* Watchpoint destructor.  */
10467
10468 watchpoint::~watchpoint ()
10469 {
10470   xfree (this->exp_string);
10471   xfree (this->exp_string_reparse);
10472   value_free (this->val);
10473 }
10474
10475 /* Implement the "re_set" breakpoint_ops method for watchpoints.  */
10476
10477 static void
10478 re_set_watchpoint (struct breakpoint *b)
10479 {
10480   struct watchpoint *w = (struct watchpoint *) b;
10481
10482   /* Watchpoint can be either on expression using entirely global
10483      variables, or it can be on local variables.
10484
10485      Watchpoints of the first kind are never auto-deleted, and even
10486      persist across program restarts.  Since they can use variables
10487      from shared libraries, we need to reparse expression as libraries
10488      are loaded and unloaded.
10489
10490      Watchpoints on local variables can also change meaning as result
10491      of solib event.  For example, if a watchpoint uses both a local
10492      and a global variables in expression, it's a local watchpoint,
10493      but unloading of a shared library will make the expression
10494      invalid.  This is not a very common use case, but we still
10495      re-evaluate expression, to avoid surprises to the user.
10496
10497      Note that for local watchpoints, we re-evaluate it only if
10498      watchpoints frame id is still valid.  If it's not, it means the
10499      watchpoint is out of scope and will be deleted soon.  In fact,
10500      I'm not sure we'll ever be called in this case.
10501
10502      If a local watchpoint's frame id is still valid, then
10503      w->exp_valid_block is likewise valid, and we can safely use it.
10504
10505      Don't do anything about disabled watchpoints, since they will be
10506      reevaluated again when enabled.  */
10507   update_watchpoint (w, 1 /* reparse */);
10508 }
10509
10510 /* Implement the "insert" breakpoint_ops method for hardware watchpoints.  */
10511
10512 static int
10513 insert_watchpoint (struct bp_location *bl)
10514 {
10515   struct watchpoint *w = (struct watchpoint *) bl->owner;
10516   int length = w->exact ? 1 : bl->length;
10517
10518   return target_insert_watchpoint (bl->address, length, bl->watchpoint_type,
10519                                    w->cond_exp.get ());
10520 }
10521
10522 /* Implement the "remove" breakpoint_ops method for hardware watchpoints.  */
10523
10524 static int
10525 remove_watchpoint (struct bp_location *bl, enum remove_bp_reason reason)
10526 {
10527   struct watchpoint *w = (struct watchpoint *) bl->owner;
10528   int length = w->exact ? 1 : bl->length;
10529
10530   return target_remove_watchpoint (bl->address, length, bl->watchpoint_type,
10531                                    w->cond_exp.get ());
10532 }
10533
10534 static int
10535 breakpoint_hit_watchpoint (const struct bp_location *bl,
10536                            struct address_space *aspace, CORE_ADDR bp_addr,
10537                            const struct target_waitstatus *ws)
10538 {
10539   struct breakpoint *b = bl->owner;
10540   struct watchpoint *w = (struct watchpoint *) b;
10541
10542   /* Continuable hardware watchpoints are treated as non-existent if the
10543      reason we stopped wasn't a hardware watchpoint (we didn't stop on
10544      some data address).  Otherwise gdb won't stop on a break instruction
10545      in the code (not from a breakpoint) when a hardware watchpoint has
10546      been defined.  Also skip watchpoints which we know did not trigger
10547      (did not match the data address).  */
10548   if (is_hardware_watchpoint (b)
10549       && w->watchpoint_triggered == watch_triggered_no)
10550     return 0;
10551
10552   return 1;
10553 }
10554
10555 static void
10556 check_status_watchpoint (bpstat bs)
10557 {
10558   gdb_assert (is_watchpoint (bs->breakpoint_at));
10559
10560   bpstat_check_watchpoint (bs);
10561 }
10562
10563 /* Implement the "resources_needed" breakpoint_ops method for
10564    hardware watchpoints.  */
10565
10566 static int
10567 resources_needed_watchpoint (const struct bp_location *bl)
10568 {
10569   struct watchpoint *w = (struct watchpoint *) bl->owner;
10570   int length = w->exact? 1 : bl->length;
10571
10572   return target_region_ok_for_hw_watchpoint (bl->address, length);
10573 }
10574
10575 /* Implement the "works_in_software_mode" breakpoint_ops method for
10576    hardware watchpoints.  */
10577
10578 static int
10579 works_in_software_mode_watchpoint (const struct breakpoint *b)
10580 {
10581   /* Read and access watchpoints only work with hardware support.  */
10582   return b->type == bp_watchpoint || b->type == bp_hardware_watchpoint;
10583 }
10584
10585 static enum print_stop_action
10586 print_it_watchpoint (bpstat bs)
10587 {
10588   struct cleanup *old_chain;
10589   struct breakpoint *b;
10590   enum print_stop_action result;
10591   struct watchpoint *w;
10592   struct ui_out *uiout = current_uiout;
10593
10594   gdb_assert (bs->bp_location_at != NULL);
10595
10596   b = bs->breakpoint_at;
10597   w = (struct watchpoint *) b;
10598
10599   old_chain = make_cleanup (null_cleanup, NULL);
10600
10601   annotate_watchpoint (b->number);
10602   maybe_print_thread_hit_breakpoint (uiout);
10603
10604   string_file stb;
10605
10606   switch (b->type)
10607     {
10608     case bp_watchpoint:
10609     case bp_hardware_watchpoint:
10610       if (uiout->is_mi_like_p ())
10611         uiout->field_string
10612           ("reason", async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
10613       mention (b);
10614       make_cleanup_ui_out_tuple_begin_end (uiout, "value");
10615       uiout->text ("\nOld value = ");
10616       watchpoint_value_print (bs->old_val, &stb);
10617       uiout->field_stream ("old", stb);
10618       uiout->text ("\nNew value = ");
10619       watchpoint_value_print (w->val, &stb);
10620       uiout->field_stream ("new", stb);
10621       uiout->text ("\n");
10622       /* More than one watchpoint may have been triggered.  */
10623       result = PRINT_UNKNOWN;
10624       break;
10625
10626     case bp_read_watchpoint:
10627       if (uiout->is_mi_like_p ())
10628         uiout->field_string
10629           ("reason", async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
10630       mention (b);
10631       make_cleanup_ui_out_tuple_begin_end (uiout, "value");
10632       uiout->text ("\nValue = ");
10633       watchpoint_value_print (w->val, &stb);
10634       uiout->field_stream ("value", stb);
10635       uiout->text ("\n");
10636       result = PRINT_UNKNOWN;
10637       break;
10638
10639     case bp_access_watchpoint:
10640       if (bs->old_val != NULL)
10641         {
10642           if (uiout->is_mi_like_p ())
10643             uiout->field_string
10644               ("reason",
10645                async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10646           mention (b);
10647           make_cleanup_ui_out_tuple_begin_end (uiout, "value");
10648           uiout->text ("\nOld value = ");
10649           watchpoint_value_print (bs->old_val, &stb);
10650           uiout->field_stream ("old", stb);
10651           uiout->text ("\nNew value = ");
10652         }
10653       else
10654         {
10655           mention (b);
10656           if (uiout->is_mi_like_p ())
10657             uiout->field_string
10658               ("reason",
10659                async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10660           make_cleanup_ui_out_tuple_begin_end (uiout, "value");
10661           uiout->text ("\nValue = ");
10662         }
10663       watchpoint_value_print (w->val, &stb);
10664       uiout->field_stream ("new", stb);
10665       uiout->text ("\n");
10666       result = PRINT_UNKNOWN;
10667       break;
10668     default:
10669       result = PRINT_UNKNOWN;
10670     }
10671
10672   do_cleanups (old_chain);
10673   return result;
10674 }
10675
10676 /* Implement the "print_mention" breakpoint_ops method for hardware
10677    watchpoints.  */
10678
10679 static void
10680 print_mention_watchpoint (struct breakpoint *b)
10681 {
10682   struct watchpoint *w = (struct watchpoint *) b;
10683   struct ui_out *uiout = current_uiout;
10684   const char *tuple_name;
10685
10686   switch (b->type)
10687     {
10688     case bp_watchpoint:
10689       uiout->text ("Watchpoint ");
10690       tuple_name = "wpt";
10691       break;
10692     case bp_hardware_watchpoint:
10693       uiout->text ("Hardware watchpoint ");
10694       tuple_name = "wpt";
10695       break;
10696     case bp_read_watchpoint:
10697       uiout->text ("Hardware read watchpoint ");
10698       tuple_name = "hw-rwpt";
10699       break;
10700     case bp_access_watchpoint:
10701       uiout->text ("Hardware access (read/write) watchpoint ");
10702       tuple_name = "hw-awpt";
10703       break;
10704     default:
10705       internal_error (__FILE__, __LINE__,
10706                       _("Invalid hardware watchpoint type."));
10707     }
10708
10709   ui_out_emit_tuple tuple_emitter (uiout, tuple_name);
10710   uiout->field_int ("number", b->number);
10711   uiout->text (": ");
10712   uiout->field_string ("exp", w->exp_string);
10713 }
10714
10715 /* Implement the "print_recreate" breakpoint_ops method for
10716    watchpoints.  */
10717
10718 static void
10719 print_recreate_watchpoint (struct breakpoint *b, struct ui_file *fp)
10720 {
10721   struct watchpoint *w = (struct watchpoint *) b;
10722
10723   switch (b->type)
10724     {
10725     case bp_watchpoint:
10726     case bp_hardware_watchpoint:
10727       fprintf_unfiltered (fp, "watch");
10728       break;
10729     case bp_read_watchpoint:
10730       fprintf_unfiltered (fp, "rwatch");
10731       break;
10732     case bp_access_watchpoint:
10733       fprintf_unfiltered (fp, "awatch");
10734       break;
10735     default:
10736       internal_error (__FILE__, __LINE__,
10737                       _("Invalid watchpoint type."));
10738     }
10739
10740   fprintf_unfiltered (fp, " %s", w->exp_string);
10741   print_recreate_thread (b, fp);
10742 }
10743
10744 /* Implement the "explains_signal" breakpoint_ops method for
10745    watchpoints.  */
10746
10747 static int
10748 explains_signal_watchpoint (struct breakpoint *b, enum gdb_signal sig)
10749 {
10750   /* A software watchpoint cannot cause a signal other than
10751      GDB_SIGNAL_TRAP.  */
10752   if (b->type == bp_watchpoint && sig != GDB_SIGNAL_TRAP)
10753     return 0;
10754
10755   return 1;
10756 }
10757
10758 /* The breakpoint_ops structure to be used in hardware watchpoints.  */
10759
10760 static struct breakpoint_ops watchpoint_breakpoint_ops;
10761
10762 /* Implement the "insert" breakpoint_ops method for
10763    masked hardware watchpoints.  */
10764
10765 static int
10766 insert_masked_watchpoint (struct bp_location *bl)
10767 {
10768   struct watchpoint *w = (struct watchpoint *) bl->owner;
10769
10770   return target_insert_mask_watchpoint (bl->address, w->hw_wp_mask,
10771                                         bl->watchpoint_type);
10772 }
10773
10774 /* Implement the "remove" breakpoint_ops method for
10775    masked hardware watchpoints.  */
10776
10777 static int
10778 remove_masked_watchpoint (struct bp_location *bl, enum remove_bp_reason reason)
10779 {
10780   struct watchpoint *w = (struct watchpoint *) bl->owner;
10781
10782   return target_remove_mask_watchpoint (bl->address, w->hw_wp_mask,
10783                                         bl->watchpoint_type);
10784 }
10785
10786 /* Implement the "resources_needed" breakpoint_ops method for
10787    masked hardware watchpoints.  */
10788
10789 static int
10790 resources_needed_masked_watchpoint (const struct bp_location *bl)
10791 {
10792   struct watchpoint *w = (struct watchpoint *) bl->owner;
10793
10794   return target_masked_watch_num_registers (bl->address, w->hw_wp_mask);
10795 }
10796
10797 /* Implement the "works_in_software_mode" breakpoint_ops method for
10798    masked hardware watchpoints.  */
10799
10800 static int
10801 works_in_software_mode_masked_watchpoint (const struct breakpoint *b)
10802 {
10803   return 0;
10804 }
10805
10806 /* Implement the "print_it" breakpoint_ops method for
10807    masked hardware watchpoints.  */
10808
10809 static enum print_stop_action
10810 print_it_masked_watchpoint (bpstat bs)
10811 {
10812   struct breakpoint *b = bs->breakpoint_at;
10813   struct ui_out *uiout = current_uiout;
10814
10815   /* Masked watchpoints have only one location.  */
10816   gdb_assert (b->loc && b->loc->next == NULL);
10817
10818   annotate_watchpoint (b->number);
10819   maybe_print_thread_hit_breakpoint (uiout);
10820
10821   switch (b->type)
10822     {
10823     case bp_hardware_watchpoint:
10824       if (uiout->is_mi_like_p ())
10825         uiout->field_string
10826           ("reason", async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
10827       break;
10828
10829     case bp_read_watchpoint:
10830       if (uiout->is_mi_like_p ())
10831         uiout->field_string
10832           ("reason", async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
10833       break;
10834
10835     case bp_access_watchpoint:
10836       if (uiout->is_mi_like_p ())
10837         uiout->field_string
10838           ("reason",
10839            async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10840       break;
10841     default:
10842       internal_error (__FILE__, __LINE__,
10843                       _("Invalid hardware watchpoint type."));
10844     }
10845
10846   mention (b);
10847   uiout->text (_("\n\
10848 Check the underlying instruction at PC for the memory\n\
10849 address and value which triggered this watchpoint.\n"));
10850   uiout->text ("\n");
10851
10852   /* More than one watchpoint may have been triggered.  */
10853   return PRINT_UNKNOWN;
10854 }
10855
10856 /* Implement the "print_one_detail" breakpoint_ops method for
10857    masked hardware watchpoints.  */
10858
10859 static void
10860 print_one_detail_masked_watchpoint (const struct breakpoint *b,
10861                                     struct ui_out *uiout)
10862 {
10863   struct watchpoint *w = (struct watchpoint *) b;
10864
10865   /* Masked watchpoints have only one location.  */
10866   gdb_assert (b->loc && b->loc->next == NULL);
10867
10868   uiout->text ("\tmask ");
10869   uiout->field_core_addr ("mask", b->loc->gdbarch, w->hw_wp_mask);
10870   uiout->text ("\n");
10871 }
10872
10873 /* Implement the "print_mention" breakpoint_ops method for
10874    masked hardware watchpoints.  */
10875
10876 static void
10877 print_mention_masked_watchpoint (struct breakpoint *b)
10878 {
10879   struct watchpoint *w = (struct watchpoint *) b;
10880   struct ui_out *uiout = current_uiout;
10881   const char *tuple_name;
10882
10883   switch (b->type)
10884     {
10885     case bp_hardware_watchpoint:
10886       uiout->text ("Masked hardware watchpoint ");
10887       tuple_name = "wpt";
10888       break;
10889     case bp_read_watchpoint:
10890       uiout->text ("Masked hardware read watchpoint ");
10891       tuple_name = "hw-rwpt";
10892       break;
10893     case bp_access_watchpoint:
10894       uiout->text ("Masked hardware access (read/write) watchpoint ");
10895       tuple_name = "hw-awpt";
10896       break;
10897     default:
10898       internal_error (__FILE__, __LINE__,
10899                       _("Invalid hardware watchpoint type."));
10900     }
10901
10902   ui_out_emit_tuple tuple_emitter (uiout, tuple_name);
10903   uiout->field_int ("number", b->number);
10904   uiout->text (": ");
10905   uiout->field_string ("exp", w->exp_string);
10906 }
10907
10908 /* Implement the "print_recreate" breakpoint_ops method for
10909    masked hardware watchpoints.  */
10910
10911 static void
10912 print_recreate_masked_watchpoint (struct breakpoint *b, struct ui_file *fp)
10913 {
10914   struct watchpoint *w = (struct watchpoint *) b;
10915   char tmp[40];
10916
10917   switch (b->type)
10918     {
10919     case bp_hardware_watchpoint:
10920       fprintf_unfiltered (fp, "watch");
10921       break;
10922     case bp_read_watchpoint:
10923       fprintf_unfiltered (fp, "rwatch");
10924       break;
10925     case bp_access_watchpoint:
10926       fprintf_unfiltered (fp, "awatch");
10927       break;
10928     default:
10929       internal_error (__FILE__, __LINE__,
10930                       _("Invalid hardware watchpoint type."));
10931     }
10932
10933   sprintf_vma (tmp, w->hw_wp_mask);
10934   fprintf_unfiltered (fp, " %s mask 0x%s", w->exp_string, tmp);
10935   print_recreate_thread (b, fp);
10936 }
10937
10938 /* The breakpoint_ops structure to be used in masked hardware watchpoints.  */
10939
10940 static struct breakpoint_ops masked_watchpoint_breakpoint_ops;
10941
10942 /* Tell whether the given watchpoint is a masked hardware watchpoint.  */
10943
10944 static int
10945 is_masked_watchpoint (const struct breakpoint *b)
10946 {
10947   return b->ops == &masked_watchpoint_breakpoint_ops;
10948 }
10949
10950 /* accessflag:  hw_write:  watch write, 
10951                 hw_read:   watch read, 
10952                 hw_access: watch access (read or write) */
10953 static void
10954 watch_command_1 (const char *arg, int accessflag, int from_tty,
10955                  int just_location, int internal)
10956 {
10957   struct breakpoint *scope_breakpoint = NULL;
10958   const struct block *exp_valid_block = NULL, *cond_exp_valid_block = NULL;
10959   struct value *val, *mark, *result;
10960   int saved_bitpos = 0, saved_bitsize = 0;
10961   const char *exp_start = NULL;
10962   const char *exp_end = NULL;
10963   const char *tok, *end_tok;
10964   int toklen = -1;
10965   const char *cond_start = NULL;
10966   const char *cond_end = NULL;
10967   enum bptype bp_type;
10968   int thread = -1;
10969   int pc = 0;
10970   /* Flag to indicate whether we are going to use masks for
10971      the hardware watchpoint.  */
10972   int use_mask = 0;
10973   CORE_ADDR mask = 0;
10974   struct watchpoint *w;
10975   char *expression;
10976   struct cleanup *back_to;
10977
10978   /* Make sure that we actually have parameters to parse.  */
10979   if (arg != NULL && arg[0] != '\0')
10980     {
10981       const char *value_start;
10982
10983       exp_end = arg + strlen (arg);
10984
10985       /* Look for "parameter value" pairs at the end
10986          of the arguments string.  */
10987       for (tok = exp_end - 1; tok > arg; tok--)
10988         {
10989           /* Skip whitespace at the end of the argument list.  */
10990           while (tok > arg && (*tok == ' ' || *tok == '\t'))
10991             tok--;
10992
10993           /* Find the beginning of the last token.
10994              This is the value of the parameter.  */
10995           while (tok > arg && (*tok != ' ' && *tok != '\t'))
10996             tok--;
10997           value_start = tok + 1;
10998
10999           /* Skip whitespace.  */
11000           while (tok > arg && (*tok == ' ' || *tok == '\t'))
11001             tok--;
11002
11003           end_tok = tok;
11004
11005           /* Find the beginning of the second to last token.
11006              This is the parameter itself.  */
11007           while (tok > arg && (*tok != ' ' && *tok != '\t'))
11008             tok--;
11009           tok++;
11010           toklen = end_tok - tok + 1;
11011
11012           if (toklen == 6 && startswith (tok, "thread"))
11013             {
11014               struct thread_info *thr;
11015               /* At this point we've found a "thread" token, which means
11016                  the user is trying to set a watchpoint that triggers
11017                  only in a specific thread.  */
11018               const char *endp;
11019
11020               if (thread != -1)
11021                 error(_("You can specify only one thread."));
11022
11023               /* Extract the thread ID from the next token.  */
11024               thr = parse_thread_id (value_start, &endp);
11025
11026               /* Check if the user provided a valid thread ID.  */
11027               if (*endp != ' ' && *endp != '\t' && *endp != '\0')
11028                 invalid_thread_id_error (value_start);
11029
11030               thread = thr->global_num;
11031             }
11032           else if (toklen == 4 && startswith (tok, "mask"))
11033             {
11034               /* We've found a "mask" token, which means the user wants to
11035                  create a hardware watchpoint that is going to have the mask
11036                  facility.  */
11037               struct value *mask_value, *mark;
11038
11039               if (use_mask)
11040                 error(_("You can specify only one mask."));
11041
11042               use_mask = just_location = 1;
11043
11044               mark = value_mark ();
11045               mask_value = parse_to_comma_and_eval (&value_start);
11046               mask = value_as_address (mask_value);
11047               value_free_to_mark (mark);
11048             }
11049           else
11050             /* We didn't recognize what we found.  We should stop here.  */
11051             break;
11052
11053           /* Truncate the string and get rid of the "parameter value" pair before
11054              the arguments string is parsed by the parse_exp_1 function.  */
11055           exp_end = tok;
11056         }
11057     }
11058   else
11059     exp_end = arg;
11060
11061   /* Parse the rest of the arguments.  From here on out, everything
11062      is in terms of a newly allocated string instead of the original
11063      ARG.  */
11064   innermost_block = NULL;
11065   expression = savestring (arg, exp_end - arg);
11066   back_to = make_cleanup (xfree, expression);
11067   exp_start = arg = expression;
11068   expression_up exp = parse_exp_1 (&arg, 0, 0, 0);
11069   exp_end = arg;
11070   /* Remove trailing whitespace from the expression before saving it.
11071      This makes the eventual display of the expression string a bit
11072      prettier.  */
11073   while (exp_end > exp_start && (exp_end[-1] == ' ' || exp_end[-1] == '\t'))
11074     --exp_end;
11075
11076   /* Checking if the expression is not constant.  */
11077   if (watchpoint_exp_is_const (exp.get ()))
11078     {
11079       int len;
11080
11081       len = exp_end - exp_start;
11082       while (len > 0 && isspace (exp_start[len - 1]))
11083         len--;
11084       error (_("Cannot watch constant value `%.*s'."), len, exp_start);
11085     }
11086
11087   exp_valid_block = innermost_block;
11088   mark = value_mark ();
11089   fetch_subexp_value (exp.get (), &pc, &val, &result, NULL, just_location);
11090
11091   if (val != NULL && just_location)
11092     {
11093       saved_bitpos = value_bitpos (val);
11094       saved_bitsize = value_bitsize (val);
11095     }
11096
11097   if (just_location)
11098     {
11099       int ret;
11100
11101       exp_valid_block = NULL;
11102       val = value_addr (result);
11103       release_value (val);
11104       value_free_to_mark (mark);
11105
11106       if (use_mask)
11107         {
11108           ret = target_masked_watch_num_registers (value_as_address (val),
11109                                                    mask);
11110           if (ret == -1)
11111             error (_("This target does not support masked watchpoints."));
11112           else if (ret == -2)
11113             error (_("Invalid mask or memory region."));
11114         }
11115     }
11116   else if (val != NULL)
11117     release_value (val);
11118
11119   tok = skip_spaces_const (arg);
11120   end_tok = skip_to_space_const (tok);
11121
11122   toklen = end_tok - tok;
11123   if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
11124     {
11125       innermost_block = NULL;
11126       tok = cond_start = end_tok + 1;
11127       parse_exp_1 (&tok, 0, 0, 0);
11128
11129       /* The watchpoint expression may not be local, but the condition
11130          may still be.  E.g.: `watch global if local > 0'.  */
11131       cond_exp_valid_block = innermost_block;
11132
11133       cond_end = tok;
11134     }
11135   if (*tok)
11136     error (_("Junk at end of command."));
11137
11138   frame_info *wp_frame = block_innermost_frame (exp_valid_block);
11139
11140   /* Save this because create_internal_breakpoint below invalidates
11141      'wp_frame'.  */
11142   frame_id watchpoint_frame = get_frame_id (wp_frame);
11143
11144   /* If the expression is "local", then set up a "watchpoint scope"
11145      breakpoint at the point where we've left the scope of the watchpoint
11146      expression.  Create the scope breakpoint before the watchpoint, so
11147      that we will encounter it first in bpstat_stop_status.  */
11148   if (exp_valid_block != NULL && wp_frame != NULL)
11149     {
11150       frame_id caller_frame_id = frame_unwind_caller_id (wp_frame);
11151
11152       if (frame_id_p (caller_frame_id))
11153         {
11154           gdbarch *caller_arch = frame_unwind_caller_arch (wp_frame);
11155           CORE_ADDR caller_pc = frame_unwind_caller_pc (wp_frame);
11156
11157           scope_breakpoint
11158             = create_internal_breakpoint (caller_arch, caller_pc,
11159                                           bp_watchpoint_scope,
11160                                           &momentary_breakpoint_ops);
11161
11162           /* create_internal_breakpoint could invalidate WP_FRAME.  */
11163           wp_frame = NULL;
11164
11165           scope_breakpoint->enable_state = bp_enabled;
11166
11167           /* Automatically delete the breakpoint when it hits.  */
11168           scope_breakpoint->disposition = disp_del;
11169
11170           /* Only break in the proper frame (help with recursion).  */
11171           scope_breakpoint->frame_id = caller_frame_id;
11172
11173           /* Set the address at which we will stop.  */
11174           scope_breakpoint->loc->gdbarch = caller_arch;
11175           scope_breakpoint->loc->requested_address = caller_pc;
11176           scope_breakpoint->loc->address
11177             = adjust_breakpoint_address (scope_breakpoint->loc->gdbarch,
11178                                          scope_breakpoint->loc->requested_address,
11179                                          scope_breakpoint->type);
11180         }
11181     }
11182
11183   /* Now set up the breakpoint.  We create all watchpoints as hardware
11184      watchpoints here even if hardware watchpoints are turned off, a call
11185      to update_watchpoint later in this function will cause the type to
11186      drop back to bp_watchpoint (software watchpoint) if required.  */
11187
11188   if (accessflag == hw_read)
11189     bp_type = bp_read_watchpoint;
11190   else if (accessflag == hw_access)
11191     bp_type = bp_access_watchpoint;
11192   else
11193     bp_type = bp_hardware_watchpoint;
11194
11195   w = new watchpoint ();
11196
11197   if (use_mask)
11198     init_raw_breakpoint_without_location (w, NULL, bp_type,
11199                                           &masked_watchpoint_breakpoint_ops);
11200   else
11201     init_raw_breakpoint_without_location (w, NULL, bp_type,
11202                                           &watchpoint_breakpoint_ops);
11203   w->thread = thread;
11204   w->disposition = disp_donttouch;
11205   w->pspace = current_program_space;
11206   w->exp = std::move (exp);
11207   w->exp_valid_block = exp_valid_block;
11208   w->cond_exp_valid_block = cond_exp_valid_block;
11209   if (just_location)
11210     {
11211       struct type *t = value_type (val);
11212       CORE_ADDR addr = value_as_address (val);
11213
11214       w->exp_string_reparse
11215         = current_language->la_watch_location_expression (t, addr).release ();
11216
11217       w->exp_string = xstrprintf ("-location %.*s",
11218                                   (int) (exp_end - exp_start), exp_start);
11219     }
11220   else
11221     w->exp_string = savestring (exp_start, exp_end - exp_start);
11222
11223   if (use_mask)
11224     {
11225       w->hw_wp_mask = mask;
11226     }
11227   else
11228     {
11229       w->val = val;
11230       w->val_bitpos = saved_bitpos;
11231       w->val_bitsize = saved_bitsize;
11232       w->val_valid = 1;
11233     }
11234
11235   if (cond_start)
11236     w->cond_string = savestring (cond_start, cond_end - cond_start);
11237   else
11238     w->cond_string = 0;
11239
11240   if (frame_id_p (watchpoint_frame))
11241     {
11242       w->watchpoint_frame = watchpoint_frame;
11243       w->watchpoint_thread = inferior_ptid;
11244     }
11245   else
11246     {
11247       w->watchpoint_frame = null_frame_id;
11248       w->watchpoint_thread = null_ptid;
11249     }
11250
11251   if (scope_breakpoint != NULL)
11252     {
11253       /* The scope breakpoint is related to the watchpoint.  We will
11254          need to act on them together.  */
11255       w->related_breakpoint = scope_breakpoint;
11256       scope_breakpoint->related_breakpoint = w;
11257     }
11258
11259   if (!just_location)
11260     value_free_to_mark (mark);
11261
11262   TRY
11263     {
11264       /* Finally update the new watchpoint.  This creates the locations
11265          that should be inserted.  */
11266       update_watchpoint (w, 1);
11267     }
11268   CATCH (e, RETURN_MASK_ALL)
11269     {
11270       delete_breakpoint (w);
11271       throw_exception (e);
11272     }
11273   END_CATCH
11274
11275   install_breakpoint (internal, w, 1);
11276   do_cleanups (back_to);
11277 }
11278
11279 /* Return count of debug registers needed to watch the given expression.
11280    If the watchpoint cannot be handled in hardware return zero.  */
11281
11282 static int
11283 can_use_hardware_watchpoint (struct value *v)
11284 {
11285   int found_memory_cnt = 0;
11286   struct value *head = v;
11287
11288   /* Did the user specifically forbid us to use hardware watchpoints? */
11289   if (!can_use_hw_watchpoints)
11290     return 0;
11291
11292   /* Make sure that the value of the expression depends only upon
11293      memory contents, and values computed from them within GDB.  If we
11294      find any register references or function calls, we can't use a
11295      hardware watchpoint.
11296
11297      The idea here is that evaluating an expression generates a series
11298      of values, one holding the value of every subexpression.  (The
11299      expression a*b+c has five subexpressions: a, b, a*b, c, and
11300      a*b+c.)  GDB's values hold almost enough information to establish
11301      the criteria given above --- they identify memory lvalues,
11302      register lvalues, computed values, etcetera.  So we can evaluate
11303      the expression, and then scan the chain of values that leaves
11304      behind to decide whether we can detect any possible change to the
11305      expression's final value using only hardware watchpoints.
11306
11307      However, I don't think that the values returned by inferior
11308      function calls are special in any way.  So this function may not
11309      notice that an expression involving an inferior function call
11310      can't be watched with hardware watchpoints.  FIXME.  */
11311   for (; v; v = value_next (v))
11312     {
11313       if (VALUE_LVAL (v) == lval_memory)
11314         {
11315           if (v != head && value_lazy (v))
11316             /* A lazy memory lvalue in the chain is one that GDB never
11317                needed to fetch; we either just used its address (e.g.,
11318                `a' in `a.b') or we never needed it at all (e.g., `a'
11319                in `a,b').  This doesn't apply to HEAD; if that is
11320                lazy then it was not readable, but watch it anyway.  */
11321             ;
11322           else
11323             {
11324               /* Ahh, memory we actually used!  Check if we can cover
11325                  it with hardware watchpoints.  */
11326               struct type *vtype = check_typedef (value_type (v));
11327
11328               /* We only watch structs and arrays if user asked for it
11329                  explicitly, never if they just happen to appear in a
11330                  middle of some value chain.  */
11331               if (v == head
11332                   || (TYPE_CODE (vtype) != TYPE_CODE_STRUCT
11333                       && TYPE_CODE (vtype) != TYPE_CODE_ARRAY))
11334                 {
11335                   CORE_ADDR vaddr = value_address (v);
11336                   int len;
11337                   int num_regs;
11338
11339                   len = (target_exact_watchpoints
11340                          && is_scalar_type_recursive (vtype))?
11341                     1 : TYPE_LENGTH (value_type (v));
11342
11343                   num_regs = target_region_ok_for_hw_watchpoint (vaddr, len);
11344                   if (!num_regs)
11345                     return 0;
11346                   else
11347                     found_memory_cnt += num_regs;
11348                 }
11349             }
11350         }
11351       else if (VALUE_LVAL (v) != not_lval
11352                && deprecated_value_modifiable (v) == 0)
11353         return 0;       /* These are values from the history (e.g., $1).  */
11354       else if (VALUE_LVAL (v) == lval_register)
11355         return 0;       /* Cannot watch a register with a HW watchpoint.  */
11356     }
11357
11358   /* The expression itself looks suitable for using a hardware
11359      watchpoint, but give the target machine a chance to reject it.  */
11360   return found_memory_cnt;
11361 }
11362
11363 void
11364 watch_command_wrapper (char *arg, int from_tty, int internal)
11365 {
11366   watch_command_1 (arg, hw_write, from_tty, 0, internal);
11367 }
11368
11369 /* A helper function that looks for the "-location" argument and then
11370    calls watch_command_1.  */
11371
11372 static void
11373 watch_maybe_just_location (char *arg, int accessflag, int from_tty)
11374 {
11375   int just_location = 0;
11376
11377   if (arg
11378       && (check_for_argument (&arg, "-location", sizeof ("-location") - 1)
11379           || check_for_argument (&arg, "-l", sizeof ("-l") - 1)))
11380     {
11381       arg = skip_spaces (arg);
11382       just_location = 1;
11383     }
11384
11385   watch_command_1 (arg, accessflag, from_tty, just_location, 0);
11386 }
11387
11388 static void
11389 watch_command (char *arg, int from_tty)
11390 {
11391   watch_maybe_just_location (arg, hw_write, from_tty);
11392 }
11393
11394 void
11395 rwatch_command_wrapper (char *arg, int from_tty, int internal)
11396 {
11397   watch_command_1 (arg, hw_read, from_tty, 0, internal);
11398 }
11399
11400 static void
11401 rwatch_command (char *arg, int from_tty)
11402 {
11403   watch_maybe_just_location (arg, hw_read, from_tty);
11404 }
11405
11406 void
11407 awatch_command_wrapper (char *arg, int from_tty, int internal)
11408 {
11409   watch_command_1 (arg, hw_access, from_tty, 0, internal);
11410 }
11411
11412 static void
11413 awatch_command (char *arg, int from_tty)
11414 {
11415   watch_maybe_just_location (arg, hw_access, from_tty);
11416 }
11417 \f
11418
11419 /* Data for the FSM that manages the until(location)/advance commands
11420    in infcmd.c.  Here because it uses the mechanisms of
11421    breakpoints.  */
11422
11423 struct until_break_fsm
11424 {
11425   /* The base class.  */
11426   struct thread_fsm thread_fsm;
11427
11428   /* The thread that as current when the command was executed.  */
11429   int thread;
11430
11431   /* The breakpoint set at the destination location.  */
11432   struct breakpoint *location_breakpoint;
11433
11434   /* Breakpoint set at the return address in the caller frame.  May be
11435      NULL.  */
11436   struct breakpoint *caller_breakpoint;
11437 };
11438
11439 static void until_break_fsm_clean_up (struct thread_fsm *self,
11440                                       struct thread_info *thread);
11441 static int until_break_fsm_should_stop (struct thread_fsm *self,
11442                                         struct thread_info *thread);
11443 static enum async_reply_reason
11444   until_break_fsm_async_reply_reason (struct thread_fsm *self);
11445
11446 /* until_break_fsm's vtable.  */
11447
11448 static struct thread_fsm_ops until_break_fsm_ops =
11449 {
11450   NULL, /* dtor */
11451   until_break_fsm_clean_up,
11452   until_break_fsm_should_stop,
11453   NULL, /* return_value */
11454   until_break_fsm_async_reply_reason,
11455 };
11456
11457 /* Allocate a new until_break_command_fsm.  */
11458
11459 static struct until_break_fsm *
11460 new_until_break_fsm (struct interp *cmd_interp, int thread,
11461                      struct breakpoint *location_breakpoint,
11462                      struct breakpoint *caller_breakpoint)
11463 {
11464   struct until_break_fsm *sm;
11465
11466   sm = XCNEW (struct until_break_fsm);
11467   thread_fsm_ctor (&sm->thread_fsm, &until_break_fsm_ops, cmd_interp);
11468
11469   sm->thread = thread;
11470   sm->location_breakpoint = location_breakpoint;
11471   sm->caller_breakpoint = caller_breakpoint;
11472
11473   return sm;
11474 }
11475
11476 /* Implementation of the 'should_stop' FSM method for the
11477    until(location)/advance commands.  */
11478
11479 static int
11480 until_break_fsm_should_stop (struct thread_fsm *self,
11481                              struct thread_info *tp)
11482 {
11483   struct until_break_fsm *sm = (struct until_break_fsm *) self;
11484
11485   if (bpstat_find_breakpoint (tp->control.stop_bpstat,
11486                               sm->location_breakpoint) != NULL
11487       || (sm->caller_breakpoint != NULL
11488           && bpstat_find_breakpoint (tp->control.stop_bpstat,
11489                                      sm->caller_breakpoint) != NULL))
11490     thread_fsm_set_finished (self);
11491
11492   return 1;
11493 }
11494
11495 /* Implementation of the 'clean_up' FSM method for the
11496    until(location)/advance commands.  */
11497
11498 static void
11499 until_break_fsm_clean_up (struct thread_fsm *self,
11500                           struct thread_info *thread)
11501 {
11502   struct until_break_fsm *sm = (struct until_break_fsm *) self;
11503
11504   /* Clean up our temporary breakpoints.  */
11505   if (sm->location_breakpoint != NULL)
11506     {
11507       delete_breakpoint (sm->location_breakpoint);
11508       sm->location_breakpoint = NULL;
11509     }
11510   if (sm->caller_breakpoint != NULL)
11511     {
11512       delete_breakpoint (sm->caller_breakpoint);
11513       sm->caller_breakpoint = NULL;
11514     }
11515   delete_longjmp_breakpoint (sm->thread);
11516 }
11517
11518 /* Implementation of the 'async_reply_reason' FSM method for the
11519    until(location)/advance commands.  */
11520
11521 static enum async_reply_reason
11522 until_break_fsm_async_reply_reason (struct thread_fsm *self)
11523 {
11524   return EXEC_ASYNC_LOCATION_REACHED;
11525 }
11526
11527 void
11528 until_break_command (char *arg, int from_tty, int anywhere)
11529 {
11530   struct symtabs_and_lines sals;
11531   struct symtab_and_line sal;
11532   struct frame_info *frame;
11533   struct gdbarch *frame_gdbarch;
11534   struct frame_id stack_frame_id;
11535   struct frame_id caller_frame_id;
11536   struct breakpoint *location_breakpoint;
11537   struct breakpoint *caller_breakpoint = NULL;
11538   struct cleanup *old_chain;
11539   int thread;
11540   struct thread_info *tp;
11541   struct until_break_fsm *sm;
11542
11543   clear_proceed_status (0);
11544
11545   /* Set a breakpoint where the user wants it and at return from
11546      this function.  */
11547
11548   event_location_up location = string_to_event_location (&arg, current_language);
11549
11550   if (last_displayed_sal_is_valid ())
11551     sals = decode_line_1 (location.get (), DECODE_LINE_FUNFIRSTLINE, NULL,
11552                           get_last_displayed_symtab (),
11553                           get_last_displayed_line ());
11554   else
11555     sals = decode_line_1 (location.get (), DECODE_LINE_FUNFIRSTLINE,
11556                           NULL, (struct symtab *) NULL, 0);
11557
11558   if (sals.nelts != 1)
11559     error (_("Couldn't get information on specified line."));
11560
11561   sal = sals.sals[0];
11562   xfree (sals.sals);    /* malloc'd, so freed.  */
11563
11564   if (*arg)
11565     error (_("Junk at end of arguments."));
11566
11567   resolve_sal_pc (&sal);
11568
11569   tp = inferior_thread ();
11570   thread = tp->global_num;
11571
11572   old_chain = make_cleanup (null_cleanup, NULL);
11573
11574   /* Note linespec handling above invalidates the frame chain.
11575      Installing a breakpoint also invalidates the frame chain (as it
11576      may need to switch threads), so do any frame handling before
11577      that.  */
11578
11579   frame = get_selected_frame (NULL);
11580   frame_gdbarch = get_frame_arch (frame);
11581   stack_frame_id = get_stack_frame_id (frame);
11582   caller_frame_id = frame_unwind_caller_id (frame);
11583
11584   /* Keep within the current frame, or in frames called by the current
11585      one.  */
11586
11587   if (frame_id_p (caller_frame_id))
11588     {
11589       struct symtab_and_line sal2;
11590       struct gdbarch *caller_gdbarch;
11591
11592       sal2 = find_pc_line (frame_unwind_caller_pc (frame), 0);
11593       sal2.pc = frame_unwind_caller_pc (frame);
11594       caller_gdbarch = frame_unwind_caller_arch (frame);
11595       caller_breakpoint = set_momentary_breakpoint (caller_gdbarch,
11596                                                     sal2,
11597                                                     caller_frame_id,
11598                                                     bp_until);
11599       make_cleanup_delete_breakpoint (caller_breakpoint);
11600
11601       set_longjmp_breakpoint (tp, caller_frame_id);
11602       make_cleanup (delete_longjmp_breakpoint_cleanup, &thread);
11603     }
11604
11605   /* set_momentary_breakpoint could invalidate FRAME.  */
11606   frame = NULL;
11607
11608   if (anywhere)
11609     /* If the user told us to continue until a specified location,
11610        we don't specify a frame at which we need to stop.  */
11611     location_breakpoint = set_momentary_breakpoint (frame_gdbarch, sal,
11612                                                     null_frame_id, bp_until);
11613   else
11614     /* Otherwise, specify the selected frame, because we want to stop
11615        only at the very same frame.  */
11616     location_breakpoint = set_momentary_breakpoint (frame_gdbarch, sal,
11617                                                     stack_frame_id, bp_until);
11618   make_cleanup_delete_breakpoint (location_breakpoint);
11619
11620   sm = new_until_break_fsm (command_interp (), tp->global_num,
11621                             location_breakpoint, caller_breakpoint);
11622   tp->thread_fsm = &sm->thread_fsm;
11623
11624   discard_cleanups (old_chain);
11625
11626   proceed (-1, GDB_SIGNAL_DEFAULT);
11627 }
11628
11629 /* This function attempts to parse an optional "if <cond>" clause
11630    from the arg string.  If one is not found, it returns NULL.
11631
11632    Else, it returns a pointer to the condition string.  (It does not
11633    attempt to evaluate the string against a particular block.)  And,
11634    it updates arg to point to the first character following the parsed
11635    if clause in the arg string.  */
11636
11637 const char *
11638 ep_parse_optional_if_clause (const char **arg)
11639 {
11640   const char *cond_string;
11641
11642   if (((*arg)[0] != 'i') || ((*arg)[1] != 'f') || !isspace ((*arg)[2]))
11643     return NULL;
11644
11645   /* Skip the "if" keyword.  */
11646   (*arg) += 2;
11647
11648   /* Skip any extra leading whitespace, and record the start of the
11649      condition string.  */
11650   *arg = skip_spaces_const (*arg);
11651   cond_string = *arg;
11652
11653   /* Assume that the condition occupies the remainder of the arg
11654      string.  */
11655   (*arg) += strlen (cond_string);
11656
11657   return cond_string;
11658 }
11659
11660 /* Commands to deal with catching events, such as signals, exceptions,
11661    process start/exit, etc.  */
11662
11663 typedef enum
11664 {
11665   catch_fork_temporary, catch_vfork_temporary,
11666   catch_fork_permanent, catch_vfork_permanent
11667 }
11668 catch_fork_kind;
11669
11670 static void
11671 catch_fork_command_1 (char *arg_entry, int from_tty,
11672                       struct cmd_list_element *command)
11673 {
11674   const char *arg = arg_entry;
11675   struct gdbarch *gdbarch = get_current_arch ();
11676   const char *cond_string = NULL;
11677   catch_fork_kind fork_kind;
11678   int tempflag;
11679
11680   fork_kind = (catch_fork_kind) (uintptr_t) get_cmd_context (command);
11681   tempflag = (fork_kind == catch_fork_temporary
11682               || fork_kind == catch_vfork_temporary);
11683
11684   if (!arg)
11685     arg = "";
11686   arg = skip_spaces_const (arg);
11687
11688   /* The allowed syntax is:
11689      catch [v]fork
11690      catch [v]fork if <cond>
11691
11692      First, check if there's an if clause.  */
11693   cond_string = ep_parse_optional_if_clause (&arg);
11694
11695   if ((*arg != '\0') && !isspace (*arg))
11696     error (_("Junk at end of arguments."));
11697
11698   /* If this target supports it, create a fork or vfork catchpoint
11699      and enable reporting of such events.  */
11700   switch (fork_kind)
11701     {
11702     case catch_fork_temporary:
11703     case catch_fork_permanent:
11704       create_fork_vfork_event_catchpoint (gdbarch, tempflag, cond_string,
11705                                           &catch_fork_breakpoint_ops);
11706       break;
11707     case catch_vfork_temporary:
11708     case catch_vfork_permanent:
11709       create_fork_vfork_event_catchpoint (gdbarch, tempflag, cond_string,
11710                                           &catch_vfork_breakpoint_ops);
11711       break;
11712     default:
11713       error (_("unsupported or unknown fork kind; cannot catch it"));
11714       break;
11715     }
11716 }
11717
11718 static void
11719 catch_exec_command_1 (char *arg_entry, int from_tty,
11720                       struct cmd_list_element *command)
11721 {
11722   const char *arg = arg_entry;
11723   struct exec_catchpoint *c;
11724   struct gdbarch *gdbarch = get_current_arch ();
11725   int tempflag;
11726   const char *cond_string = NULL;
11727
11728   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
11729
11730   if (!arg)
11731     arg = "";
11732   arg = skip_spaces_const (arg);
11733
11734   /* The allowed syntax is:
11735      catch exec
11736      catch exec if <cond>
11737
11738      First, check if there's an if clause.  */
11739   cond_string = ep_parse_optional_if_clause (&arg);
11740
11741   if ((*arg != '\0') && !isspace (*arg))
11742     error (_("Junk at end of arguments."));
11743
11744   c = new exec_catchpoint ();
11745   init_catchpoint (c, gdbarch, tempflag, cond_string,
11746                    &catch_exec_breakpoint_ops);
11747   c->exec_pathname = NULL;
11748
11749   install_breakpoint (0, c, 1);
11750 }
11751
11752 void
11753 init_ada_exception_breakpoint (struct breakpoint *b,
11754                                struct gdbarch *gdbarch,
11755                                struct symtab_and_line sal,
11756                                char *addr_string,
11757                                const struct breakpoint_ops *ops,
11758                                int tempflag,
11759                                int enabled,
11760                                int from_tty)
11761 {
11762   if (from_tty)
11763     {
11764       struct gdbarch *loc_gdbarch = get_sal_arch (sal);
11765       if (!loc_gdbarch)
11766         loc_gdbarch = gdbarch;
11767
11768       describe_other_breakpoints (loc_gdbarch,
11769                                   sal.pspace, sal.pc, sal.section, -1);
11770       /* FIXME: brobecker/2006-12-28: Actually, re-implement a special
11771          version for exception catchpoints, because two catchpoints
11772          used for different exception names will use the same address.
11773          In this case, a "breakpoint ... also set at..." warning is
11774          unproductive.  Besides, the warning phrasing is also a bit
11775          inappropriate, we should use the word catchpoint, and tell
11776          the user what type of catchpoint it is.  The above is good
11777          enough for now, though.  */
11778     }
11779
11780   init_raw_breakpoint (b, gdbarch, sal, bp_breakpoint, ops);
11781
11782   b->enable_state = enabled ? bp_enabled : bp_disabled;
11783   b->disposition = tempflag ? disp_del : disp_donttouch;
11784   b->location = string_to_event_location (&addr_string,
11785                                           language_def (language_ada));
11786   b->language = language_ada;
11787 }
11788
11789 static void
11790 catch_command (char *arg, int from_tty)
11791 {
11792   error (_("Catch requires an event name."));
11793 }
11794 \f
11795
11796 static void
11797 tcatch_command (char *arg, int from_tty)
11798 {
11799   error (_("Catch requires an event name."));
11800 }
11801
11802 /* A qsort comparison function that sorts breakpoints in order.  */
11803
11804 static int
11805 compare_breakpoints (const void *a, const void *b)
11806 {
11807   const breakpoint_p *ba = (const breakpoint_p *) a;
11808   uintptr_t ua = (uintptr_t) *ba;
11809   const breakpoint_p *bb = (const breakpoint_p *) b;
11810   uintptr_t ub = (uintptr_t) *bb;
11811
11812   if ((*ba)->number < (*bb)->number)
11813     return -1;
11814   else if ((*ba)->number > (*bb)->number)
11815     return 1;
11816
11817   /* Now sort by address, in case we see, e..g, two breakpoints with
11818      the number 0.  */
11819   if (ua < ub)
11820     return -1;
11821   return ua > ub ? 1 : 0;
11822 }
11823
11824 /* Delete breakpoints by address or line.  */
11825
11826 static void
11827 clear_command (char *arg, int from_tty)
11828 {
11829   struct breakpoint *b, *prev;
11830   VEC(breakpoint_p) *found = 0;
11831   int ix;
11832   int default_match;
11833   struct symtabs_and_lines sals;
11834   struct symtab_and_line sal;
11835   int i;
11836   struct cleanup *cleanups = make_cleanup (null_cleanup, NULL);
11837
11838   if (arg)
11839     {
11840       sals = decode_line_with_current_source (arg,
11841                                               (DECODE_LINE_FUNFIRSTLINE
11842                                                | DECODE_LINE_LIST_MODE));
11843       make_cleanup (xfree, sals.sals);
11844       default_match = 0;
11845     }
11846   else
11847     {
11848       sals.sals = XNEW (struct symtab_and_line);
11849       make_cleanup (xfree, sals.sals);
11850       init_sal (&sal);          /* Initialize to zeroes.  */
11851
11852       /* Set sal's line, symtab, pc, and pspace to the values
11853          corresponding to the last call to print_frame_info.  If the
11854          codepoint is not valid, this will set all the fields to 0.  */
11855       get_last_displayed_sal (&sal);
11856       if (sal.symtab == 0)
11857         error (_("No source file specified."));
11858
11859       sals.sals[0] = sal;
11860       sals.nelts = 1;
11861
11862       default_match = 1;
11863     }
11864
11865   /* We don't call resolve_sal_pc here.  That's not as bad as it
11866      seems, because all existing breakpoints typically have both
11867      file/line and pc set.  So, if clear is given file/line, we can
11868      match this to existing breakpoint without obtaining pc at all.
11869
11870      We only support clearing given the address explicitly 
11871      present in breakpoint table.  Say, we've set breakpoint 
11872      at file:line.  There were several PC values for that file:line,
11873      due to optimization, all in one block.
11874
11875      We've picked one PC value.  If "clear" is issued with another
11876      PC corresponding to the same file:line, the breakpoint won't
11877      be cleared.  We probably can still clear the breakpoint, but 
11878      since the other PC value is never presented to user, user
11879      can only find it by guessing, and it does not seem important
11880      to support that.  */
11881
11882   /* For each line spec given, delete bps which correspond to it.  Do
11883      it in two passes, solely to preserve the current behavior that
11884      from_tty is forced true if we delete more than one
11885      breakpoint.  */
11886
11887   found = NULL;
11888   make_cleanup (VEC_cleanup (breakpoint_p), &found);
11889   for (i = 0; i < sals.nelts; i++)
11890     {
11891       const char *sal_fullname;
11892
11893       /* If exact pc given, clear bpts at that pc.
11894          If line given (pc == 0), clear all bpts on specified line.
11895          If defaulting, clear all bpts on default line
11896          or at default pc.
11897
11898          defaulting    sal.pc != 0    tests to do
11899
11900          0              1             pc
11901          1              1             pc _and_ line
11902          0              0             line
11903          1              0             <can't happen> */
11904
11905       sal = sals.sals[i];
11906       sal_fullname = (sal.symtab == NULL
11907                       ? NULL : symtab_to_fullname (sal.symtab));
11908
11909       /* Find all matching breakpoints and add them to 'found'.  */
11910       ALL_BREAKPOINTS (b)
11911         {
11912           int match = 0;
11913           /* Are we going to delete b?  */
11914           if (b->type != bp_none && !is_watchpoint (b))
11915             {
11916               struct bp_location *loc = b->loc;
11917               for (; loc; loc = loc->next)
11918                 {
11919                   /* If the user specified file:line, don't allow a PC
11920                      match.  This matches historical gdb behavior.  */
11921                   int pc_match = (!sal.explicit_line
11922                                   && sal.pc
11923                                   && (loc->pspace == sal.pspace)
11924                                   && (loc->address == sal.pc)
11925                                   && (!section_is_overlay (loc->section)
11926                                       || loc->section == sal.section));
11927                   int line_match = 0;
11928
11929                   if ((default_match || sal.explicit_line)
11930                       && loc->symtab != NULL
11931                       && sal_fullname != NULL
11932                       && sal.pspace == loc->pspace
11933                       && loc->line_number == sal.line
11934                       && filename_cmp (symtab_to_fullname (loc->symtab),
11935                                        sal_fullname) == 0)
11936                     line_match = 1;
11937
11938                   if (pc_match || line_match)
11939                     {
11940                       match = 1;
11941                       break;
11942                     }
11943                 }
11944             }
11945
11946           if (match)
11947             VEC_safe_push(breakpoint_p, found, b);
11948         }
11949     }
11950
11951   /* Now go thru the 'found' chain and delete them.  */
11952   if (VEC_empty(breakpoint_p, found))
11953     {
11954       if (arg)
11955         error (_("No breakpoint at %s."), arg);
11956       else
11957         error (_("No breakpoint at this line."));
11958     }
11959
11960   /* Remove duplicates from the vec.  */
11961   qsort (VEC_address (breakpoint_p, found),
11962          VEC_length (breakpoint_p, found),
11963          sizeof (breakpoint_p),
11964          compare_breakpoints);
11965   prev = VEC_index (breakpoint_p, found, 0);
11966   for (ix = 1; VEC_iterate (breakpoint_p, found, ix, b); ++ix)
11967     {
11968       if (b == prev)
11969         {
11970           VEC_ordered_remove (breakpoint_p, found, ix);
11971           --ix;
11972         }
11973     }
11974
11975   if (VEC_length(breakpoint_p, found) > 1)
11976     from_tty = 1;       /* Always report if deleted more than one.  */
11977   if (from_tty)
11978     {
11979       if (VEC_length(breakpoint_p, found) == 1)
11980         printf_unfiltered (_("Deleted breakpoint "));
11981       else
11982         printf_unfiltered (_("Deleted breakpoints "));
11983     }
11984
11985   for (ix = 0; VEC_iterate(breakpoint_p, found, ix, b); ix++)
11986     {
11987       if (from_tty)
11988         printf_unfiltered ("%d ", b->number);
11989       delete_breakpoint (b);
11990     }
11991   if (from_tty)
11992     putchar_unfiltered ('\n');
11993
11994   do_cleanups (cleanups);
11995 }
11996 \f
11997 /* Delete breakpoint in BS if they are `delete' breakpoints and
11998    all breakpoints that are marked for deletion, whether hit or not.
11999    This is called after any breakpoint is hit, or after errors.  */
12000
12001 void
12002 breakpoint_auto_delete (bpstat bs)
12003 {
12004   struct breakpoint *b, *b_tmp;
12005
12006   for (; bs; bs = bs->next)
12007     if (bs->breakpoint_at
12008         && bs->breakpoint_at->disposition == disp_del
12009         && bs->stop)
12010       delete_breakpoint (bs->breakpoint_at);
12011
12012   ALL_BREAKPOINTS_SAFE (b, b_tmp)
12013   {
12014     if (b->disposition == disp_del_at_next_stop)
12015       delete_breakpoint (b);
12016   }
12017 }
12018
12019 /* A comparison function for bp_location AP and BP being interfaced to
12020    qsort.  Sort elements primarily by their ADDRESS (no matter what
12021    does breakpoint_address_is_meaningful say for its OWNER),
12022    secondarily by ordering first permanent elements and
12023    terciarily just ensuring the array is sorted stable way despite
12024    qsort being an unstable algorithm.  */
12025
12026 static int
12027 bp_locations_compare (const void *ap, const void *bp)
12028 {
12029   const struct bp_location *a = *(const struct bp_location **) ap;
12030   const struct bp_location *b = *(const struct bp_location **) bp;
12031
12032   if (a->address != b->address)
12033     return (a->address > b->address) - (a->address < b->address);
12034
12035   /* Sort locations at the same address by their pspace number, keeping
12036      locations of the same inferior (in a multi-inferior environment)
12037      grouped.  */
12038
12039   if (a->pspace->num != b->pspace->num)
12040     return ((a->pspace->num > b->pspace->num)
12041             - (a->pspace->num < b->pspace->num));
12042
12043   /* Sort permanent breakpoints first.  */
12044   if (a->permanent != b->permanent)
12045     return (a->permanent < b->permanent) - (a->permanent > b->permanent);
12046
12047   /* Make the internal GDB representation stable across GDB runs
12048      where A and B memory inside GDB can differ.  Breakpoint locations of
12049      the same type at the same address can be sorted in arbitrary order.  */
12050
12051   if (a->owner->number != b->owner->number)
12052     return ((a->owner->number > b->owner->number)
12053             - (a->owner->number < b->owner->number));
12054
12055   return (a > b) - (a < b);
12056 }
12057
12058 /* Set bp_locations_placed_address_before_address_max and
12059    bp_locations_shadow_len_after_address_max according to the current
12060    content of the bp_locations array.  */
12061
12062 static void
12063 bp_locations_target_extensions_update (void)
12064 {
12065   struct bp_location *bl, **blp_tmp;
12066
12067   bp_locations_placed_address_before_address_max = 0;
12068   bp_locations_shadow_len_after_address_max = 0;
12069
12070   ALL_BP_LOCATIONS (bl, blp_tmp)
12071     {
12072       CORE_ADDR start, end, addr;
12073
12074       if (!bp_location_has_shadow (bl))
12075         continue;
12076
12077       start = bl->target_info.placed_address;
12078       end = start + bl->target_info.shadow_len;
12079
12080       gdb_assert (bl->address >= start);
12081       addr = bl->address - start;
12082       if (addr > bp_locations_placed_address_before_address_max)
12083         bp_locations_placed_address_before_address_max = addr;
12084
12085       /* Zero SHADOW_LEN would not pass bp_location_has_shadow.  */
12086
12087       gdb_assert (bl->address < end);
12088       addr = end - bl->address;
12089       if (addr > bp_locations_shadow_len_after_address_max)
12090         bp_locations_shadow_len_after_address_max = addr;
12091     }
12092 }
12093
12094 /* Download tracepoint locations if they haven't been.  */
12095
12096 static void
12097 download_tracepoint_locations (void)
12098 {
12099   struct breakpoint *b;
12100   enum tribool can_download_tracepoint = TRIBOOL_UNKNOWN;
12101
12102   scoped_restore_current_pspace_and_thread restore_pspace_thread;
12103
12104   ALL_TRACEPOINTS (b)
12105     {
12106       struct bp_location *bl;
12107       struct tracepoint *t;
12108       int bp_location_downloaded = 0;
12109
12110       if ((b->type == bp_fast_tracepoint
12111            ? !may_insert_fast_tracepoints
12112            : !may_insert_tracepoints))
12113         continue;
12114
12115       if (can_download_tracepoint == TRIBOOL_UNKNOWN)
12116         {
12117           if (target_can_download_tracepoint ())
12118             can_download_tracepoint = TRIBOOL_TRUE;
12119           else
12120             can_download_tracepoint = TRIBOOL_FALSE;
12121         }
12122
12123       if (can_download_tracepoint == TRIBOOL_FALSE)
12124         break;
12125
12126       for (bl = b->loc; bl; bl = bl->next)
12127         {
12128           /* In tracepoint, locations are _never_ duplicated, so
12129              should_be_inserted is equivalent to
12130              unduplicated_should_be_inserted.  */
12131           if (!should_be_inserted (bl) || bl->inserted)
12132             continue;
12133
12134           switch_to_program_space_and_thread (bl->pspace);
12135
12136           target_download_tracepoint (bl);
12137
12138           bl->inserted = 1;
12139           bp_location_downloaded = 1;
12140         }
12141       t = (struct tracepoint *) b;
12142       t->number_on_target = b->number;
12143       if (bp_location_downloaded)
12144         observer_notify_breakpoint_modified (b);
12145     }
12146 }
12147
12148 /* Swap the insertion/duplication state between two locations.  */
12149
12150 static void
12151 swap_insertion (struct bp_location *left, struct bp_location *right)
12152 {
12153   const int left_inserted = left->inserted;
12154   const int left_duplicate = left->duplicate;
12155   const int left_needs_update = left->needs_update;
12156   const struct bp_target_info left_target_info = left->target_info;
12157
12158   /* Locations of tracepoints can never be duplicated.  */
12159   if (is_tracepoint (left->owner))
12160     gdb_assert (!left->duplicate);
12161   if (is_tracepoint (right->owner))
12162     gdb_assert (!right->duplicate);
12163
12164   left->inserted = right->inserted;
12165   left->duplicate = right->duplicate;
12166   left->needs_update = right->needs_update;
12167   left->target_info = right->target_info;
12168   right->inserted = left_inserted;
12169   right->duplicate = left_duplicate;
12170   right->needs_update = left_needs_update;
12171   right->target_info = left_target_info;
12172 }
12173
12174 /* Force the re-insertion of the locations at ADDRESS.  This is called
12175    once a new/deleted/modified duplicate location is found and we are evaluating
12176    conditions on the target's side.  Such conditions need to be updated on
12177    the target.  */
12178
12179 static void
12180 force_breakpoint_reinsertion (struct bp_location *bl)
12181 {
12182   struct bp_location **locp = NULL, **loc2p;
12183   struct bp_location *loc;
12184   CORE_ADDR address = 0;
12185   int pspace_num;
12186
12187   address = bl->address;
12188   pspace_num = bl->pspace->num;
12189
12190   /* This is only meaningful if the target is
12191      evaluating conditions and if the user has
12192      opted for condition evaluation on the target's
12193      side.  */
12194   if (gdb_evaluates_breakpoint_condition_p ()
12195       || !target_supports_evaluation_of_breakpoint_conditions ())
12196     return;
12197
12198   /* Flag all breakpoint locations with this address and
12199      the same program space as the location
12200      as "its condition has changed".  We need to
12201      update the conditions on the target's side.  */
12202   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, address)
12203     {
12204       loc = *loc2p;
12205
12206       if (!is_breakpoint (loc->owner)
12207           || pspace_num != loc->pspace->num)
12208         continue;
12209
12210       /* Flag the location appropriately.  We use a different state to
12211          let everyone know that we already updated the set of locations
12212          with addr bl->address and program space bl->pspace.  This is so
12213          we don't have to keep calling these functions just to mark locations
12214          that have already been marked.  */
12215       loc->condition_changed = condition_updated;
12216
12217       /* Free the agent expression bytecode as well.  We will compute
12218          it later on.  */
12219       loc->cond_bytecode.reset ();
12220     }
12221 }
12222 /* Called whether new breakpoints are created, or existing breakpoints
12223    deleted, to update the global location list and recompute which
12224    locations are duplicate of which.
12225
12226    The INSERT_MODE flag determines whether locations may not, may, or
12227    shall be inserted now.  See 'enum ugll_insert_mode' for more
12228    info.  */
12229
12230 static void
12231 update_global_location_list (enum ugll_insert_mode insert_mode)
12232 {
12233   struct breakpoint *b;
12234   struct bp_location **locp, *loc;
12235   struct cleanup *cleanups;
12236   /* Last breakpoint location address that was marked for update.  */
12237   CORE_ADDR last_addr = 0;
12238   /* Last breakpoint location program space that was marked for update.  */
12239   int last_pspace_num = -1;
12240
12241   /* Used in the duplicates detection below.  When iterating over all
12242      bp_locations, points to the first bp_location of a given address.
12243      Breakpoints and watchpoints of different types are never
12244      duplicates of each other.  Keep one pointer for each type of
12245      breakpoint/watchpoint, so we only need to loop over all locations
12246      once.  */
12247   struct bp_location *bp_loc_first;  /* breakpoint */
12248   struct bp_location *wp_loc_first;  /* hardware watchpoint */
12249   struct bp_location *awp_loc_first; /* access watchpoint */
12250   struct bp_location *rwp_loc_first; /* read watchpoint */
12251
12252   /* Saved former bp_locations array which we compare against the newly
12253      built bp_locations from the current state of ALL_BREAKPOINTS.  */
12254   struct bp_location **old_locations, **old_locp;
12255   unsigned old_locations_count;
12256
12257   old_locations = bp_locations;
12258   old_locations_count = bp_locations_count;
12259   bp_locations = NULL;
12260   bp_locations_count = 0;
12261   cleanups = make_cleanup (xfree, old_locations);
12262
12263   ALL_BREAKPOINTS (b)
12264     for (loc = b->loc; loc; loc = loc->next)
12265       bp_locations_count++;
12266
12267   bp_locations = XNEWVEC (struct bp_location *, bp_locations_count);
12268   locp = bp_locations;
12269   ALL_BREAKPOINTS (b)
12270     for (loc = b->loc; loc; loc = loc->next)
12271       *locp++ = loc;
12272   qsort (bp_locations, bp_locations_count, sizeof (*bp_locations),
12273          bp_locations_compare);
12274
12275   bp_locations_target_extensions_update ();
12276
12277   /* Identify bp_location instances that are no longer present in the
12278      new list, and therefore should be freed.  Note that it's not
12279      necessary that those locations should be removed from inferior --
12280      if there's another location at the same address (previously
12281      marked as duplicate), we don't need to remove/insert the
12282      location.
12283      
12284      LOCP is kept in sync with OLD_LOCP, each pointing to the current
12285      and former bp_location array state respectively.  */
12286
12287   locp = bp_locations;
12288   for (old_locp = old_locations;
12289        old_locp < old_locations + old_locations_count;
12290        old_locp++)
12291     {
12292       struct bp_location *old_loc = *old_locp;
12293       struct bp_location **loc2p;
12294
12295       /* Tells if 'old_loc' is found among the new locations.  If
12296          not, we have to free it.  */
12297       int found_object = 0;
12298       /* Tells if the location should remain inserted in the target.  */
12299       int keep_in_target = 0;
12300       int removed = 0;
12301
12302       /* Skip LOCP entries which will definitely never be needed.
12303          Stop either at or being the one matching OLD_LOC.  */
12304       while (locp < bp_locations + bp_locations_count
12305              && (*locp)->address < old_loc->address)
12306         locp++;
12307
12308       for (loc2p = locp;
12309            (loc2p < bp_locations + bp_locations_count
12310             && (*loc2p)->address == old_loc->address);
12311            loc2p++)
12312         {
12313           /* Check if this is a new/duplicated location or a duplicated
12314              location that had its condition modified.  If so, we want to send
12315              its condition to the target if evaluation of conditions is taking
12316              place there.  */
12317           if ((*loc2p)->condition_changed == condition_modified
12318               && (last_addr != old_loc->address
12319                   || last_pspace_num != old_loc->pspace->num))
12320             {
12321               force_breakpoint_reinsertion (*loc2p);
12322               last_pspace_num = old_loc->pspace->num;
12323             }
12324
12325           if (*loc2p == old_loc)
12326             found_object = 1;
12327         }
12328
12329       /* We have already handled this address, update it so that we don't
12330          have to go through updates again.  */
12331       last_addr = old_loc->address;
12332
12333       /* Target-side condition evaluation: Handle deleted locations.  */
12334       if (!found_object)
12335         force_breakpoint_reinsertion (old_loc);
12336
12337       /* If this location is no longer present, and inserted, look if
12338          there's maybe a new location at the same address.  If so,
12339          mark that one inserted, and don't remove this one.  This is
12340          needed so that we don't have a time window where a breakpoint
12341          at certain location is not inserted.  */
12342
12343       if (old_loc->inserted)
12344         {
12345           /* If the location is inserted now, we might have to remove
12346              it.  */
12347
12348           if (found_object && should_be_inserted (old_loc))
12349             {
12350               /* The location is still present in the location list,
12351                  and still should be inserted.  Don't do anything.  */
12352               keep_in_target = 1;
12353             }
12354           else
12355             {
12356               /* This location still exists, but it won't be kept in the
12357                  target since it may have been disabled.  We proceed to
12358                  remove its target-side condition.  */
12359
12360               /* The location is either no longer present, or got
12361                  disabled.  See if there's another location at the
12362                  same address, in which case we don't need to remove
12363                  this one from the target.  */
12364
12365               /* OLD_LOC comes from existing struct breakpoint.  */
12366               if (breakpoint_address_is_meaningful (old_loc->owner))
12367                 {
12368                   for (loc2p = locp;
12369                        (loc2p < bp_locations + bp_locations_count
12370                         && (*loc2p)->address == old_loc->address);
12371                        loc2p++)
12372                     {
12373                       struct bp_location *loc2 = *loc2p;
12374
12375                       if (breakpoint_locations_match (loc2, old_loc))
12376                         {
12377                           /* Read watchpoint locations are switched to
12378                              access watchpoints, if the former are not
12379                              supported, but the latter are.  */
12380                           if (is_hardware_watchpoint (old_loc->owner))
12381                             {
12382                               gdb_assert (is_hardware_watchpoint (loc2->owner));
12383                               loc2->watchpoint_type = old_loc->watchpoint_type;
12384                             }
12385
12386                           /* loc2 is a duplicated location. We need to check
12387                              if it should be inserted in case it will be
12388                              unduplicated.  */
12389                           if (loc2 != old_loc
12390                               && unduplicated_should_be_inserted (loc2))
12391                             {
12392                               swap_insertion (old_loc, loc2);
12393                               keep_in_target = 1;
12394                               break;
12395                             }
12396                         }
12397                     }
12398                 }
12399             }
12400
12401           if (!keep_in_target)
12402             {
12403               if (remove_breakpoint (old_loc))
12404                 {
12405                   /* This is just about all we can do.  We could keep
12406                      this location on the global list, and try to
12407                      remove it next time, but there's no particular
12408                      reason why we will succeed next time.
12409                      
12410                      Note that at this point, old_loc->owner is still
12411                      valid, as delete_breakpoint frees the breakpoint
12412                      only after calling us.  */
12413                   printf_filtered (_("warning: Error removing "
12414                                      "breakpoint %d\n"), 
12415                                    old_loc->owner->number);
12416                 }
12417               removed = 1;
12418             }
12419         }
12420
12421       if (!found_object)
12422         {
12423           if (removed && target_is_non_stop_p ()
12424               && need_moribund_for_location_type (old_loc))
12425             {
12426               /* This location was removed from the target.  In
12427                  non-stop mode, a race condition is possible where
12428                  we've removed a breakpoint, but stop events for that
12429                  breakpoint are already queued and will arrive later.
12430                  We apply an heuristic to be able to distinguish such
12431                  SIGTRAPs from other random SIGTRAPs: we keep this
12432                  breakpoint location for a bit, and will retire it
12433                  after we see some number of events.  The theory here
12434                  is that reporting of events should, "on the average",
12435                  be fair, so after a while we'll see events from all
12436                  threads that have anything of interest, and no longer
12437                  need to keep this breakpoint location around.  We
12438                  don't hold locations forever so to reduce chances of
12439                  mistaking a non-breakpoint SIGTRAP for a breakpoint
12440                  SIGTRAP.
12441
12442                  The heuristic failing can be disastrous on
12443                  decr_pc_after_break targets.
12444
12445                  On decr_pc_after_break targets, like e.g., x86-linux,
12446                  if we fail to recognize a late breakpoint SIGTRAP,
12447                  because events_till_retirement has reached 0 too
12448                  soon, we'll fail to do the PC adjustment, and report
12449                  a random SIGTRAP to the user.  When the user resumes
12450                  the inferior, it will most likely immediately crash
12451                  with SIGILL/SIGBUS/SIGSEGV, or worse, get silently
12452                  corrupted, because of being resumed e.g., in the
12453                  middle of a multi-byte instruction, or skipped a
12454                  one-byte instruction.  This was actually seen happen
12455                  on native x86-linux, and should be less rare on
12456                  targets that do not support new thread events, like
12457                  remote, due to the heuristic depending on
12458                  thread_count.
12459
12460                  Mistaking a random SIGTRAP for a breakpoint trap
12461                  causes similar symptoms (PC adjustment applied when
12462                  it shouldn't), but then again, playing with SIGTRAPs
12463                  behind the debugger's back is asking for trouble.
12464
12465                  Since hardware watchpoint traps are always
12466                  distinguishable from other traps, so we don't need to
12467                  apply keep hardware watchpoint moribund locations
12468                  around.  We simply always ignore hardware watchpoint
12469                  traps we can no longer explain.  */
12470
12471               old_loc->events_till_retirement = 3 * (thread_count () + 1);
12472               old_loc->owner = NULL;
12473
12474               VEC_safe_push (bp_location_p, moribund_locations, old_loc);
12475             }
12476           else
12477             {
12478               old_loc->owner = NULL;
12479               decref_bp_location (&old_loc);
12480             }
12481         }
12482     }
12483
12484   /* Rescan breakpoints at the same address and section, marking the
12485      first one as "first" and any others as "duplicates".  This is so
12486      that the bpt instruction is only inserted once.  If we have a
12487      permanent breakpoint at the same place as BPT, make that one the
12488      official one, and the rest as duplicates.  Permanent breakpoints
12489      are sorted first for the same address.
12490
12491      Do the same for hardware watchpoints, but also considering the
12492      watchpoint's type (regular/access/read) and length.  */
12493
12494   bp_loc_first = NULL;
12495   wp_loc_first = NULL;
12496   awp_loc_first = NULL;
12497   rwp_loc_first = NULL;
12498   ALL_BP_LOCATIONS (loc, locp)
12499     {
12500       /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always
12501          non-NULL.  */
12502       struct bp_location **loc_first_p;
12503       b = loc->owner;
12504
12505       if (!unduplicated_should_be_inserted (loc)
12506           || !breakpoint_address_is_meaningful (b)
12507           /* Don't detect duplicate for tracepoint locations because they are
12508            never duplicated.  See the comments in field `duplicate' of
12509            `struct bp_location'.  */
12510           || is_tracepoint (b))
12511         {
12512           /* Clear the condition modification flag.  */
12513           loc->condition_changed = condition_unchanged;
12514           continue;
12515         }
12516
12517       if (b->type == bp_hardware_watchpoint)
12518         loc_first_p = &wp_loc_first;
12519       else if (b->type == bp_read_watchpoint)
12520         loc_first_p = &rwp_loc_first;
12521       else if (b->type == bp_access_watchpoint)
12522         loc_first_p = &awp_loc_first;
12523       else
12524         loc_first_p = &bp_loc_first;
12525
12526       if (*loc_first_p == NULL
12527           || (overlay_debugging && loc->section != (*loc_first_p)->section)
12528           || !breakpoint_locations_match (loc, *loc_first_p))
12529         {
12530           *loc_first_p = loc;
12531           loc->duplicate = 0;
12532
12533           if (is_breakpoint (loc->owner) && loc->condition_changed)
12534             {
12535               loc->needs_update = 1;
12536               /* Clear the condition modification flag.  */
12537               loc->condition_changed = condition_unchanged;
12538             }
12539           continue;
12540         }
12541
12542
12543       /* This and the above ensure the invariant that the first location
12544          is not duplicated, and is the inserted one.
12545          All following are marked as duplicated, and are not inserted.  */
12546       if (loc->inserted)
12547         swap_insertion (loc, *loc_first_p);
12548       loc->duplicate = 1;
12549
12550       /* Clear the condition modification flag.  */
12551       loc->condition_changed = condition_unchanged;
12552     }
12553
12554   if (insert_mode == UGLL_INSERT || breakpoints_should_be_inserted_now ())
12555     {
12556       if (insert_mode != UGLL_DONT_INSERT)
12557         insert_breakpoint_locations ();
12558       else
12559         {
12560           /* Even though the caller told us to not insert new
12561              locations, we may still need to update conditions on the
12562              target's side of breakpoints that were already inserted
12563              if the target is evaluating breakpoint conditions.  We
12564              only update conditions for locations that are marked
12565              "needs_update".  */
12566           update_inserted_breakpoint_locations ();
12567         }
12568     }
12569
12570   if (insert_mode != UGLL_DONT_INSERT)
12571     download_tracepoint_locations ();
12572
12573   do_cleanups (cleanups);
12574 }
12575
12576 void
12577 breakpoint_retire_moribund (void)
12578 {
12579   struct bp_location *loc;
12580   int ix;
12581
12582   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
12583     if (--(loc->events_till_retirement) == 0)
12584       {
12585         decref_bp_location (&loc);
12586         VEC_unordered_remove (bp_location_p, moribund_locations, ix);
12587         --ix;
12588       }
12589 }
12590
12591 static void
12592 update_global_location_list_nothrow (enum ugll_insert_mode insert_mode)
12593 {
12594
12595   TRY
12596     {
12597       update_global_location_list (insert_mode);
12598     }
12599   CATCH (e, RETURN_MASK_ERROR)
12600     {
12601     }
12602   END_CATCH
12603 }
12604
12605 /* Clear BKP from a BPS.  */
12606
12607 static void
12608 bpstat_remove_bp_location (bpstat bps, struct breakpoint *bpt)
12609 {
12610   bpstat bs;
12611
12612   for (bs = bps; bs; bs = bs->next)
12613     if (bs->breakpoint_at == bpt)
12614       {
12615         bs->breakpoint_at = NULL;
12616         bs->old_val = NULL;
12617         /* bs->commands will be freed later.  */
12618       }
12619 }
12620
12621 /* Callback for iterate_over_threads.  */
12622 static int
12623 bpstat_remove_breakpoint_callback (struct thread_info *th, void *data)
12624 {
12625   struct breakpoint *bpt = (struct breakpoint *) data;
12626
12627   bpstat_remove_bp_location (th->control.stop_bpstat, bpt);
12628   return 0;
12629 }
12630
12631 /* Helper for breakpoint and tracepoint breakpoint_ops->mention
12632    callbacks.  */
12633
12634 static void
12635 say_where (struct breakpoint *b)
12636 {
12637   struct value_print_options opts;
12638
12639   get_user_print_options (&opts);
12640
12641   /* i18n: cagney/2005-02-11: Below needs to be merged into a
12642      single string.  */
12643   if (b->loc == NULL)
12644     {
12645       /* For pending locations, the output differs slightly based
12646          on b->extra_string.  If this is non-NULL, it contains either
12647          a condition or dprintf arguments.  */
12648       if (b->extra_string == NULL)
12649         {
12650           printf_filtered (_(" (%s) pending."),
12651                            event_location_to_string (b->location.get ()));
12652         }
12653       else if (b->type == bp_dprintf)
12654         {
12655           printf_filtered (_(" (%s,%s) pending."),
12656                            event_location_to_string (b->location.get ()),
12657                            b->extra_string);
12658         }
12659       else
12660         {
12661           printf_filtered (_(" (%s %s) pending."),
12662                            event_location_to_string (b->location.get ()),
12663                            b->extra_string);
12664         }
12665     }
12666   else
12667     {
12668       if (opts.addressprint || b->loc->symtab == NULL)
12669         {
12670           printf_filtered (" at ");
12671           fputs_filtered (paddress (b->loc->gdbarch, b->loc->address),
12672                           gdb_stdout);
12673         }
12674       if (b->loc->symtab != NULL)
12675         {
12676           /* If there is a single location, we can print the location
12677              more nicely.  */
12678           if (b->loc->next == NULL)
12679             printf_filtered (": file %s, line %d.",
12680                              symtab_to_filename_for_display (b->loc->symtab),
12681                              b->loc->line_number);
12682           else
12683             /* This is not ideal, but each location may have a
12684                different file name, and this at least reflects the
12685                real situation somewhat.  */
12686             printf_filtered (": %s.",
12687                              event_location_to_string (b->location.get ()));
12688         }
12689
12690       if (b->loc->next)
12691         {
12692           struct bp_location *loc = b->loc;
12693           int n = 0;
12694           for (; loc; loc = loc->next)
12695             ++n;
12696           printf_filtered (" (%d locations)", n);
12697         }
12698     }
12699 }
12700
12701 /* Default bp_location_ops methods.  */
12702
12703 static void
12704 bp_location_dtor (struct bp_location *self)
12705 {
12706   xfree (self->function_name);
12707 }
12708
12709 static const struct bp_location_ops bp_location_ops =
12710 {
12711   bp_location_dtor
12712 };
12713
12714 /* Destructor for the breakpoint base class.  */
12715
12716 breakpoint::~breakpoint ()
12717 {
12718   decref_counted_command_line (&this->commands);
12719   xfree (this->cond_string);
12720   xfree (this->extra_string);
12721   xfree (this->filter);
12722 }
12723
12724 static struct bp_location *
12725 base_breakpoint_allocate_location (struct breakpoint *self)
12726 {
12727   return new bp_location (&bp_location_ops, self);
12728 }
12729
12730 static void
12731 base_breakpoint_re_set (struct breakpoint *b)
12732 {
12733   /* Nothing to re-set. */
12734 }
12735
12736 #define internal_error_pure_virtual_called() \
12737   gdb_assert_not_reached ("pure virtual function called")
12738
12739 static int
12740 base_breakpoint_insert_location (struct bp_location *bl)
12741 {
12742   internal_error_pure_virtual_called ();
12743 }
12744
12745 static int
12746 base_breakpoint_remove_location (struct bp_location *bl,
12747                                  enum remove_bp_reason reason)
12748 {
12749   internal_error_pure_virtual_called ();
12750 }
12751
12752 static int
12753 base_breakpoint_breakpoint_hit (const struct bp_location *bl,
12754                                 struct address_space *aspace,
12755                                 CORE_ADDR bp_addr,
12756                                 const struct target_waitstatus *ws)
12757 {
12758   internal_error_pure_virtual_called ();
12759 }
12760
12761 static void
12762 base_breakpoint_check_status (bpstat bs)
12763 {
12764   /* Always stop.   */
12765 }
12766
12767 /* A "works_in_software_mode" breakpoint_ops method that just internal
12768    errors.  */
12769
12770 static int
12771 base_breakpoint_works_in_software_mode (const struct breakpoint *b)
12772 {
12773   internal_error_pure_virtual_called ();
12774 }
12775
12776 /* A "resources_needed" breakpoint_ops method that just internal
12777    errors.  */
12778
12779 static int
12780 base_breakpoint_resources_needed (const struct bp_location *bl)
12781 {
12782   internal_error_pure_virtual_called ();
12783 }
12784
12785 static enum print_stop_action
12786 base_breakpoint_print_it (bpstat bs)
12787 {
12788   internal_error_pure_virtual_called ();
12789 }
12790
12791 static void
12792 base_breakpoint_print_one_detail (const struct breakpoint *self,
12793                                   struct ui_out *uiout)
12794 {
12795   /* nothing */
12796 }
12797
12798 static void
12799 base_breakpoint_print_mention (struct breakpoint *b)
12800 {
12801   internal_error_pure_virtual_called ();
12802 }
12803
12804 static void
12805 base_breakpoint_print_recreate (struct breakpoint *b, struct ui_file *fp)
12806 {
12807   internal_error_pure_virtual_called ();
12808 }
12809
12810 static void
12811 base_breakpoint_create_sals_from_location
12812   (const struct event_location *location,
12813    struct linespec_result *canonical,
12814    enum bptype type_wanted)
12815 {
12816   internal_error_pure_virtual_called ();
12817 }
12818
12819 static void
12820 base_breakpoint_create_breakpoints_sal (struct gdbarch *gdbarch,
12821                                         struct linespec_result *c,
12822                                         gdb::unique_xmalloc_ptr<char> cond_string,
12823                                         gdb::unique_xmalloc_ptr<char> extra_string,
12824                                         enum bptype type_wanted,
12825                                         enum bpdisp disposition,
12826                                         int thread,
12827                                         int task, int ignore_count,
12828                                         const struct breakpoint_ops *o,
12829                                         int from_tty, int enabled,
12830                                         int internal, unsigned flags)
12831 {
12832   internal_error_pure_virtual_called ();
12833 }
12834
12835 static void
12836 base_breakpoint_decode_location (struct breakpoint *b,
12837                                  const struct event_location *location,
12838                                  struct program_space *search_pspace,
12839                                  struct symtabs_and_lines *sals)
12840 {
12841   internal_error_pure_virtual_called ();
12842 }
12843
12844 /* The default 'explains_signal' method.  */
12845
12846 static int
12847 base_breakpoint_explains_signal (struct breakpoint *b, enum gdb_signal sig)
12848 {
12849   return 1;
12850 }
12851
12852 /* The default "after_condition_true" method.  */
12853
12854 static void
12855 base_breakpoint_after_condition_true (struct bpstats *bs)
12856 {
12857   /* Nothing to do.   */
12858 }
12859
12860 struct breakpoint_ops base_breakpoint_ops =
12861 {
12862   base_breakpoint_allocate_location,
12863   base_breakpoint_re_set,
12864   base_breakpoint_insert_location,
12865   base_breakpoint_remove_location,
12866   base_breakpoint_breakpoint_hit,
12867   base_breakpoint_check_status,
12868   base_breakpoint_resources_needed,
12869   base_breakpoint_works_in_software_mode,
12870   base_breakpoint_print_it,
12871   NULL,
12872   base_breakpoint_print_one_detail,
12873   base_breakpoint_print_mention,
12874   base_breakpoint_print_recreate,
12875   base_breakpoint_create_sals_from_location,
12876   base_breakpoint_create_breakpoints_sal,
12877   base_breakpoint_decode_location,
12878   base_breakpoint_explains_signal,
12879   base_breakpoint_after_condition_true,
12880 };
12881
12882 /* Default breakpoint_ops methods.  */
12883
12884 static void
12885 bkpt_re_set (struct breakpoint *b)
12886 {
12887   /* FIXME: is this still reachable?  */
12888   if (breakpoint_event_location_empty_p (b))
12889     {
12890       /* Anything without a location can't be re-set.  */
12891       delete_breakpoint (b);
12892       return;
12893     }
12894
12895   breakpoint_re_set_default (b);
12896 }
12897
12898 static int
12899 bkpt_insert_location (struct bp_location *bl)
12900 {
12901   CORE_ADDR addr = bl->target_info.reqstd_address;
12902
12903   bl->target_info.kind = breakpoint_kind (bl, &addr);
12904   bl->target_info.placed_address = addr;
12905
12906   if (bl->loc_type == bp_loc_hardware_breakpoint)
12907     return target_insert_hw_breakpoint (bl->gdbarch, &bl->target_info);
12908   else
12909     return target_insert_breakpoint (bl->gdbarch, &bl->target_info);
12910 }
12911
12912 static int
12913 bkpt_remove_location (struct bp_location *bl, enum remove_bp_reason reason)
12914 {
12915   if (bl->loc_type == bp_loc_hardware_breakpoint)
12916     return target_remove_hw_breakpoint (bl->gdbarch, &bl->target_info);
12917   else
12918     return target_remove_breakpoint (bl->gdbarch, &bl->target_info, reason);
12919 }
12920
12921 static int
12922 bkpt_breakpoint_hit (const struct bp_location *bl,
12923                      struct address_space *aspace, CORE_ADDR bp_addr,
12924                      const struct target_waitstatus *ws)
12925 {
12926   if (ws->kind != TARGET_WAITKIND_STOPPED
12927       || ws->value.sig != GDB_SIGNAL_TRAP)
12928     return 0;
12929
12930   if (!breakpoint_address_match (bl->pspace->aspace, bl->address,
12931                                  aspace, bp_addr))
12932     return 0;
12933
12934   if (overlay_debugging         /* unmapped overlay section */
12935       && section_is_overlay (bl->section)
12936       && !section_is_mapped (bl->section))
12937     return 0;
12938
12939   return 1;
12940 }
12941
12942 static int
12943 dprintf_breakpoint_hit (const struct bp_location *bl,
12944                         struct address_space *aspace, CORE_ADDR bp_addr,
12945                         const struct target_waitstatus *ws)
12946 {
12947   if (dprintf_style == dprintf_style_agent
12948       && target_can_run_breakpoint_commands ())
12949     {
12950       /* An agent-style dprintf never causes a stop.  If we see a trap
12951          for this address it must be for a breakpoint that happens to
12952          be set at the same address.  */
12953       return 0;
12954     }
12955
12956   return bkpt_breakpoint_hit (bl, aspace, bp_addr, ws);
12957 }
12958
12959 static int
12960 bkpt_resources_needed (const struct bp_location *bl)
12961 {
12962   gdb_assert (bl->owner->type == bp_hardware_breakpoint);
12963
12964   return 1;
12965 }
12966
12967 static enum print_stop_action
12968 bkpt_print_it (bpstat bs)
12969 {
12970   struct breakpoint *b;
12971   const struct bp_location *bl;
12972   int bp_temp;
12973   struct ui_out *uiout = current_uiout;
12974
12975   gdb_assert (bs->bp_location_at != NULL);
12976
12977   bl = bs->bp_location_at;
12978   b = bs->breakpoint_at;
12979
12980   bp_temp = b->disposition == disp_del;
12981   if (bl->address != bl->requested_address)
12982     breakpoint_adjustment_warning (bl->requested_address,
12983                                    bl->address,
12984                                    b->number, 1);
12985   annotate_breakpoint (b->number);
12986   maybe_print_thread_hit_breakpoint (uiout);
12987
12988   if (bp_temp)
12989     uiout->text ("Temporary breakpoint ");
12990   else
12991     uiout->text ("Breakpoint ");
12992   if (uiout->is_mi_like_p ())
12993     {
12994       uiout->field_string ("reason",
12995                            async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
12996       uiout->field_string ("disp", bpdisp_text (b->disposition));
12997     }
12998   uiout->field_int ("bkptno", b->number);
12999   uiout->text (", ");
13000
13001   return PRINT_SRC_AND_LOC;
13002 }
13003
13004 static void
13005 bkpt_print_mention (struct breakpoint *b)
13006 {
13007   if (current_uiout->is_mi_like_p ())
13008     return;
13009
13010   switch (b->type)
13011     {
13012     case bp_breakpoint:
13013     case bp_gnu_ifunc_resolver:
13014       if (b->disposition == disp_del)
13015         printf_filtered (_("Temporary breakpoint"));
13016       else
13017         printf_filtered (_("Breakpoint"));
13018       printf_filtered (_(" %d"), b->number);
13019       if (b->type == bp_gnu_ifunc_resolver)
13020         printf_filtered (_(" at gnu-indirect-function resolver"));
13021       break;
13022     case bp_hardware_breakpoint:
13023       printf_filtered (_("Hardware assisted breakpoint %d"), b->number);
13024       break;
13025     case bp_dprintf:
13026       printf_filtered (_("Dprintf %d"), b->number);
13027       break;
13028     }
13029
13030   say_where (b);
13031 }
13032
13033 static void
13034 bkpt_print_recreate (struct breakpoint *tp, struct ui_file *fp)
13035 {
13036   if (tp->type == bp_breakpoint && tp->disposition == disp_del)
13037     fprintf_unfiltered (fp, "tbreak");
13038   else if (tp->type == bp_breakpoint)
13039     fprintf_unfiltered (fp, "break");
13040   else if (tp->type == bp_hardware_breakpoint
13041            && tp->disposition == disp_del)
13042     fprintf_unfiltered (fp, "thbreak");
13043   else if (tp->type == bp_hardware_breakpoint)
13044     fprintf_unfiltered (fp, "hbreak");
13045   else
13046     internal_error (__FILE__, __LINE__,
13047                     _("unhandled breakpoint type %d"), (int) tp->type);
13048
13049   fprintf_unfiltered (fp, " %s",
13050                       event_location_to_string (tp->location.get ()));
13051
13052   /* Print out extra_string if this breakpoint is pending.  It might
13053      contain, for example, conditions that were set by the user.  */
13054   if (tp->loc == NULL && tp->extra_string != NULL)
13055     fprintf_unfiltered (fp, " %s", tp->extra_string);
13056
13057   print_recreate_thread (tp, fp);
13058 }
13059
13060 static void
13061 bkpt_create_sals_from_location (const struct event_location *location,
13062                                 struct linespec_result *canonical,
13063                                 enum bptype type_wanted)
13064 {
13065   create_sals_from_location_default (location, canonical, type_wanted);
13066 }
13067
13068 static void
13069 bkpt_create_breakpoints_sal (struct gdbarch *gdbarch,
13070                              struct linespec_result *canonical,
13071                              gdb::unique_xmalloc_ptr<char> cond_string,
13072                              gdb::unique_xmalloc_ptr<char> extra_string,
13073                              enum bptype type_wanted,
13074                              enum bpdisp disposition,
13075                              int thread,
13076                              int task, int ignore_count,
13077                              const struct breakpoint_ops *ops,
13078                              int from_tty, int enabled,
13079                              int internal, unsigned flags)
13080 {
13081   create_breakpoints_sal_default (gdbarch, canonical,
13082                                   std::move (cond_string),
13083                                   std::move (extra_string),
13084                                   type_wanted,
13085                                   disposition, thread, task,
13086                                   ignore_count, ops, from_tty,
13087                                   enabled, internal, flags);
13088 }
13089
13090 static void
13091 bkpt_decode_location (struct breakpoint *b,
13092                       const struct event_location *location,
13093                       struct program_space *search_pspace,
13094                       struct symtabs_and_lines *sals)
13095 {
13096   decode_location_default (b, location, search_pspace, sals);
13097 }
13098
13099 /* Virtual table for internal breakpoints.  */
13100
13101 static void
13102 internal_bkpt_re_set (struct breakpoint *b)
13103 {
13104   switch (b->type)
13105     {
13106       /* Delete overlay event and longjmp master breakpoints; they
13107          will be reset later by breakpoint_re_set.  */
13108     case bp_overlay_event:
13109     case bp_longjmp_master:
13110     case bp_std_terminate_master:
13111     case bp_exception_master:
13112       delete_breakpoint (b);
13113       break;
13114
13115       /* This breakpoint is special, it's set up when the inferior
13116          starts and we really don't want to touch it.  */
13117     case bp_shlib_event:
13118
13119       /* Like bp_shlib_event, this breakpoint type is special.  Once
13120          it is set up, we do not want to touch it.  */
13121     case bp_thread_event:
13122       break;
13123     }
13124 }
13125
13126 static void
13127 internal_bkpt_check_status (bpstat bs)
13128 {
13129   if (bs->breakpoint_at->type == bp_shlib_event)
13130     {
13131       /* If requested, stop when the dynamic linker notifies GDB of
13132          events.  This allows the user to get control and place
13133          breakpoints in initializer routines for dynamically loaded
13134          objects (among other things).  */
13135       bs->stop = stop_on_solib_events;
13136       bs->print = stop_on_solib_events;
13137     }
13138   else
13139     bs->stop = 0;
13140 }
13141
13142 static enum print_stop_action
13143 internal_bkpt_print_it (bpstat bs)
13144 {
13145   struct breakpoint *b;
13146
13147   b = bs->breakpoint_at;
13148
13149   switch (b->type)
13150     {
13151     case bp_shlib_event:
13152       /* Did we stop because the user set the stop_on_solib_events
13153          variable?  (If so, we report this as a generic, "Stopped due
13154          to shlib event" message.) */
13155       print_solib_event (0);
13156       break;
13157
13158     case bp_thread_event:
13159       /* Not sure how we will get here.
13160          GDB should not stop for these breakpoints.  */
13161       printf_filtered (_("Thread Event Breakpoint: gdb should not stop!\n"));
13162       break;
13163
13164     case bp_overlay_event:
13165       /* By analogy with the thread event, GDB should not stop for these.  */
13166       printf_filtered (_("Overlay Event Breakpoint: gdb should not stop!\n"));
13167       break;
13168
13169     case bp_longjmp_master:
13170       /* These should never be enabled.  */
13171       printf_filtered (_("Longjmp Master Breakpoint: gdb should not stop!\n"));
13172       break;
13173
13174     case bp_std_terminate_master:
13175       /* These should never be enabled.  */
13176       printf_filtered (_("std::terminate Master Breakpoint: "
13177                          "gdb should not stop!\n"));
13178       break;
13179
13180     case bp_exception_master:
13181       /* These should never be enabled.  */
13182       printf_filtered (_("Exception Master Breakpoint: "
13183                          "gdb should not stop!\n"));
13184       break;
13185     }
13186
13187   return PRINT_NOTHING;
13188 }
13189
13190 static void
13191 internal_bkpt_print_mention (struct breakpoint *b)
13192 {
13193   /* Nothing to mention.  These breakpoints are internal.  */
13194 }
13195
13196 /* Virtual table for momentary breakpoints  */
13197
13198 static void
13199 momentary_bkpt_re_set (struct breakpoint *b)
13200 {
13201   /* Keep temporary breakpoints, which can be encountered when we step
13202      over a dlopen call and solib_add is resetting the breakpoints.
13203      Otherwise these should have been blown away via the cleanup chain
13204      or by breakpoint_init_inferior when we rerun the executable.  */
13205 }
13206
13207 static void
13208 momentary_bkpt_check_status (bpstat bs)
13209 {
13210   /* Nothing.  The point of these breakpoints is causing a stop.  */
13211 }
13212
13213 static enum print_stop_action
13214 momentary_bkpt_print_it (bpstat bs)
13215 {
13216   return PRINT_UNKNOWN;
13217 }
13218
13219 static void
13220 momentary_bkpt_print_mention (struct breakpoint *b)
13221 {
13222   /* Nothing to mention.  These breakpoints are internal.  */
13223 }
13224
13225 /* Ensure INITIATING_FRAME is cleared when no such breakpoint exists.
13226
13227    It gets cleared already on the removal of the first one of such placed
13228    breakpoints.  This is OK as they get all removed altogether.  */
13229
13230 longjmp_breakpoint::~longjmp_breakpoint ()
13231 {
13232   thread_info *tp = find_thread_global_id (this->thread);
13233
13234   if (tp != NULL)
13235     tp->initiating_frame = null_frame_id;
13236 }
13237
13238 /* Specific methods for probe breakpoints.  */
13239
13240 static int
13241 bkpt_probe_insert_location (struct bp_location *bl)
13242 {
13243   int v = bkpt_insert_location (bl);
13244
13245   if (v == 0)
13246     {
13247       /* The insertion was successful, now let's set the probe's semaphore
13248          if needed.  */
13249       if (bl->probe.probe->pops->set_semaphore != NULL)
13250         bl->probe.probe->pops->set_semaphore (bl->probe.probe,
13251                                               bl->probe.objfile,
13252                                               bl->gdbarch);
13253     }
13254
13255   return v;
13256 }
13257
13258 static int
13259 bkpt_probe_remove_location (struct bp_location *bl,
13260                             enum remove_bp_reason reason)
13261 {
13262   /* Let's clear the semaphore before removing the location.  */
13263   if (bl->probe.probe->pops->clear_semaphore != NULL)
13264     bl->probe.probe->pops->clear_semaphore (bl->probe.probe,
13265                                             bl->probe.objfile,
13266                                             bl->gdbarch);
13267
13268   return bkpt_remove_location (bl, reason);
13269 }
13270
13271 static void
13272 bkpt_probe_create_sals_from_location (const struct event_location *location,
13273                                       struct linespec_result *canonical,
13274                                       enum bptype type_wanted)
13275 {
13276   struct linespec_sals lsal;
13277
13278   lsal.sals = parse_probes (location, NULL, canonical);
13279   lsal.canonical
13280     = xstrdup (event_location_to_string (canonical->location.get ()));
13281   VEC_safe_push (linespec_sals, canonical->sals, &lsal);
13282 }
13283
13284 static void
13285 bkpt_probe_decode_location (struct breakpoint *b,
13286                             const struct event_location *location,
13287                             struct program_space *search_pspace,
13288                             struct symtabs_and_lines *sals)
13289 {
13290   *sals = parse_probes (location, search_pspace, NULL);
13291   if (!sals->sals)
13292     error (_("probe not found"));
13293 }
13294
13295 /* The breakpoint_ops structure to be used in tracepoints.  */
13296
13297 static void
13298 tracepoint_re_set (struct breakpoint *b)
13299 {
13300   breakpoint_re_set_default (b);
13301 }
13302
13303 static int
13304 tracepoint_breakpoint_hit (const struct bp_location *bl,
13305                            struct address_space *aspace, CORE_ADDR bp_addr,
13306                            const struct target_waitstatus *ws)
13307 {
13308   /* By definition, the inferior does not report stops at
13309      tracepoints.  */
13310   return 0;
13311 }
13312
13313 static void
13314 tracepoint_print_one_detail (const struct breakpoint *self,
13315                              struct ui_out *uiout)
13316 {
13317   struct tracepoint *tp = (struct tracepoint *) self;
13318   if (tp->static_trace_marker_id)
13319     {
13320       gdb_assert (self->type == bp_static_tracepoint);
13321
13322       uiout->text ("\tmarker id is ");
13323       uiout->field_string ("static-tracepoint-marker-string-id",
13324                            tp->static_trace_marker_id);
13325       uiout->text ("\n");
13326     }
13327 }
13328
13329 static void
13330 tracepoint_print_mention (struct breakpoint *b)
13331 {
13332   if (current_uiout->is_mi_like_p ())
13333     return;
13334
13335   switch (b->type)
13336     {
13337     case bp_tracepoint:
13338       printf_filtered (_("Tracepoint"));
13339       printf_filtered (_(" %d"), b->number);
13340       break;
13341     case bp_fast_tracepoint:
13342       printf_filtered (_("Fast tracepoint"));
13343       printf_filtered (_(" %d"), b->number);
13344       break;
13345     case bp_static_tracepoint:
13346       printf_filtered (_("Static tracepoint"));
13347       printf_filtered (_(" %d"), b->number);
13348       break;
13349     default:
13350       internal_error (__FILE__, __LINE__,
13351                       _("unhandled tracepoint type %d"), (int) b->type);
13352     }
13353
13354   say_where (b);
13355 }
13356
13357 static void
13358 tracepoint_print_recreate (struct breakpoint *self, struct ui_file *fp)
13359 {
13360   struct tracepoint *tp = (struct tracepoint *) self;
13361
13362   if (self->type == bp_fast_tracepoint)
13363     fprintf_unfiltered (fp, "ftrace");
13364   else if (self->type == bp_static_tracepoint)
13365     fprintf_unfiltered (fp, "strace");
13366   else if (self->type == bp_tracepoint)
13367     fprintf_unfiltered (fp, "trace");
13368   else
13369     internal_error (__FILE__, __LINE__,
13370                     _("unhandled tracepoint type %d"), (int) self->type);
13371
13372   fprintf_unfiltered (fp, " %s",
13373                       event_location_to_string (self->location.get ()));
13374   print_recreate_thread (self, fp);
13375
13376   if (tp->pass_count)
13377     fprintf_unfiltered (fp, "  passcount %d\n", tp->pass_count);
13378 }
13379
13380 static void
13381 tracepoint_create_sals_from_location (const struct event_location *location,
13382                                       struct linespec_result *canonical,
13383                                       enum bptype type_wanted)
13384 {
13385   create_sals_from_location_default (location, canonical, type_wanted);
13386 }
13387
13388 static void
13389 tracepoint_create_breakpoints_sal (struct gdbarch *gdbarch,
13390                                    struct linespec_result *canonical,
13391                                    gdb::unique_xmalloc_ptr<char> cond_string,
13392                                    gdb::unique_xmalloc_ptr<char> extra_string,
13393                                    enum bptype type_wanted,
13394                                    enum bpdisp disposition,
13395                                    int thread,
13396                                    int task, int ignore_count,
13397                                    const struct breakpoint_ops *ops,
13398                                    int from_tty, int enabled,
13399                                    int internal, unsigned flags)
13400 {
13401   create_breakpoints_sal_default (gdbarch, canonical,
13402                                   std::move (cond_string),
13403                                   std::move (extra_string),
13404                                   type_wanted,
13405                                   disposition, thread, task,
13406                                   ignore_count, ops, from_tty,
13407                                   enabled, internal, flags);
13408 }
13409
13410 static void
13411 tracepoint_decode_location (struct breakpoint *b,
13412                             const struct event_location *location,
13413                             struct program_space *search_pspace,
13414                             struct symtabs_and_lines *sals)
13415 {
13416   decode_location_default (b, location, search_pspace, sals);
13417 }
13418
13419 struct breakpoint_ops tracepoint_breakpoint_ops;
13420
13421 /* The breakpoint_ops structure to be use on tracepoints placed in a
13422    static probe.  */
13423
13424 static void
13425 tracepoint_probe_create_sals_from_location
13426   (const struct event_location *location,
13427    struct linespec_result *canonical,
13428    enum bptype type_wanted)
13429 {
13430   /* We use the same method for breakpoint on probes.  */
13431   bkpt_probe_create_sals_from_location (location, canonical, type_wanted);
13432 }
13433
13434 static void
13435 tracepoint_probe_decode_location (struct breakpoint *b,
13436                                   const struct event_location *location,
13437                                   struct program_space *search_pspace,
13438                                   struct symtabs_and_lines *sals)
13439 {
13440   /* We use the same method for breakpoint on probes.  */
13441   bkpt_probe_decode_location (b, location, search_pspace, sals);
13442 }
13443
13444 static struct breakpoint_ops tracepoint_probe_breakpoint_ops;
13445
13446 /* Dprintf breakpoint_ops methods.  */
13447
13448 static void
13449 dprintf_re_set (struct breakpoint *b)
13450 {
13451   breakpoint_re_set_default (b);
13452
13453   /* extra_string should never be non-NULL for dprintf.  */
13454   gdb_assert (b->extra_string != NULL);
13455
13456   /* 1 - connect to target 1, that can run breakpoint commands.
13457      2 - create a dprintf, which resolves fine.
13458      3 - disconnect from target 1
13459      4 - connect to target 2, that can NOT run breakpoint commands.
13460
13461      After steps #3/#4, you'll want the dprintf command list to
13462      be updated, because target 1 and 2 may well return different
13463      answers for target_can_run_breakpoint_commands().
13464      Given absence of finer grained resetting, we get to do
13465      it all the time.  */
13466   if (b->extra_string != NULL)
13467     update_dprintf_command_list (b);
13468 }
13469
13470 /* Implement the "print_recreate" breakpoint_ops method for dprintf.  */
13471
13472 static void
13473 dprintf_print_recreate (struct breakpoint *tp, struct ui_file *fp)
13474 {
13475   fprintf_unfiltered (fp, "dprintf %s,%s",
13476                       event_location_to_string (tp->location.get ()),
13477                       tp->extra_string);
13478   print_recreate_thread (tp, fp);
13479 }
13480
13481 /* Implement the "after_condition_true" breakpoint_ops method for
13482    dprintf.
13483
13484    dprintf's are implemented with regular commands in their command
13485    list, but we run the commands here instead of before presenting the
13486    stop to the user, as dprintf's don't actually cause a stop.  This
13487    also makes it so that the commands of multiple dprintfs at the same
13488    address are all handled.  */
13489
13490 static void
13491 dprintf_after_condition_true (struct bpstats *bs)
13492 {
13493   struct cleanup *old_chain;
13494   struct bpstats tmp_bs = { NULL };
13495   struct bpstats *tmp_bs_p = &tmp_bs;
13496
13497   /* dprintf's never cause a stop.  This wasn't set in the
13498      check_status hook instead because that would make the dprintf's
13499      condition not be evaluated.  */
13500   bs->stop = 0;
13501
13502   /* Run the command list here.  Take ownership of it instead of
13503      copying.  We never want these commands to run later in
13504      bpstat_do_actions, if a breakpoint that causes a stop happens to
13505      be set at same address as this dprintf, or even if running the
13506      commands here throws.  */
13507   tmp_bs.commands = bs->commands;
13508   bs->commands = NULL;
13509   old_chain = make_cleanup_decref_counted_command_line (&tmp_bs.commands);
13510
13511   bpstat_do_actions_1 (&tmp_bs_p);
13512
13513   /* 'tmp_bs.commands' will usually be NULL by now, but
13514      bpstat_do_actions_1 may return early without processing the whole
13515      list.  */
13516   do_cleanups (old_chain);
13517 }
13518
13519 /* The breakpoint_ops structure to be used on static tracepoints with
13520    markers (`-m').  */
13521
13522 static void
13523 strace_marker_create_sals_from_location (const struct event_location *location,
13524                                          struct linespec_result *canonical,
13525                                          enum bptype type_wanted)
13526 {
13527   struct linespec_sals lsal;
13528   const char *arg_start, *arg;
13529   char *str;
13530   struct cleanup *cleanup;
13531
13532   arg = arg_start = get_linespec_location (location);
13533   lsal.sals = decode_static_tracepoint_spec (&arg);
13534
13535   str = savestring (arg_start, arg - arg_start);
13536   cleanup = make_cleanup (xfree, str);
13537   canonical->location = new_linespec_location (&str);
13538   do_cleanups (cleanup);
13539
13540   lsal.canonical
13541     = xstrdup (event_location_to_string (canonical->location.get ()));
13542   VEC_safe_push (linespec_sals, canonical->sals, &lsal);
13543 }
13544
13545 static void
13546 strace_marker_create_breakpoints_sal (struct gdbarch *gdbarch,
13547                                       struct linespec_result *canonical,
13548                                       gdb::unique_xmalloc_ptr<char> cond_string,
13549                                       gdb::unique_xmalloc_ptr<char> extra_string,
13550                                       enum bptype type_wanted,
13551                                       enum bpdisp disposition,
13552                                       int thread,
13553                                       int task, int ignore_count,
13554                                       const struct breakpoint_ops *ops,
13555                                       int from_tty, int enabled,
13556                                       int internal, unsigned flags)
13557 {
13558   int i;
13559   struct linespec_sals *lsal = VEC_index (linespec_sals,
13560                                           canonical->sals, 0);
13561
13562   /* If the user is creating a static tracepoint by marker id
13563      (strace -m MARKER_ID), then store the sals index, so that
13564      breakpoint_re_set can try to match up which of the newly
13565      found markers corresponds to this one, and, don't try to
13566      expand multiple locations for each sal, given than SALS
13567      already should contain all sals for MARKER_ID.  */
13568
13569   for (i = 0; i < lsal->sals.nelts; ++i)
13570     {
13571       struct symtabs_and_lines expanded;
13572       struct tracepoint *tp;
13573       event_location_up location;
13574
13575       expanded.nelts = 1;
13576       expanded.sals = &lsal->sals.sals[i];
13577
13578       location = copy_event_location (canonical->location.get ());
13579
13580       tp = new tracepoint ();
13581       init_breakpoint_sal (tp, gdbarch, expanded,
13582                            std::move (location), NULL,
13583                            std::move (cond_string),
13584                            std::move (extra_string),
13585                            type_wanted, disposition,
13586                            thread, task, ignore_count, ops,
13587                            from_tty, enabled, internal, flags,
13588                            canonical->special_display);
13589       /* Given that its possible to have multiple markers with
13590          the same string id, if the user is creating a static
13591          tracepoint by marker id ("strace -m MARKER_ID"), then
13592          store the sals index, so that breakpoint_re_set can
13593          try to match up which of the newly found markers
13594          corresponds to this one  */
13595       tp->static_trace_marker_id_idx = i;
13596
13597       install_breakpoint (internal, tp, 0);
13598     }
13599 }
13600
13601 static void
13602 strace_marker_decode_location (struct breakpoint *b,
13603                                const struct event_location *location,
13604                                struct program_space *search_pspace,
13605                                struct symtabs_and_lines *sals)
13606 {
13607   struct tracepoint *tp = (struct tracepoint *) b;
13608   const char *s = get_linespec_location (location);
13609
13610   *sals = decode_static_tracepoint_spec (&s);
13611   if (sals->nelts > tp->static_trace_marker_id_idx)
13612     {
13613       sals->sals[0] = sals->sals[tp->static_trace_marker_id_idx];
13614       sals->nelts = 1;
13615     }
13616   else
13617     error (_("marker %s not found"), tp->static_trace_marker_id);
13618 }
13619
13620 static struct breakpoint_ops strace_marker_breakpoint_ops;
13621
13622 static int
13623 strace_marker_p (struct breakpoint *b)
13624 {
13625   return b->ops == &strace_marker_breakpoint_ops;
13626 }
13627
13628 /* Delete a breakpoint and clean up all traces of it in the data
13629    structures.  */
13630
13631 void
13632 delete_breakpoint (struct breakpoint *bpt)
13633 {
13634   struct breakpoint *b;
13635
13636   gdb_assert (bpt != NULL);
13637
13638   /* Has this bp already been deleted?  This can happen because
13639      multiple lists can hold pointers to bp's.  bpstat lists are
13640      especial culprits.
13641
13642      One example of this happening is a watchpoint's scope bp.  When
13643      the scope bp triggers, we notice that the watchpoint is out of
13644      scope, and delete it.  We also delete its scope bp.  But the
13645      scope bp is marked "auto-deleting", and is already on a bpstat.
13646      That bpstat is then checked for auto-deleting bp's, which are
13647      deleted.
13648
13649      A real solution to this problem might involve reference counts in
13650      bp's, and/or giving them pointers back to their referencing
13651      bpstat's, and teaching delete_breakpoint to only free a bp's
13652      storage when no more references were extent.  A cheaper bandaid
13653      was chosen.  */
13654   if (bpt->type == bp_none)
13655     return;
13656
13657   /* At least avoid this stale reference until the reference counting
13658      of breakpoints gets resolved.  */
13659   if (bpt->related_breakpoint != bpt)
13660     {
13661       struct breakpoint *related;
13662       struct watchpoint *w;
13663
13664       if (bpt->type == bp_watchpoint_scope)
13665         w = (struct watchpoint *) bpt->related_breakpoint;
13666       else if (bpt->related_breakpoint->type == bp_watchpoint_scope)
13667         w = (struct watchpoint *) bpt;
13668       else
13669         w = NULL;
13670       if (w != NULL)
13671         watchpoint_del_at_next_stop (w);
13672
13673       /* Unlink bpt from the bpt->related_breakpoint ring.  */
13674       for (related = bpt; related->related_breakpoint != bpt;
13675            related = related->related_breakpoint);
13676       related->related_breakpoint = bpt->related_breakpoint;
13677       bpt->related_breakpoint = bpt;
13678     }
13679
13680   /* watch_command_1 creates a watchpoint but only sets its number if
13681      update_watchpoint succeeds in creating its bp_locations.  If there's
13682      a problem in that process, we'll be asked to delete the half-created
13683      watchpoint.  In that case, don't announce the deletion.  */
13684   if (bpt->number)
13685     observer_notify_breakpoint_deleted (bpt);
13686
13687   if (breakpoint_chain == bpt)
13688     breakpoint_chain = bpt->next;
13689
13690   ALL_BREAKPOINTS (b)
13691     if (b->next == bpt)
13692     {
13693       b->next = bpt->next;
13694       break;
13695     }
13696
13697   /* Be sure no bpstat's are pointing at the breakpoint after it's
13698      been freed.  */
13699   /* FIXME, how can we find all bpstat's?  We just check stop_bpstat
13700      in all threads for now.  Note that we cannot just remove bpstats
13701      pointing at bpt from the stop_bpstat list entirely, as breakpoint
13702      commands are associated with the bpstat; if we remove it here,
13703      then the later call to bpstat_do_actions (&stop_bpstat); in
13704      event-top.c won't do anything, and temporary breakpoints with
13705      commands won't work.  */
13706
13707   iterate_over_threads (bpstat_remove_breakpoint_callback, bpt);
13708
13709   /* Now that breakpoint is removed from breakpoint list, update the
13710      global location list.  This will remove locations that used to
13711      belong to this breakpoint.  Do this before freeing the breakpoint
13712      itself, since remove_breakpoint looks at location's owner.  It
13713      might be better design to have location completely
13714      self-contained, but it's not the case now.  */
13715   update_global_location_list (UGLL_DONT_INSERT);
13716
13717   /* On the chance that someone will soon try again to delete this
13718      same bp, we mark it as deleted before freeing its storage.  */
13719   bpt->type = bp_none;
13720   delete bpt;
13721 }
13722
13723 static void
13724 do_delete_breakpoint_cleanup (void *b)
13725 {
13726   delete_breakpoint ((struct breakpoint *) b);
13727 }
13728
13729 struct cleanup *
13730 make_cleanup_delete_breakpoint (struct breakpoint *b)
13731 {
13732   return make_cleanup (do_delete_breakpoint_cleanup, b);
13733 }
13734
13735 /* Iterator function to call a user-provided callback function once
13736    for each of B and its related breakpoints.  */
13737
13738 static void
13739 iterate_over_related_breakpoints (struct breakpoint *b,
13740                                   void (*function) (struct breakpoint *,
13741                                                     void *),
13742                                   void *data)
13743 {
13744   struct breakpoint *related;
13745
13746   related = b;
13747   do
13748     {
13749       struct breakpoint *next;
13750
13751       /* FUNCTION may delete RELATED.  */
13752       next = related->related_breakpoint;
13753
13754       if (next == related)
13755         {
13756           /* RELATED is the last ring entry.  */
13757           function (related, data);
13758
13759           /* FUNCTION may have deleted it, so we'd never reach back to
13760              B.  There's nothing left to do anyway, so just break
13761              out.  */
13762           break;
13763         }
13764       else
13765         function (related, data);
13766
13767       related = next;
13768     }
13769   while (related != b);
13770 }
13771
13772 static void
13773 do_delete_breakpoint (struct breakpoint *b, void *ignore)
13774 {
13775   delete_breakpoint (b);
13776 }
13777
13778 /* A callback for map_breakpoint_numbers that calls
13779    delete_breakpoint.  */
13780
13781 static void
13782 do_map_delete_breakpoint (struct breakpoint *b, void *ignore)
13783 {
13784   iterate_over_related_breakpoints (b, do_delete_breakpoint, NULL);
13785 }
13786
13787 void
13788 delete_command (char *arg, int from_tty)
13789 {
13790   struct breakpoint *b, *b_tmp;
13791
13792   dont_repeat ();
13793
13794   if (arg == 0)
13795     {
13796       int breaks_to_delete = 0;
13797
13798       /* Delete all breakpoints if no argument.  Do not delete
13799          internal breakpoints, these have to be deleted with an
13800          explicit breakpoint number argument.  */
13801       ALL_BREAKPOINTS (b)
13802         if (user_breakpoint_p (b))
13803           {
13804             breaks_to_delete = 1;
13805             break;
13806           }
13807
13808       /* Ask user only if there are some breakpoints to delete.  */
13809       if (!from_tty
13810           || (breaks_to_delete && query (_("Delete all breakpoints? "))))
13811         {
13812           ALL_BREAKPOINTS_SAFE (b, b_tmp)
13813             if (user_breakpoint_p (b))
13814               delete_breakpoint (b);
13815         }
13816     }
13817   else
13818     map_breakpoint_numbers (arg, do_map_delete_breakpoint, NULL);
13819 }
13820
13821 /* Return true if all locations of B bound to PSPACE are pending.  If
13822    PSPACE is NULL, all locations of all program spaces are
13823    considered.  */
13824
13825 static int
13826 all_locations_are_pending (struct breakpoint *b, struct program_space *pspace)
13827 {
13828   struct bp_location *loc;
13829
13830   for (loc = b->loc; loc != NULL; loc = loc->next)
13831     if ((pspace == NULL
13832          || loc->pspace == pspace)
13833         && !loc->shlib_disabled
13834         && !loc->pspace->executing_startup)
13835       return 0;
13836   return 1;
13837 }
13838
13839 /* Subroutine of update_breakpoint_locations to simplify it.
13840    Return non-zero if multiple fns in list LOC have the same name.
13841    Null names are ignored.  */
13842
13843 static int
13844 ambiguous_names_p (struct bp_location *loc)
13845 {
13846   struct bp_location *l;
13847   htab_t htab = htab_create_alloc (13, htab_hash_string,
13848                                    (int (*) (const void *, 
13849                                              const void *)) streq,
13850                                    NULL, xcalloc, xfree);
13851
13852   for (l = loc; l != NULL; l = l->next)
13853     {
13854       const char **slot;
13855       const char *name = l->function_name;
13856
13857       /* Allow for some names to be NULL, ignore them.  */
13858       if (name == NULL)
13859         continue;
13860
13861       slot = (const char **) htab_find_slot (htab, (const void *) name,
13862                                              INSERT);
13863       /* NOTE: We can assume slot != NULL here because xcalloc never
13864          returns NULL.  */
13865       if (*slot != NULL)
13866         {
13867           htab_delete (htab);
13868           return 1;
13869         }
13870       *slot = name;
13871     }
13872
13873   htab_delete (htab);
13874   return 0;
13875 }
13876
13877 /* When symbols change, it probably means the sources changed as well,
13878    and it might mean the static tracepoint markers are no longer at
13879    the same address or line numbers they used to be at last we
13880    checked.  Losing your static tracepoints whenever you rebuild is
13881    undesirable.  This function tries to resync/rematch gdb static
13882    tracepoints with the markers on the target, for static tracepoints
13883    that have not been set by marker id.  Static tracepoint that have
13884    been set by marker id are reset by marker id in breakpoint_re_set.
13885    The heuristic is:
13886
13887    1) For a tracepoint set at a specific address, look for a marker at
13888    the old PC.  If one is found there, assume to be the same marker.
13889    If the name / string id of the marker found is different from the
13890    previous known name, assume that means the user renamed the marker
13891    in the sources, and output a warning.
13892
13893    2) For a tracepoint set at a given line number, look for a marker
13894    at the new address of the old line number.  If one is found there,
13895    assume to be the same marker.  If the name / string id of the
13896    marker found is different from the previous known name, assume that
13897    means the user renamed the marker in the sources, and output a
13898    warning.
13899
13900    3) If a marker is no longer found at the same address or line, it
13901    may mean the marker no longer exists.  But it may also just mean
13902    the code changed a bit.  Maybe the user added a few lines of code
13903    that made the marker move up or down (in line number terms).  Ask
13904    the target for info about the marker with the string id as we knew
13905    it.  If found, update line number and address in the matching
13906    static tracepoint.  This will get confused if there's more than one
13907    marker with the same ID (possible in UST, although unadvised
13908    precisely because it confuses tools).  */
13909
13910 static struct symtab_and_line
13911 update_static_tracepoint (struct breakpoint *b, struct symtab_and_line sal)
13912 {
13913   struct tracepoint *tp = (struct tracepoint *) b;
13914   struct static_tracepoint_marker marker;
13915   CORE_ADDR pc;
13916
13917   pc = sal.pc;
13918   if (sal.line)
13919     find_line_pc (sal.symtab, sal.line, &pc);
13920
13921   if (target_static_tracepoint_marker_at (pc, &marker))
13922     {
13923       if (strcmp (tp->static_trace_marker_id, marker.str_id) != 0)
13924         warning (_("static tracepoint %d changed probed marker from %s to %s"),
13925                  b->number,
13926                  tp->static_trace_marker_id, marker.str_id);
13927
13928       xfree (tp->static_trace_marker_id);
13929       tp->static_trace_marker_id = xstrdup (marker.str_id);
13930       release_static_tracepoint_marker (&marker);
13931
13932       return sal;
13933     }
13934
13935   /* Old marker wasn't found on target at lineno.  Try looking it up
13936      by string ID.  */
13937   if (!sal.explicit_pc
13938       && sal.line != 0
13939       && sal.symtab != NULL
13940       && tp->static_trace_marker_id != NULL)
13941     {
13942       VEC(static_tracepoint_marker_p) *markers;
13943
13944       markers
13945         = target_static_tracepoint_markers_by_strid (tp->static_trace_marker_id);
13946
13947       if (!VEC_empty(static_tracepoint_marker_p, markers))
13948         {
13949           struct symtab_and_line sal2;
13950           struct symbol *sym;
13951           struct static_tracepoint_marker *tpmarker;
13952           struct ui_out *uiout = current_uiout;
13953           struct explicit_location explicit_loc;
13954
13955           tpmarker = VEC_index (static_tracepoint_marker_p, markers, 0);
13956
13957           xfree (tp->static_trace_marker_id);
13958           tp->static_trace_marker_id = xstrdup (tpmarker->str_id);
13959
13960           warning (_("marker for static tracepoint %d (%s) not "
13961                      "found at previous line number"),
13962                    b->number, tp->static_trace_marker_id);
13963
13964           init_sal (&sal2);
13965
13966           sal2.pc = tpmarker->address;
13967
13968           sal2 = find_pc_line (tpmarker->address, 0);
13969           sym = find_pc_sect_function (tpmarker->address, NULL);
13970           uiout->text ("Now in ");
13971           if (sym)
13972             {
13973               uiout->field_string ("func", SYMBOL_PRINT_NAME (sym));
13974               uiout->text (" at ");
13975             }
13976           uiout->field_string ("file",
13977                                symtab_to_filename_for_display (sal2.symtab));
13978           uiout->text (":");
13979
13980           if (uiout->is_mi_like_p ())
13981             {
13982               const char *fullname = symtab_to_fullname (sal2.symtab);
13983
13984               uiout->field_string ("fullname", fullname);
13985             }
13986
13987           uiout->field_int ("line", sal2.line);
13988           uiout->text ("\n");
13989
13990           b->loc->line_number = sal2.line;
13991           b->loc->symtab = sym != NULL ? sal2.symtab : NULL;
13992
13993           b->location.reset (NULL);
13994           initialize_explicit_location (&explicit_loc);
13995           explicit_loc.source_filename
13996             = ASTRDUP (symtab_to_filename_for_display (sal2.symtab));
13997           explicit_loc.line_offset.offset = b->loc->line_number;
13998           explicit_loc.line_offset.sign = LINE_OFFSET_NONE;
13999           b->location = new_explicit_location (&explicit_loc);
14000
14001           /* Might be nice to check if function changed, and warn if
14002              so.  */
14003
14004           release_static_tracepoint_marker (tpmarker);
14005         }
14006     }
14007   return sal;
14008 }
14009
14010 /* Returns 1 iff locations A and B are sufficiently same that
14011    we don't need to report breakpoint as changed.  */
14012
14013 static int
14014 locations_are_equal (struct bp_location *a, struct bp_location *b)
14015 {
14016   while (a && b)
14017     {
14018       if (a->address != b->address)
14019         return 0;
14020
14021       if (a->shlib_disabled != b->shlib_disabled)
14022         return 0;
14023
14024       if (a->enabled != b->enabled)
14025         return 0;
14026
14027       a = a->next;
14028       b = b->next;
14029     }
14030
14031   if ((a == NULL) != (b == NULL))
14032     return 0;
14033
14034   return 1;
14035 }
14036
14037 /* Split all locations of B that are bound to PSPACE out of B's
14038    location list to a separate list and return that list's head.  If
14039    PSPACE is NULL, hoist out all locations of B.  */
14040
14041 static struct bp_location *
14042 hoist_existing_locations (struct breakpoint *b, struct program_space *pspace)
14043 {
14044   struct bp_location head;
14045   struct bp_location *i = b->loc;
14046   struct bp_location **i_link = &b->loc;
14047   struct bp_location *hoisted = &head;
14048
14049   if (pspace == NULL)
14050     {
14051       i = b->loc;
14052       b->loc = NULL;
14053       return i;
14054     }
14055
14056   head.next = NULL;
14057
14058   while (i != NULL)
14059     {
14060       if (i->pspace == pspace)
14061         {
14062           *i_link = i->next;
14063           i->next = NULL;
14064           hoisted->next = i;
14065           hoisted = i;
14066         }
14067       else
14068         i_link = &i->next;
14069       i = *i_link;
14070     }
14071
14072   return head.next;
14073 }
14074
14075 /* Create new breakpoint locations for B (a hardware or software
14076    breakpoint) based on SALS and SALS_END.  If SALS_END.NELTS is not
14077    zero, then B is a ranged breakpoint.  Only recreates locations for
14078    FILTER_PSPACE.  Locations of other program spaces are left
14079    untouched.  */
14080
14081 void
14082 update_breakpoint_locations (struct breakpoint *b,
14083                              struct program_space *filter_pspace,
14084                              struct symtabs_and_lines sals,
14085                              struct symtabs_and_lines sals_end)
14086 {
14087   int i;
14088   struct bp_location *existing_locations;
14089
14090   if (sals_end.nelts != 0 && (sals.nelts != 1 || sals_end.nelts != 1))
14091     {
14092       /* Ranged breakpoints have only one start location and one end
14093          location.  */
14094       b->enable_state = bp_disabled;
14095       printf_unfiltered (_("Could not reset ranged breakpoint %d: "
14096                            "multiple locations found\n"),
14097                          b->number);
14098       return;
14099     }
14100
14101   /* If there's no new locations, and all existing locations are
14102      pending, don't do anything.  This optimizes the common case where
14103      all locations are in the same shared library, that was unloaded.
14104      We'd like to retain the location, so that when the library is
14105      loaded again, we don't loose the enabled/disabled status of the
14106      individual locations.  */
14107   if (all_locations_are_pending (b, filter_pspace) && sals.nelts == 0)
14108     return;
14109
14110   existing_locations = hoist_existing_locations (b, filter_pspace);
14111
14112   for (i = 0; i < sals.nelts; ++i)
14113     {
14114       struct bp_location *new_loc;
14115
14116       switch_to_program_space_and_thread (sals.sals[i].pspace);
14117
14118       new_loc = add_location_to_breakpoint (b, &(sals.sals[i]));
14119
14120       /* Reparse conditions, they might contain references to the
14121          old symtab.  */
14122       if (b->cond_string != NULL)
14123         {
14124           const char *s;
14125
14126           s = b->cond_string;
14127           TRY
14128             {
14129               new_loc->cond = parse_exp_1 (&s, sals.sals[i].pc,
14130                                            block_for_pc (sals.sals[i].pc), 
14131                                            0);
14132             }
14133           CATCH (e, RETURN_MASK_ERROR)
14134             {
14135               warning (_("failed to reevaluate condition "
14136                          "for breakpoint %d: %s"), 
14137                        b->number, e.message);
14138               new_loc->enabled = 0;
14139             }
14140           END_CATCH
14141         }
14142
14143       if (sals_end.nelts)
14144         {
14145           CORE_ADDR end = find_breakpoint_range_end (sals_end.sals[0]);
14146
14147           new_loc->length = end - sals.sals[0].pc + 1;
14148         }
14149     }
14150
14151   /* If possible, carry over 'disable' status from existing
14152      breakpoints.  */
14153   {
14154     struct bp_location *e = existing_locations;
14155     /* If there are multiple breakpoints with the same function name,
14156        e.g. for inline functions, comparing function names won't work.
14157        Instead compare pc addresses; this is just a heuristic as things
14158        may have moved, but in practice it gives the correct answer
14159        often enough until a better solution is found.  */
14160     int have_ambiguous_names = ambiguous_names_p (b->loc);
14161
14162     for (; e; e = e->next)
14163       {
14164         if (!e->enabled && e->function_name)
14165           {
14166             struct bp_location *l = b->loc;
14167             if (have_ambiguous_names)
14168               {
14169                 for (; l; l = l->next)
14170                   if (breakpoint_locations_match (e, l))
14171                     {
14172                       l->enabled = 0;
14173                       break;
14174                     }
14175               }
14176             else
14177               {
14178                 for (; l; l = l->next)
14179                   if (l->function_name
14180                       && strcmp (e->function_name, l->function_name) == 0)
14181                     {
14182                       l->enabled = 0;
14183                       break;
14184                     }
14185               }
14186           }
14187       }
14188   }
14189
14190   if (!locations_are_equal (existing_locations, b->loc))
14191     observer_notify_breakpoint_modified (b);
14192 }
14193
14194 /* Find the SaL locations corresponding to the given LOCATION.
14195    On return, FOUND will be 1 if any SaL was found, zero otherwise.  */
14196
14197 static struct symtabs_and_lines
14198 location_to_sals (struct breakpoint *b, struct event_location *location,
14199                   struct program_space *search_pspace, int *found)
14200 {
14201   struct symtabs_and_lines sals = {0};
14202   struct gdb_exception exception = exception_none;
14203
14204   gdb_assert (b->ops != NULL);
14205
14206   TRY
14207     {
14208       b->ops->decode_location (b, location, search_pspace, &sals);
14209     }
14210   CATCH (e, RETURN_MASK_ERROR)
14211     {
14212       int not_found_and_ok = 0;
14213
14214       exception = e;
14215
14216       /* For pending breakpoints, it's expected that parsing will
14217          fail until the right shared library is loaded.  User has
14218          already told to create pending breakpoints and don't need
14219          extra messages.  If breakpoint is in bp_shlib_disabled
14220          state, then user already saw the message about that
14221          breakpoint being disabled, and don't want to see more
14222          errors.  */
14223       if (e.error == NOT_FOUND_ERROR
14224           && (b->condition_not_parsed
14225               || (b->loc != NULL
14226                   && search_pspace != NULL
14227                   && b->loc->pspace != search_pspace)
14228               || (b->loc && b->loc->shlib_disabled)
14229               || (b->loc && b->loc->pspace->executing_startup)
14230               || b->enable_state == bp_disabled))
14231         not_found_and_ok = 1;
14232
14233       if (!not_found_and_ok)
14234         {
14235           /* We surely don't want to warn about the same breakpoint
14236              10 times.  One solution, implemented here, is disable
14237              the breakpoint on error.  Another solution would be to
14238              have separate 'warning emitted' flag.  Since this
14239              happens only when a binary has changed, I don't know
14240              which approach is better.  */
14241           b->enable_state = bp_disabled;
14242           throw_exception (e);
14243         }
14244     }
14245   END_CATCH
14246
14247   if (exception.reason == 0 || exception.error != NOT_FOUND_ERROR)
14248     {
14249       int i;
14250
14251       for (i = 0; i < sals.nelts; ++i)
14252         resolve_sal_pc (&sals.sals[i]);
14253       if (b->condition_not_parsed && b->extra_string != NULL)
14254         {
14255           char *cond_string, *extra_string;
14256           int thread, task;
14257
14258           find_condition_and_thread (b->extra_string, sals.sals[0].pc,
14259                                      &cond_string, &thread, &task,
14260                                      &extra_string);
14261           gdb_assert (b->cond_string == NULL);
14262           if (cond_string)
14263             b->cond_string = cond_string;
14264           b->thread = thread;
14265           b->task = task;
14266           if (extra_string)
14267             {
14268               xfree (b->extra_string);
14269               b->extra_string = extra_string;
14270             }
14271           b->condition_not_parsed = 0;
14272         }
14273
14274       if (b->type == bp_static_tracepoint && !strace_marker_p (b))
14275         sals.sals[0] = update_static_tracepoint (b, sals.sals[0]);
14276
14277       *found = 1;
14278     }
14279   else
14280     *found = 0;
14281
14282   return sals;
14283 }
14284
14285 /* The default re_set method, for typical hardware or software
14286    breakpoints.  Reevaluate the breakpoint and recreate its
14287    locations.  */
14288
14289 static void
14290 breakpoint_re_set_default (struct breakpoint *b)
14291 {
14292   int found;
14293   struct symtabs_and_lines sals, sals_end;
14294   struct symtabs_and_lines expanded = {0};
14295   struct symtabs_and_lines expanded_end = {0};
14296   struct program_space *filter_pspace = current_program_space;
14297
14298   sals = location_to_sals (b, b->location.get (), filter_pspace, &found);
14299   if (found)
14300     {
14301       make_cleanup (xfree, sals.sals);
14302       expanded = sals;
14303     }
14304
14305   if (b->location_range_end != NULL)
14306     {
14307       sals_end = location_to_sals (b, b->location_range_end.get (),
14308                                    filter_pspace, &found);
14309       if (found)
14310         {
14311           make_cleanup (xfree, sals_end.sals);
14312           expanded_end = sals_end;
14313         }
14314     }
14315
14316   update_breakpoint_locations (b, filter_pspace, expanded, expanded_end);
14317 }
14318
14319 /* Default method for creating SALs from an address string.  It basically
14320    calls parse_breakpoint_sals.  Return 1 for success, zero for failure.  */
14321
14322 static void
14323 create_sals_from_location_default (const struct event_location *location,
14324                                    struct linespec_result *canonical,
14325                                    enum bptype type_wanted)
14326 {
14327   parse_breakpoint_sals (location, canonical);
14328 }
14329
14330 /* Call create_breakpoints_sal for the given arguments.  This is the default
14331    function for the `create_breakpoints_sal' method of
14332    breakpoint_ops.  */
14333
14334 static void
14335 create_breakpoints_sal_default (struct gdbarch *gdbarch,
14336                                 struct linespec_result *canonical,
14337                                 gdb::unique_xmalloc_ptr<char> cond_string,
14338                                 gdb::unique_xmalloc_ptr<char> extra_string,
14339                                 enum bptype type_wanted,
14340                                 enum bpdisp disposition,
14341                                 int thread,
14342                                 int task, int ignore_count,
14343                                 const struct breakpoint_ops *ops,
14344                                 int from_tty, int enabled,
14345                                 int internal, unsigned flags)
14346 {
14347   create_breakpoints_sal (gdbarch, canonical,
14348                           std::move (cond_string),
14349                           std::move (extra_string),
14350                           type_wanted, disposition,
14351                           thread, task, ignore_count, ops, from_tty,
14352                           enabled, internal, flags);
14353 }
14354
14355 /* Decode the line represented by S by calling decode_line_full.  This is the
14356    default function for the `decode_location' method of breakpoint_ops.  */
14357
14358 static void
14359 decode_location_default (struct breakpoint *b,
14360                          const struct event_location *location,
14361                          struct program_space *search_pspace,
14362                          struct symtabs_and_lines *sals)
14363 {
14364   struct linespec_result canonical;
14365
14366   decode_line_full (location, DECODE_LINE_FUNFIRSTLINE, search_pspace,
14367                     (struct symtab *) NULL, 0,
14368                     &canonical, multiple_symbols_all,
14369                     b->filter);
14370
14371   /* We should get 0 or 1 resulting SALs.  */
14372   gdb_assert (VEC_length (linespec_sals, canonical.sals) < 2);
14373
14374   if (VEC_length (linespec_sals, canonical.sals) > 0)
14375     {
14376       struct linespec_sals *lsal;
14377
14378       lsal = VEC_index (linespec_sals, canonical.sals, 0);
14379       *sals = lsal->sals;
14380       /* Arrange it so the destructor does not free the
14381          contents.  */
14382       lsal->sals.sals = NULL;
14383     }
14384 }
14385
14386 /* Prepare the global context for a re-set of breakpoint B.  */
14387
14388 static struct cleanup *
14389 prepare_re_set_context (struct breakpoint *b)
14390 {
14391   input_radix = b->input_radix;
14392   set_language (b->language);
14393
14394   return make_cleanup (null_cleanup, NULL);
14395 }
14396
14397 /* Reset a breakpoint given it's struct breakpoint * BINT.
14398    The value we return ends up being the return value from catch_errors.
14399    Unused in this case.  */
14400
14401 static int
14402 breakpoint_re_set_one (void *bint)
14403 {
14404   /* Get past catch_errs.  */
14405   struct breakpoint *b = (struct breakpoint *) bint;
14406   struct cleanup *cleanups;
14407
14408   cleanups = prepare_re_set_context (b);
14409   b->ops->re_set (b);
14410   do_cleanups (cleanups);
14411   return 0;
14412 }
14413
14414 /* Re-set breakpoint locations for the current program space.
14415    Locations bound to other program spaces are left untouched.  */
14416
14417 void
14418 breakpoint_re_set (void)
14419 {
14420   struct breakpoint *b, *b_tmp;
14421   enum language save_language;
14422   int save_input_radix;
14423
14424   save_language = current_language->la_language;
14425   save_input_radix = input_radix;
14426
14427   {
14428     scoped_restore_current_pspace_and_thread restore_pspace_thread;
14429
14430     /* Note: we must not try to insert locations until after all
14431        breakpoints have been re-set.  Otherwise, e.g., when re-setting
14432        breakpoint 1, we'd insert the locations of breakpoint 2, which
14433        hadn't been re-set yet, and thus may have stale locations.  */
14434
14435     ALL_BREAKPOINTS_SAFE (b, b_tmp)
14436       {
14437         /* Format possible error msg.  */
14438         char *message = xstrprintf ("Error in re-setting breakpoint %d: ",
14439                                     b->number);
14440         struct cleanup *cleanups = make_cleanup (xfree, message);
14441         catch_errors (breakpoint_re_set_one, b, message, RETURN_MASK_ALL);
14442         do_cleanups (cleanups);
14443       }
14444     set_language (save_language);
14445     input_radix = save_input_radix;
14446
14447     jit_breakpoint_re_set ();
14448   }
14449
14450   create_overlay_event_breakpoint ();
14451   create_longjmp_master_breakpoint ();
14452   create_std_terminate_master_breakpoint ();
14453   create_exception_master_breakpoint ();
14454
14455   /* Now we can insert.  */
14456   update_global_location_list (UGLL_MAY_INSERT);
14457 }
14458 \f
14459 /* Reset the thread number of this breakpoint:
14460
14461    - If the breakpoint is for all threads, leave it as-is.
14462    - Else, reset it to the current thread for inferior_ptid.  */
14463 void
14464 breakpoint_re_set_thread (struct breakpoint *b)
14465 {
14466   if (b->thread != -1)
14467     {
14468       if (in_thread_list (inferior_ptid))
14469         b->thread = ptid_to_global_thread_id (inferior_ptid);
14470
14471       /* We're being called after following a fork.  The new fork is
14472          selected as current, and unless this was a vfork will have a
14473          different program space from the original thread.  Reset that
14474          as well.  */
14475       b->loc->pspace = current_program_space;
14476     }
14477 }
14478
14479 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
14480    If from_tty is nonzero, it prints a message to that effect,
14481    which ends with a period (no newline).  */
14482
14483 void
14484 set_ignore_count (int bptnum, int count, int from_tty)
14485 {
14486   struct breakpoint *b;
14487
14488   if (count < 0)
14489     count = 0;
14490
14491   ALL_BREAKPOINTS (b)
14492     if (b->number == bptnum)
14493     {
14494       if (is_tracepoint (b))
14495         {
14496           if (from_tty && count != 0)
14497             printf_filtered (_("Ignore count ignored for tracepoint %d."),
14498                              bptnum);
14499           return;
14500         }
14501       
14502       b->ignore_count = count;
14503       if (from_tty)
14504         {
14505           if (count == 0)
14506             printf_filtered (_("Will stop next time "
14507                                "breakpoint %d is reached."),
14508                              bptnum);
14509           else if (count == 1)
14510             printf_filtered (_("Will ignore next crossing of breakpoint %d."),
14511                              bptnum);
14512           else
14513             printf_filtered (_("Will ignore next %d "
14514                                "crossings of breakpoint %d."),
14515                              count, bptnum);
14516         }
14517       observer_notify_breakpoint_modified (b);
14518       return;
14519     }
14520
14521   error (_("No breakpoint number %d."), bptnum);
14522 }
14523
14524 /* Command to set ignore-count of breakpoint N to COUNT.  */
14525
14526 static void
14527 ignore_command (char *args, int from_tty)
14528 {
14529   char *p = args;
14530   int num;
14531
14532   if (p == 0)
14533     error_no_arg (_("a breakpoint number"));
14534
14535   num = get_number (&p);
14536   if (num == 0)
14537     error (_("bad breakpoint number: '%s'"), args);
14538   if (*p == 0)
14539     error (_("Second argument (specified ignore-count) is missing."));
14540
14541   set_ignore_count (num,
14542                     longest_to_int (value_as_long (parse_and_eval (p))),
14543                     from_tty);
14544   if (from_tty)
14545     printf_filtered ("\n");
14546 }
14547 \f
14548 /* Call FUNCTION on each of the breakpoints
14549    whose numbers are given in ARGS.  */
14550
14551 static void
14552 map_breakpoint_numbers (const char *args,
14553                         void (*function) (struct breakpoint *,
14554                                           void *),
14555                         void *data)
14556 {
14557   int num;
14558   struct breakpoint *b, *tmp;
14559
14560   if (args == 0 || *args == '\0')
14561     error_no_arg (_("one or more breakpoint numbers"));
14562
14563   number_or_range_parser parser (args);
14564
14565   while (!parser.finished ())
14566     {
14567       const char *p = parser.cur_tok ();
14568       bool match = false;
14569
14570       num = parser.get_number ();
14571       if (num == 0)
14572         {
14573           warning (_("bad breakpoint number at or near '%s'"), p);
14574         }
14575       else
14576         {
14577           ALL_BREAKPOINTS_SAFE (b, tmp)
14578             if (b->number == num)
14579               {
14580                 match = true;
14581                 function (b, data);
14582                 break;
14583               }
14584           if (!match)
14585             printf_unfiltered (_("No breakpoint number %d.\n"), num);
14586         }
14587     }
14588 }
14589
14590 static struct bp_location *
14591 find_location_by_number (char *number)
14592 {
14593   char *dot = strchr (number, '.');
14594   char *p1;
14595   int bp_num;
14596   int loc_num;
14597   struct breakpoint *b;
14598   struct bp_location *loc;  
14599
14600   *dot = '\0';
14601
14602   p1 = number;
14603   bp_num = get_number (&p1);
14604   if (bp_num == 0)
14605     error (_("Bad breakpoint number '%s'"), number);
14606
14607   ALL_BREAKPOINTS (b)
14608     if (b->number == bp_num)
14609       {
14610         break;
14611       }
14612
14613   if (!b || b->number != bp_num)
14614     error (_("Bad breakpoint number '%s'"), number);
14615   
14616   p1 = dot+1;
14617   loc_num = get_number (&p1);
14618   if (loc_num == 0)
14619     error (_("Bad breakpoint location number '%s'"), number);
14620
14621   --loc_num;
14622   loc = b->loc;
14623   for (;loc_num && loc; --loc_num, loc = loc->next)
14624     ;
14625   if (!loc)
14626     error (_("Bad breakpoint location number '%s'"), dot+1);
14627     
14628   return loc;  
14629 }
14630
14631
14632 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
14633    If from_tty is nonzero, it prints a message to that effect,
14634    which ends with a period (no newline).  */
14635
14636 void
14637 disable_breakpoint (struct breakpoint *bpt)
14638 {
14639   /* Never disable a watchpoint scope breakpoint; we want to
14640      hit them when we leave scope so we can delete both the
14641      watchpoint and its scope breakpoint at that time.  */
14642   if (bpt->type == bp_watchpoint_scope)
14643     return;
14644
14645   bpt->enable_state = bp_disabled;
14646
14647   /* Mark breakpoint locations modified.  */
14648   mark_breakpoint_modified (bpt);
14649
14650   if (target_supports_enable_disable_tracepoint ()
14651       && current_trace_status ()->running && is_tracepoint (bpt))
14652     {
14653       struct bp_location *location;
14654      
14655       for (location = bpt->loc; location; location = location->next)
14656         target_disable_tracepoint (location);
14657     }
14658
14659   update_global_location_list (UGLL_DONT_INSERT);
14660
14661   observer_notify_breakpoint_modified (bpt);
14662 }
14663
14664 /* A callback for iterate_over_related_breakpoints.  */
14665
14666 static void
14667 do_disable_breakpoint (struct breakpoint *b, void *ignore)
14668 {
14669   disable_breakpoint (b);
14670 }
14671
14672 /* A callback for map_breakpoint_numbers that calls
14673    disable_breakpoint.  */
14674
14675 static void
14676 do_map_disable_breakpoint (struct breakpoint *b, void *ignore)
14677 {
14678   iterate_over_related_breakpoints (b, do_disable_breakpoint, NULL);
14679 }
14680
14681 static void
14682 disable_command (char *args, int from_tty)
14683 {
14684   if (args == 0)
14685     {
14686       struct breakpoint *bpt;
14687
14688       ALL_BREAKPOINTS (bpt)
14689         if (user_breakpoint_p (bpt))
14690           disable_breakpoint (bpt);
14691     }
14692   else
14693     {
14694       char *num = extract_arg (&args);
14695
14696       while (num)
14697         {
14698           if (strchr (num, '.'))
14699             {
14700               struct bp_location *loc = find_location_by_number (num);
14701
14702               if (loc)
14703                 {
14704                   if (loc->enabled)
14705                     {
14706                       loc->enabled = 0;
14707                       mark_breakpoint_location_modified (loc);
14708                     }
14709                   if (target_supports_enable_disable_tracepoint ()
14710                       && current_trace_status ()->running && loc->owner
14711                       && is_tracepoint (loc->owner))
14712                     target_disable_tracepoint (loc);
14713                 }
14714               update_global_location_list (UGLL_DONT_INSERT);
14715             }
14716           else
14717             map_breakpoint_numbers (num, do_map_disable_breakpoint, NULL);
14718           num = extract_arg (&args);
14719         }
14720     }
14721 }
14722
14723 static void
14724 enable_breakpoint_disp (struct breakpoint *bpt, enum bpdisp disposition,
14725                         int count)
14726 {
14727   int target_resources_ok;
14728
14729   if (bpt->type == bp_hardware_breakpoint)
14730     {
14731       int i;
14732       i = hw_breakpoint_used_count ();
14733       target_resources_ok = 
14734         target_can_use_hardware_watchpoint (bp_hardware_breakpoint, 
14735                                             i + 1, 0);
14736       if (target_resources_ok == 0)
14737         error (_("No hardware breakpoint support in the target."));
14738       else if (target_resources_ok < 0)
14739         error (_("Hardware breakpoints used exceeds limit."));
14740     }
14741
14742   if (is_watchpoint (bpt))
14743     {
14744       /* Initialize it just to avoid a GCC false warning.  */
14745       enum enable_state orig_enable_state = bp_disabled;
14746
14747       TRY
14748         {
14749           struct watchpoint *w = (struct watchpoint *) bpt;
14750
14751           orig_enable_state = bpt->enable_state;
14752           bpt->enable_state = bp_enabled;
14753           update_watchpoint (w, 1 /* reparse */);
14754         }
14755       CATCH (e, RETURN_MASK_ALL)
14756         {
14757           bpt->enable_state = orig_enable_state;
14758           exception_fprintf (gdb_stderr, e, _("Cannot enable watchpoint %d: "),
14759                              bpt->number);
14760           return;
14761         }
14762       END_CATCH
14763     }
14764
14765   bpt->enable_state = bp_enabled;
14766
14767   /* Mark breakpoint locations modified.  */
14768   mark_breakpoint_modified (bpt);
14769
14770   if (target_supports_enable_disable_tracepoint ()
14771       && current_trace_status ()->running && is_tracepoint (bpt))
14772     {
14773       struct bp_location *location;
14774
14775       for (location = bpt->loc; location; location = location->next)
14776         target_enable_tracepoint (location);
14777     }
14778
14779   bpt->disposition = disposition;
14780   bpt->enable_count = count;
14781   update_global_location_list (UGLL_MAY_INSERT);
14782
14783   observer_notify_breakpoint_modified (bpt);
14784 }
14785
14786
14787 void
14788 enable_breakpoint (struct breakpoint *bpt)
14789 {
14790   enable_breakpoint_disp (bpt, bpt->disposition, 0);
14791 }
14792
14793 static void
14794 do_enable_breakpoint (struct breakpoint *bpt, void *arg)
14795 {
14796   enable_breakpoint (bpt);
14797 }
14798
14799 /* A callback for map_breakpoint_numbers that calls
14800    enable_breakpoint.  */
14801
14802 static void
14803 do_map_enable_breakpoint (struct breakpoint *b, void *ignore)
14804 {
14805   iterate_over_related_breakpoints (b, do_enable_breakpoint, NULL);
14806 }
14807
14808 /* The enable command enables the specified breakpoints (or all defined
14809    breakpoints) so they once again become (or continue to be) effective
14810    in stopping the inferior.  */
14811
14812 static void
14813 enable_command (char *args, int from_tty)
14814 {
14815   if (args == 0)
14816     {
14817       struct breakpoint *bpt;
14818
14819       ALL_BREAKPOINTS (bpt)
14820         if (user_breakpoint_p (bpt))
14821           enable_breakpoint (bpt);
14822     }
14823   else
14824     {
14825       char *num = extract_arg (&args);
14826
14827       while (num)
14828         {
14829           if (strchr (num, '.'))
14830             {
14831               struct bp_location *loc = find_location_by_number (num);
14832
14833               if (loc)
14834                 {
14835                   if (!loc->enabled)
14836                     {
14837                       loc->enabled = 1;
14838                       mark_breakpoint_location_modified (loc);
14839                     }
14840                   if (target_supports_enable_disable_tracepoint ()
14841                       && current_trace_status ()->running && loc->owner
14842                       && is_tracepoint (loc->owner))
14843                     target_enable_tracepoint (loc);
14844                 }
14845               update_global_location_list (UGLL_MAY_INSERT);
14846             }
14847           else
14848             map_breakpoint_numbers (num, do_map_enable_breakpoint, NULL);
14849           num = extract_arg (&args);
14850         }
14851     }
14852 }
14853
14854 /* This struct packages up disposition data for application to multiple
14855    breakpoints.  */
14856
14857 struct disp_data
14858 {
14859   enum bpdisp disp;
14860   int count;
14861 };
14862
14863 static void
14864 do_enable_breakpoint_disp (struct breakpoint *bpt, void *arg)
14865 {
14866   struct disp_data disp_data = *(struct disp_data *) arg;
14867
14868   enable_breakpoint_disp (bpt, disp_data.disp, disp_data.count);
14869 }
14870
14871 static void
14872 do_map_enable_once_breakpoint (struct breakpoint *bpt, void *ignore)
14873 {
14874   struct disp_data disp = { disp_disable, 1 };
14875
14876   iterate_over_related_breakpoints (bpt, do_enable_breakpoint_disp, &disp);
14877 }
14878
14879 static void
14880 enable_once_command (char *args, int from_tty)
14881 {
14882   map_breakpoint_numbers (args, do_map_enable_once_breakpoint, NULL);
14883 }
14884
14885 static void
14886 do_map_enable_count_breakpoint (struct breakpoint *bpt, void *countptr)
14887 {
14888   struct disp_data disp = { disp_disable, *(int *) countptr };
14889
14890   iterate_over_related_breakpoints (bpt, do_enable_breakpoint_disp, &disp);
14891 }
14892
14893 static void
14894 enable_count_command (char *args, int from_tty)
14895 {
14896   int count;
14897
14898   if (args == NULL)
14899     error_no_arg (_("hit count"));
14900
14901   count = get_number (&args);
14902
14903   map_breakpoint_numbers (args, do_map_enable_count_breakpoint, &count);
14904 }
14905
14906 static void
14907 do_map_enable_delete_breakpoint (struct breakpoint *bpt, void *ignore)
14908 {
14909   struct disp_data disp = { disp_del, 1 };
14910
14911   iterate_over_related_breakpoints (bpt, do_enable_breakpoint_disp, &disp);
14912 }
14913
14914 static void
14915 enable_delete_command (char *args, int from_tty)
14916 {
14917   map_breakpoint_numbers (args, do_map_enable_delete_breakpoint, NULL);
14918 }
14919 \f
14920 static void
14921 set_breakpoint_cmd (char *args, int from_tty)
14922 {
14923 }
14924
14925 static void
14926 show_breakpoint_cmd (char *args, int from_tty)
14927 {
14928 }
14929
14930 /* Invalidate last known value of any hardware watchpoint if
14931    the memory which that value represents has been written to by
14932    GDB itself.  */
14933
14934 static void
14935 invalidate_bp_value_on_memory_change (struct inferior *inferior,
14936                                       CORE_ADDR addr, ssize_t len,
14937                                       const bfd_byte *data)
14938 {
14939   struct breakpoint *bp;
14940
14941   ALL_BREAKPOINTS (bp)
14942     if (bp->enable_state == bp_enabled
14943         && bp->type == bp_hardware_watchpoint)
14944       {
14945         struct watchpoint *wp = (struct watchpoint *) bp;
14946
14947         if (wp->val_valid && wp->val)
14948           {
14949             struct bp_location *loc;
14950
14951             for (loc = bp->loc; loc != NULL; loc = loc->next)
14952               if (loc->loc_type == bp_loc_hardware_watchpoint
14953                   && loc->address + loc->length > addr
14954                   && addr + len > loc->address)
14955                 {
14956                   value_free (wp->val);
14957                   wp->val = NULL;
14958                   wp->val_valid = 0;
14959                 }
14960           }
14961       }
14962 }
14963
14964 /* Create and insert a breakpoint for software single step.  */
14965
14966 void
14967 insert_single_step_breakpoint (struct gdbarch *gdbarch,
14968                                struct address_space *aspace, 
14969                                CORE_ADDR next_pc)
14970 {
14971   struct thread_info *tp = inferior_thread ();
14972   struct symtab_and_line sal;
14973   CORE_ADDR pc = next_pc;
14974
14975   if (tp->control.single_step_breakpoints == NULL)
14976     {
14977       tp->control.single_step_breakpoints
14978         = new_single_step_breakpoint (tp->global_num, gdbarch);
14979     }
14980
14981   sal = find_pc_line (pc, 0);
14982   sal.pc = pc;
14983   sal.section = find_pc_overlay (pc);
14984   sal.explicit_pc = 1;
14985   add_location_to_breakpoint (tp->control.single_step_breakpoints, &sal);
14986
14987   update_global_location_list (UGLL_INSERT);
14988 }
14989
14990 /* Insert single step breakpoints according to the current state.  */
14991
14992 int
14993 insert_single_step_breakpoints (struct gdbarch *gdbarch)
14994 {
14995   struct regcache *regcache = get_current_regcache ();
14996   std::vector<CORE_ADDR> next_pcs;
14997
14998   next_pcs = gdbarch_software_single_step (gdbarch, regcache);
14999
15000   if (!next_pcs.empty ())
15001     {
15002       struct frame_info *frame = get_current_frame ();
15003       struct address_space *aspace = get_frame_address_space (frame);
15004
15005       for (CORE_ADDR pc : next_pcs)
15006         insert_single_step_breakpoint (gdbarch, aspace, pc);
15007
15008       return 1;
15009     }
15010   else
15011     return 0;
15012 }
15013
15014 /* See breakpoint.h.  */
15015
15016 int
15017 breakpoint_has_location_inserted_here (struct breakpoint *bp,
15018                                        struct address_space *aspace,
15019                                        CORE_ADDR pc)
15020 {
15021   struct bp_location *loc;
15022
15023   for (loc = bp->loc; loc != NULL; loc = loc->next)
15024     if (loc->inserted
15025         && breakpoint_location_address_match (loc, aspace, pc))
15026       return 1;
15027
15028   return 0;
15029 }
15030
15031 /* Check whether a software single-step breakpoint is inserted at
15032    PC.  */
15033
15034 int
15035 single_step_breakpoint_inserted_here_p (struct address_space *aspace,
15036                                         CORE_ADDR pc)
15037 {
15038   struct breakpoint *bpt;
15039
15040   ALL_BREAKPOINTS (bpt)
15041     {
15042       if (bpt->type == bp_single_step
15043           && breakpoint_has_location_inserted_here (bpt, aspace, pc))
15044         return 1;
15045     }
15046   return 0;
15047 }
15048
15049 /* Tracepoint-specific operations.  */
15050
15051 /* Set tracepoint count to NUM.  */
15052 static void
15053 set_tracepoint_count (int num)
15054 {
15055   tracepoint_count = num;
15056   set_internalvar_integer (lookup_internalvar ("tpnum"), num);
15057 }
15058
15059 static void
15060 trace_command (char *arg, int from_tty)
15061 {
15062   struct breakpoint_ops *ops;
15063
15064   event_location_up location = string_to_event_location (&arg,
15065                                                          current_language);
15066   if (location != NULL
15067       && event_location_type (location.get ()) == PROBE_LOCATION)
15068     ops = &tracepoint_probe_breakpoint_ops;
15069   else
15070     ops = &tracepoint_breakpoint_ops;
15071
15072   create_breakpoint (get_current_arch (),
15073                      location.get (),
15074                      NULL, 0, arg, 1 /* parse arg */,
15075                      0 /* tempflag */,
15076                      bp_tracepoint /* type_wanted */,
15077                      0 /* Ignore count */,
15078                      pending_break_support,
15079                      ops,
15080                      from_tty,
15081                      1 /* enabled */,
15082                      0 /* internal */, 0);
15083 }
15084
15085 static void
15086 ftrace_command (char *arg, int from_tty)
15087 {
15088   event_location_up location = string_to_event_location (&arg,
15089                                                          current_language);
15090   create_breakpoint (get_current_arch (),
15091                      location.get (),
15092                      NULL, 0, arg, 1 /* parse arg */,
15093                      0 /* tempflag */,
15094                      bp_fast_tracepoint /* type_wanted */,
15095                      0 /* Ignore count */,
15096                      pending_break_support,
15097                      &tracepoint_breakpoint_ops,
15098                      from_tty,
15099                      1 /* enabled */,
15100                      0 /* internal */, 0);
15101 }
15102
15103 /* strace command implementation.  Creates a static tracepoint.  */
15104
15105 static void
15106 strace_command (char *arg, int from_tty)
15107 {
15108   struct breakpoint_ops *ops;
15109   event_location_up location;
15110   struct cleanup *back_to;
15111
15112   /* Decide if we are dealing with a static tracepoint marker (`-m'),
15113      or with a normal static tracepoint.  */
15114   if (arg && startswith (arg, "-m") && isspace (arg[2]))
15115     {
15116       ops = &strace_marker_breakpoint_ops;
15117       location = new_linespec_location (&arg);
15118     }
15119   else
15120     {
15121       ops = &tracepoint_breakpoint_ops;
15122       location = string_to_event_location (&arg, current_language);
15123     }
15124
15125   create_breakpoint (get_current_arch (),
15126                      location.get (),
15127                      NULL, 0, arg, 1 /* parse arg */,
15128                      0 /* tempflag */,
15129                      bp_static_tracepoint /* type_wanted */,
15130                      0 /* Ignore count */,
15131                      pending_break_support,
15132                      ops,
15133                      from_tty,
15134                      1 /* enabled */,
15135                      0 /* internal */, 0);
15136 }
15137
15138 /* Set up a fake reader function that gets command lines from a linked
15139    list that was acquired during tracepoint uploading.  */
15140
15141 static struct uploaded_tp *this_utp;
15142 static int next_cmd;
15143
15144 static char *
15145 read_uploaded_action (void)
15146 {
15147   char *rslt;
15148
15149   VEC_iterate (char_ptr, this_utp->cmd_strings, next_cmd, rslt);
15150
15151   next_cmd++;
15152
15153   return rslt;
15154 }
15155
15156 /* Given information about a tracepoint as recorded on a target (which
15157    can be either a live system or a trace file), attempt to create an
15158    equivalent GDB tracepoint.  This is not a reliable process, since
15159    the target does not necessarily have all the information used when
15160    the tracepoint was originally defined.  */
15161   
15162 struct tracepoint *
15163 create_tracepoint_from_upload (struct uploaded_tp *utp)
15164 {
15165   char *addr_str, small_buf[100];
15166   struct tracepoint *tp;
15167
15168   if (utp->at_string)
15169     addr_str = utp->at_string;
15170   else
15171     {
15172       /* In the absence of a source location, fall back to raw
15173          address.  Since there is no way to confirm that the address
15174          means the same thing as when the trace was started, warn the
15175          user.  */
15176       warning (_("Uploaded tracepoint %d has no "
15177                  "source location, using raw address"),
15178                utp->number);
15179       xsnprintf (small_buf, sizeof (small_buf), "*%s", hex_string (utp->addr));
15180       addr_str = small_buf;
15181     }
15182
15183   /* There's not much we can do with a sequence of bytecodes.  */
15184   if (utp->cond && !utp->cond_string)
15185     warning (_("Uploaded tracepoint %d condition "
15186                "has no source form, ignoring it"),
15187              utp->number);
15188
15189   event_location_up location = string_to_event_location (&addr_str,
15190                                                          current_language);
15191   if (!create_breakpoint (get_current_arch (),
15192                           location.get (),
15193                           utp->cond_string, -1, addr_str,
15194                           0 /* parse cond/thread */,
15195                           0 /* tempflag */,
15196                           utp->type /* type_wanted */,
15197                           0 /* Ignore count */,
15198                           pending_break_support,
15199                           &tracepoint_breakpoint_ops,
15200                           0 /* from_tty */,
15201                           utp->enabled /* enabled */,
15202                           0 /* internal */,
15203                           CREATE_BREAKPOINT_FLAGS_INSERTED))
15204     return NULL;
15205
15206   /* Get the tracepoint we just created.  */
15207   tp = get_tracepoint (tracepoint_count);
15208   gdb_assert (tp != NULL);
15209
15210   if (utp->pass > 0)
15211     {
15212       xsnprintf (small_buf, sizeof (small_buf), "%d %d", utp->pass,
15213                  tp->number);
15214
15215       trace_pass_command (small_buf, 0);
15216     }
15217
15218   /* If we have uploaded versions of the original commands, set up a
15219      special-purpose "reader" function and call the usual command line
15220      reader, then pass the result to the breakpoint command-setting
15221      function.  */
15222   if (!VEC_empty (char_ptr, utp->cmd_strings))
15223     {
15224       command_line_up cmd_list;
15225
15226       this_utp = utp;
15227       next_cmd = 0;
15228
15229       cmd_list = read_command_lines_1 (read_uploaded_action, 1, NULL, NULL);
15230
15231       breakpoint_set_commands (tp, std::move (cmd_list));
15232     }
15233   else if (!VEC_empty (char_ptr, utp->actions)
15234            || !VEC_empty (char_ptr, utp->step_actions))
15235     warning (_("Uploaded tracepoint %d actions "
15236                "have no source form, ignoring them"),
15237              utp->number);
15238
15239   /* Copy any status information that might be available.  */
15240   tp->hit_count = utp->hit_count;
15241   tp->traceframe_usage = utp->traceframe_usage;
15242
15243   return tp;
15244 }
15245   
15246 /* Print information on tracepoint number TPNUM_EXP, or all if
15247    omitted.  */
15248
15249 static void
15250 tracepoints_info (char *args, int from_tty)
15251 {
15252   struct ui_out *uiout = current_uiout;
15253   int num_printed;
15254
15255   num_printed = breakpoint_1 (args, 0, is_tracepoint);
15256
15257   if (num_printed == 0)
15258     {
15259       if (args == NULL || *args == '\0')
15260         uiout->message ("No tracepoints.\n");
15261       else
15262         uiout->message ("No tracepoint matching '%s'.\n", args);
15263     }
15264
15265   default_collect_info ();
15266 }
15267
15268 /* The 'enable trace' command enables tracepoints.
15269    Not supported by all targets.  */
15270 static void
15271 enable_trace_command (char *args, int from_tty)
15272 {
15273   enable_command (args, from_tty);
15274 }
15275
15276 /* The 'disable trace' command disables tracepoints.
15277    Not supported by all targets.  */
15278 static void
15279 disable_trace_command (char *args, int from_tty)
15280 {
15281   disable_command (args, from_tty);
15282 }
15283
15284 /* Remove a tracepoint (or all if no argument).  */
15285 static void
15286 delete_trace_command (char *arg, int from_tty)
15287 {
15288   struct breakpoint *b, *b_tmp;
15289
15290   dont_repeat ();
15291
15292   if (arg == 0)
15293     {
15294       int breaks_to_delete = 0;
15295
15296       /* Delete all breakpoints if no argument.
15297          Do not delete internal or call-dummy breakpoints, these
15298          have to be deleted with an explicit breakpoint number 
15299          argument.  */
15300       ALL_TRACEPOINTS (b)
15301         if (is_tracepoint (b) && user_breakpoint_p (b))
15302           {
15303             breaks_to_delete = 1;
15304             break;
15305           }
15306
15307       /* Ask user only if there are some breakpoints to delete.  */
15308       if (!from_tty
15309           || (breaks_to_delete && query (_("Delete all tracepoints? "))))
15310         {
15311           ALL_BREAKPOINTS_SAFE (b, b_tmp)
15312             if (is_tracepoint (b) && user_breakpoint_p (b))
15313               delete_breakpoint (b);
15314         }
15315     }
15316   else
15317     map_breakpoint_numbers (arg, do_map_delete_breakpoint, NULL);
15318 }
15319
15320 /* Helper function for trace_pass_command.  */
15321
15322 static void
15323 trace_pass_set_count (struct tracepoint *tp, int count, int from_tty)
15324 {
15325   tp->pass_count = count;
15326   observer_notify_breakpoint_modified (tp);
15327   if (from_tty)
15328     printf_filtered (_("Setting tracepoint %d's passcount to %d\n"),
15329                      tp->number, count);
15330 }
15331
15332 /* Set passcount for tracepoint.
15333
15334    First command argument is passcount, second is tracepoint number.
15335    If tracepoint number omitted, apply to most recently defined.
15336    Also accepts special argument "all".  */
15337
15338 static void
15339 trace_pass_command (char *args, int from_tty)
15340 {
15341   struct tracepoint *t1;
15342   unsigned int count;
15343
15344   if (args == 0 || *args == 0)
15345     error (_("passcount command requires an "
15346              "argument (count + optional TP num)"));
15347
15348   count = strtoul (args, &args, 10);    /* Count comes first, then TP num.  */
15349
15350   args = skip_spaces (args);
15351   if (*args && strncasecmp (args, "all", 3) == 0)
15352     {
15353       struct breakpoint *b;
15354
15355       args += 3;                        /* Skip special argument "all".  */
15356       if (*args)
15357         error (_("Junk at end of arguments."));
15358
15359       ALL_TRACEPOINTS (b)
15360       {
15361         t1 = (struct tracepoint *) b;
15362         trace_pass_set_count (t1, count, from_tty);
15363       }
15364     }
15365   else if (*args == '\0')
15366     {
15367       t1 = get_tracepoint_by_number (&args, NULL);
15368       if (t1)
15369         trace_pass_set_count (t1, count, from_tty);
15370     }
15371   else
15372     {
15373       number_or_range_parser parser (args);
15374       while (!parser.finished ())
15375         {
15376           t1 = get_tracepoint_by_number (&args, &parser);
15377           if (t1)
15378             trace_pass_set_count (t1, count, from_tty);
15379         }
15380     }
15381 }
15382
15383 struct tracepoint *
15384 get_tracepoint (int num)
15385 {
15386   struct breakpoint *t;
15387
15388   ALL_TRACEPOINTS (t)
15389     if (t->number == num)
15390       return (struct tracepoint *) t;
15391
15392   return NULL;
15393 }
15394
15395 /* Find the tracepoint with the given target-side number (which may be
15396    different from the tracepoint number after disconnecting and
15397    reconnecting).  */
15398
15399 struct tracepoint *
15400 get_tracepoint_by_number_on_target (int num)
15401 {
15402   struct breakpoint *b;
15403
15404   ALL_TRACEPOINTS (b)
15405     {
15406       struct tracepoint *t = (struct tracepoint *) b;
15407
15408       if (t->number_on_target == num)
15409         return t;
15410     }
15411
15412   return NULL;
15413 }
15414
15415 /* Utility: parse a tracepoint number and look it up in the list.
15416    If STATE is not NULL, use, get_number_or_range_state and ignore ARG.
15417    If the argument is missing, the most recent tracepoint
15418    (tracepoint_count) is returned.  */
15419
15420 struct tracepoint *
15421 get_tracepoint_by_number (char **arg,
15422                           number_or_range_parser *parser)
15423 {
15424   struct breakpoint *t;
15425   int tpnum;
15426   char *instring = arg == NULL ? NULL : *arg;
15427
15428   if (parser != NULL)
15429     {
15430       gdb_assert (!parser->finished ());
15431       tpnum = parser->get_number ();
15432     }
15433   else if (arg == NULL || *arg == NULL || ! **arg)
15434     tpnum = tracepoint_count;
15435   else
15436     tpnum = get_number (arg);
15437
15438   if (tpnum <= 0)
15439     {
15440       if (instring && *instring)
15441         printf_filtered (_("bad tracepoint number at or near '%s'\n"), 
15442                          instring);
15443       else
15444         printf_filtered (_("No previous tracepoint\n"));
15445       return NULL;
15446     }
15447
15448   ALL_TRACEPOINTS (t)
15449     if (t->number == tpnum)
15450     {
15451       return (struct tracepoint *) t;
15452     }
15453
15454   printf_unfiltered ("No tracepoint number %d.\n", tpnum);
15455   return NULL;
15456 }
15457
15458 void
15459 print_recreate_thread (struct breakpoint *b, struct ui_file *fp)
15460 {
15461   if (b->thread != -1)
15462     fprintf_unfiltered (fp, " thread %d", b->thread);
15463
15464   if (b->task != 0)
15465     fprintf_unfiltered (fp, " task %d", b->task);
15466
15467   fprintf_unfiltered (fp, "\n");
15468 }
15469
15470 /* Save information on user settable breakpoints (watchpoints, etc) to
15471    a new script file named FILENAME.  If FILTER is non-NULL, call it
15472    on each breakpoint and only include the ones for which it returns
15473    non-zero.  */
15474
15475 static void
15476 save_breakpoints (char *filename, int from_tty,
15477                   int (*filter) (const struct breakpoint *))
15478 {
15479   struct breakpoint *tp;
15480   int any = 0;
15481   struct cleanup *cleanup;
15482   int extra_trace_bits = 0;
15483
15484   if (filename == 0 || *filename == 0)
15485     error (_("Argument required (file name in which to save)"));
15486
15487   /* See if we have anything to save.  */
15488   ALL_BREAKPOINTS (tp)
15489   {
15490     /* Skip internal and momentary breakpoints.  */
15491     if (!user_breakpoint_p (tp))
15492       continue;
15493
15494     /* If we have a filter, only save the breakpoints it accepts.  */
15495     if (filter && !filter (tp))
15496       continue;
15497
15498     any = 1;
15499
15500     if (is_tracepoint (tp))
15501       {
15502         extra_trace_bits = 1;
15503
15504         /* We can stop searching.  */
15505         break;
15506       }
15507   }
15508
15509   if (!any)
15510     {
15511       warning (_("Nothing to save."));
15512       return;
15513     }
15514
15515   filename = tilde_expand (filename);
15516   cleanup = make_cleanup (xfree, filename);
15517
15518   stdio_file fp;
15519
15520   if (!fp.open (filename, "w"))
15521     error (_("Unable to open file '%s' for saving (%s)"),
15522            filename, safe_strerror (errno));
15523
15524   if (extra_trace_bits)
15525     save_trace_state_variables (&fp);
15526
15527   ALL_BREAKPOINTS (tp)
15528   {
15529     /* Skip internal and momentary breakpoints.  */
15530     if (!user_breakpoint_p (tp))
15531       continue;
15532
15533     /* If we have a filter, only save the breakpoints it accepts.  */
15534     if (filter && !filter (tp))
15535       continue;
15536
15537     tp->ops->print_recreate (tp, &fp);
15538
15539     /* Note, we can't rely on tp->number for anything, as we can't
15540        assume the recreated breakpoint numbers will match.  Use $bpnum
15541        instead.  */
15542
15543     if (tp->cond_string)
15544       fp.printf ("  condition $bpnum %s\n", tp->cond_string);
15545
15546     if (tp->ignore_count)
15547       fp.printf ("  ignore $bpnum %d\n", tp->ignore_count);
15548
15549     if (tp->type != bp_dprintf && tp->commands)
15550       {
15551         fp.puts ("  commands\n");
15552         
15553         current_uiout->redirect (&fp);
15554         TRY
15555           {
15556             print_command_lines (current_uiout, tp->commands->commands, 2);
15557           }
15558         CATCH (ex, RETURN_MASK_ALL)
15559           {
15560           current_uiout->redirect (NULL);
15561             throw_exception (ex);
15562           }
15563         END_CATCH
15564
15565         current_uiout->redirect (NULL);
15566         fp.puts ("  end\n");
15567       }
15568
15569     if (tp->enable_state == bp_disabled)
15570       fp.puts ("disable $bpnum\n");
15571
15572     /* If this is a multi-location breakpoint, check if the locations
15573        should be individually disabled.  Watchpoint locations are
15574        special, and not user visible.  */
15575     if (!is_watchpoint (tp) && tp->loc && tp->loc->next)
15576       {
15577         struct bp_location *loc;
15578         int n = 1;
15579
15580         for (loc = tp->loc; loc != NULL; loc = loc->next, n++)
15581           if (!loc->enabled)
15582             fp.printf ("disable $bpnum.%d\n", n);
15583       }
15584   }
15585
15586   if (extra_trace_bits && *default_collect)
15587     fp.printf ("set default-collect %s\n", default_collect);
15588
15589   if (from_tty)
15590     printf_filtered (_("Saved to file '%s'.\n"), filename);
15591   do_cleanups (cleanup);
15592 }
15593
15594 /* The `save breakpoints' command.  */
15595
15596 static void
15597 save_breakpoints_command (char *args, int from_tty)
15598 {
15599   save_breakpoints (args, from_tty, NULL);
15600 }
15601
15602 /* The `save tracepoints' command.  */
15603
15604 static void
15605 save_tracepoints_command (char *args, int from_tty)
15606 {
15607   save_breakpoints (args, from_tty, is_tracepoint);
15608 }
15609
15610 /* Create a vector of all tracepoints.  */
15611
15612 VEC(breakpoint_p) *
15613 all_tracepoints (void)
15614 {
15615   VEC(breakpoint_p) *tp_vec = 0;
15616   struct breakpoint *tp;
15617
15618   ALL_TRACEPOINTS (tp)
15619   {
15620     VEC_safe_push (breakpoint_p, tp_vec, tp);
15621   }
15622
15623   return tp_vec;
15624 }
15625
15626 \f
15627 /* This help string is used to consolidate all the help string for specifying
15628    locations used by several commands.  */
15629
15630 #define LOCATION_HELP_STRING \
15631 "Linespecs are colon-separated lists of location parameters, such as\n\
15632 source filename, function name, label name, and line number.\n\
15633 Example: To specify the start of a label named \"the_top\" in the\n\
15634 function \"fact\" in the file \"factorial.c\", use\n\
15635 \"factorial.c:fact:the_top\".\n\
15636 \n\
15637 Address locations begin with \"*\" and specify an exact address in the\n\
15638 program.  Example: To specify the fourth byte past the start function\n\
15639 \"main\", use \"*main + 4\".\n\
15640 \n\
15641 Explicit locations are similar to linespecs but use an option/argument\n\
15642 syntax to specify location parameters.\n\
15643 Example: To specify the start of the label named \"the_top\" in the\n\
15644 function \"fact\" in the file \"factorial.c\", use \"-source factorial.c\n\
15645 -function fact -label the_top\".\n"
15646
15647 /* This help string is used for the break, hbreak, tbreak and thbreak
15648    commands.  It is defined as a macro to prevent duplication.
15649    COMMAND should be a string constant containing the name of the
15650    command.  */
15651
15652 #define BREAK_ARGS_HELP(command) \
15653 command" [PROBE_MODIFIER] [LOCATION] [thread THREADNUM] [if CONDITION]\n\
15654 PROBE_MODIFIER shall be present if the command is to be placed in a\n\
15655 probe point.  Accepted values are `-probe' (for a generic, automatically\n\
15656 guessed probe type), `-probe-stap' (for a SystemTap probe) or \n\
15657 `-probe-dtrace' (for a DTrace probe).\n\
15658 LOCATION may be a linespec, address, or explicit location as described\n\
15659 below.\n\
15660 \n\
15661 With no LOCATION, uses current execution address of the selected\n\
15662 stack frame.  This is useful for breaking on return to a stack frame.\n\
15663 \n\
15664 THREADNUM is the number from \"info threads\".\n\
15665 CONDITION is a boolean expression.\n\
15666 \n" LOCATION_HELP_STRING "\n\
15667 Multiple breakpoints at one place are permitted, and useful if their\n\
15668 conditions are different.\n\
15669 \n\
15670 Do \"help breakpoints\" for info on other commands dealing with breakpoints."
15671
15672 /* List of subcommands for "catch".  */
15673 static struct cmd_list_element *catch_cmdlist;
15674
15675 /* List of subcommands for "tcatch".  */
15676 static struct cmd_list_element *tcatch_cmdlist;
15677
15678 void
15679 add_catch_command (const char *name, const char *docstring,
15680                    cmd_sfunc_ftype *sfunc,
15681                    completer_ftype *completer,
15682                    void *user_data_catch,
15683                    void *user_data_tcatch)
15684 {
15685   struct cmd_list_element *command;
15686
15687   command = add_cmd (name, class_breakpoint, NULL, docstring,
15688                      &catch_cmdlist);
15689   set_cmd_sfunc (command, sfunc);
15690   set_cmd_context (command, user_data_catch);
15691   set_cmd_completer (command, completer);
15692
15693   command = add_cmd (name, class_breakpoint, NULL, docstring,
15694                      &tcatch_cmdlist);
15695   set_cmd_sfunc (command, sfunc);
15696   set_cmd_context (command, user_data_tcatch);
15697   set_cmd_completer (command, completer);
15698 }
15699
15700 static void
15701 save_command (char *arg, int from_tty)
15702 {
15703   printf_unfiltered (_("\"save\" must be followed by "
15704                        "the name of a save subcommand.\n"));
15705   help_list (save_cmdlist, "save ", all_commands, gdb_stdout);
15706 }
15707
15708 struct breakpoint *
15709 iterate_over_breakpoints (int (*callback) (struct breakpoint *, void *),
15710                           void *data)
15711 {
15712   struct breakpoint *b, *b_tmp;
15713
15714   ALL_BREAKPOINTS_SAFE (b, b_tmp)
15715     {
15716       if ((*callback) (b, data))
15717         return b;
15718     }
15719
15720   return NULL;
15721 }
15722
15723 /* Zero if any of the breakpoint's locations could be a location where
15724    functions have been inlined, nonzero otherwise.  */
15725
15726 static int
15727 is_non_inline_function (struct breakpoint *b)
15728 {
15729   /* The shared library event breakpoint is set on the address of a
15730      non-inline function.  */
15731   if (b->type == bp_shlib_event)
15732     return 1;
15733
15734   return 0;
15735 }
15736
15737 /* Nonzero if the specified PC cannot be a location where functions
15738    have been inlined.  */
15739
15740 int
15741 pc_at_non_inline_function (struct address_space *aspace, CORE_ADDR pc,
15742                            const struct target_waitstatus *ws)
15743 {
15744   struct breakpoint *b;
15745   struct bp_location *bl;
15746
15747   ALL_BREAKPOINTS (b)
15748     {
15749       if (!is_non_inline_function (b))
15750         continue;
15751
15752       for (bl = b->loc; bl != NULL; bl = bl->next)
15753         {
15754           if (!bl->shlib_disabled
15755               && bpstat_check_location (bl, aspace, pc, ws))
15756             return 1;
15757         }
15758     }
15759
15760   return 0;
15761 }
15762
15763 /* Remove any references to OBJFILE which is going to be freed.  */
15764
15765 void
15766 breakpoint_free_objfile (struct objfile *objfile)
15767 {
15768   struct bp_location **locp, *loc;
15769
15770   ALL_BP_LOCATIONS (loc, locp)
15771     if (loc->symtab != NULL && SYMTAB_OBJFILE (loc->symtab) == objfile)
15772       loc->symtab = NULL;
15773 }
15774
15775 void
15776 initialize_breakpoint_ops (void)
15777 {
15778   static int initialized = 0;
15779
15780   struct breakpoint_ops *ops;
15781
15782   if (initialized)
15783     return;
15784   initialized = 1;
15785
15786   /* The breakpoint_ops structure to be inherit by all kinds of
15787      breakpoints (real breakpoints, i.e., user "break" breakpoints,
15788      internal and momentary breakpoints, etc.).  */
15789   ops = &bkpt_base_breakpoint_ops;
15790   *ops = base_breakpoint_ops;
15791   ops->re_set = bkpt_re_set;
15792   ops->insert_location = bkpt_insert_location;
15793   ops->remove_location = bkpt_remove_location;
15794   ops->breakpoint_hit = bkpt_breakpoint_hit;
15795   ops->create_sals_from_location = bkpt_create_sals_from_location;
15796   ops->create_breakpoints_sal = bkpt_create_breakpoints_sal;
15797   ops->decode_location = bkpt_decode_location;
15798
15799   /* The breakpoint_ops structure to be used in regular breakpoints.  */
15800   ops = &bkpt_breakpoint_ops;
15801   *ops = bkpt_base_breakpoint_ops;
15802   ops->re_set = bkpt_re_set;
15803   ops->resources_needed = bkpt_resources_needed;
15804   ops->print_it = bkpt_print_it;
15805   ops->print_mention = bkpt_print_mention;
15806   ops->print_recreate = bkpt_print_recreate;
15807
15808   /* Ranged breakpoints.  */
15809   ops = &ranged_breakpoint_ops;
15810   *ops = bkpt_breakpoint_ops;
15811   ops->breakpoint_hit = breakpoint_hit_ranged_breakpoint;
15812   ops->resources_needed = resources_needed_ranged_breakpoint;
15813   ops->print_it = print_it_ranged_breakpoint;
15814   ops->print_one = print_one_ranged_breakpoint;
15815   ops->print_one_detail = print_one_detail_ranged_breakpoint;
15816   ops->print_mention = print_mention_ranged_breakpoint;
15817   ops->print_recreate = print_recreate_ranged_breakpoint;
15818
15819   /* Internal breakpoints.  */
15820   ops = &internal_breakpoint_ops;
15821   *ops = bkpt_base_breakpoint_ops;
15822   ops->re_set = internal_bkpt_re_set;
15823   ops->check_status = internal_bkpt_check_status;
15824   ops->print_it = internal_bkpt_print_it;
15825   ops->print_mention = internal_bkpt_print_mention;
15826
15827   /* Momentary breakpoints.  */
15828   ops = &momentary_breakpoint_ops;
15829   *ops = bkpt_base_breakpoint_ops;
15830   ops->re_set = momentary_bkpt_re_set;
15831   ops->check_status = momentary_bkpt_check_status;
15832   ops->print_it = momentary_bkpt_print_it;
15833   ops->print_mention = momentary_bkpt_print_mention;
15834
15835   /* Probe breakpoints.  */
15836   ops = &bkpt_probe_breakpoint_ops;
15837   *ops = bkpt_breakpoint_ops;
15838   ops->insert_location = bkpt_probe_insert_location;
15839   ops->remove_location = bkpt_probe_remove_location;
15840   ops->create_sals_from_location = bkpt_probe_create_sals_from_location;
15841   ops->decode_location = bkpt_probe_decode_location;
15842
15843   /* Watchpoints.  */
15844   ops = &watchpoint_breakpoint_ops;
15845   *ops = base_breakpoint_ops;
15846   ops->re_set = re_set_watchpoint;
15847   ops->insert_location = insert_watchpoint;
15848   ops->remove_location = remove_watchpoint;
15849   ops->breakpoint_hit = breakpoint_hit_watchpoint;
15850   ops->check_status = check_status_watchpoint;
15851   ops->resources_needed = resources_needed_watchpoint;
15852   ops->works_in_software_mode = works_in_software_mode_watchpoint;
15853   ops->print_it = print_it_watchpoint;
15854   ops->print_mention = print_mention_watchpoint;
15855   ops->print_recreate = print_recreate_watchpoint;
15856   ops->explains_signal = explains_signal_watchpoint;
15857
15858   /* Masked watchpoints.  */
15859   ops = &masked_watchpoint_breakpoint_ops;
15860   *ops = watchpoint_breakpoint_ops;
15861   ops->insert_location = insert_masked_watchpoint;
15862   ops->remove_location = remove_masked_watchpoint;
15863   ops->resources_needed = resources_needed_masked_watchpoint;
15864   ops->works_in_software_mode = works_in_software_mode_masked_watchpoint;
15865   ops->print_it = print_it_masked_watchpoint;
15866   ops->print_one_detail = print_one_detail_masked_watchpoint;
15867   ops->print_mention = print_mention_masked_watchpoint;
15868   ops->print_recreate = print_recreate_masked_watchpoint;
15869
15870   /* Tracepoints.  */
15871   ops = &tracepoint_breakpoint_ops;
15872   *ops = base_breakpoint_ops;
15873   ops->re_set = tracepoint_re_set;
15874   ops->breakpoint_hit = tracepoint_breakpoint_hit;
15875   ops->print_one_detail = tracepoint_print_one_detail;
15876   ops->print_mention = tracepoint_print_mention;
15877   ops->print_recreate = tracepoint_print_recreate;
15878   ops->create_sals_from_location = tracepoint_create_sals_from_location;
15879   ops->create_breakpoints_sal = tracepoint_create_breakpoints_sal;
15880   ops->decode_location = tracepoint_decode_location;
15881
15882   /* Probe tracepoints.  */
15883   ops = &tracepoint_probe_breakpoint_ops;
15884   *ops = tracepoint_breakpoint_ops;
15885   ops->create_sals_from_location = tracepoint_probe_create_sals_from_location;
15886   ops->decode_location = tracepoint_probe_decode_location;
15887
15888   /* Static tracepoints with marker (`-m').  */
15889   ops = &strace_marker_breakpoint_ops;
15890   *ops = tracepoint_breakpoint_ops;
15891   ops->create_sals_from_location = strace_marker_create_sals_from_location;
15892   ops->create_breakpoints_sal = strace_marker_create_breakpoints_sal;
15893   ops->decode_location = strace_marker_decode_location;
15894
15895   /* Fork catchpoints.  */
15896   ops = &catch_fork_breakpoint_ops;
15897   *ops = base_breakpoint_ops;
15898   ops->insert_location = insert_catch_fork;
15899   ops->remove_location = remove_catch_fork;
15900   ops->breakpoint_hit = breakpoint_hit_catch_fork;
15901   ops->print_it = print_it_catch_fork;
15902   ops->print_one = print_one_catch_fork;
15903   ops->print_mention = print_mention_catch_fork;
15904   ops->print_recreate = print_recreate_catch_fork;
15905
15906   /* Vfork catchpoints.  */
15907   ops = &catch_vfork_breakpoint_ops;
15908   *ops = base_breakpoint_ops;
15909   ops->insert_location = insert_catch_vfork;
15910   ops->remove_location = remove_catch_vfork;
15911   ops->breakpoint_hit = breakpoint_hit_catch_vfork;
15912   ops->print_it = print_it_catch_vfork;
15913   ops->print_one = print_one_catch_vfork;
15914   ops->print_mention = print_mention_catch_vfork;
15915   ops->print_recreate = print_recreate_catch_vfork;
15916
15917   /* Exec catchpoints.  */
15918   ops = &catch_exec_breakpoint_ops;
15919   *ops = base_breakpoint_ops;
15920   ops->insert_location = insert_catch_exec;
15921   ops->remove_location = remove_catch_exec;
15922   ops->breakpoint_hit = breakpoint_hit_catch_exec;
15923   ops->print_it = print_it_catch_exec;
15924   ops->print_one = print_one_catch_exec;
15925   ops->print_mention = print_mention_catch_exec;
15926   ops->print_recreate = print_recreate_catch_exec;
15927
15928   /* Solib-related catchpoints.  */
15929   ops = &catch_solib_breakpoint_ops;
15930   *ops = base_breakpoint_ops;
15931   ops->insert_location = insert_catch_solib;
15932   ops->remove_location = remove_catch_solib;
15933   ops->breakpoint_hit = breakpoint_hit_catch_solib;
15934   ops->check_status = check_status_catch_solib;
15935   ops->print_it = print_it_catch_solib;
15936   ops->print_one = print_one_catch_solib;
15937   ops->print_mention = print_mention_catch_solib;
15938   ops->print_recreate = print_recreate_catch_solib;
15939
15940   ops = &dprintf_breakpoint_ops;
15941   *ops = bkpt_base_breakpoint_ops;
15942   ops->re_set = dprintf_re_set;
15943   ops->resources_needed = bkpt_resources_needed;
15944   ops->print_it = bkpt_print_it;
15945   ops->print_mention = bkpt_print_mention;
15946   ops->print_recreate = dprintf_print_recreate;
15947   ops->after_condition_true = dprintf_after_condition_true;
15948   ops->breakpoint_hit = dprintf_breakpoint_hit;
15949 }
15950
15951 /* Chain containing all defined "enable breakpoint" subcommands.  */
15952
15953 static struct cmd_list_element *enablebreaklist = NULL;
15954
15955 void
15956 _initialize_breakpoint (void)
15957 {
15958   struct cmd_list_element *c;
15959
15960   initialize_breakpoint_ops ();
15961
15962   observer_attach_solib_unloaded (disable_breakpoints_in_unloaded_shlib);
15963   observer_attach_free_objfile (disable_breakpoints_in_freed_objfile);
15964   observer_attach_memory_changed (invalidate_bp_value_on_memory_change);
15965
15966   breakpoint_objfile_key
15967     = register_objfile_data_with_cleanup (NULL, free_breakpoint_probes);
15968
15969   breakpoint_chain = 0;
15970   /* Don't bother to call set_breakpoint_count.  $bpnum isn't useful
15971      before a breakpoint is set.  */
15972   breakpoint_count = 0;
15973
15974   tracepoint_count = 0;
15975
15976   add_com ("ignore", class_breakpoint, ignore_command, _("\
15977 Set ignore-count of breakpoint number N to COUNT.\n\
15978 Usage is `ignore N COUNT'."));
15979
15980   add_com ("commands", class_breakpoint, commands_command, _("\
15981 Set commands to be executed when the given breakpoints are hit.\n\
15982 Give a space-separated breakpoint list as argument after \"commands\".\n\
15983 A list element can be a breakpoint number (e.g. `5') or a range of numbers\n\
15984 (e.g. `5-7').\n\
15985 With no argument, the targeted breakpoint is the last one set.\n\
15986 The commands themselves follow starting on the next line.\n\
15987 Type a line containing \"end\" to indicate the end of them.\n\
15988 Give \"silent\" as the first line to make the breakpoint silent;\n\
15989 then no output is printed when it is hit, except what the commands print."));
15990
15991   c = add_com ("condition", class_breakpoint, condition_command, _("\
15992 Specify breakpoint number N to break only if COND is true.\n\
15993 Usage is `condition N COND', where N is an integer and COND is an\n\
15994 expression to be evaluated whenever breakpoint N is reached."));
15995   set_cmd_completer (c, condition_completer);
15996
15997   c = add_com ("tbreak", class_breakpoint, tbreak_command, _("\
15998 Set a temporary breakpoint.\n\
15999 Like \"break\" except the breakpoint is only temporary,\n\
16000 so it will be deleted when hit.  Equivalent to \"break\" followed\n\
16001 by using \"enable delete\" on the breakpoint number.\n\
16002 \n"
16003 BREAK_ARGS_HELP ("tbreak")));
16004   set_cmd_completer (c, location_completer);
16005
16006   c = add_com ("hbreak", class_breakpoint, hbreak_command, _("\
16007 Set a hardware assisted breakpoint.\n\
16008 Like \"break\" except the breakpoint requires hardware support,\n\
16009 some target hardware may not have this support.\n\
16010 \n"
16011 BREAK_ARGS_HELP ("hbreak")));
16012   set_cmd_completer (c, location_completer);
16013
16014   c = add_com ("thbreak", class_breakpoint, thbreak_command, _("\
16015 Set a temporary hardware assisted breakpoint.\n\
16016 Like \"hbreak\" except the breakpoint is only temporary,\n\
16017 so it will be deleted when hit.\n\
16018 \n"
16019 BREAK_ARGS_HELP ("thbreak")));
16020   set_cmd_completer (c, location_completer);
16021
16022   add_prefix_cmd ("enable", class_breakpoint, enable_command, _("\
16023 Enable some breakpoints.\n\
16024 Give breakpoint numbers (separated by spaces) as arguments.\n\
16025 With no subcommand, breakpoints are enabled until you command otherwise.\n\
16026 This is used to cancel the effect of the \"disable\" command.\n\
16027 With a subcommand you can enable temporarily."),
16028                   &enablelist, "enable ", 1, &cmdlist);
16029
16030   add_com_alias ("en", "enable", class_breakpoint, 1);
16031
16032   add_prefix_cmd ("breakpoints", class_breakpoint, enable_command, _("\
16033 Enable some breakpoints.\n\
16034 Give breakpoint numbers (separated by spaces) as arguments.\n\
16035 This is used to cancel the effect of the \"disable\" command.\n\
16036 May be abbreviated to simply \"enable\".\n"),
16037                    &enablebreaklist, "enable breakpoints ", 1, &enablelist);
16038
16039   add_cmd ("once", no_class, enable_once_command, _("\
16040 Enable breakpoints for one hit.  Give breakpoint numbers.\n\
16041 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
16042            &enablebreaklist);
16043
16044   add_cmd ("delete", no_class, enable_delete_command, _("\
16045 Enable breakpoints and delete when hit.  Give breakpoint numbers.\n\
16046 If a breakpoint is hit while enabled in this fashion, it is deleted."),
16047            &enablebreaklist);
16048
16049   add_cmd ("count", no_class, enable_count_command, _("\
16050 Enable breakpoints for COUNT hits.  Give count and then breakpoint numbers.\n\
16051 If a breakpoint is hit while enabled in this fashion,\n\
16052 the count is decremented; when it reaches zero, the breakpoint is disabled."),
16053            &enablebreaklist);
16054
16055   add_cmd ("delete", no_class, enable_delete_command, _("\
16056 Enable breakpoints and delete when hit.  Give breakpoint numbers.\n\
16057 If a breakpoint is hit while enabled in this fashion, it is deleted."),
16058            &enablelist);
16059
16060   add_cmd ("once", no_class, enable_once_command, _("\
16061 Enable breakpoints for one hit.  Give breakpoint numbers.\n\
16062 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
16063            &enablelist);
16064
16065   add_cmd ("count", no_class, enable_count_command, _("\
16066 Enable breakpoints for COUNT hits.  Give count and then breakpoint numbers.\n\
16067 If a breakpoint is hit while enabled in this fashion,\n\
16068 the count is decremented; when it reaches zero, the breakpoint is disabled."),
16069            &enablelist);
16070
16071   add_prefix_cmd ("disable", class_breakpoint, disable_command, _("\
16072 Disable some breakpoints.\n\
16073 Arguments are breakpoint numbers with spaces in between.\n\
16074 To disable all breakpoints, give no argument.\n\
16075 A disabled breakpoint is not forgotten, but has no effect until re-enabled."),
16076                   &disablelist, "disable ", 1, &cmdlist);
16077   add_com_alias ("dis", "disable", class_breakpoint, 1);
16078   add_com_alias ("disa", "disable", class_breakpoint, 1);
16079
16080   add_cmd ("breakpoints", class_alias, disable_command, _("\
16081 Disable some breakpoints.\n\
16082 Arguments are breakpoint numbers with spaces in between.\n\
16083 To disable all breakpoints, give no argument.\n\
16084 A disabled breakpoint is not forgotten, but has no effect until re-enabled.\n\
16085 This command may be abbreviated \"disable\"."),
16086            &disablelist);
16087
16088   add_prefix_cmd ("delete", class_breakpoint, delete_command, _("\
16089 Delete some breakpoints or auto-display expressions.\n\
16090 Arguments are breakpoint numbers with spaces in between.\n\
16091 To delete all breakpoints, give no argument.\n\
16092 \n\
16093 Also a prefix command for deletion of other GDB objects.\n\
16094 The \"unset\" command is also an alias for \"delete\"."),
16095                   &deletelist, "delete ", 1, &cmdlist);
16096   add_com_alias ("d", "delete", class_breakpoint, 1);
16097   add_com_alias ("del", "delete", class_breakpoint, 1);
16098
16099   add_cmd ("breakpoints", class_alias, delete_command, _("\
16100 Delete some breakpoints or auto-display expressions.\n\
16101 Arguments are breakpoint numbers with spaces in between.\n\
16102 To delete all breakpoints, give no argument.\n\
16103 This command may be abbreviated \"delete\"."),
16104            &deletelist);
16105
16106   add_com ("clear", class_breakpoint, clear_command, _("\
16107 Clear breakpoint at specified location.\n\
16108 Argument may be a linespec, explicit, or address location as described below.\n\
16109 \n\
16110 With no argument, clears all breakpoints in the line that the selected frame\n\
16111 is executing in.\n"
16112 "\n" LOCATION_HELP_STRING "\n\
16113 See also the \"delete\" command which clears breakpoints by number."));
16114   add_com_alias ("cl", "clear", class_breakpoint, 1);
16115
16116   c = add_com ("break", class_breakpoint, break_command, _("\
16117 Set breakpoint at specified location.\n"
16118 BREAK_ARGS_HELP ("break")));
16119   set_cmd_completer (c, location_completer);
16120
16121   add_com_alias ("b", "break", class_run, 1);
16122   add_com_alias ("br", "break", class_run, 1);
16123   add_com_alias ("bre", "break", class_run, 1);
16124   add_com_alias ("brea", "break", class_run, 1);
16125
16126   if (dbx_commands)
16127     {
16128       add_abbrev_prefix_cmd ("stop", class_breakpoint, stop_command, _("\
16129 Break in function/address or break at a line in the current file."),
16130                              &stoplist, "stop ", 1, &cmdlist);
16131       add_cmd ("in", class_breakpoint, stopin_command,
16132                _("Break in function or address."), &stoplist);
16133       add_cmd ("at", class_breakpoint, stopat_command,
16134                _("Break at a line in the current file."), &stoplist);
16135       add_com ("status", class_info, breakpoints_info, _("\
16136 Status of user-settable breakpoints, or breakpoint number NUMBER.\n\
16137 The \"Type\" column indicates one of:\n\
16138 \tbreakpoint     - normal breakpoint\n\
16139 \twatchpoint     - watchpoint\n\
16140 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
16141 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
16142 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
16143 address and file/line number respectively.\n\
16144 \n\
16145 Convenience variable \"$_\" and default examine address for \"x\"\n\
16146 are set to the address of the last breakpoint listed unless the command\n\
16147 is prefixed with \"server \".\n\n\
16148 Convenience variable \"$bpnum\" contains the number of the last\n\
16149 breakpoint set."));
16150     }
16151
16152   add_info ("breakpoints", breakpoints_info, _("\
16153 Status of specified breakpoints (all user-settable breakpoints if no argument).\n\
16154 The \"Type\" column indicates one of:\n\
16155 \tbreakpoint     - normal breakpoint\n\
16156 \twatchpoint     - watchpoint\n\
16157 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
16158 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
16159 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
16160 address and file/line number respectively.\n\
16161 \n\
16162 Convenience variable \"$_\" and default examine address for \"x\"\n\
16163 are set to the address of the last breakpoint listed unless the command\n\
16164 is prefixed with \"server \".\n\n\
16165 Convenience variable \"$bpnum\" contains the number of the last\n\
16166 breakpoint set."));
16167
16168   add_info_alias ("b", "breakpoints", 1);
16169
16170   add_cmd ("breakpoints", class_maintenance, maintenance_info_breakpoints, _("\
16171 Status of all breakpoints, or breakpoint number NUMBER.\n\
16172 The \"Type\" column indicates one of:\n\
16173 \tbreakpoint     - normal breakpoint\n\
16174 \twatchpoint     - watchpoint\n\
16175 \tlongjmp        - internal breakpoint used to step through longjmp()\n\
16176 \tlongjmp resume - internal breakpoint at the target of longjmp()\n\
16177 \tuntil          - internal breakpoint used by the \"until\" command\n\
16178 \tfinish         - internal breakpoint used by the \"finish\" command\n\
16179 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
16180 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
16181 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
16182 address and file/line number respectively.\n\
16183 \n\
16184 Convenience variable \"$_\" and default examine address for \"x\"\n\
16185 are set to the address of the last breakpoint listed unless the command\n\
16186 is prefixed with \"server \".\n\n\
16187 Convenience variable \"$bpnum\" contains the number of the last\n\
16188 breakpoint set."),
16189            &maintenanceinfolist);
16190
16191   add_prefix_cmd ("catch", class_breakpoint, catch_command, _("\
16192 Set catchpoints to catch events."),
16193                   &catch_cmdlist, "catch ",
16194                   0/*allow-unknown*/, &cmdlist);
16195
16196   add_prefix_cmd ("tcatch", class_breakpoint, tcatch_command, _("\
16197 Set temporary catchpoints to catch events."),
16198                   &tcatch_cmdlist, "tcatch ",
16199                   0/*allow-unknown*/, &cmdlist);
16200
16201   add_catch_command ("fork", _("Catch calls to fork."),
16202                      catch_fork_command_1,
16203                      NULL,
16204                      (void *) (uintptr_t) catch_fork_permanent,
16205                      (void *) (uintptr_t) catch_fork_temporary);
16206   add_catch_command ("vfork", _("Catch calls to vfork."),
16207                      catch_fork_command_1,
16208                      NULL,
16209                      (void *) (uintptr_t) catch_vfork_permanent,
16210                      (void *) (uintptr_t) catch_vfork_temporary);
16211   add_catch_command ("exec", _("Catch calls to exec."),
16212                      catch_exec_command_1,
16213                      NULL,
16214                      CATCH_PERMANENT,
16215                      CATCH_TEMPORARY);
16216   add_catch_command ("load", _("Catch loads of shared libraries.\n\
16217 Usage: catch load [REGEX]\n\
16218 If REGEX is given, only stop for libraries matching the regular expression."),
16219                      catch_load_command_1,
16220                      NULL,
16221                      CATCH_PERMANENT,
16222                      CATCH_TEMPORARY);
16223   add_catch_command ("unload", _("Catch unloads of shared libraries.\n\
16224 Usage: catch unload [REGEX]\n\
16225 If REGEX is given, only stop for libraries matching the regular expression."),
16226                      catch_unload_command_1,
16227                      NULL,
16228                      CATCH_PERMANENT,
16229                      CATCH_TEMPORARY);
16230
16231   c = add_com ("watch", class_breakpoint, watch_command, _("\
16232 Set a watchpoint for an expression.\n\
16233 Usage: watch [-l|-location] EXPRESSION\n\
16234 A watchpoint stops execution of your program whenever the value of\n\
16235 an expression changes.\n\
16236 If -l or -location is given, this evaluates EXPRESSION and watches\n\
16237 the memory to which it refers."));
16238   set_cmd_completer (c, expression_completer);
16239
16240   c = add_com ("rwatch", class_breakpoint, rwatch_command, _("\
16241 Set a read watchpoint for an expression.\n\
16242 Usage: rwatch [-l|-location] EXPRESSION\n\
16243 A watchpoint stops execution of your program whenever the value of\n\
16244 an expression is read.\n\
16245 If -l or -location is given, this evaluates EXPRESSION and watches\n\
16246 the memory to which it refers."));
16247   set_cmd_completer (c, expression_completer);
16248
16249   c = add_com ("awatch", class_breakpoint, awatch_command, _("\
16250 Set a watchpoint for an expression.\n\
16251 Usage: awatch [-l|-location] EXPRESSION\n\
16252 A watchpoint stops execution of your program whenever the value of\n\
16253 an expression is either read or written.\n\
16254 If -l or -location is given, this evaluates EXPRESSION and watches\n\
16255 the memory to which it refers."));
16256   set_cmd_completer (c, expression_completer);
16257
16258   add_info ("watchpoints", watchpoints_info, _("\
16259 Status of specified watchpoints (all watchpoints if no argument)."));
16260
16261   /* XXX: cagney/2005-02-23: This should be a boolean, and should
16262      respond to changes - contrary to the description.  */
16263   add_setshow_zinteger_cmd ("can-use-hw-watchpoints", class_support,
16264                             &can_use_hw_watchpoints, _("\
16265 Set debugger's willingness to use watchpoint hardware."), _("\
16266 Show debugger's willingness to use watchpoint hardware."), _("\
16267 If zero, gdb will not use hardware for new watchpoints, even if\n\
16268 such is available.  (However, any hardware watchpoints that were\n\
16269 created before setting this to nonzero, will continue to use watchpoint\n\
16270 hardware.)"),
16271                             NULL,
16272                             show_can_use_hw_watchpoints,
16273                             &setlist, &showlist);
16274
16275   can_use_hw_watchpoints = 1;
16276
16277   /* Tracepoint manipulation commands.  */
16278
16279   c = add_com ("trace", class_breakpoint, trace_command, _("\
16280 Set a tracepoint at specified location.\n\
16281 \n"
16282 BREAK_ARGS_HELP ("trace") "\n\
16283 Do \"help tracepoints\" for info on other tracepoint commands."));
16284   set_cmd_completer (c, location_completer);
16285
16286   add_com_alias ("tp", "trace", class_alias, 0);
16287   add_com_alias ("tr", "trace", class_alias, 1);
16288   add_com_alias ("tra", "trace", class_alias, 1);
16289   add_com_alias ("trac", "trace", class_alias, 1);
16290
16291   c = add_com ("ftrace", class_breakpoint, ftrace_command, _("\
16292 Set a fast tracepoint at specified location.\n\
16293 \n"
16294 BREAK_ARGS_HELP ("ftrace") "\n\
16295 Do \"help tracepoints\" for info on other tracepoint commands."));
16296   set_cmd_completer (c, location_completer);
16297
16298   c = add_com ("strace", class_breakpoint, strace_command, _("\
16299 Set a static tracepoint at location or marker.\n\
16300 \n\
16301 strace [LOCATION] [if CONDITION]\n\
16302 LOCATION may be a linespec, explicit, or address location (described below) \n\
16303 or -m MARKER_ID.\n\n\
16304 If a marker id is specified, probe the marker with that name.  With\n\
16305 no LOCATION, uses current execution address of the selected stack frame.\n\
16306 Static tracepoints accept an extra collect action -- ``collect $_sdata''.\n\
16307 This collects arbitrary user data passed in the probe point call to the\n\
16308 tracing library.  You can inspect it when analyzing the trace buffer,\n\
16309 by printing the $_sdata variable like any other convenience variable.\n\
16310 \n\
16311 CONDITION is a boolean expression.\n\
16312 \n" LOCATION_HELP_STRING "\n\
16313 Multiple tracepoints at one place are permitted, and useful if their\n\
16314 conditions are different.\n\
16315 \n\
16316 Do \"help breakpoints\" for info on other commands dealing with breakpoints.\n\
16317 Do \"help tracepoints\" for info on other tracepoint commands."));
16318   set_cmd_completer (c, location_completer);
16319
16320   add_info ("tracepoints", tracepoints_info, _("\
16321 Status of specified tracepoints (all tracepoints if no argument).\n\
16322 Convenience variable \"$tpnum\" contains the number of the\n\
16323 last tracepoint set."));
16324
16325   add_info_alias ("tp", "tracepoints", 1);
16326
16327   add_cmd ("tracepoints", class_trace, delete_trace_command, _("\
16328 Delete specified tracepoints.\n\
16329 Arguments are tracepoint numbers, separated by spaces.\n\
16330 No argument means delete all tracepoints."),
16331            &deletelist);
16332   add_alias_cmd ("tr", "tracepoints", class_trace, 1, &deletelist);
16333
16334   c = add_cmd ("tracepoints", class_trace, disable_trace_command, _("\
16335 Disable specified tracepoints.\n\
16336 Arguments are tracepoint numbers, separated by spaces.\n\
16337 No argument means disable all tracepoints."),
16338            &disablelist);
16339   deprecate_cmd (c, "disable");
16340
16341   c = add_cmd ("tracepoints", class_trace, enable_trace_command, _("\
16342 Enable specified tracepoints.\n\
16343 Arguments are tracepoint numbers, separated by spaces.\n\
16344 No argument means enable all tracepoints."),
16345            &enablelist);
16346   deprecate_cmd (c, "enable");
16347
16348   add_com ("passcount", class_trace, trace_pass_command, _("\
16349 Set the passcount for a tracepoint.\n\
16350 The trace will end when the tracepoint has been passed 'count' times.\n\
16351 Usage: passcount COUNT TPNUM, where TPNUM may also be \"all\";\n\
16352 if TPNUM is omitted, passcount refers to the last tracepoint defined."));
16353
16354   add_prefix_cmd ("save", class_breakpoint, save_command,
16355                   _("Save breakpoint definitions as a script."),
16356                   &save_cmdlist, "save ",
16357                   0/*allow-unknown*/, &cmdlist);
16358
16359   c = add_cmd ("breakpoints", class_breakpoint, save_breakpoints_command, _("\
16360 Save current breakpoint definitions as a script.\n\
16361 This includes all types of breakpoints (breakpoints, watchpoints,\n\
16362 catchpoints, tracepoints).  Use the 'source' command in another debug\n\
16363 session to restore them."),
16364                &save_cmdlist);
16365   set_cmd_completer (c, filename_completer);
16366
16367   c = add_cmd ("tracepoints", class_trace, save_tracepoints_command, _("\
16368 Save current tracepoint definitions as a script.\n\
16369 Use the 'source' command in another debug session to restore them."),
16370                &save_cmdlist);
16371   set_cmd_completer (c, filename_completer);
16372
16373   c = add_com_alias ("save-tracepoints", "save tracepoints", class_trace, 0);
16374   deprecate_cmd (c, "save tracepoints");
16375
16376   add_prefix_cmd ("breakpoint", class_maintenance, set_breakpoint_cmd, _("\
16377 Breakpoint specific settings\n\
16378 Configure various breakpoint-specific variables such as\n\
16379 pending breakpoint behavior"),
16380                   &breakpoint_set_cmdlist, "set breakpoint ",
16381                   0/*allow-unknown*/, &setlist);
16382   add_prefix_cmd ("breakpoint", class_maintenance, show_breakpoint_cmd, _("\
16383 Breakpoint specific settings\n\
16384 Configure various breakpoint-specific variables such as\n\
16385 pending breakpoint behavior"),
16386                   &breakpoint_show_cmdlist, "show breakpoint ",
16387                   0/*allow-unknown*/, &showlist);
16388
16389   add_setshow_auto_boolean_cmd ("pending", no_class,
16390                                 &pending_break_support, _("\
16391 Set debugger's behavior regarding pending breakpoints."), _("\
16392 Show debugger's behavior regarding pending breakpoints."), _("\
16393 If on, an unrecognized breakpoint location will cause gdb to create a\n\
16394 pending breakpoint.  If off, an unrecognized breakpoint location results in\n\
16395 an error.  If auto, an unrecognized breakpoint location results in a\n\
16396 user-query to see if a pending breakpoint should be created."),
16397                                 NULL,
16398                                 show_pending_break_support,
16399                                 &breakpoint_set_cmdlist,
16400                                 &breakpoint_show_cmdlist);
16401
16402   pending_break_support = AUTO_BOOLEAN_AUTO;
16403
16404   add_setshow_boolean_cmd ("auto-hw", no_class,
16405                            &automatic_hardware_breakpoints, _("\
16406 Set automatic usage of hardware breakpoints."), _("\
16407 Show automatic usage of hardware breakpoints."), _("\
16408 If set, the debugger will automatically use hardware breakpoints for\n\
16409 breakpoints set with \"break\" but falling in read-only memory.  If not set,\n\
16410 a warning will be emitted for such breakpoints."),
16411                            NULL,
16412                            show_automatic_hardware_breakpoints,
16413                            &breakpoint_set_cmdlist,
16414                            &breakpoint_show_cmdlist);
16415
16416   add_setshow_boolean_cmd ("always-inserted", class_support,
16417                            &always_inserted_mode, _("\
16418 Set mode for inserting breakpoints."), _("\
16419 Show mode for inserting breakpoints."), _("\
16420 When this mode is on, breakpoints are inserted immediately as soon as\n\
16421 they're created, kept inserted even when execution stops, and removed\n\
16422 only when the user deletes them.  When this mode is off (the default),\n\
16423 breakpoints are inserted only when execution continues, and removed\n\
16424 when execution stops."),
16425                                 NULL,
16426                                 &show_always_inserted_mode,
16427                                 &breakpoint_set_cmdlist,
16428                                 &breakpoint_show_cmdlist);
16429
16430   add_setshow_enum_cmd ("condition-evaluation", class_breakpoint,
16431                         condition_evaluation_enums,
16432                         &condition_evaluation_mode_1, _("\
16433 Set mode of breakpoint condition evaluation."), _("\
16434 Show mode of breakpoint condition evaluation."), _("\
16435 When this is set to \"host\", breakpoint conditions will be\n\
16436 evaluated on the host's side by GDB.  When it is set to \"target\",\n\
16437 breakpoint conditions will be downloaded to the target (if the target\n\
16438 supports such feature) and conditions will be evaluated on the target's side.\n\
16439 If this is set to \"auto\" (default), this will be automatically set to\n\
16440 \"target\" if it supports condition evaluation, otherwise it will\n\
16441 be set to \"gdb\""),
16442                            &set_condition_evaluation_mode,
16443                            &show_condition_evaluation_mode,
16444                            &breakpoint_set_cmdlist,
16445                            &breakpoint_show_cmdlist);
16446
16447   add_com ("break-range", class_breakpoint, break_range_command, _("\
16448 Set a breakpoint for an address range.\n\
16449 break-range START-LOCATION, END-LOCATION\n\
16450 where START-LOCATION and END-LOCATION can be one of the following:\n\
16451   LINENUM, for that line in the current file,\n\
16452   FILE:LINENUM, for that line in that file,\n\
16453   +OFFSET, for that number of lines after the current line\n\
16454            or the start of the range\n\
16455   FUNCTION, for the first line in that function,\n\
16456   FILE:FUNCTION, to distinguish among like-named static functions.\n\
16457   *ADDRESS, for the instruction at that address.\n\
16458 \n\
16459 The breakpoint will stop execution of the inferior whenever it executes\n\
16460 an instruction at any address within the [START-LOCATION, END-LOCATION]\n\
16461 range (including START-LOCATION and END-LOCATION)."));
16462
16463   c = add_com ("dprintf", class_breakpoint, dprintf_command, _("\
16464 Set a dynamic printf at specified location.\n\
16465 dprintf location,format string,arg1,arg2,...\n\
16466 location may be a linespec, explicit, or address location.\n"
16467 "\n" LOCATION_HELP_STRING));
16468   set_cmd_completer (c, location_completer);
16469
16470   add_setshow_enum_cmd ("dprintf-style", class_support,
16471                         dprintf_style_enums, &dprintf_style, _("\
16472 Set the style of usage for dynamic printf."), _("\
16473 Show the style of usage for dynamic printf."), _("\
16474 This setting chooses how GDB will do a dynamic printf.\n\
16475 If the value is \"gdb\", then the printing is done by GDB to its own\n\
16476 console, as with the \"printf\" command.\n\
16477 If the value is \"call\", the print is done by calling a function in your\n\
16478 program; by default printf(), but you can choose a different function or\n\
16479 output stream by setting dprintf-function and dprintf-channel."),
16480                         update_dprintf_commands, NULL,
16481                         &setlist, &showlist);
16482
16483   dprintf_function = xstrdup ("printf");
16484   add_setshow_string_cmd ("dprintf-function", class_support,
16485                           &dprintf_function, _("\
16486 Set the function to use for dynamic printf"), _("\
16487 Show the function to use for dynamic printf"), NULL,
16488                           update_dprintf_commands, NULL,
16489                           &setlist, &showlist);
16490
16491   dprintf_channel = xstrdup ("");
16492   add_setshow_string_cmd ("dprintf-channel", class_support,
16493                           &dprintf_channel, _("\
16494 Set the channel to use for dynamic printf"), _("\
16495 Show the channel to use for dynamic printf"), NULL,
16496                           update_dprintf_commands, NULL,
16497                           &setlist, &showlist);
16498
16499   add_setshow_boolean_cmd ("disconnected-dprintf", no_class,
16500                            &disconnected_dprintf, _("\
16501 Set whether dprintf continues after GDB disconnects."), _("\
16502 Show whether dprintf continues after GDB disconnects."), _("\
16503 Use this to let dprintf commands continue to hit and produce output\n\
16504 even if GDB disconnects or detaches from the target."),
16505                            NULL,
16506                            NULL,
16507                            &setlist, &showlist);
16508
16509   add_com ("agent-printf", class_vars, agent_printf_command, _("\
16510 agent-printf \"printf format string\", arg1, arg2, arg3, ..., argn\n\
16511 (target agent only) This is useful for formatted output in user-defined commands."));
16512
16513   automatic_hardware_breakpoints = 1;
16514
16515   observer_attach_about_to_proceed (breakpoint_about_to_proceed);
16516   observer_attach_thread_exit (remove_threaded_breakpoints);
16517 }