c0ab1d76241d90be28f88baf0731213598de7faf
[external/binutils.git] / gdb / breakpoint.c
1 /* Everything about breakpoints, for GDB.
2
3    Copyright (C) 1986-2015 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 "xml-syscall.h"
60 #include "parser-defs.h"
61 #include "gdb_regex.h"
62 #include "probe.h"
63 #include "cli/cli-utils.h"
64 #include "continuations.h"
65 #include "stack.h"
66 #include "skip.h"
67 #include "ax-gdb.h"
68 #include "dummy-frame.h"
69 #include "interps.h"
70 #include "format.h"
71
72 /* readline include files */
73 #include "readline/readline.h"
74 #include "readline/history.h"
75
76 /* readline defines this.  */
77 #undef savestring
78
79 #include "mi/mi-common.h"
80 #include "extension.h"
81
82 /* Enums for exception-handling support.  */
83 enum exception_event_kind
84 {
85   EX_EVENT_THROW,
86   EX_EVENT_RETHROW,
87   EX_EVENT_CATCH
88 };
89
90 /* Prototypes for local functions.  */
91
92 static void enable_delete_command (char *, int);
93
94 static void enable_once_command (char *, int);
95
96 static void enable_count_command (char *, int);
97
98 static void disable_command (char *, int);
99
100 static void enable_command (char *, int);
101
102 static void map_breakpoint_numbers (char *, void (*) (struct breakpoint *,
103                                                       void *),
104                                     void *);
105
106 static void ignore_command (char *, int);
107
108 static int breakpoint_re_set_one (void *);
109
110 static void breakpoint_re_set_default (struct breakpoint *);
111
112 static void create_sals_from_address_default (char **,
113                                               struct linespec_result *,
114                                               enum bptype, char *,
115                                               char **);
116
117 static void create_breakpoints_sal_default (struct gdbarch *,
118                                             struct linespec_result *,
119                                             char *, char *, enum bptype,
120                                             enum bpdisp, int, int,
121                                             int,
122                                             const struct breakpoint_ops *,
123                                             int, int, int, unsigned);
124
125 static void decode_linespec_default (struct breakpoint *, char **,
126                                      struct symtabs_and_lines *);
127
128 static void clear_command (char *, int);
129
130 static void catch_command (char *, int);
131
132 static int can_use_hardware_watchpoint (struct value *);
133
134 static void break_command_1 (char *, int, int);
135
136 static void mention (struct breakpoint *);
137
138 static struct breakpoint *set_raw_breakpoint_without_location (struct gdbarch *,
139                                                                enum bptype,
140                                                                const struct breakpoint_ops *);
141 static struct bp_location *add_location_to_breakpoint (struct breakpoint *,
142                                                        const struct symtab_and_line *);
143
144 /* This function is used in gdbtk sources and thus can not be made
145    static.  */
146 struct breakpoint *set_raw_breakpoint (struct gdbarch *gdbarch,
147                                        struct symtab_and_line,
148                                        enum bptype,
149                                        const struct breakpoint_ops *);
150
151 static struct breakpoint *
152   momentary_breakpoint_from_master (struct breakpoint *orig,
153                                     enum bptype type,
154                                     const struct breakpoint_ops *ops,
155                                     int loc_enabled);
156
157 static void breakpoint_adjustment_warning (CORE_ADDR, CORE_ADDR, int, int);
158
159 static CORE_ADDR adjust_breakpoint_address (struct gdbarch *gdbarch,
160                                             CORE_ADDR bpaddr,
161                                             enum bptype bptype);
162
163 static void describe_other_breakpoints (struct gdbarch *,
164                                         struct program_space *, CORE_ADDR,
165                                         struct obj_section *, int);
166
167 static int watchpoint_locations_match (struct bp_location *loc1,
168                                        struct bp_location *loc2);
169
170 static int breakpoint_location_address_match (struct bp_location *bl,
171                                               struct address_space *aspace,
172                                               CORE_ADDR addr);
173
174 static void breakpoints_info (char *, int);
175
176 static void watchpoints_info (char *, int);
177
178 static int breakpoint_1 (char *, int, 
179                          int (*) (const struct breakpoint *));
180
181 static int breakpoint_cond_eval (void *);
182
183 static void cleanup_executing_breakpoints (void *);
184
185 static void commands_command (char *, int);
186
187 static void condition_command (char *, int);
188
189 typedef enum
190   {
191     mark_inserted,
192     mark_uninserted
193   }
194 insertion_state_t;
195
196 static int remove_breakpoint (struct bp_location *, insertion_state_t);
197 static int remove_breakpoint_1 (struct bp_location *, insertion_state_t);
198
199 static enum print_stop_action print_bp_stop_message (bpstat bs);
200
201 static int watchpoint_check (void *);
202
203 static void maintenance_info_breakpoints (char *, int);
204
205 static int hw_breakpoint_used_count (void);
206
207 static int hw_watchpoint_use_count (struct breakpoint *);
208
209 static int hw_watchpoint_used_count_others (struct breakpoint *except,
210                                             enum bptype type,
211                                             int *other_type_used);
212
213 static void hbreak_command (char *, int);
214
215 static void thbreak_command (char *, int);
216
217 static void enable_breakpoint_disp (struct breakpoint *, enum bpdisp,
218                                     int count);
219
220 static void stop_command (char *arg, int from_tty);
221
222 static void stopin_command (char *arg, int from_tty);
223
224 static void stopat_command (char *arg, int from_tty);
225
226 static void tcatch_command (char *arg, int from_tty);
227
228 static void free_bp_location (struct bp_location *loc);
229 static void incref_bp_location (struct bp_location *loc);
230 static void decref_bp_location (struct bp_location **loc);
231
232 static struct bp_location *allocate_bp_location (struct breakpoint *bpt);
233
234 /* update_global_location_list's modes of operation wrt to whether to
235    insert locations now.  */
236 enum ugll_insert_mode
237 {
238   /* Don't insert any breakpoint locations into the inferior, only
239      remove already-inserted locations that no longer should be
240      inserted.  Functions that delete a breakpoint or breakpoints
241      should specify this mode, so that deleting a breakpoint doesn't
242      have the side effect of inserting the locations of other
243      breakpoints that are marked not-inserted, but should_be_inserted
244      returns true on them.
245
246      This behavior is useful is situations close to tear-down -- e.g.,
247      after an exec, while the target still has execution, but
248      breakpoint shadows of the previous executable image should *NOT*
249      be restored to the new image; or before detaching, where the
250      target still has execution and wants to delete breakpoints from
251      GDB's lists, and all breakpoints had already been removed from
252      the inferior.  */
253   UGLL_DONT_INSERT,
254
255   /* May insert breakpoints iff breakpoints_should_be_inserted_now
256      claims breakpoints should be inserted now.  */
257   UGLL_MAY_INSERT,
258
259   /* Insert locations now, irrespective of
260      breakpoints_should_be_inserted_now.  E.g., say all threads are
261      stopped right now, and the user did "continue".  We need to
262      insert breakpoints _before_ resuming the target, but
263      UGLL_MAY_INSERT wouldn't insert them, because
264      breakpoints_should_be_inserted_now returns false at that point,
265      as no thread is running yet.  */
266   UGLL_INSERT
267 };
268
269 static void update_global_location_list (enum ugll_insert_mode);
270
271 static void update_global_location_list_nothrow (enum ugll_insert_mode);
272
273 static int is_hardware_watchpoint (const struct breakpoint *bpt);
274
275 static void insert_breakpoint_locations (void);
276
277 static int syscall_catchpoint_p (struct breakpoint *b);
278
279 static void tracepoints_info (char *, int);
280
281 static void delete_trace_command (char *, int);
282
283 static void enable_trace_command (char *, int);
284
285 static void disable_trace_command (char *, int);
286
287 static void trace_pass_command (char *, int);
288
289 static void set_tracepoint_count (int num);
290
291 static int is_masked_watchpoint (const struct breakpoint *b);
292
293 static struct bp_location **get_first_locp_gte_addr (CORE_ADDR address);
294
295 /* Return 1 if B refers to a static tracepoint set by marker ("-m"), zero
296    otherwise.  */
297
298 static int strace_marker_p (struct breakpoint *b);
299
300 /* The breakpoint_ops structure to be inherited by all breakpoint_ops
301    that are implemented on top of software or hardware breakpoints
302    (user breakpoints, internal and momentary breakpoints, etc.).  */
303 static struct breakpoint_ops bkpt_base_breakpoint_ops;
304
305 /* Internal breakpoints class type.  */
306 static struct breakpoint_ops internal_breakpoint_ops;
307
308 /* Momentary breakpoints class type.  */
309 static struct breakpoint_ops momentary_breakpoint_ops;
310
311 /* Momentary breakpoints for bp_longjmp and bp_exception class type.  */
312 static struct breakpoint_ops longjmp_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       if (always_inserted_mode)
475         {
476           /* The user wants breakpoints inserted even if all threads
477              are stopped.  */
478           return 1;
479         }
480
481       if (threads_are_executing ())
482         return 1;
483     }
484   return 0;
485 }
486
487 static const char condition_evaluation_both[] = "host or target";
488
489 /* Modes for breakpoint condition evaluation.  */
490 static const char condition_evaluation_auto[] = "auto";
491 static const char condition_evaluation_host[] = "host";
492 static const char condition_evaluation_target[] = "target";
493 static const char *const condition_evaluation_enums[] = {
494   condition_evaluation_auto,
495   condition_evaluation_host,
496   condition_evaluation_target,
497   NULL
498 };
499
500 /* Global that holds the current mode for breakpoint condition evaluation.  */
501 static const char *condition_evaluation_mode_1 = condition_evaluation_auto;
502
503 /* Global that we use to display information to the user (gets its value from
504    condition_evaluation_mode_1.  */
505 static const char *condition_evaluation_mode = condition_evaluation_auto;
506
507 /* Translate a condition evaluation mode MODE into either "host"
508    or "target".  This is used mostly to translate from "auto" to the
509    real setting that is being used.  It returns the translated
510    evaluation mode.  */
511
512 static const char *
513 translate_condition_evaluation_mode (const char *mode)
514 {
515   if (mode == condition_evaluation_auto)
516     {
517       if (target_supports_evaluation_of_breakpoint_conditions ())
518         return condition_evaluation_target;
519       else
520         return condition_evaluation_host;
521     }
522   else
523     return mode;
524 }
525
526 /* Discovers what condition_evaluation_auto translates to.  */
527
528 static const char *
529 breakpoint_condition_evaluation_mode (void)
530 {
531   return translate_condition_evaluation_mode (condition_evaluation_mode);
532 }
533
534 /* Return true if GDB should evaluate breakpoint conditions or false
535    otherwise.  */
536
537 static int
538 gdb_evaluates_breakpoint_condition_p (void)
539 {
540   const char *mode = breakpoint_condition_evaluation_mode ();
541
542   return (mode == condition_evaluation_host);
543 }
544
545 void _initialize_breakpoint (void);
546
547 /* Are we executing breakpoint commands?  */
548 static int executing_breakpoint_commands;
549
550 /* Are overlay event breakpoints enabled? */
551 static int overlay_events_enabled;
552
553 /* See description in breakpoint.h. */
554 int target_exact_watchpoints = 0;
555
556 /* Walk the following statement or block through all breakpoints.
557    ALL_BREAKPOINTS_SAFE does so even if the statement deletes the
558    current breakpoint.  */
559
560 #define ALL_BREAKPOINTS(B)  for (B = breakpoint_chain; B; B = B->next)
561
562 #define ALL_BREAKPOINTS_SAFE(B,TMP)     \
563         for (B = breakpoint_chain;      \
564              B ? (TMP=B->next, 1): 0;   \
565              B = TMP)
566
567 /* Similar iterator for the low-level breakpoints.  SAFE variant is
568    not provided so update_global_location_list must not be called
569    while executing the block of ALL_BP_LOCATIONS.  */
570
571 #define ALL_BP_LOCATIONS(B,BP_TMP)                                      \
572         for (BP_TMP = bp_location;                                      \
573              BP_TMP < bp_location + bp_location_count && (B = *BP_TMP); \
574              BP_TMP++)
575
576 /* Iterates through locations with address ADDRESS for the currently selected
577    program space.  BP_LOCP_TMP points to each object.  BP_LOCP_START points
578    to where the loop should start from.
579    If BP_LOCP_START is a NULL pointer, the macro automatically seeks the
580    appropriate location to start with.  */
581
582 #define ALL_BP_LOCATIONS_AT_ADDR(BP_LOCP_TMP, BP_LOCP_START, ADDRESS)   \
583         for (BP_LOCP_START = BP_LOCP_START == NULL ? get_first_locp_gte_addr (ADDRESS) : BP_LOCP_START, \
584              BP_LOCP_TMP = BP_LOCP_START;                               \
585              BP_LOCP_START                                              \
586              && (BP_LOCP_TMP < bp_location + bp_location_count          \
587              && (*BP_LOCP_TMP)->address == ADDRESS);                    \
588              BP_LOCP_TMP++)
589
590 /* Iterator for tracepoints only.  */
591
592 #define ALL_TRACEPOINTS(B)  \
593   for (B = breakpoint_chain; B; B = B->next)  \
594     if (is_tracepoint (B))
595
596 /* Chains of all breakpoints defined.  */
597
598 struct breakpoint *breakpoint_chain;
599
600 /* Array is sorted by bp_location_compare - primarily by the ADDRESS.  */
601
602 static struct bp_location **bp_location;
603
604 /* Number of elements of BP_LOCATION.  */
605
606 static unsigned bp_location_count;
607
608 /* Maximum alignment offset between bp_target_info.PLACED_ADDRESS and
609    ADDRESS for the current elements of BP_LOCATION which get a valid
610    result from bp_location_has_shadow.  You can use it for roughly
611    limiting the subrange of BP_LOCATION to scan for shadow bytes for
612    an address you need to read.  */
613
614 static CORE_ADDR bp_location_placed_address_before_address_max;
615
616 /* Maximum offset plus alignment between bp_target_info.PLACED_ADDRESS
617    + bp_target_info.SHADOW_LEN and ADDRESS for the current elements of
618    BP_LOCATION which get a valid result from bp_location_has_shadow.
619    You can use it for roughly limiting the subrange of BP_LOCATION to
620    scan for shadow bytes for an address you need to read.  */
621
622 static CORE_ADDR bp_location_shadow_len_after_address_max;
623
624 /* The locations that no longer correspond to any breakpoint, unlinked
625    from bp_location array, but for which a hit may still be reported
626    by a target.  */
627 VEC(bp_location_p) *moribund_locations = NULL;
628
629 /* Number of last breakpoint made.  */
630
631 static int breakpoint_count;
632
633 /* The value of `breakpoint_count' before the last command that
634    created breakpoints.  If the last (break-like) command created more
635    than one breakpoint, then the difference between BREAKPOINT_COUNT
636    and PREV_BREAKPOINT_COUNT is more than one.  */
637 static int prev_breakpoint_count;
638
639 /* Number of last tracepoint made.  */
640
641 static int tracepoint_count;
642
643 static struct cmd_list_element *breakpoint_set_cmdlist;
644 static struct cmd_list_element *breakpoint_show_cmdlist;
645 struct cmd_list_element *save_cmdlist;
646
647 /* See declaration at breakpoint.h.  */
648
649 struct breakpoint *
650 breakpoint_find_if (int (*func) (struct breakpoint *b, void *d),
651                     void *user_data)
652 {
653   struct breakpoint *b = NULL;
654
655   ALL_BREAKPOINTS (b)
656     {
657       if (func (b, user_data) != 0)
658         break;
659     }
660
661   return b;
662 }
663
664 /* Return whether a breakpoint is an active enabled breakpoint.  */
665 static int
666 breakpoint_enabled (struct breakpoint *b)
667 {
668   return (b->enable_state == bp_enabled);
669 }
670
671 /* Set breakpoint count to NUM.  */
672
673 static void
674 set_breakpoint_count (int num)
675 {
676   prev_breakpoint_count = breakpoint_count;
677   breakpoint_count = num;
678   set_internalvar_integer (lookup_internalvar ("bpnum"), num);
679 }
680
681 /* Used by `start_rbreak_breakpoints' below, to record the current
682    breakpoint count before "rbreak" creates any breakpoint.  */
683 static int rbreak_start_breakpoint_count;
684
685 /* Called at the start an "rbreak" command to record the first
686    breakpoint made.  */
687
688 void
689 start_rbreak_breakpoints (void)
690 {
691   rbreak_start_breakpoint_count = breakpoint_count;
692 }
693
694 /* Called at the end of an "rbreak" command to record the last
695    breakpoint made.  */
696
697 void
698 end_rbreak_breakpoints (void)
699 {
700   prev_breakpoint_count = rbreak_start_breakpoint_count;
701 }
702
703 /* Used in run_command to zero the hit count when a new run starts.  */
704
705 void
706 clear_breakpoint_hit_counts (void)
707 {
708   struct breakpoint *b;
709
710   ALL_BREAKPOINTS (b)
711     b->hit_count = 0;
712 }
713
714 /* Allocate a new counted_command_line with reference count of 1.
715    The new structure owns COMMANDS.  */
716
717 static struct counted_command_line *
718 alloc_counted_command_line (struct command_line *commands)
719 {
720   struct counted_command_line *result
721     = xmalloc (sizeof (struct counted_command_line));
722
723   result->refc = 1;
724   result->commands = commands;
725   return result;
726 }
727
728 /* Increment reference count.  This does nothing if CMD is NULL.  */
729
730 static void
731 incref_counted_command_line (struct counted_command_line *cmd)
732 {
733   if (cmd)
734     ++cmd->refc;
735 }
736
737 /* Decrement reference count.  If the reference count reaches 0,
738    destroy the counted_command_line.  Sets *CMDP to NULL.  This does
739    nothing if *CMDP is NULL.  */
740
741 static void
742 decref_counted_command_line (struct counted_command_line **cmdp)
743 {
744   if (*cmdp)
745     {
746       if (--(*cmdp)->refc == 0)
747         {
748           free_command_lines (&(*cmdp)->commands);
749           xfree (*cmdp);
750         }
751       *cmdp = NULL;
752     }
753 }
754
755 /* A cleanup function that calls decref_counted_command_line.  */
756
757 static void
758 do_cleanup_counted_command_line (void *arg)
759 {
760   decref_counted_command_line (arg);
761 }
762
763 /* Create a cleanup that calls decref_counted_command_line on the
764    argument.  */
765
766 static struct cleanup *
767 make_cleanup_decref_counted_command_line (struct counted_command_line **cmdp)
768 {
769   return make_cleanup (do_cleanup_counted_command_line, cmdp);
770 }
771
772 \f
773 /* Return the breakpoint with the specified number, or NULL
774    if the number does not refer to an existing breakpoint.  */
775
776 struct breakpoint *
777 get_breakpoint (int num)
778 {
779   struct breakpoint *b;
780
781   ALL_BREAKPOINTS (b)
782     if (b->number == num)
783       return b;
784   
785   return NULL;
786 }
787
788 \f
789
790 /* Mark locations as "conditions have changed" in case the target supports
791    evaluating conditions on its side.  */
792
793 static void
794 mark_breakpoint_modified (struct breakpoint *b)
795 {
796   struct bp_location *loc;
797
798   /* This is only meaningful if the target is
799      evaluating conditions and if the user has
800      opted for condition evaluation on the target's
801      side.  */
802   if (gdb_evaluates_breakpoint_condition_p ()
803       || !target_supports_evaluation_of_breakpoint_conditions ())
804     return;
805
806   if (!is_breakpoint (b))
807     return;
808
809   for (loc = b->loc; loc; loc = loc->next)
810     loc->condition_changed = condition_modified;
811 }
812
813 /* Mark location as "conditions have changed" in case the target supports
814    evaluating conditions on its side.  */
815
816 static void
817 mark_breakpoint_location_modified (struct bp_location *loc)
818 {
819   /* This is only meaningful if the target is
820      evaluating conditions and if the user has
821      opted for condition evaluation on the target's
822      side.  */
823   if (gdb_evaluates_breakpoint_condition_p ()
824       || !target_supports_evaluation_of_breakpoint_conditions ())
825
826     return;
827
828   if (!is_breakpoint (loc->owner))
829     return;
830
831   loc->condition_changed = condition_modified;
832 }
833
834 /* Sets the condition-evaluation mode using the static global
835    condition_evaluation_mode.  */
836
837 static void
838 set_condition_evaluation_mode (char *args, int from_tty,
839                                struct cmd_list_element *c)
840 {
841   const char *old_mode, *new_mode;
842
843   if ((condition_evaluation_mode_1 == condition_evaluation_target)
844       && !target_supports_evaluation_of_breakpoint_conditions ())
845     {
846       condition_evaluation_mode_1 = condition_evaluation_mode;
847       warning (_("Target does not support breakpoint condition evaluation.\n"
848                  "Using host evaluation mode instead."));
849       return;
850     }
851
852   new_mode = translate_condition_evaluation_mode (condition_evaluation_mode_1);
853   old_mode = translate_condition_evaluation_mode (condition_evaluation_mode);
854
855   /* Flip the switch.  Flip it even if OLD_MODE == NEW_MODE as one of the
856      settings was "auto".  */
857   condition_evaluation_mode = condition_evaluation_mode_1;
858
859   /* Only update the mode if the user picked a different one.  */
860   if (new_mode != old_mode)
861     {
862       struct bp_location *loc, **loc_tmp;
863       /* If the user switched to a different evaluation mode, we
864          need to synch the changes with the target as follows:
865
866          "host" -> "target": Send all (valid) conditions to the target.
867          "target" -> "host": Remove all the conditions from the target.
868       */
869
870       if (new_mode == condition_evaluation_target)
871         {
872           /* Mark everything modified and synch conditions with the
873              target.  */
874           ALL_BP_LOCATIONS (loc, loc_tmp)
875             mark_breakpoint_location_modified (loc);
876         }
877       else
878         {
879           /* Manually mark non-duplicate locations to synch conditions
880              with the target.  We do this to remove all the conditions the
881              target knows about.  */
882           ALL_BP_LOCATIONS (loc, loc_tmp)
883             if (is_breakpoint (loc->owner) && loc->inserted)
884               loc->needs_update = 1;
885         }
886
887       /* Do the update.  */
888       update_global_location_list (UGLL_MAY_INSERT);
889     }
890
891   return;
892 }
893
894 /* Shows the current mode of breakpoint condition evaluation.  Explicitly shows
895    what "auto" is translating to.  */
896
897 static void
898 show_condition_evaluation_mode (struct ui_file *file, int from_tty,
899                                 struct cmd_list_element *c, const char *value)
900 {
901   if (condition_evaluation_mode == condition_evaluation_auto)
902     fprintf_filtered (file,
903                       _("Breakpoint condition evaluation "
904                         "mode is %s (currently %s).\n"),
905                       value,
906                       breakpoint_condition_evaluation_mode ());
907   else
908     fprintf_filtered (file, _("Breakpoint condition evaluation mode is %s.\n"),
909                       value);
910 }
911
912 /* A comparison function for bp_location AP and BP that is used by
913    bsearch.  This comparison function only cares about addresses, unlike
914    the more general bp_location_compare function.  */
915
916 static int
917 bp_location_compare_addrs (const void *ap, const void *bp)
918 {
919   struct bp_location *a = *(void **) ap;
920   struct bp_location *b = *(void **) bp;
921
922   if (a->address == b->address)
923     return 0;
924   else
925     return ((a->address > b->address) - (a->address < b->address));
926 }
927
928 /* Helper function to skip all bp_locations with addresses
929    less than ADDRESS.  It returns the first bp_location that
930    is greater than or equal to ADDRESS.  If none is found, just
931    return NULL.  */
932
933 static struct bp_location **
934 get_first_locp_gte_addr (CORE_ADDR address)
935 {
936   struct bp_location dummy_loc;
937   struct bp_location *dummy_locp = &dummy_loc;
938   struct bp_location **locp_found = NULL;
939
940   /* Initialize the dummy location's address field.  */
941   memset (&dummy_loc, 0, sizeof (struct bp_location));
942   dummy_loc.address = address;
943
944   /* Find a close match to the first location at ADDRESS.  */
945   locp_found = bsearch (&dummy_locp, bp_location, bp_location_count,
946                         sizeof (struct bp_location **),
947                         bp_location_compare_addrs);
948
949   /* Nothing was found, nothing left to do.  */
950   if (locp_found == NULL)
951     return NULL;
952
953   /* We may have found a location that is at ADDRESS but is not the first in the
954      location's list.  Go backwards (if possible) and locate the first one.  */
955   while ((locp_found - 1) >= bp_location
956          && (*(locp_found - 1))->address == address)
957     locp_found--;
958
959   return locp_found;
960 }
961
962 void
963 set_breakpoint_condition (struct breakpoint *b, char *exp,
964                           int from_tty)
965 {
966   xfree (b->cond_string);
967   b->cond_string = NULL;
968
969   if (is_watchpoint (b))
970     {
971       struct watchpoint *w = (struct watchpoint *) b;
972
973       xfree (w->cond_exp);
974       w->cond_exp = NULL;
975     }
976   else
977     {
978       struct bp_location *loc;
979
980       for (loc = b->loc; loc; loc = loc->next)
981         {
982           xfree (loc->cond);
983           loc->cond = NULL;
984
985           /* No need to free the condition agent expression
986              bytecode (if we have one).  We will handle this
987              when we go through update_global_location_list.  */
988         }
989     }
990
991   if (*exp == 0)
992     {
993       if (from_tty)
994         printf_filtered (_("Breakpoint %d now unconditional.\n"), b->number);
995     }
996   else
997     {
998       const char *arg = exp;
999
1000       /* I don't know if it matters whether this is the string the user
1001          typed in or the decompiled expression.  */
1002       b->cond_string = xstrdup (arg);
1003       b->condition_not_parsed = 0;
1004
1005       if (is_watchpoint (b))
1006         {
1007           struct watchpoint *w = (struct watchpoint *) b;
1008
1009           innermost_block = NULL;
1010           arg = exp;
1011           w->cond_exp = parse_exp_1 (&arg, 0, 0, 0);
1012           if (*arg)
1013             error (_("Junk at end of expression"));
1014           w->cond_exp_valid_block = innermost_block;
1015         }
1016       else
1017         {
1018           struct bp_location *loc;
1019
1020           for (loc = b->loc; loc; loc = loc->next)
1021             {
1022               arg = exp;
1023               loc->cond =
1024                 parse_exp_1 (&arg, loc->address,
1025                              block_for_pc (loc->address), 0);
1026               if (*arg)
1027                 error (_("Junk at end of expression"));
1028             }
1029         }
1030     }
1031   mark_breakpoint_modified (b);
1032
1033   observer_notify_breakpoint_modified (b);
1034 }
1035
1036 /* Completion for the "condition" command.  */
1037
1038 static VEC (char_ptr) *
1039 condition_completer (struct cmd_list_element *cmd,
1040                      const char *text, const char *word)
1041 {
1042   const char *space;
1043
1044   text = skip_spaces_const (text);
1045   space = skip_to_space_const (text);
1046   if (*space == '\0')
1047     {
1048       int len;
1049       struct breakpoint *b;
1050       VEC (char_ptr) *result = NULL;
1051
1052       if (text[0] == '$')
1053         {
1054           /* We don't support completion of history indices.  */
1055           if (isdigit (text[1]))
1056             return NULL;
1057           return complete_internalvar (&text[1]);
1058         }
1059
1060       /* We're completing the breakpoint number.  */
1061       len = strlen (text);
1062
1063       ALL_BREAKPOINTS (b)
1064         {
1065           char number[50];
1066
1067           xsnprintf (number, sizeof (number), "%d", b->number);
1068
1069           if (strncmp (number, text, len) == 0)
1070             VEC_safe_push (char_ptr, result, xstrdup (number));
1071         }
1072
1073       return result;
1074     }
1075
1076   /* We're completing the expression part.  */
1077   text = skip_spaces_const (space);
1078   return expression_completer (cmd, text, word);
1079 }
1080
1081 /* condition N EXP -- set break condition of breakpoint N to EXP.  */
1082
1083 static void
1084 condition_command (char *arg, int from_tty)
1085 {
1086   struct breakpoint *b;
1087   char *p;
1088   int bnum;
1089
1090   if (arg == 0)
1091     error_no_arg (_("breakpoint number"));
1092
1093   p = arg;
1094   bnum = get_number (&p);
1095   if (bnum == 0)
1096     error (_("Bad breakpoint argument: '%s'"), arg);
1097
1098   ALL_BREAKPOINTS (b)
1099     if (b->number == bnum)
1100       {
1101         /* Check if this breakpoint has a "stop" method implemented in an
1102            extension language.  This method and conditions entered into GDB
1103            from the CLI are mutually exclusive.  */
1104         const struct extension_language_defn *extlang
1105           = get_breakpoint_cond_ext_lang (b, EXT_LANG_NONE);
1106
1107         if (extlang != NULL)
1108           {
1109             error (_("Only one stop condition allowed.  There is currently"
1110                      " a %s stop condition defined for this breakpoint."),
1111                    ext_lang_capitalized_name (extlang));
1112           }
1113         set_breakpoint_condition (b, p, from_tty);
1114
1115         if (is_breakpoint (b))
1116           update_global_location_list (UGLL_MAY_INSERT);
1117
1118         return;
1119       }
1120
1121   error (_("No breakpoint number %d."), bnum);
1122 }
1123
1124 /* Check that COMMAND do not contain commands that are suitable
1125    only for tracepoints and not suitable for ordinary breakpoints.
1126    Throw if any such commands is found.  */
1127
1128 static void
1129 check_no_tracepoint_commands (struct command_line *commands)
1130 {
1131   struct command_line *c;
1132
1133   for (c = commands; c; c = c->next)
1134     {
1135       int i;
1136
1137       if (c->control_type == while_stepping_control)
1138         error (_("The 'while-stepping' command can "
1139                  "only be used for tracepoints"));
1140
1141       for (i = 0; i < c->body_count; ++i)
1142         check_no_tracepoint_commands ((c->body_list)[i]);
1143
1144       /* Not that command parsing removes leading whitespace and comment
1145          lines and also empty lines.  So, we only need to check for
1146          command directly.  */
1147       if (strstr (c->line, "collect ") == c->line)
1148         error (_("The 'collect' command can only be used for tracepoints"));
1149
1150       if (strstr (c->line, "teval ") == c->line)
1151         error (_("The 'teval' command can only be used for tracepoints"));
1152     }
1153 }
1154
1155 /* Encapsulate tests for different types of tracepoints.  */
1156
1157 static int
1158 is_tracepoint_type (enum bptype type)
1159 {
1160   return (type == bp_tracepoint
1161           || type == bp_fast_tracepoint
1162           || type == bp_static_tracepoint);
1163 }
1164
1165 int
1166 is_tracepoint (const struct breakpoint *b)
1167 {
1168   return is_tracepoint_type (b->type);
1169 }
1170
1171 /* A helper function that validates that COMMANDS are valid for a
1172    breakpoint.  This function will throw an exception if a problem is
1173    found.  */
1174
1175 static void
1176 validate_commands_for_breakpoint (struct breakpoint *b,
1177                                   struct command_line *commands)
1178 {
1179   if (is_tracepoint (b))
1180     {
1181       struct tracepoint *t = (struct tracepoint *) b;
1182       struct command_line *c;
1183       struct command_line *while_stepping = 0;
1184
1185       /* Reset the while-stepping step count.  The previous commands
1186          might have included a while-stepping action, while the new
1187          ones might not.  */
1188       t->step_count = 0;
1189
1190       /* We need to verify that each top-level element of commands is
1191          valid for tracepoints, that there's at most one
1192          while-stepping element, and that the while-stepping's body
1193          has valid tracing commands excluding nested while-stepping.
1194          We also need to validate the tracepoint action line in the
1195          context of the tracepoint --- validate_actionline actually
1196          has side effects, like setting the tracepoint's
1197          while-stepping STEP_COUNT, in addition to checking if the
1198          collect/teval actions parse and make sense in the
1199          tracepoint's context.  */
1200       for (c = commands; c; c = c->next)
1201         {
1202           if (c->control_type == while_stepping_control)
1203             {
1204               if (b->type == bp_fast_tracepoint)
1205                 error (_("The 'while-stepping' command "
1206                          "cannot be used for fast tracepoint"));
1207               else if (b->type == bp_static_tracepoint)
1208                 error (_("The 'while-stepping' command "
1209                          "cannot be used for static tracepoint"));
1210
1211               if (while_stepping)
1212                 error (_("The 'while-stepping' command "
1213                          "can be used only once"));
1214               else
1215                 while_stepping = c;
1216             }
1217
1218           validate_actionline (c->line, b);
1219         }
1220       if (while_stepping)
1221         {
1222           struct command_line *c2;
1223
1224           gdb_assert (while_stepping->body_count == 1);
1225           c2 = while_stepping->body_list[0];
1226           for (; c2; c2 = c2->next)
1227             {
1228               if (c2->control_type == while_stepping_control)
1229                 error (_("The 'while-stepping' command cannot be nested"));
1230             }
1231         }
1232     }
1233   else
1234     {
1235       check_no_tracepoint_commands (commands);
1236     }
1237 }
1238
1239 /* Return a vector of all the static tracepoints set at ADDR.  The
1240    caller is responsible for releasing the vector.  */
1241
1242 VEC(breakpoint_p) *
1243 static_tracepoints_here (CORE_ADDR addr)
1244 {
1245   struct breakpoint *b;
1246   VEC(breakpoint_p) *found = 0;
1247   struct bp_location *loc;
1248
1249   ALL_BREAKPOINTS (b)
1250     if (b->type == bp_static_tracepoint)
1251       {
1252         for (loc = b->loc; loc; loc = loc->next)
1253           if (loc->address == addr)
1254             VEC_safe_push(breakpoint_p, found, b);
1255       }
1256
1257   return found;
1258 }
1259
1260 /* Set the command list of B to COMMANDS.  If breakpoint is tracepoint,
1261    validate that only allowed commands are included.  */
1262
1263 void
1264 breakpoint_set_commands (struct breakpoint *b, 
1265                          struct command_line *commands)
1266 {
1267   validate_commands_for_breakpoint (b, commands);
1268
1269   decref_counted_command_line (&b->commands);
1270   b->commands = alloc_counted_command_line (commands);
1271   observer_notify_breakpoint_modified (b);
1272 }
1273
1274 /* Set the internal `silent' flag on the breakpoint.  Note that this
1275    is not the same as the "silent" that may appear in the breakpoint's
1276    commands.  */
1277
1278 void
1279 breakpoint_set_silent (struct breakpoint *b, int silent)
1280 {
1281   int old_silent = b->silent;
1282
1283   b->silent = silent;
1284   if (old_silent != silent)
1285     observer_notify_breakpoint_modified (b);
1286 }
1287
1288 /* Set the thread for this breakpoint.  If THREAD is -1, make the
1289    breakpoint work for any thread.  */
1290
1291 void
1292 breakpoint_set_thread (struct breakpoint *b, int thread)
1293 {
1294   int old_thread = b->thread;
1295
1296   b->thread = thread;
1297   if (old_thread != thread)
1298     observer_notify_breakpoint_modified (b);
1299 }
1300
1301 /* Set the task for this breakpoint.  If TASK is 0, make the
1302    breakpoint work for any task.  */
1303
1304 void
1305 breakpoint_set_task (struct breakpoint *b, int task)
1306 {
1307   int old_task = b->task;
1308
1309   b->task = task;
1310   if (old_task != task)
1311     observer_notify_breakpoint_modified (b);
1312 }
1313
1314 void
1315 check_tracepoint_command (char *line, void *closure)
1316 {
1317   struct breakpoint *b = closure;
1318
1319   validate_actionline (line, b);
1320 }
1321
1322 /* A structure used to pass information through
1323    map_breakpoint_numbers.  */
1324
1325 struct commands_info
1326 {
1327   /* True if the command was typed at a tty.  */
1328   int from_tty;
1329
1330   /* The breakpoint range spec.  */
1331   char *arg;
1332
1333   /* Non-NULL if the body of the commands are being read from this
1334      already-parsed command.  */
1335   struct command_line *control;
1336
1337   /* The command lines read from the user, or NULL if they have not
1338      yet been read.  */
1339   struct counted_command_line *cmd;
1340 };
1341
1342 /* A callback for map_breakpoint_numbers that sets the commands for
1343    commands_command.  */
1344
1345 static void
1346 do_map_commands_command (struct breakpoint *b, void *data)
1347 {
1348   struct commands_info *info = data;
1349
1350   if (info->cmd == NULL)
1351     {
1352       struct command_line *l;
1353
1354       if (info->control != NULL)
1355         l = copy_command_lines (info->control->body_list[0]);
1356       else
1357         {
1358           struct cleanup *old_chain;
1359           char *str;
1360
1361           str = xstrprintf (_("Type commands for breakpoint(s) "
1362                               "%s, one per line."),
1363                             info->arg);
1364
1365           old_chain = make_cleanup (xfree, str);
1366
1367           l = read_command_lines (str,
1368                                   info->from_tty, 1,
1369                                   (is_tracepoint (b)
1370                                    ? check_tracepoint_command : 0),
1371                                   b);
1372
1373           do_cleanups (old_chain);
1374         }
1375
1376       info->cmd = alloc_counted_command_line (l);
1377     }
1378
1379   /* If a breakpoint was on the list more than once, we don't need to
1380      do anything.  */
1381   if (b->commands != info->cmd)
1382     {
1383       validate_commands_for_breakpoint (b, info->cmd->commands);
1384       incref_counted_command_line (info->cmd);
1385       decref_counted_command_line (&b->commands);
1386       b->commands = info->cmd;
1387       observer_notify_breakpoint_modified (b);
1388     }
1389 }
1390
1391 static void
1392 commands_command_1 (char *arg, int from_tty, 
1393                     struct command_line *control)
1394 {
1395   struct cleanup *cleanups;
1396   struct commands_info info;
1397
1398   info.from_tty = from_tty;
1399   info.control = control;
1400   info.cmd = NULL;
1401   /* If we read command lines from the user, then `info' will hold an
1402      extra reference to the commands that we must clean up.  */
1403   cleanups = make_cleanup_decref_counted_command_line (&info.cmd);
1404
1405   if (arg == NULL || !*arg)
1406     {
1407       if (breakpoint_count - prev_breakpoint_count > 1)
1408         arg = xstrprintf ("%d-%d", prev_breakpoint_count + 1, 
1409                           breakpoint_count);
1410       else if (breakpoint_count > 0)
1411         arg = xstrprintf ("%d", breakpoint_count);
1412       else
1413         {
1414           /* So that we don't try to free the incoming non-NULL
1415              argument in the cleanup below.  Mapping breakpoint
1416              numbers will fail in this case.  */
1417           arg = NULL;
1418         }
1419     }
1420   else
1421     /* The command loop has some static state, so we need to preserve
1422        our argument.  */
1423     arg = xstrdup (arg);
1424
1425   if (arg != NULL)
1426     make_cleanup (xfree, arg);
1427
1428   info.arg = arg;
1429
1430   map_breakpoint_numbers (arg, do_map_commands_command, &info);
1431
1432   if (info.cmd == NULL)
1433     error (_("No breakpoints specified."));
1434
1435   do_cleanups (cleanups);
1436 }
1437
1438 static void
1439 commands_command (char *arg, int from_tty)
1440 {
1441   commands_command_1 (arg, from_tty, NULL);
1442 }
1443
1444 /* Like commands_command, but instead of reading the commands from
1445    input stream, takes them from an already parsed command structure.
1446
1447    This is used by cli-script.c to DTRT with breakpoint commands
1448    that are part of if and while bodies.  */
1449 enum command_control_type
1450 commands_from_control_command (char *arg, struct command_line *cmd)
1451 {
1452   commands_command_1 (arg, 0, cmd);
1453   return simple_control;
1454 }
1455
1456 /* Return non-zero if BL->TARGET_INFO contains valid information.  */
1457
1458 static int
1459 bp_location_has_shadow (struct bp_location *bl)
1460 {
1461   if (bl->loc_type != bp_loc_software_breakpoint)
1462     return 0;
1463   if (!bl->inserted)
1464     return 0;
1465   if (bl->target_info.shadow_len == 0)
1466     /* BL isn't valid, or doesn't shadow memory.  */
1467     return 0;
1468   return 1;
1469 }
1470
1471 /* Update BUF, which is LEN bytes read from the target address
1472    MEMADDR, by replacing a memory breakpoint with its shadowed
1473    contents.
1474
1475    If READBUF is not NULL, this buffer must not overlap with the of
1476    the breakpoint location's shadow_contents buffer.  Otherwise, a
1477    failed assertion internal error will be raised.  */
1478
1479 static void
1480 one_breakpoint_xfer_memory (gdb_byte *readbuf, gdb_byte *writebuf,
1481                             const gdb_byte *writebuf_org,
1482                             ULONGEST memaddr, LONGEST len,
1483                             struct bp_target_info *target_info,
1484                             struct gdbarch *gdbarch)
1485 {
1486   /* Now do full processing of the found relevant range of elements.  */
1487   CORE_ADDR bp_addr = 0;
1488   int bp_size = 0;
1489   int bptoffset = 0;
1490
1491   if (!breakpoint_address_match (target_info->placed_address_space, 0,
1492                                  current_program_space->aspace, 0))
1493     {
1494       /* The breakpoint is inserted in a different address space.  */
1495       return;
1496     }
1497
1498   /* Addresses and length of the part of the breakpoint that
1499      we need to copy.  */
1500   bp_addr = target_info->placed_address;
1501   bp_size = target_info->shadow_len;
1502
1503   if (bp_addr + bp_size <= memaddr)
1504     {
1505       /* The breakpoint is entirely before the chunk of memory we are
1506          reading.  */
1507       return;
1508     }
1509
1510   if (bp_addr >= memaddr + len)
1511     {
1512       /* The breakpoint is entirely after the chunk of memory we are
1513          reading.  */
1514       return;
1515     }
1516
1517   /* Offset within shadow_contents.  */
1518   if (bp_addr < memaddr)
1519     {
1520       /* Only copy the second part of the breakpoint.  */
1521       bp_size -= memaddr - bp_addr;
1522       bptoffset = memaddr - bp_addr;
1523       bp_addr = memaddr;
1524     }
1525
1526   if (bp_addr + bp_size > memaddr + len)
1527     {
1528       /* Only copy the first part of the breakpoint.  */
1529       bp_size -= (bp_addr + bp_size) - (memaddr + len);
1530     }
1531
1532   if (readbuf != NULL)
1533     {
1534       /* Verify that the readbuf buffer does not overlap with the
1535          shadow_contents buffer.  */
1536       gdb_assert (target_info->shadow_contents >= readbuf + len
1537                   || readbuf >= (target_info->shadow_contents
1538                                  + target_info->shadow_len));
1539
1540       /* Update the read buffer with this inserted breakpoint's
1541          shadow.  */
1542       memcpy (readbuf + bp_addr - memaddr,
1543               target_info->shadow_contents + bptoffset, bp_size);
1544     }
1545   else
1546     {
1547       const unsigned char *bp;
1548       CORE_ADDR addr = target_info->reqstd_address;
1549       int placed_size;
1550
1551       /* Update the shadow with what we want to write to memory.  */
1552       memcpy (target_info->shadow_contents + bptoffset,
1553               writebuf_org + bp_addr - memaddr, bp_size);
1554
1555       /* Determine appropriate breakpoint contents and size for this
1556          address.  */
1557       bp = gdbarch_breakpoint_from_pc (gdbarch, &addr, &placed_size);
1558
1559       /* Update the final write buffer with this inserted
1560          breakpoint's INSN.  */
1561       memcpy (writebuf + bp_addr - memaddr, bp + bptoffset, bp_size);
1562     }
1563 }
1564
1565 /* Update BUF, which is LEN bytes read from the target address MEMADDR,
1566    by replacing any memory breakpoints with their shadowed contents.
1567
1568    If READBUF is not NULL, this buffer must not overlap with any of
1569    the breakpoint location's shadow_contents buffers.  Otherwise,
1570    a failed assertion internal error will be raised.
1571
1572    The range of shadowed area by each bp_location is:
1573      bl->address - bp_location_placed_address_before_address_max
1574      up to bl->address + bp_location_shadow_len_after_address_max
1575    The range we were requested to resolve shadows for is:
1576      memaddr ... memaddr + len
1577    Thus the safe cutoff boundaries for performance optimization are
1578      memaddr + len <= (bl->address
1579                        - bp_location_placed_address_before_address_max)
1580    and:
1581      bl->address + bp_location_shadow_len_after_address_max <= memaddr  */
1582
1583 void
1584 breakpoint_xfer_memory (gdb_byte *readbuf, gdb_byte *writebuf,
1585                         const gdb_byte *writebuf_org,
1586                         ULONGEST memaddr, LONGEST len)
1587 {
1588   /* Left boundary, right boundary and median element of our binary
1589      search.  */
1590   unsigned bc_l, bc_r, bc;
1591   size_t i;
1592
1593   /* Find BC_L which is a leftmost element which may affect BUF
1594      content.  It is safe to report lower value but a failure to
1595      report higher one.  */
1596
1597   bc_l = 0;
1598   bc_r = bp_location_count;
1599   while (bc_l + 1 < bc_r)
1600     {
1601       struct bp_location *bl;
1602
1603       bc = (bc_l + bc_r) / 2;
1604       bl = bp_location[bc];
1605
1606       /* Check first BL->ADDRESS will not overflow due to the added
1607          constant.  Then advance the left boundary only if we are sure
1608          the BC element can in no way affect the BUF content (MEMADDR
1609          to MEMADDR + LEN range).
1610
1611          Use the BP_LOCATION_SHADOW_LEN_AFTER_ADDRESS_MAX safety
1612          offset so that we cannot miss a breakpoint with its shadow
1613          range tail still reaching MEMADDR.  */
1614
1615       if ((bl->address + bp_location_shadow_len_after_address_max
1616            >= bl->address)
1617           && (bl->address + bp_location_shadow_len_after_address_max
1618               <= memaddr))
1619         bc_l = bc;
1620       else
1621         bc_r = bc;
1622     }
1623
1624   /* Due to the binary search above, we need to make sure we pick the
1625      first location that's at BC_L's address.  E.g., if there are
1626      multiple locations at the same address, BC_L may end up pointing
1627      at a duplicate location, and miss the "master"/"inserted"
1628      location.  Say, given locations L1, L2 and L3 at addresses A and
1629      B:
1630
1631       L1@A, L2@A, L3@B, ...
1632
1633      BC_L could end up pointing at location L2, while the "master"
1634      location could be L1.  Since the `loc->inserted' flag is only set
1635      on "master" locations, we'd forget to restore the shadow of L1
1636      and L2.  */
1637   while (bc_l > 0
1638          && bp_location[bc_l]->address == bp_location[bc_l - 1]->address)
1639     bc_l--;
1640
1641   /* Now do full processing of the found relevant range of elements.  */
1642
1643   for (bc = bc_l; bc < bp_location_count; bc++)
1644   {
1645     struct bp_location *bl = bp_location[bc];
1646     CORE_ADDR bp_addr = 0;
1647     int bp_size = 0;
1648     int bptoffset = 0;
1649
1650     /* bp_location array has BL->OWNER always non-NULL.  */
1651     if (bl->owner->type == bp_none)
1652       warning (_("reading through apparently deleted breakpoint #%d?"),
1653                bl->owner->number);
1654
1655     /* Performance optimization: any further element can no longer affect BUF
1656        content.  */
1657
1658     if (bl->address >= bp_location_placed_address_before_address_max
1659         && memaddr + len <= (bl->address
1660                              - bp_location_placed_address_before_address_max))
1661       break;
1662
1663     if (!bp_location_has_shadow (bl))
1664       continue;
1665
1666     one_breakpoint_xfer_memory (readbuf, writebuf, writebuf_org,
1667                                 memaddr, len, &bl->target_info, bl->gdbarch);
1668   }
1669 }
1670
1671 \f
1672
1673 /* Return true if BPT is either a software breakpoint or a hardware
1674    breakpoint.  */
1675
1676 int
1677 is_breakpoint (const struct breakpoint *bpt)
1678 {
1679   return (bpt->type == bp_breakpoint
1680           || bpt->type == bp_hardware_breakpoint
1681           || bpt->type == bp_dprintf);
1682 }
1683
1684 /* Return true if BPT is of any hardware watchpoint kind.  */
1685
1686 static int
1687 is_hardware_watchpoint (const struct breakpoint *bpt)
1688 {
1689   return (bpt->type == bp_hardware_watchpoint
1690           || bpt->type == bp_read_watchpoint
1691           || bpt->type == bp_access_watchpoint);
1692 }
1693
1694 /* Return true if BPT is of any watchpoint kind, hardware or
1695    software.  */
1696
1697 int
1698 is_watchpoint (const struct breakpoint *bpt)
1699 {
1700   return (is_hardware_watchpoint (bpt)
1701           || bpt->type == bp_watchpoint);
1702 }
1703
1704 /* Returns true if the current thread and its running state are safe
1705    to evaluate or update watchpoint B.  Watchpoints on local
1706    expressions need to be evaluated in the context of the thread that
1707    was current when the watchpoint was created, and, that thread needs
1708    to be stopped to be able to select the correct frame context.
1709    Watchpoints on global expressions can be evaluated on any thread,
1710    and in any state.  It is presently left to the target allowing
1711    memory accesses when threads are running.  */
1712
1713 static int
1714 watchpoint_in_thread_scope (struct watchpoint *b)
1715 {
1716   return (b->base.pspace == current_program_space
1717           && (ptid_equal (b->watchpoint_thread, null_ptid)
1718               || (ptid_equal (inferior_ptid, b->watchpoint_thread)
1719                   && !is_executing (inferior_ptid))));
1720 }
1721
1722 /* Set watchpoint B to disp_del_at_next_stop, even including its possible
1723    associated bp_watchpoint_scope breakpoint.  */
1724
1725 static void
1726 watchpoint_del_at_next_stop (struct watchpoint *w)
1727 {
1728   struct breakpoint *b = &w->base;
1729
1730   if (b->related_breakpoint != b)
1731     {
1732       gdb_assert (b->related_breakpoint->type == bp_watchpoint_scope);
1733       gdb_assert (b->related_breakpoint->related_breakpoint == b);
1734       b->related_breakpoint->disposition = disp_del_at_next_stop;
1735       b->related_breakpoint->related_breakpoint = b->related_breakpoint;
1736       b->related_breakpoint = b;
1737     }
1738   b->disposition = disp_del_at_next_stop;
1739 }
1740
1741 /* Extract a bitfield value from value VAL using the bit parameters contained in
1742    watchpoint W.  */
1743
1744 static struct value *
1745 extract_bitfield_from_watchpoint_value (struct watchpoint *w, struct value *val)
1746 {
1747   struct value *bit_val;
1748
1749   if (val == NULL)
1750     return NULL;
1751
1752   bit_val = allocate_value (value_type (val));
1753
1754   unpack_value_bitfield (bit_val,
1755                          w->val_bitpos,
1756                          w->val_bitsize,
1757                          value_contents_for_printing (val),
1758                          value_offset (val),
1759                          val);
1760
1761   return bit_val;
1762 }
1763
1764 /* Assuming that B is a watchpoint:
1765    - Reparse watchpoint expression, if REPARSE is non-zero
1766    - Evaluate expression and store the result in B->val
1767    - Evaluate the condition if there is one, and store the result
1768      in b->loc->cond.
1769    - Update the list of values that must be watched in B->loc.
1770
1771    If the watchpoint disposition is disp_del_at_next_stop, then do
1772    nothing.  If this is local watchpoint that is out of scope, delete
1773    it.
1774
1775    Even with `set breakpoint always-inserted on' the watchpoints are
1776    removed + inserted on each stop here.  Normal breakpoints must
1777    never be removed because they might be missed by a running thread
1778    when debugging in non-stop mode.  On the other hand, hardware
1779    watchpoints (is_hardware_watchpoint; processed here) are specific
1780    to each LWP since they are stored in each LWP's hardware debug
1781    registers.  Therefore, such LWP must be stopped first in order to
1782    be able to modify its hardware watchpoints.
1783
1784    Hardware watchpoints must be reset exactly once after being
1785    presented to the user.  It cannot be done sooner, because it would
1786    reset the data used to present the watchpoint hit to the user.  And
1787    it must not be done later because it could display the same single
1788    watchpoint hit during multiple GDB stops.  Note that the latter is
1789    relevant only to the hardware watchpoint types bp_read_watchpoint
1790    and bp_access_watchpoint.  False hit by bp_hardware_watchpoint is
1791    not user-visible - its hit is suppressed if the memory content has
1792    not changed.
1793
1794    The following constraints influence the location where we can reset
1795    hardware watchpoints:
1796
1797    * target_stopped_by_watchpoint and target_stopped_data_address are
1798      called several times when GDB stops.
1799
1800    [linux] 
1801    * Multiple hardware watchpoints can be hit at the same time,
1802      causing GDB to stop.  GDB only presents one hardware watchpoint
1803      hit at a time as the reason for stopping, and all the other hits
1804      are presented later, one after the other, each time the user
1805      requests the execution to be resumed.  Execution is not resumed
1806      for the threads still having pending hit event stored in
1807      LWP_INFO->STATUS.  While the watchpoint is already removed from
1808      the inferior on the first stop the thread hit event is kept being
1809      reported from its cached value by linux_nat_stopped_data_address
1810      until the real thread resume happens after the watchpoint gets
1811      presented and thus its LWP_INFO->STATUS gets reset.
1812
1813    Therefore the hardware watchpoint hit can get safely reset on the
1814    watchpoint removal from inferior.  */
1815
1816 static void
1817 update_watchpoint (struct watchpoint *b, int reparse)
1818 {
1819   int within_current_scope;
1820   struct frame_id saved_frame_id;
1821   int frame_saved;
1822
1823   /* If this is a local watchpoint, we only want to check if the
1824      watchpoint frame is in scope if the current thread is the thread
1825      that was used to create the watchpoint.  */
1826   if (!watchpoint_in_thread_scope (b))
1827     return;
1828
1829   if (b->base.disposition == disp_del_at_next_stop)
1830     return;
1831  
1832   frame_saved = 0;
1833
1834   /* Determine if the watchpoint is within scope.  */
1835   if (b->exp_valid_block == NULL)
1836     within_current_scope = 1;
1837   else
1838     {
1839       struct frame_info *fi = get_current_frame ();
1840       struct gdbarch *frame_arch = get_frame_arch (fi);
1841       CORE_ADDR frame_pc = get_frame_pc (fi);
1842
1843       /* If we're in a function epilogue, unwinding may not work
1844          properly, so do not attempt to recreate locations at this
1845          point.  See similar comments in watchpoint_check.  */
1846       if (gdbarch_in_function_epilogue_p (frame_arch, frame_pc))
1847         return;
1848
1849       /* Save the current frame's ID so we can restore it after
1850          evaluating the watchpoint expression on its own frame.  */
1851       /* FIXME drow/2003-09-09: It would be nice if evaluate_expression
1852          took a frame parameter, so that we didn't have to change the
1853          selected frame.  */
1854       frame_saved = 1;
1855       saved_frame_id = get_frame_id (get_selected_frame (NULL));
1856
1857       fi = frame_find_by_id (b->watchpoint_frame);
1858       within_current_scope = (fi != NULL);
1859       if (within_current_scope)
1860         select_frame (fi);
1861     }
1862
1863   /* We don't free locations.  They are stored in the bp_location array
1864      and update_global_location_list will eventually delete them and
1865      remove breakpoints if needed.  */
1866   b->base.loc = NULL;
1867
1868   if (within_current_scope && reparse)
1869     {
1870       const char *s;
1871
1872       if (b->exp)
1873         {
1874           xfree (b->exp);
1875           b->exp = NULL;
1876         }
1877       s = b->exp_string_reparse ? b->exp_string_reparse : b->exp_string;
1878       b->exp = parse_exp_1 (&s, 0, b->exp_valid_block, 0);
1879       /* If the meaning of expression itself changed, the old value is
1880          no longer relevant.  We don't want to report a watchpoint hit
1881          to the user when the old value and the new value may actually
1882          be completely different objects.  */
1883       value_free (b->val);
1884       b->val = NULL;
1885       b->val_valid = 0;
1886
1887       /* Note that unlike with breakpoints, the watchpoint's condition
1888          expression is stored in the breakpoint object, not in the
1889          locations (re)created below.  */
1890       if (b->base.cond_string != NULL)
1891         {
1892           if (b->cond_exp != NULL)
1893             {
1894               xfree (b->cond_exp);
1895               b->cond_exp = NULL;
1896             }
1897
1898           s = b->base.cond_string;
1899           b->cond_exp = parse_exp_1 (&s, 0, b->cond_exp_valid_block, 0);
1900         }
1901     }
1902
1903   /* If we failed to parse the expression, for example because
1904      it refers to a global variable in a not-yet-loaded shared library,
1905      don't try to insert watchpoint.  We don't automatically delete
1906      such watchpoint, though, since failure to parse expression
1907      is different from out-of-scope watchpoint.  */
1908   if (!target_has_execution)
1909     {
1910       /* Without execution, memory can't change.  No use to try and
1911          set watchpoint locations.  The watchpoint will be reset when
1912          the target gains execution, through breakpoint_re_set.  */
1913       if (!can_use_hw_watchpoints)
1914         {
1915           if (b->base.ops->works_in_software_mode (&b->base))
1916             b->base.type = bp_watchpoint;
1917           else
1918             error (_("Can't set read/access watchpoint when "
1919                      "hardware watchpoints are disabled."));
1920         }
1921     }
1922   else if (within_current_scope && b->exp)
1923     {
1924       int pc = 0;
1925       struct value *val_chain, *v, *result, *next;
1926       struct program_space *frame_pspace;
1927
1928       fetch_subexp_value (b->exp, &pc, &v, &result, &val_chain, 0);
1929
1930       /* Avoid setting b->val if it's already set.  The meaning of
1931          b->val is 'the last value' user saw, and we should update
1932          it only if we reported that last value to user.  As it
1933          happens, the code that reports it updates b->val directly.
1934          We don't keep track of the memory value for masked
1935          watchpoints.  */
1936       if (!b->val_valid && !is_masked_watchpoint (&b->base))
1937         {
1938           if (b->val_bitsize != 0)
1939             {
1940               v = extract_bitfield_from_watchpoint_value (b, v);
1941               if (v != NULL)
1942                 release_value (v);
1943             }
1944           b->val = v;
1945           b->val_valid = 1;
1946         }
1947
1948       frame_pspace = get_frame_program_space (get_selected_frame (NULL));
1949
1950       /* Look at each value on the value chain.  */
1951       for (v = val_chain; v; v = value_next (v))
1952         {
1953           /* If it's a memory location, and GDB actually needed
1954              its contents to evaluate the expression, then we
1955              must watch it.  If the first value returned is
1956              still lazy, that means an error occurred reading it;
1957              watch it anyway in case it becomes readable.  */
1958           if (VALUE_LVAL (v) == lval_memory
1959               && (v == val_chain || ! value_lazy (v)))
1960             {
1961               struct type *vtype = check_typedef (value_type (v));
1962
1963               /* We only watch structs and arrays if user asked
1964                  for it explicitly, never if they just happen to
1965                  appear in the middle of some value chain.  */
1966               if (v == result
1967                   || (TYPE_CODE (vtype) != TYPE_CODE_STRUCT
1968                       && TYPE_CODE (vtype) != TYPE_CODE_ARRAY))
1969                 {
1970                   CORE_ADDR addr;
1971                   int type;
1972                   struct bp_location *loc, **tmp;
1973                   int bitpos = 0, bitsize = 0;
1974
1975                   if (value_bitsize (v) != 0)
1976                     {
1977                       /* Extract the bit parameters out from the bitfield
1978                          sub-expression.  */
1979                       bitpos = value_bitpos (v);
1980                       bitsize = value_bitsize (v);
1981                     }
1982                   else if (v == result && b->val_bitsize != 0)
1983                     {
1984                      /* If VAL_BITSIZE != 0 then RESULT is actually a bitfield
1985                         lvalue whose bit parameters are saved in the fields
1986                         VAL_BITPOS and VAL_BITSIZE.  */
1987                       bitpos = b->val_bitpos;
1988                       bitsize = b->val_bitsize;
1989                     }
1990
1991                   addr = value_address (v);
1992                   if (bitsize != 0)
1993                     {
1994                       /* Skip the bytes that don't contain the bitfield.  */
1995                       addr += bitpos / 8;
1996                     }
1997
1998                   type = hw_write;
1999                   if (b->base.type == bp_read_watchpoint)
2000                     type = hw_read;
2001                   else if (b->base.type == bp_access_watchpoint)
2002                     type = hw_access;
2003
2004                   loc = allocate_bp_location (&b->base);
2005                   for (tmp = &(b->base.loc); *tmp != NULL; tmp = &((*tmp)->next))
2006                     ;
2007                   *tmp = loc;
2008                   loc->gdbarch = get_type_arch (value_type (v));
2009
2010                   loc->pspace = frame_pspace;
2011                   loc->address = addr;
2012
2013                   if (bitsize != 0)
2014                     {
2015                       /* Just cover the bytes that make up the bitfield.  */
2016                       loc->length = ((bitpos % 8) + bitsize + 7) / 8;
2017                     }
2018                   else
2019                     loc->length = TYPE_LENGTH (value_type (v));
2020
2021                   loc->watchpoint_type = type;
2022                 }
2023             }
2024         }
2025
2026       /* Change the type of breakpoint between hardware assisted or
2027          an ordinary watchpoint depending on the hardware support
2028          and free hardware slots.  REPARSE is set when the inferior
2029          is started.  */
2030       if (reparse)
2031         {
2032           int reg_cnt;
2033           enum bp_loc_type loc_type;
2034           struct bp_location *bl;
2035
2036           reg_cnt = can_use_hardware_watchpoint (val_chain);
2037
2038           if (reg_cnt)
2039             {
2040               int i, target_resources_ok, other_type_used;
2041               enum bptype type;
2042
2043               /* Use an exact watchpoint when there's only one memory region to be
2044                  watched, and only one debug register is needed to watch it.  */
2045               b->exact = target_exact_watchpoints && reg_cnt == 1;
2046
2047               /* We need to determine how many resources are already
2048                  used for all other hardware watchpoints plus this one
2049                  to see if we still have enough resources to also fit
2050                  this watchpoint in as well.  */
2051
2052               /* If this is a software watchpoint, we try to turn it
2053                  to a hardware one -- count resources as if B was of
2054                  hardware watchpoint type.  */
2055               type = b->base.type;
2056               if (type == bp_watchpoint)
2057                 type = bp_hardware_watchpoint;
2058
2059               /* This watchpoint may or may not have been placed on
2060                  the list yet at this point (it won't be in the list
2061                  if we're trying to create it for the first time,
2062                  through watch_command), so always account for it
2063                  manually.  */
2064
2065               /* Count resources used by all watchpoints except B.  */
2066               i = hw_watchpoint_used_count_others (&b->base, type, &other_type_used);
2067
2068               /* Add in the resources needed for B.  */
2069               i += hw_watchpoint_use_count (&b->base);
2070
2071               target_resources_ok
2072                 = target_can_use_hardware_watchpoint (type, i, other_type_used);
2073               if (target_resources_ok <= 0)
2074                 {
2075                   int sw_mode = b->base.ops->works_in_software_mode (&b->base);
2076
2077                   if (target_resources_ok == 0 && !sw_mode)
2078                     error (_("Target does not support this type of "
2079                              "hardware watchpoint."));
2080                   else if (target_resources_ok < 0 && !sw_mode)
2081                     error (_("There are not enough available hardware "
2082                              "resources for this watchpoint."));
2083
2084                   /* Downgrade to software watchpoint.  */
2085                   b->base.type = bp_watchpoint;
2086                 }
2087               else
2088                 {
2089                   /* If this was a software watchpoint, we've just
2090                      found we have enough resources to turn it to a
2091                      hardware watchpoint.  Otherwise, this is a
2092                      nop.  */
2093                   b->base.type = type;
2094                 }
2095             }
2096           else if (!b->base.ops->works_in_software_mode (&b->base))
2097             {
2098               if (!can_use_hw_watchpoints)
2099                 error (_("Can't set read/access watchpoint when "
2100                          "hardware watchpoints are disabled."));
2101               else
2102                 error (_("Expression cannot be implemented with "
2103                          "read/access watchpoint."));
2104             }
2105           else
2106             b->base.type = bp_watchpoint;
2107
2108           loc_type = (b->base.type == bp_watchpoint? bp_loc_other
2109                       : bp_loc_hardware_watchpoint);
2110           for (bl = b->base.loc; bl; bl = bl->next)
2111             bl->loc_type = loc_type;
2112         }
2113
2114       for (v = val_chain; v; v = next)
2115         {
2116           next = value_next (v);
2117           if (v != b->val)
2118             value_free (v);
2119         }
2120
2121       /* If a software watchpoint is not watching any memory, then the
2122          above left it without any location set up.  But,
2123          bpstat_stop_status requires a location to be able to report
2124          stops, so make sure there's at least a dummy one.  */
2125       if (b->base.type == bp_watchpoint && b->base.loc == NULL)
2126         {
2127           struct breakpoint *base = &b->base;
2128           base->loc = allocate_bp_location (base);
2129           base->loc->pspace = frame_pspace;
2130           base->loc->address = -1;
2131           base->loc->length = -1;
2132           base->loc->watchpoint_type = -1;
2133         }
2134     }
2135   else if (!within_current_scope)
2136     {
2137       printf_filtered (_("\
2138 Watchpoint %d deleted because the program has left the block\n\
2139 in which its expression is valid.\n"),
2140                        b->base.number);
2141       watchpoint_del_at_next_stop (b);
2142     }
2143
2144   /* Restore the selected frame.  */
2145   if (frame_saved)
2146     select_frame (frame_find_by_id (saved_frame_id));
2147 }
2148
2149
2150 /* Returns 1 iff breakpoint location should be
2151    inserted in the inferior.  We don't differentiate the type of BL's owner
2152    (breakpoint vs. tracepoint), although insert_location in tracepoint's
2153    breakpoint_ops is not defined, because in insert_bp_location,
2154    tracepoint's insert_location will not be called.  */
2155 static int
2156 should_be_inserted (struct bp_location *bl)
2157 {
2158   if (bl->owner == NULL || !breakpoint_enabled (bl->owner))
2159     return 0;
2160
2161   if (bl->owner->disposition == disp_del_at_next_stop)
2162     return 0;
2163
2164   if (!bl->enabled || bl->shlib_disabled || bl->duplicate)
2165     return 0;
2166
2167   if (user_breakpoint_p (bl->owner) && bl->pspace->executing_startup)
2168     return 0;
2169
2170   /* This is set for example, when we're attached to the parent of a
2171      vfork, and have detached from the child.  The child is running
2172      free, and we expect it to do an exec or exit, at which point the
2173      OS makes the parent schedulable again (and the target reports
2174      that the vfork is done).  Until the child is done with the shared
2175      memory region, do not insert breakpoints in the parent, otherwise
2176      the child could still trip on the parent's breakpoints.  Since
2177      the parent is blocked anyway, it won't miss any breakpoint.  */
2178   if (bl->pspace->breakpoints_not_allowed)
2179     return 0;
2180
2181   /* Don't insert a breakpoint if we're trying to step past its
2182      location.  */
2183   if ((bl->loc_type == bp_loc_software_breakpoint
2184        || bl->loc_type == bp_loc_hardware_breakpoint)
2185       && stepping_past_instruction_at (bl->pspace->aspace,
2186                                        bl->address))
2187     {
2188       if (debug_infrun)
2189         {
2190           fprintf_unfiltered (gdb_stdlog,
2191                               "infrun: skipping breakpoint: "
2192                               "stepping past insn at: %s\n",
2193                               paddress (bl->gdbarch, bl->address));
2194         }
2195       return 0;
2196     }
2197
2198   /* Don't insert watchpoints if we're trying to step past the
2199      instruction that triggered one.  */
2200   if ((bl->loc_type == bp_loc_hardware_watchpoint)
2201       && stepping_past_nonsteppable_watchpoint ())
2202     {
2203       if (debug_infrun)
2204         {
2205           fprintf_unfiltered (gdb_stdlog,
2206                               "infrun: stepping past non-steppable watchpoint. "
2207                               "skipping watchpoint at %s:%d\n",
2208                               paddress (bl->gdbarch, bl->address),
2209                               bl->length);
2210         }
2211       return 0;
2212     }
2213
2214   return 1;
2215 }
2216
2217 /* Same as should_be_inserted but does the check assuming
2218    that the location is not duplicated.  */
2219
2220 static int
2221 unduplicated_should_be_inserted (struct bp_location *bl)
2222 {
2223   int result;
2224   const int save_duplicate = bl->duplicate;
2225
2226   bl->duplicate = 0;
2227   result = should_be_inserted (bl);
2228   bl->duplicate = save_duplicate;
2229   return result;
2230 }
2231
2232 /* Parses a conditional described by an expression COND into an
2233    agent expression bytecode suitable for evaluation
2234    by the bytecode interpreter.  Return NULL if there was
2235    any error during parsing.  */
2236
2237 static struct agent_expr *
2238 parse_cond_to_aexpr (CORE_ADDR scope, struct expression *cond)
2239 {
2240   struct agent_expr *aexpr = NULL;
2241
2242   if (!cond)
2243     return NULL;
2244
2245   /* We don't want to stop processing, so catch any errors
2246      that may show up.  */
2247   TRY
2248     {
2249       aexpr = gen_eval_for_expr (scope, cond);
2250     }
2251
2252   CATCH (ex, RETURN_MASK_ERROR)
2253     {
2254       /* If we got here, it means the condition could not be parsed to a valid
2255          bytecode expression and thus can't be evaluated on the target's side.
2256          It's no use iterating through the conditions.  */
2257       return NULL;
2258     }
2259   END_CATCH
2260
2261   /* We have a valid agent expression.  */
2262   return aexpr;
2263 }
2264
2265 /* Based on location BL, create a list of breakpoint conditions to be
2266    passed on to the target.  If we have duplicated locations with different
2267    conditions, we will add such conditions to the list.  The idea is that the
2268    target will evaluate the list of conditions and will only notify GDB when
2269    one of them is true.  */
2270
2271 static void
2272 build_target_condition_list (struct bp_location *bl)
2273 {
2274   struct bp_location **locp = NULL, **loc2p;
2275   int null_condition_or_parse_error = 0;
2276   int modified = bl->needs_update;
2277   struct bp_location *loc;
2278
2279   /* Release conditions left over from a previous insert.  */
2280   VEC_free (agent_expr_p, bl->target_info.conditions);
2281
2282   /* This is only meaningful if the target is
2283      evaluating conditions and if the user has
2284      opted for condition evaluation on the target's
2285      side.  */
2286   if (gdb_evaluates_breakpoint_condition_p ()
2287       || !target_supports_evaluation_of_breakpoint_conditions ())
2288     return;
2289
2290   /* Do a first pass to check for locations with no assigned
2291      conditions or conditions that fail to parse to a valid agent expression
2292      bytecode.  If any of these happen, then it's no use to send conditions
2293      to the target since this location will always trigger and generate a
2294      response back to GDB.  */
2295   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2296     {
2297       loc = (*loc2p);
2298       if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2299         {
2300           if (modified)
2301             {
2302               struct agent_expr *aexpr;
2303
2304               /* Re-parse the conditions since something changed.  In that
2305                  case we already freed the condition bytecodes (see
2306                  force_breakpoint_reinsertion).  We just
2307                  need to parse the condition to bytecodes again.  */
2308               aexpr = parse_cond_to_aexpr (bl->address, loc->cond);
2309               loc->cond_bytecode = aexpr;
2310
2311               /* Check if we managed to parse the conditional expression
2312                  correctly.  If not, we will not send this condition
2313                  to the target.  */
2314               if (aexpr)
2315                 continue;
2316             }
2317
2318           /* If we have a NULL bytecode expression, it means something
2319              went wrong or we have a null condition expression.  */
2320           if (!loc->cond_bytecode)
2321             {
2322               null_condition_or_parse_error = 1;
2323               break;
2324             }
2325         }
2326     }
2327
2328   /* If any of these happened, it means we will have to evaluate the conditions
2329      for the location's address on gdb's side.  It is no use keeping bytecodes
2330      for all the other duplicate locations, thus we free all of them here.
2331
2332      This is so we have a finer control over which locations' conditions are
2333      being evaluated by GDB or the remote stub.  */
2334   if (null_condition_or_parse_error)
2335     {
2336       ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2337         {
2338           loc = (*loc2p);
2339           if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2340             {
2341               /* Only go as far as the first NULL bytecode is
2342                  located.  */
2343               if (!loc->cond_bytecode)
2344                 return;
2345
2346               free_agent_expr (loc->cond_bytecode);
2347               loc->cond_bytecode = NULL;
2348             }
2349         }
2350     }
2351
2352   /* No NULL conditions or failed bytecode generation.  Build a condition list
2353      for this location's address.  */
2354   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2355     {
2356       loc = (*loc2p);
2357       if (loc->cond
2358           && is_breakpoint (loc->owner)
2359           && loc->pspace->num == bl->pspace->num
2360           && loc->owner->enable_state == bp_enabled
2361           && loc->enabled)
2362         /* Add the condition to the vector.  This will be used later to send the
2363            conditions to the target.  */
2364         VEC_safe_push (agent_expr_p, bl->target_info.conditions,
2365                        loc->cond_bytecode);
2366     }
2367
2368   return;
2369 }
2370
2371 /* Parses a command described by string CMD into an agent expression
2372    bytecode suitable for evaluation by the bytecode interpreter.
2373    Return NULL if there was any error during parsing.  */
2374
2375 static struct agent_expr *
2376 parse_cmd_to_aexpr (CORE_ADDR scope, char *cmd)
2377 {
2378   struct cleanup *old_cleanups = 0;
2379   struct expression *expr, **argvec;
2380   struct agent_expr *aexpr = NULL;
2381   const char *cmdrest;
2382   const char *format_start, *format_end;
2383   struct format_piece *fpieces;
2384   int nargs;
2385   struct gdbarch *gdbarch = get_current_arch ();
2386
2387   if (!cmd)
2388     return NULL;
2389
2390   cmdrest = cmd;
2391
2392   if (*cmdrest == ',')
2393     ++cmdrest;
2394   cmdrest = skip_spaces_const (cmdrest);
2395
2396   if (*cmdrest++ != '"')
2397     error (_("No format string following the location"));
2398
2399   format_start = cmdrest;
2400
2401   fpieces = parse_format_string (&cmdrest);
2402
2403   old_cleanups = make_cleanup (free_format_pieces_cleanup, &fpieces);
2404
2405   format_end = cmdrest;
2406
2407   if (*cmdrest++ != '"')
2408     error (_("Bad format string, non-terminated '\"'."));
2409   
2410   cmdrest = skip_spaces_const (cmdrest);
2411
2412   if (!(*cmdrest == ',' || *cmdrest == '\0'))
2413     error (_("Invalid argument syntax"));
2414
2415   if (*cmdrest == ',')
2416     cmdrest++;
2417   cmdrest = skip_spaces_const (cmdrest);
2418
2419   /* For each argument, make an expression.  */
2420
2421   argvec = (struct expression **) alloca (strlen (cmd)
2422                                          * sizeof (struct expression *));
2423
2424   nargs = 0;
2425   while (*cmdrest != '\0')
2426     {
2427       const char *cmd1;
2428
2429       cmd1 = cmdrest;
2430       expr = parse_exp_1 (&cmd1, scope, block_for_pc (scope), 1);
2431       argvec[nargs++] = expr;
2432       cmdrest = cmd1;
2433       if (*cmdrest == ',')
2434         ++cmdrest;
2435     }
2436
2437   /* We don't want to stop processing, so catch any errors
2438      that may show up.  */
2439   TRY
2440     {
2441       aexpr = gen_printf (scope, gdbarch, 0, 0,
2442                           format_start, format_end - format_start,
2443                           fpieces, nargs, argvec);
2444     }
2445   CATCH (ex, RETURN_MASK_ERROR)
2446     {
2447       /* If we got here, it means the command could not be parsed to a valid
2448          bytecode expression and thus can't be evaluated on the target's side.
2449          It's no use iterating through the other commands.  */
2450       aexpr = NULL;
2451     }
2452   END_CATCH
2453
2454   do_cleanups (old_cleanups);
2455
2456   /* We have a valid agent expression, return it.  */
2457   return aexpr;
2458 }
2459
2460 /* Based on location BL, create a list of breakpoint commands to be
2461    passed on to the target.  If we have duplicated locations with
2462    different commands, we will add any such to the list.  */
2463
2464 static void
2465 build_target_command_list (struct bp_location *bl)
2466 {
2467   struct bp_location **locp = NULL, **loc2p;
2468   int null_command_or_parse_error = 0;
2469   int modified = bl->needs_update;
2470   struct bp_location *loc;
2471
2472   /* Release commands left over from a previous insert.  */
2473   VEC_free (agent_expr_p, bl->target_info.tcommands);
2474
2475   if (!target_can_run_breakpoint_commands ())
2476     return;
2477
2478   /* For now, limit to agent-style dprintf breakpoints.  */
2479   if (dprintf_style != dprintf_style_agent)
2480     return;
2481
2482   /* For now, if we have any duplicate location that isn't a dprintf,
2483      don't install the target-side commands, as that would make the
2484      breakpoint not be reported to the core, and we'd lose
2485      control.  */
2486   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2487     {
2488       loc = (*loc2p);
2489       if (is_breakpoint (loc->owner)
2490           && loc->pspace->num == bl->pspace->num
2491           && loc->owner->type != bp_dprintf)
2492         return;
2493     }
2494
2495   /* Do a first pass to check for locations with no assigned
2496      conditions or conditions that fail to parse to a valid agent expression
2497      bytecode.  If any of these happen, then it's no use to send conditions
2498      to the target since this location will always trigger and generate a
2499      response back to GDB.  */
2500   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2501     {
2502       loc = (*loc2p);
2503       if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2504         {
2505           if (modified)
2506             {
2507               struct agent_expr *aexpr;
2508
2509               /* Re-parse the commands since something changed.  In that
2510                  case we already freed the command bytecodes (see
2511                  force_breakpoint_reinsertion).  We just
2512                  need to parse the command to bytecodes again.  */
2513               aexpr = parse_cmd_to_aexpr (bl->address,
2514                                           loc->owner->extra_string);
2515               loc->cmd_bytecode = aexpr;
2516
2517               if (!aexpr)
2518                 continue;
2519             }
2520
2521           /* If we have a NULL bytecode expression, it means something
2522              went wrong or we have a null command expression.  */
2523           if (!loc->cmd_bytecode)
2524             {
2525               null_command_or_parse_error = 1;
2526               break;
2527             }
2528         }
2529     }
2530
2531   /* If anything failed, then we're not doing target-side commands,
2532      and so clean up.  */
2533   if (null_command_or_parse_error)
2534     {
2535       ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2536         {
2537           loc = (*loc2p);
2538           if (is_breakpoint (loc->owner)
2539               && loc->pspace->num == bl->pspace->num)
2540             {
2541               /* Only go as far as the first NULL bytecode is
2542                  located.  */
2543               if (loc->cmd_bytecode == NULL)
2544                 return;
2545
2546               free_agent_expr (loc->cmd_bytecode);
2547               loc->cmd_bytecode = NULL;
2548             }
2549         }
2550     }
2551
2552   /* No NULL commands or failed bytecode generation.  Build a command list
2553      for this location's address.  */
2554   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2555     {
2556       loc = (*loc2p);
2557       if (loc->owner->extra_string
2558           && is_breakpoint (loc->owner)
2559           && loc->pspace->num == bl->pspace->num
2560           && loc->owner->enable_state == bp_enabled
2561           && loc->enabled)
2562         /* Add the command to the vector.  This will be used later
2563            to send the commands to the target.  */
2564         VEC_safe_push (agent_expr_p, bl->target_info.tcommands,
2565                        loc->cmd_bytecode);
2566     }
2567
2568   bl->target_info.persist = 0;
2569   /* Maybe flag this location as persistent.  */
2570   if (bl->owner->type == bp_dprintf && disconnected_dprintf)
2571     bl->target_info.persist = 1;
2572 }
2573
2574 /* Insert a low-level "breakpoint" of some type.  BL is the breakpoint
2575    location.  Any error messages are printed to TMP_ERROR_STREAM; and
2576    DISABLED_BREAKS, and HW_BREAKPOINT_ERROR are used to report problems.
2577    Returns 0 for success, 1 if the bp_location type is not supported or
2578    -1 for failure.
2579
2580    NOTE drow/2003-09-09: This routine could be broken down to an
2581    object-style method for each breakpoint or catchpoint type.  */
2582 static int
2583 insert_bp_location (struct bp_location *bl,
2584                     struct ui_file *tmp_error_stream,
2585                     int *disabled_breaks,
2586                     int *hw_breakpoint_error,
2587                     int *hw_bp_error_explained_already)
2588 {
2589   enum errors bp_err = GDB_NO_ERROR;
2590   const char *bp_err_message = NULL;
2591
2592   if (!should_be_inserted (bl) || (bl->inserted && !bl->needs_update))
2593     return 0;
2594
2595   /* Note we don't initialize bl->target_info, as that wipes out
2596      the breakpoint location's shadow_contents if the breakpoint
2597      is still inserted at that location.  This in turn breaks
2598      target_read_memory which depends on these buffers when
2599      a memory read is requested at the breakpoint location:
2600      Once the target_info has been wiped, we fail to see that
2601      we have a breakpoint inserted at that address and thus
2602      read the breakpoint instead of returning the data saved in
2603      the breakpoint location's shadow contents.  */
2604   bl->target_info.reqstd_address = bl->address;
2605   bl->target_info.placed_address_space = bl->pspace->aspace;
2606   bl->target_info.length = bl->length;
2607
2608   /* When working with target-side conditions, we must pass all the conditions
2609      for the same breakpoint address down to the target since GDB will not
2610      insert those locations.  With a list of breakpoint conditions, the target
2611      can decide when to stop and notify GDB.  */
2612
2613   if (is_breakpoint (bl->owner))
2614     {
2615       build_target_condition_list (bl);
2616       build_target_command_list (bl);
2617       /* Reset the modification marker.  */
2618       bl->needs_update = 0;
2619     }
2620
2621   if (bl->loc_type == bp_loc_software_breakpoint
2622       || bl->loc_type == bp_loc_hardware_breakpoint)
2623     {
2624       if (bl->owner->type != bp_hardware_breakpoint)
2625         {
2626           /* If the explicitly specified breakpoint type
2627              is not hardware breakpoint, check the memory map to see
2628              if the breakpoint address is in read only memory or not.
2629
2630              Two important cases are:
2631              - location type is not hardware breakpoint, memory
2632              is readonly.  We change the type of the location to
2633              hardware breakpoint.
2634              - location type is hardware breakpoint, memory is
2635              read-write.  This means we've previously made the
2636              location hardware one, but then the memory map changed,
2637              so we undo.
2638              
2639              When breakpoints are removed, remove_breakpoints will use
2640              location types we've just set here, the only possible
2641              problem is that memory map has changed during running
2642              program, but it's not going to work anyway with current
2643              gdb.  */
2644           struct mem_region *mr 
2645             = lookup_mem_region (bl->target_info.reqstd_address);
2646           
2647           if (mr)
2648             {
2649               if (automatic_hardware_breakpoints)
2650                 {
2651                   enum bp_loc_type new_type;
2652                   
2653                   if (mr->attrib.mode != MEM_RW)
2654                     new_type = bp_loc_hardware_breakpoint;
2655                   else 
2656                     new_type = bp_loc_software_breakpoint;
2657                   
2658                   if (new_type != bl->loc_type)
2659                     {
2660                       static int said = 0;
2661
2662                       bl->loc_type = new_type;
2663                       if (!said)
2664                         {
2665                           fprintf_filtered (gdb_stdout,
2666                                             _("Note: automatically using "
2667                                               "hardware breakpoints for "
2668                                               "read-only addresses.\n"));
2669                           said = 1;
2670                         }
2671                     }
2672                 }
2673               else if (bl->loc_type == bp_loc_software_breakpoint
2674                        && mr->attrib.mode != MEM_RW)
2675                 {
2676                   fprintf_unfiltered (tmp_error_stream,
2677                                       _("Cannot insert breakpoint %d.\n"
2678                                         "Cannot set software breakpoint "
2679                                         "at read-only address %s\n"),
2680                                       bl->owner->number,
2681                                       paddress (bl->gdbarch, bl->address));
2682                   return 1;
2683                 }
2684             }
2685         }
2686         
2687       /* First check to see if we have to handle an overlay.  */
2688       if (overlay_debugging == ovly_off
2689           || bl->section == NULL
2690           || !(section_is_overlay (bl->section)))
2691         {
2692           /* No overlay handling: just set the breakpoint.  */
2693           TRY
2694             {
2695               int val;
2696
2697               val = bl->owner->ops->insert_location (bl);
2698               if (val)
2699                 bp_err = GENERIC_ERROR;
2700             }
2701           CATCH (e, RETURN_MASK_ALL)
2702             {
2703               bp_err = e.error;
2704               bp_err_message = e.message;
2705             }
2706           END_CATCH
2707         }
2708       else
2709         {
2710           /* This breakpoint is in an overlay section.
2711              Shall we set a breakpoint at the LMA?  */
2712           if (!overlay_events_enabled)
2713             {
2714               /* Yes -- overlay event support is not active, 
2715                  so we must try to set a breakpoint at the LMA.
2716                  This will not work for a hardware breakpoint.  */
2717               if (bl->loc_type == bp_loc_hardware_breakpoint)
2718                 warning (_("hardware breakpoint %d not supported in overlay!"),
2719                          bl->owner->number);
2720               else
2721                 {
2722                   CORE_ADDR addr = overlay_unmapped_address (bl->address,
2723                                                              bl->section);
2724                   /* Set a software (trap) breakpoint at the LMA.  */
2725                   bl->overlay_target_info = bl->target_info;
2726                   bl->overlay_target_info.reqstd_address = addr;
2727
2728                   /* No overlay handling: just set the breakpoint.  */
2729                   TRY
2730                     {
2731                       int val;
2732
2733                       val = target_insert_breakpoint (bl->gdbarch,
2734                                                       &bl->overlay_target_info);
2735                       if (val)
2736                         bp_err = GENERIC_ERROR;
2737                     }
2738                   CATCH (e, RETURN_MASK_ALL)
2739                     {
2740                       bp_err = e.error;
2741                       bp_err_message = e.message;
2742                     }
2743                   END_CATCH
2744
2745                   if (bp_err != GDB_NO_ERROR)
2746                     fprintf_unfiltered (tmp_error_stream,
2747                                         "Overlay breakpoint %d "
2748                                         "failed: in ROM?\n",
2749                                         bl->owner->number);
2750                 }
2751             }
2752           /* Shall we set a breakpoint at the VMA? */
2753           if (section_is_mapped (bl->section))
2754             {
2755               /* Yes.  This overlay section is mapped into memory.  */
2756               TRY
2757                 {
2758                   int val;
2759
2760                   val = bl->owner->ops->insert_location (bl);
2761                   if (val)
2762                     bp_err = GENERIC_ERROR;
2763                 }
2764               CATCH (e, RETURN_MASK_ALL)
2765                 {
2766                   bp_err = e.error;
2767                   bp_err_message = e.message;
2768                 }
2769               END_CATCH
2770             }
2771           else
2772             {
2773               /* No.  This breakpoint will not be inserted.  
2774                  No error, but do not mark the bp as 'inserted'.  */
2775               return 0;
2776             }
2777         }
2778
2779       if (bp_err != GDB_NO_ERROR)
2780         {
2781           /* Can't set the breakpoint.  */
2782
2783           /* In some cases, we might not be able to insert a
2784              breakpoint in a shared library that has already been
2785              removed, but we have not yet processed the shlib unload
2786              event.  Unfortunately, some targets that implement
2787              breakpoint insertion themselves can't tell why the
2788              breakpoint insertion failed (e.g., the remote target
2789              doesn't define error codes), so we must treat generic
2790              errors as memory errors.  */
2791           if ((bp_err == GENERIC_ERROR || bp_err == MEMORY_ERROR)
2792               && bl->loc_type == bp_loc_software_breakpoint
2793               && (solib_name_from_address (bl->pspace, bl->address)
2794                   || shared_objfile_contains_address_p (bl->pspace,
2795                                                         bl->address)))
2796             {
2797               /* See also: disable_breakpoints_in_shlibs.  */
2798               bl->shlib_disabled = 1;
2799               observer_notify_breakpoint_modified (bl->owner);
2800               if (!*disabled_breaks)
2801                 {
2802                   fprintf_unfiltered (tmp_error_stream, 
2803                                       "Cannot insert breakpoint %d.\n", 
2804                                       bl->owner->number);
2805                   fprintf_unfiltered (tmp_error_stream, 
2806                                       "Temporarily disabling shared "
2807                                       "library breakpoints:\n");
2808                 }
2809               *disabled_breaks = 1;
2810               fprintf_unfiltered (tmp_error_stream,
2811                                   "breakpoint #%d\n", bl->owner->number);
2812               return 0;
2813             }
2814           else
2815             {
2816               if (bl->loc_type == bp_loc_hardware_breakpoint)
2817                 {
2818                   *hw_breakpoint_error = 1;
2819                   *hw_bp_error_explained_already = bp_err_message != NULL;
2820                   fprintf_unfiltered (tmp_error_stream,
2821                                       "Cannot insert hardware breakpoint %d%s",
2822                                       bl->owner->number, bp_err_message ? ":" : ".\n");
2823                   if (bp_err_message != NULL)
2824                     fprintf_unfiltered (tmp_error_stream, "%s.\n", bp_err_message);
2825                 }
2826               else
2827                 {
2828                   if (bp_err_message == NULL)
2829                     {
2830                       char *message
2831                         = memory_error_message (TARGET_XFER_E_IO,
2832                                                 bl->gdbarch, bl->address);
2833                       struct cleanup *old_chain = make_cleanup (xfree, message);
2834
2835                       fprintf_unfiltered (tmp_error_stream,
2836                                           "Cannot insert breakpoint %d.\n"
2837                                           "%s\n",
2838                                           bl->owner->number, message);
2839                       do_cleanups (old_chain);
2840                     }
2841                   else
2842                     {
2843                       fprintf_unfiltered (tmp_error_stream,
2844                                           "Cannot insert breakpoint %d: %s\n",
2845                                           bl->owner->number,
2846                                           bp_err_message);
2847                     }
2848                 }
2849               return 1;
2850
2851             }
2852         }
2853       else
2854         bl->inserted = 1;
2855
2856       return 0;
2857     }
2858
2859   else if (bl->loc_type == bp_loc_hardware_watchpoint
2860            /* NOTE drow/2003-09-08: This state only exists for removing
2861               watchpoints.  It's not clear that it's necessary...  */
2862            && bl->owner->disposition != disp_del_at_next_stop)
2863     {
2864       int val;
2865
2866       gdb_assert (bl->owner->ops != NULL
2867                   && bl->owner->ops->insert_location != NULL);
2868
2869       val = bl->owner->ops->insert_location (bl);
2870
2871       /* If trying to set a read-watchpoint, and it turns out it's not
2872          supported, try emulating one with an access watchpoint.  */
2873       if (val == 1 && bl->watchpoint_type == hw_read)
2874         {
2875           struct bp_location *loc, **loc_temp;
2876
2877           /* But don't try to insert it, if there's already another
2878              hw_access location that would be considered a duplicate
2879              of this one.  */
2880           ALL_BP_LOCATIONS (loc, loc_temp)
2881             if (loc != bl
2882                 && loc->watchpoint_type == hw_access
2883                 && watchpoint_locations_match (bl, loc))
2884               {
2885                 bl->duplicate = 1;
2886                 bl->inserted = 1;
2887                 bl->target_info = loc->target_info;
2888                 bl->watchpoint_type = hw_access;
2889                 val = 0;
2890                 break;
2891               }
2892
2893           if (val == 1)
2894             {
2895               bl->watchpoint_type = hw_access;
2896               val = bl->owner->ops->insert_location (bl);
2897
2898               if (val)
2899                 /* Back to the original value.  */
2900                 bl->watchpoint_type = hw_read;
2901             }
2902         }
2903
2904       bl->inserted = (val == 0);
2905     }
2906
2907   else if (bl->owner->type == bp_catchpoint)
2908     {
2909       int val;
2910
2911       gdb_assert (bl->owner->ops != NULL
2912                   && bl->owner->ops->insert_location != NULL);
2913
2914       val = bl->owner->ops->insert_location (bl);
2915       if (val)
2916         {
2917           bl->owner->enable_state = bp_disabled;
2918
2919           if (val == 1)
2920             warning (_("\
2921 Error inserting catchpoint %d: Your system does not support this type\n\
2922 of catchpoint."), bl->owner->number);
2923           else
2924             warning (_("Error inserting catchpoint %d."), bl->owner->number);
2925         }
2926
2927       bl->inserted = (val == 0);
2928
2929       /* We've already printed an error message if there was a problem
2930          inserting this catchpoint, and we've disabled the catchpoint,
2931          so just return success.  */
2932       return 0;
2933     }
2934
2935   return 0;
2936 }
2937
2938 /* This function is called when program space PSPACE is about to be
2939    deleted.  It takes care of updating breakpoints to not reference
2940    PSPACE anymore.  */
2941
2942 void
2943 breakpoint_program_space_exit (struct program_space *pspace)
2944 {
2945   struct breakpoint *b, *b_temp;
2946   struct bp_location *loc, **loc_temp;
2947
2948   /* Remove any breakpoint that was set through this program space.  */
2949   ALL_BREAKPOINTS_SAFE (b, b_temp)
2950     {
2951       if (b->pspace == pspace)
2952         delete_breakpoint (b);
2953     }
2954
2955   /* Breakpoints set through other program spaces could have locations
2956      bound to PSPACE as well.  Remove those.  */
2957   ALL_BP_LOCATIONS (loc, loc_temp)
2958     {
2959       struct bp_location *tmp;
2960
2961       if (loc->pspace == pspace)
2962         {
2963           /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
2964           if (loc->owner->loc == loc)
2965             loc->owner->loc = loc->next;
2966           else
2967             for (tmp = loc->owner->loc; tmp->next != NULL; tmp = tmp->next)
2968               if (tmp->next == loc)
2969                 {
2970                   tmp->next = loc->next;
2971                   break;
2972                 }
2973         }
2974     }
2975
2976   /* Now update the global location list to permanently delete the
2977      removed locations above.  */
2978   update_global_location_list (UGLL_DONT_INSERT);
2979 }
2980
2981 /* Make sure all breakpoints are inserted in inferior.
2982    Throws exception on any error.
2983    A breakpoint that is already inserted won't be inserted
2984    again, so calling this function twice is safe.  */
2985 void
2986 insert_breakpoints (void)
2987 {
2988   struct breakpoint *bpt;
2989
2990   ALL_BREAKPOINTS (bpt)
2991     if (is_hardware_watchpoint (bpt))
2992       {
2993         struct watchpoint *w = (struct watchpoint *) bpt;
2994
2995         update_watchpoint (w, 0 /* don't reparse.  */);
2996       }
2997
2998   /* Updating watchpoints creates new locations, so update the global
2999      location list.  Explicitly tell ugll to insert locations and
3000      ignore breakpoints_always_inserted_mode.  */
3001   update_global_location_list (UGLL_INSERT);
3002 }
3003
3004 /* Invoke CALLBACK for each of bp_location.  */
3005
3006 void
3007 iterate_over_bp_locations (walk_bp_location_callback callback)
3008 {
3009   struct bp_location *loc, **loc_tmp;
3010
3011   ALL_BP_LOCATIONS (loc, loc_tmp)
3012     {
3013       callback (loc, NULL);
3014     }
3015 }
3016
3017 /* This is used when we need to synch breakpoint conditions between GDB and the
3018    target.  It is the case with deleting and disabling of breakpoints when using
3019    always-inserted mode.  */
3020
3021 static void
3022 update_inserted_breakpoint_locations (void)
3023 {
3024   struct bp_location *bl, **blp_tmp;
3025   int error_flag = 0;
3026   int val = 0;
3027   int disabled_breaks = 0;
3028   int hw_breakpoint_error = 0;
3029   int hw_bp_details_reported = 0;
3030
3031   struct ui_file *tmp_error_stream = mem_fileopen ();
3032   struct cleanup *cleanups = make_cleanup_ui_file_delete (tmp_error_stream);
3033
3034   /* Explicitly mark the warning -- this will only be printed if
3035      there was an error.  */
3036   fprintf_unfiltered (tmp_error_stream, "Warning:\n");
3037
3038   save_current_space_and_thread ();
3039
3040   ALL_BP_LOCATIONS (bl, blp_tmp)
3041     {
3042       /* We only want to update software breakpoints and hardware
3043          breakpoints.  */
3044       if (!is_breakpoint (bl->owner))
3045         continue;
3046
3047       /* We only want to update locations that are already inserted
3048          and need updating.  This is to avoid unwanted insertion during
3049          deletion of breakpoints.  */
3050       if (!bl->inserted || (bl->inserted && !bl->needs_update))
3051         continue;
3052
3053       switch_to_program_space_and_thread (bl->pspace);
3054
3055       /* For targets that support global breakpoints, there's no need
3056          to select an inferior to insert breakpoint to.  In fact, even
3057          if we aren't attached to any process yet, we should still
3058          insert breakpoints.  */
3059       if (!gdbarch_has_global_breakpoints (target_gdbarch ())
3060           && ptid_equal (inferior_ptid, null_ptid))
3061         continue;
3062
3063       val = insert_bp_location (bl, tmp_error_stream, &disabled_breaks,
3064                                     &hw_breakpoint_error, &hw_bp_details_reported);
3065       if (val)
3066         error_flag = val;
3067     }
3068
3069   if (error_flag)
3070     {
3071       target_terminal_ours_for_output ();
3072       error_stream (tmp_error_stream);
3073     }
3074
3075   do_cleanups (cleanups);
3076 }
3077
3078 /* Used when starting or continuing the program.  */
3079
3080 static void
3081 insert_breakpoint_locations (void)
3082 {
3083   struct breakpoint *bpt;
3084   struct bp_location *bl, **blp_tmp;
3085   int error_flag = 0;
3086   int val = 0;
3087   int disabled_breaks = 0;
3088   int hw_breakpoint_error = 0;
3089   int hw_bp_error_explained_already = 0;
3090
3091   struct ui_file *tmp_error_stream = mem_fileopen ();
3092   struct cleanup *cleanups = make_cleanup_ui_file_delete (tmp_error_stream);
3093   
3094   /* Explicitly mark the warning -- this will only be printed if
3095      there was an error.  */
3096   fprintf_unfiltered (tmp_error_stream, "Warning:\n");
3097
3098   save_current_space_and_thread ();
3099
3100   ALL_BP_LOCATIONS (bl, blp_tmp)
3101     {
3102       if (!should_be_inserted (bl) || (bl->inserted && !bl->needs_update))
3103         continue;
3104
3105       /* There is no point inserting thread-specific breakpoints if
3106          the thread no longer exists.  ALL_BP_LOCATIONS bp_location
3107          has BL->OWNER always non-NULL.  */
3108       if (bl->owner->thread != -1
3109           && !valid_thread_id (bl->owner->thread))
3110         continue;
3111
3112       switch_to_program_space_and_thread (bl->pspace);
3113
3114       /* For targets that support global breakpoints, there's no need
3115          to select an inferior to insert breakpoint to.  In fact, even
3116          if we aren't attached to any process yet, we should still
3117          insert breakpoints.  */
3118       if (!gdbarch_has_global_breakpoints (target_gdbarch ())
3119           && ptid_equal (inferior_ptid, null_ptid))
3120         continue;
3121
3122       val = insert_bp_location (bl, tmp_error_stream, &disabled_breaks,
3123                                     &hw_breakpoint_error, &hw_bp_error_explained_already);
3124       if (val)
3125         error_flag = val;
3126     }
3127
3128   /* If we failed to insert all locations of a watchpoint, remove
3129      them, as half-inserted watchpoint is of limited use.  */
3130   ALL_BREAKPOINTS (bpt)  
3131     {
3132       int some_failed = 0;
3133       struct bp_location *loc;
3134
3135       if (!is_hardware_watchpoint (bpt))
3136         continue;
3137
3138       if (!breakpoint_enabled (bpt))
3139         continue;
3140
3141       if (bpt->disposition == disp_del_at_next_stop)
3142         continue;
3143       
3144       for (loc = bpt->loc; loc; loc = loc->next)
3145         if (!loc->inserted && should_be_inserted (loc))
3146           {
3147             some_failed = 1;
3148             break;
3149           }
3150       if (some_failed)
3151         {
3152           for (loc = bpt->loc; loc; loc = loc->next)
3153             if (loc->inserted)
3154               remove_breakpoint (loc, mark_uninserted);
3155
3156           hw_breakpoint_error = 1;
3157           fprintf_unfiltered (tmp_error_stream,
3158                               "Could not insert hardware watchpoint %d.\n", 
3159                               bpt->number);
3160           error_flag = -1;
3161         }
3162     }
3163
3164   if (error_flag)
3165     {
3166       /* If a hardware breakpoint or watchpoint was inserted, add a
3167          message about possibly exhausted resources.  */
3168       if (hw_breakpoint_error && !hw_bp_error_explained_already)
3169         {
3170           fprintf_unfiltered (tmp_error_stream, 
3171                               "Could not insert hardware breakpoints:\n\
3172 You may have requested too many hardware breakpoints/watchpoints.\n");
3173         }
3174       target_terminal_ours_for_output ();
3175       error_stream (tmp_error_stream);
3176     }
3177
3178   do_cleanups (cleanups);
3179 }
3180
3181 /* Used when the program stops.
3182    Returns zero if successful, or non-zero if there was a problem
3183    removing a breakpoint location.  */
3184
3185 int
3186 remove_breakpoints (void)
3187 {
3188   struct bp_location *bl, **blp_tmp;
3189   int val = 0;
3190
3191   ALL_BP_LOCATIONS (bl, blp_tmp)
3192   {
3193     if (bl->inserted && !is_tracepoint (bl->owner))
3194       val |= remove_breakpoint (bl, mark_uninserted);
3195   }
3196   return val;
3197 }
3198
3199 /* When a thread exits, remove breakpoints that are related to
3200    that thread.  */
3201
3202 static void
3203 remove_threaded_breakpoints (struct thread_info *tp, int silent)
3204 {
3205   struct breakpoint *b, *b_tmp;
3206
3207   ALL_BREAKPOINTS_SAFE (b, b_tmp)
3208     {
3209       if (b->thread == tp->num && user_breakpoint_p (b))
3210         {
3211           b->disposition = disp_del_at_next_stop;
3212
3213           printf_filtered (_("\
3214 Thread-specific breakpoint %d deleted - thread %d no longer in the thread list.\n"),
3215                           b->number, tp->num);
3216
3217           /* Hide it from the user.  */
3218           b->number = 0;
3219        }
3220     }
3221 }
3222
3223 /* Remove breakpoints of process PID.  */
3224
3225 int
3226 remove_breakpoints_pid (int pid)
3227 {
3228   struct bp_location *bl, **blp_tmp;
3229   int val;
3230   struct inferior *inf = find_inferior_pid (pid);
3231
3232   ALL_BP_LOCATIONS (bl, blp_tmp)
3233   {
3234     if (bl->pspace != inf->pspace)
3235       continue;
3236
3237     if (bl->inserted && !bl->target_info.persist)
3238       {
3239         val = remove_breakpoint (bl, mark_uninserted);
3240         if (val != 0)
3241           return val;
3242       }
3243   }
3244   return 0;
3245 }
3246
3247 int
3248 reattach_breakpoints (int pid)
3249 {
3250   struct cleanup *old_chain;
3251   struct bp_location *bl, **blp_tmp;
3252   int val;
3253   struct ui_file *tmp_error_stream;
3254   int dummy1 = 0, dummy2 = 0, dummy3 = 0;
3255   struct inferior *inf;
3256   struct thread_info *tp;
3257
3258   tp = any_live_thread_of_process (pid);
3259   if (tp == NULL)
3260     return 1;
3261
3262   inf = find_inferior_pid (pid);
3263   old_chain = save_inferior_ptid ();
3264
3265   inferior_ptid = tp->ptid;
3266
3267   tmp_error_stream = mem_fileopen ();
3268   make_cleanup_ui_file_delete (tmp_error_stream);
3269
3270   ALL_BP_LOCATIONS (bl, blp_tmp)
3271   {
3272     if (bl->pspace != inf->pspace)
3273       continue;
3274
3275     if (bl->inserted)
3276       {
3277         bl->inserted = 0;
3278         val = insert_bp_location (bl, tmp_error_stream, &dummy1, &dummy2, &dummy3);
3279         if (val != 0)
3280           {
3281             do_cleanups (old_chain);
3282             return val;
3283           }
3284       }
3285   }
3286   do_cleanups (old_chain);
3287   return 0;
3288 }
3289
3290 static int internal_breakpoint_number = -1;
3291
3292 /* Set the breakpoint number of B, depending on the value of INTERNAL.
3293    If INTERNAL is non-zero, the breakpoint number will be populated
3294    from internal_breakpoint_number and that variable decremented.
3295    Otherwise the breakpoint number will be populated from
3296    breakpoint_count and that value incremented.  Internal breakpoints
3297    do not set the internal var bpnum.  */
3298 static void
3299 set_breakpoint_number (int internal, struct breakpoint *b)
3300 {
3301   if (internal)
3302     b->number = internal_breakpoint_number--;
3303   else
3304     {
3305       set_breakpoint_count (breakpoint_count + 1);
3306       b->number = breakpoint_count;
3307     }
3308 }
3309
3310 static struct breakpoint *
3311 create_internal_breakpoint (struct gdbarch *gdbarch,
3312                             CORE_ADDR address, enum bptype type,
3313                             const struct breakpoint_ops *ops)
3314 {
3315   struct symtab_and_line sal;
3316   struct breakpoint *b;
3317
3318   init_sal (&sal);              /* Initialize to zeroes.  */
3319
3320   sal.pc = address;
3321   sal.section = find_pc_overlay (sal.pc);
3322   sal.pspace = current_program_space;
3323
3324   b = set_raw_breakpoint (gdbarch, sal, type, ops);
3325   b->number = internal_breakpoint_number--;
3326   b->disposition = disp_donttouch;
3327
3328   return b;
3329 }
3330
3331 static const char *const longjmp_names[] =
3332   {
3333     "longjmp", "_longjmp", "siglongjmp", "_siglongjmp"
3334   };
3335 #define NUM_LONGJMP_NAMES ARRAY_SIZE(longjmp_names)
3336
3337 /* Per-objfile data private to breakpoint.c.  */
3338 struct breakpoint_objfile_data
3339 {
3340   /* Minimal symbol for "_ovly_debug_event" (if any).  */
3341   struct bound_minimal_symbol overlay_msym;
3342
3343   /* Minimal symbol(s) for "longjmp", "siglongjmp", etc. (if any).  */
3344   struct bound_minimal_symbol longjmp_msym[NUM_LONGJMP_NAMES];
3345
3346   /* True if we have looked for longjmp probes.  */
3347   int longjmp_searched;
3348
3349   /* SystemTap probe points for longjmp (if any).  */
3350   VEC (probe_p) *longjmp_probes;
3351
3352   /* Minimal symbol for "std::terminate()" (if any).  */
3353   struct bound_minimal_symbol terminate_msym;
3354
3355   /* Minimal symbol for "_Unwind_DebugHook" (if any).  */
3356   struct bound_minimal_symbol exception_msym;
3357
3358   /* True if we have looked for exception probes.  */
3359   int exception_searched;
3360
3361   /* SystemTap probe points for unwinding (if any).  */
3362   VEC (probe_p) *exception_probes;
3363 };
3364
3365 static const struct objfile_data *breakpoint_objfile_key;
3366
3367 /* Minimal symbol not found sentinel.  */
3368 static struct minimal_symbol msym_not_found;
3369
3370 /* Returns TRUE if MSYM point to the "not found" sentinel.  */
3371
3372 static int
3373 msym_not_found_p (const struct minimal_symbol *msym)
3374 {
3375   return msym == &msym_not_found;
3376 }
3377
3378 /* Return per-objfile data needed by breakpoint.c.
3379    Allocate the data if necessary.  */
3380
3381 static struct breakpoint_objfile_data *
3382 get_breakpoint_objfile_data (struct objfile *objfile)
3383 {
3384   struct breakpoint_objfile_data *bp_objfile_data;
3385
3386   bp_objfile_data = objfile_data (objfile, breakpoint_objfile_key);
3387   if (bp_objfile_data == NULL)
3388     {
3389       bp_objfile_data = obstack_alloc (&objfile->objfile_obstack,
3390                                        sizeof (*bp_objfile_data));
3391
3392       memset (bp_objfile_data, 0, sizeof (*bp_objfile_data));
3393       set_objfile_data (objfile, breakpoint_objfile_key, bp_objfile_data);
3394     }
3395   return bp_objfile_data;
3396 }
3397
3398 static void
3399 free_breakpoint_probes (struct objfile *obj, void *data)
3400 {
3401   struct breakpoint_objfile_data *bp_objfile_data = data;
3402
3403   VEC_free (probe_p, bp_objfile_data->longjmp_probes);
3404   VEC_free (probe_p, bp_objfile_data->exception_probes);
3405 }
3406
3407 static void
3408 create_overlay_event_breakpoint (void)
3409 {
3410   struct objfile *objfile;
3411   const char *const func_name = "_ovly_debug_event";
3412
3413   ALL_OBJFILES (objfile)
3414     {
3415       struct breakpoint *b;
3416       struct breakpoint_objfile_data *bp_objfile_data;
3417       CORE_ADDR addr;
3418
3419       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3420
3421       if (msym_not_found_p (bp_objfile_data->overlay_msym.minsym))
3422         continue;
3423
3424       if (bp_objfile_data->overlay_msym.minsym == NULL)
3425         {
3426           struct bound_minimal_symbol m;
3427
3428           m = lookup_minimal_symbol_text (func_name, objfile);
3429           if (m.minsym == NULL)
3430             {
3431               /* Avoid future lookups in this objfile.  */
3432               bp_objfile_data->overlay_msym.minsym = &msym_not_found;
3433               continue;
3434             }
3435           bp_objfile_data->overlay_msym = m;
3436         }
3437
3438       addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->overlay_msym);
3439       b = create_internal_breakpoint (get_objfile_arch (objfile), addr,
3440                                       bp_overlay_event,
3441                                       &internal_breakpoint_ops);
3442       b->addr_string = xstrdup (func_name);
3443
3444       if (overlay_debugging == ovly_auto)
3445         {
3446           b->enable_state = bp_enabled;
3447           overlay_events_enabled = 1;
3448         }
3449       else
3450        {
3451          b->enable_state = bp_disabled;
3452          overlay_events_enabled = 0;
3453        }
3454     }
3455   update_global_location_list (UGLL_MAY_INSERT);
3456 }
3457
3458 static void
3459 create_longjmp_master_breakpoint (void)
3460 {
3461   struct program_space *pspace;
3462   struct cleanup *old_chain;
3463
3464   old_chain = save_current_program_space ();
3465
3466   ALL_PSPACES (pspace)
3467   {
3468     struct objfile *objfile;
3469
3470     set_current_program_space (pspace);
3471
3472     ALL_OBJFILES (objfile)
3473     {
3474       int i;
3475       struct gdbarch *gdbarch;
3476       struct breakpoint_objfile_data *bp_objfile_data;
3477
3478       gdbarch = get_objfile_arch (objfile);
3479
3480       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3481
3482       if (!bp_objfile_data->longjmp_searched)
3483         {
3484           VEC (probe_p) *ret;
3485
3486           ret = find_probes_in_objfile (objfile, "libc", "longjmp");
3487           if (ret != NULL)
3488             {
3489               /* We are only interested in checking one element.  */
3490               struct probe *p = VEC_index (probe_p, ret, 0);
3491
3492               if (!can_evaluate_probe_arguments (p))
3493                 {
3494                   /* We cannot use the probe interface here, because it does
3495                      not know how to evaluate arguments.  */
3496                   VEC_free (probe_p, ret);
3497                   ret = NULL;
3498                 }
3499             }
3500           bp_objfile_data->longjmp_probes = ret;
3501           bp_objfile_data->longjmp_searched = 1;
3502         }
3503
3504       if (bp_objfile_data->longjmp_probes != NULL)
3505         {
3506           int i;
3507           struct probe *probe;
3508           struct gdbarch *gdbarch = get_objfile_arch (objfile);
3509
3510           for (i = 0;
3511                VEC_iterate (probe_p,
3512                             bp_objfile_data->longjmp_probes,
3513                             i, probe);
3514                ++i)
3515             {
3516               struct breakpoint *b;
3517
3518               b = create_internal_breakpoint (gdbarch,
3519                                               get_probe_address (probe,
3520                                                                  objfile),
3521                                               bp_longjmp_master,
3522                                               &internal_breakpoint_ops);
3523               b->addr_string = xstrdup ("-probe-stap libc:longjmp");
3524               b->enable_state = bp_disabled;
3525             }
3526
3527           continue;
3528         }
3529
3530       if (!gdbarch_get_longjmp_target_p (gdbarch))
3531         continue;
3532
3533       for (i = 0; i < NUM_LONGJMP_NAMES; i++)
3534         {
3535           struct breakpoint *b;
3536           const char *func_name;
3537           CORE_ADDR addr;
3538
3539           if (msym_not_found_p (bp_objfile_data->longjmp_msym[i].minsym))
3540             continue;
3541
3542           func_name = longjmp_names[i];
3543           if (bp_objfile_data->longjmp_msym[i].minsym == NULL)
3544             {
3545               struct bound_minimal_symbol m;
3546
3547               m = lookup_minimal_symbol_text (func_name, objfile);
3548               if (m.minsym == NULL)
3549                 {
3550                   /* Prevent future lookups in this objfile.  */
3551                   bp_objfile_data->longjmp_msym[i].minsym = &msym_not_found;
3552                   continue;
3553                 }
3554               bp_objfile_data->longjmp_msym[i] = m;
3555             }
3556
3557           addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->longjmp_msym[i]);
3558           b = create_internal_breakpoint (gdbarch, addr, bp_longjmp_master,
3559                                           &internal_breakpoint_ops);
3560           b->addr_string = xstrdup (func_name);
3561           b->enable_state = bp_disabled;
3562         }
3563     }
3564   }
3565   update_global_location_list (UGLL_MAY_INSERT);
3566
3567   do_cleanups (old_chain);
3568 }
3569
3570 /* Create a master std::terminate breakpoint.  */
3571 static void
3572 create_std_terminate_master_breakpoint (void)
3573 {
3574   struct program_space *pspace;
3575   struct cleanup *old_chain;
3576   const char *const func_name = "std::terminate()";
3577
3578   old_chain = save_current_program_space ();
3579
3580   ALL_PSPACES (pspace)
3581   {
3582     struct objfile *objfile;
3583     CORE_ADDR addr;
3584
3585     set_current_program_space (pspace);
3586
3587     ALL_OBJFILES (objfile)
3588     {
3589       struct breakpoint *b;
3590       struct breakpoint_objfile_data *bp_objfile_data;
3591
3592       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3593
3594       if (msym_not_found_p (bp_objfile_data->terminate_msym.minsym))
3595         continue;
3596
3597       if (bp_objfile_data->terminate_msym.minsym == NULL)
3598         {
3599           struct bound_minimal_symbol m;
3600
3601           m = lookup_minimal_symbol (func_name, NULL, objfile);
3602           if (m.minsym == NULL || (MSYMBOL_TYPE (m.minsym) != mst_text
3603                                    && MSYMBOL_TYPE (m.minsym) != mst_file_text))
3604             {
3605               /* Prevent future lookups in this objfile.  */
3606               bp_objfile_data->terminate_msym.minsym = &msym_not_found;
3607               continue;
3608             }
3609           bp_objfile_data->terminate_msym = m;
3610         }
3611
3612       addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->terminate_msym);
3613       b = create_internal_breakpoint (get_objfile_arch (objfile), addr,
3614                                       bp_std_terminate_master,
3615                                       &internal_breakpoint_ops);
3616       b->addr_string = xstrdup (func_name);
3617       b->enable_state = bp_disabled;
3618     }
3619   }
3620
3621   update_global_location_list (UGLL_MAY_INSERT);
3622
3623   do_cleanups (old_chain);
3624 }
3625
3626 /* Install a master breakpoint on the unwinder's debug hook.  */
3627
3628 static void
3629 create_exception_master_breakpoint (void)
3630 {
3631   struct objfile *objfile;
3632   const char *const func_name = "_Unwind_DebugHook";
3633
3634   ALL_OBJFILES (objfile)
3635     {
3636       struct breakpoint *b;
3637       struct gdbarch *gdbarch;
3638       struct breakpoint_objfile_data *bp_objfile_data;
3639       CORE_ADDR addr;
3640
3641       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3642
3643       /* We prefer the SystemTap probe point if it exists.  */
3644       if (!bp_objfile_data->exception_searched)
3645         {
3646           VEC (probe_p) *ret;
3647
3648           ret = find_probes_in_objfile (objfile, "libgcc", "unwind");
3649
3650           if (ret != NULL)
3651             {
3652               /* We are only interested in checking one element.  */
3653               struct probe *p = VEC_index (probe_p, ret, 0);
3654
3655               if (!can_evaluate_probe_arguments (p))
3656                 {
3657                   /* We cannot use the probe interface here, because it does
3658                      not know how to evaluate arguments.  */
3659                   VEC_free (probe_p, ret);
3660                   ret = NULL;
3661                 }
3662             }
3663           bp_objfile_data->exception_probes = ret;
3664           bp_objfile_data->exception_searched = 1;
3665         }
3666
3667       if (bp_objfile_data->exception_probes != NULL)
3668         {
3669           struct gdbarch *gdbarch = get_objfile_arch (objfile);
3670           int i;
3671           struct probe *probe;
3672
3673           for (i = 0;
3674                VEC_iterate (probe_p,
3675                             bp_objfile_data->exception_probes,
3676                             i, probe);
3677                ++i)
3678             {
3679               struct breakpoint *b;
3680
3681               b = create_internal_breakpoint (gdbarch,
3682                                               get_probe_address (probe,
3683                                                                  objfile),
3684                                               bp_exception_master,
3685                                               &internal_breakpoint_ops);
3686               b->addr_string = xstrdup ("-probe-stap libgcc:unwind");
3687               b->enable_state = bp_disabled;
3688             }
3689
3690           continue;
3691         }
3692
3693       /* Otherwise, try the hook function.  */
3694
3695       if (msym_not_found_p (bp_objfile_data->exception_msym.minsym))
3696         continue;
3697
3698       gdbarch = get_objfile_arch (objfile);
3699
3700       if (bp_objfile_data->exception_msym.minsym == NULL)
3701         {
3702           struct bound_minimal_symbol debug_hook;
3703
3704           debug_hook = lookup_minimal_symbol (func_name, NULL, objfile);
3705           if (debug_hook.minsym == NULL)
3706             {
3707               bp_objfile_data->exception_msym.minsym = &msym_not_found;
3708               continue;
3709             }
3710
3711           bp_objfile_data->exception_msym = debug_hook;
3712         }
3713
3714       addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->exception_msym);
3715       addr = gdbarch_convert_from_func_ptr_addr (gdbarch, addr,
3716                                                  &current_target);
3717       b = create_internal_breakpoint (gdbarch, addr, bp_exception_master,
3718                                       &internal_breakpoint_ops);
3719       b->addr_string = xstrdup (func_name);
3720       b->enable_state = bp_disabled;
3721     }
3722
3723   update_global_location_list (UGLL_MAY_INSERT);
3724 }
3725
3726 void
3727 update_breakpoints_after_exec (void)
3728 {
3729   struct breakpoint *b, *b_tmp;
3730   struct bp_location *bploc, **bplocp_tmp;
3731
3732   /* We're about to delete breakpoints from GDB's lists.  If the
3733      INSERTED flag is true, GDB will try to lift the breakpoints by
3734      writing the breakpoints' "shadow contents" back into memory.  The
3735      "shadow contents" are NOT valid after an exec, so GDB should not
3736      do that.  Instead, the target is responsible from marking
3737      breakpoints out as soon as it detects an exec.  We don't do that
3738      here instead, because there may be other attempts to delete
3739      breakpoints after detecting an exec and before reaching here.  */
3740   ALL_BP_LOCATIONS (bploc, bplocp_tmp)
3741     if (bploc->pspace == current_program_space)
3742       gdb_assert (!bploc->inserted);
3743
3744   ALL_BREAKPOINTS_SAFE (b, b_tmp)
3745   {
3746     if (b->pspace != current_program_space)
3747       continue;
3748
3749     /* Solib breakpoints must be explicitly reset after an exec().  */
3750     if (b->type == bp_shlib_event)
3751       {
3752         delete_breakpoint (b);
3753         continue;
3754       }
3755
3756     /* JIT breakpoints must be explicitly reset after an exec().  */
3757     if (b->type == bp_jit_event)
3758       {
3759         delete_breakpoint (b);
3760         continue;
3761       }
3762
3763     /* Thread event breakpoints must be set anew after an exec(),
3764        as must overlay event and longjmp master breakpoints.  */
3765     if (b->type == bp_thread_event || b->type == bp_overlay_event
3766         || b->type == bp_longjmp_master || b->type == bp_std_terminate_master
3767         || b->type == bp_exception_master)
3768       {
3769         delete_breakpoint (b);
3770         continue;
3771       }
3772
3773     /* Step-resume breakpoints are meaningless after an exec().  */
3774     if (b->type == bp_step_resume || b->type == bp_hp_step_resume)
3775       {
3776         delete_breakpoint (b);
3777         continue;
3778       }
3779
3780     /* Just like single-step breakpoints.  */
3781     if (b->type == bp_single_step)
3782       {
3783         delete_breakpoint (b);
3784         continue;
3785       }
3786
3787     /* Longjmp and longjmp-resume breakpoints are also meaningless
3788        after an exec.  */
3789     if (b->type == bp_longjmp || b->type == bp_longjmp_resume
3790         || b->type == bp_longjmp_call_dummy
3791         || b->type == bp_exception || b->type == bp_exception_resume)
3792       {
3793         delete_breakpoint (b);
3794         continue;
3795       }
3796
3797     if (b->type == bp_catchpoint)
3798       {
3799         /* For now, none of the bp_catchpoint breakpoints need to
3800            do anything at this point.  In the future, if some of
3801            the catchpoints need to something, we will need to add
3802            a new method, and call this method from here.  */
3803         continue;
3804       }
3805
3806     /* bp_finish is a special case.  The only way we ought to be able
3807        to see one of these when an exec() has happened, is if the user
3808        caught a vfork, and then said "finish".  Ordinarily a finish just
3809        carries them to the call-site of the current callee, by setting
3810        a temporary bp there and resuming.  But in this case, the finish
3811        will carry them entirely through the vfork & exec.
3812
3813        We don't want to allow a bp_finish to remain inserted now.  But
3814        we can't safely delete it, 'cause finish_command has a handle to
3815        the bp on a bpstat, and will later want to delete it.  There's a
3816        chance (and I've seen it happen) that if we delete the bp_finish
3817        here, that its storage will get reused by the time finish_command
3818        gets 'round to deleting the "use to be a bp_finish" breakpoint.
3819        We really must allow finish_command to delete a bp_finish.
3820
3821        In the absence of a general solution for the "how do we know
3822        it's safe to delete something others may have handles to?"
3823        problem, what we'll do here is just uninsert the bp_finish, and
3824        let finish_command delete it.
3825
3826        (We know the bp_finish is "doomed" in the sense that it's
3827        momentary, and will be deleted as soon as finish_command sees
3828        the inferior stopped.  So it doesn't matter that the bp's
3829        address is probably bogus in the new a.out, unlike e.g., the
3830        solib breakpoints.)  */
3831
3832     if (b->type == bp_finish)
3833       {
3834         continue;
3835       }
3836
3837     /* Without a symbolic address, we have little hope of the
3838        pre-exec() address meaning the same thing in the post-exec()
3839        a.out.  */
3840     if (b->addr_string == NULL)
3841       {
3842         delete_breakpoint (b);
3843         continue;
3844       }
3845   }
3846 }
3847
3848 int
3849 detach_breakpoints (ptid_t ptid)
3850 {
3851   struct bp_location *bl, **blp_tmp;
3852   int val = 0;
3853   struct cleanup *old_chain = save_inferior_ptid ();
3854   struct inferior *inf = current_inferior ();
3855
3856   if (ptid_get_pid (ptid) == ptid_get_pid (inferior_ptid))
3857     error (_("Cannot detach breakpoints of inferior_ptid"));
3858
3859   /* Set inferior_ptid; remove_breakpoint_1 uses this global.  */
3860   inferior_ptid = ptid;
3861   ALL_BP_LOCATIONS (bl, blp_tmp)
3862   {
3863     if (bl->pspace != inf->pspace)
3864       continue;
3865
3866     /* This function must physically remove breakpoints locations
3867        from the specified ptid, without modifying the breakpoint
3868        package's state.  Locations of type bp_loc_other are only
3869        maintained at GDB side.  So, there is no need to remove
3870        these bp_loc_other locations.  Moreover, removing these
3871        would modify the breakpoint package's state.  */
3872     if (bl->loc_type == bp_loc_other)
3873       continue;
3874
3875     if (bl->inserted)
3876       val |= remove_breakpoint_1 (bl, mark_inserted);
3877   }
3878
3879   do_cleanups (old_chain);
3880   return val;
3881 }
3882
3883 /* Remove the breakpoint location BL from the current address space.
3884    Note that this is used to detach breakpoints from a child fork.
3885    When we get here, the child isn't in the inferior list, and neither
3886    do we have objects to represent its address space --- we should
3887    *not* look at bl->pspace->aspace here.  */
3888
3889 static int
3890 remove_breakpoint_1 (struct bp_location *bl, insertion_state_t is)
3891 {
3892   int val;
3893
3894   /* BL is never in moribund_locations by our callers.  */
3895   gdb_assert (bl->owner != NULL);
3896
3897   if (bl->permanent)
3898     /* Permanent breakpoints cannot be inserted or removed.  */
3899     return 0;
3900
3901   /* The type of none suggests that owner is actually deleted.
3902      This should not ever happen.  */
3903   gdb_assert (bl->owner->type != bp_none);
3904
3905   if (bl->loc_type == bp_loc_software_breakpoint
3906       || bl->loc_type == bp_loc_hardware_breakpoint)
3907     {
3908       /* "Normal" instruction breakpoint: either the standard
3909          trap-instruction bp (bp_breakpoint), or a
3910          bp_hardware_breakpoint.  */
3911
3912       /* First check to see if we have to handle an overlay.  */
3913       if (overlay_debugging == ovly_off
3914           || bl->section == NULL
3915           || !(section_is_overlay (bl->section)))
3916         {
3917           /* No overlay handling: just remove the breakpoint.  */
3918
3919           /* If we're trying to uninsert a memory breakpoint that we
3920              know is set in a dynamic object that is marked
3921              shlib_disabled, then either the dynamic object was
3922              removed with "remove-symbol-file" or with
3923              "nosharedlibrary".  In the former case, we don't know
3924              whether another dynamic object might have loaded over the
3925              breakpoint's address -- the user might well let us know
3926              about it next with add-symbol-file (the whole point of
3927              add-symbol-file is letting the user manually maintain a
3928              list of dynamically loaded objects).  If we have the
3929              breakpoint's shadow memory, that is, this is a software
3930              breakpoint managed by GDB, check whether the breakpoint
3931              is still inserted in memory, to avoid overwriting wrong
3932              code with stale saved shadow contents.  Note that HW
3933              breakpoints don't have shadow memory, as they're
3934              implemented using a mechanism that is not dependent on
3935              being able to modify the target's memory, and as such
3936              they should always be removed.  */
3937           if (bl->shlib_disabled
3938               && bl->target_info.shadow_len != 0
3939               && !memory_validate_breakpoint (bl->gdbarch, &bl->target_info))
3940             val = 0;
3941           else
3942             val = bl->owner->ops->remove_location (bl);
3943         }
3944       else
3945         {
3946           /* This breakpoint is in an overlay section.
3947              Did we set a breakpoint at the LMA?  */
3948           if (!overlay_events_enabled)
3949               {
3950                 /* Yes -- overlay event support is not active, so we
3951                    should have set a breakpoint at the LMA.  Remove it.  
3952                 */
3953                 /* Ignore any failures: if the LMA is in ROM, we will
3954                    have already warned when we failed to insert it.  */
3955                 if (bl->loc_type == bp_loc_hardware_breakpoint)
3956                   target_remove_hw_breakpoint (bl->gdbarch,
3957                                                &bl->overlay_target_info);
3958                 else
3959                   target_remove_breakpoint (bl->gdbarch,
3960                                             &bl->overlay_target_info);
3961               }
3962           /* Did we set a breakpoint at the VMA? 
3963              If so, we will have marked the breakpoint 'inserted'.  */
3964           if (bl->inserted)
3965             {
3966               /* Yes -- remove it.  Previously we did not bother to
3967                  remove the breakpoint if the section had been
3968                  unmapped, but let's not rely on that being safe.  We
3969                  don't know what the overlay manager might do.  */
3970
3971               /* However, we should remove *software* breakpoints only
3972                  if the section is still mapped, or else we overwrite
3973                  wrong code with the saved shadow contents.  */
3974               if (bl->loc_type == bp_loc_hardware_breakpoint
3975                   || section_is_mapped (bl->section))
3976                 val = bl->owner->ops->remove_location (bl);
3977               else
3978                 val = 0;
3979             }
3980           else
3981             {
3982               /* No -- not inserted, so no need to remove.  No error.  */
3983               val = 0;
3984             }
3985         }
3986
3987       /* In some cases, we might not be able to remove a breakpoint in
3988          a shared library that has already been removed, but we have
3989          not yet processed the shlib unload event.  Similarly for an
3990          unloaded add-symbol-file object - the user might not yet have
3991          had the chance to remove-symbol-file it.  shlib_disabled will
3992          be set if the library/object has already been removed, but
3993          the breakpoint hasn't been uninserted yet, e.g., after
3994          "nosharedlibrary" or "remove-symbol-file" with breakpoints
3995          always-inserted mode.  */
3996       if (val
3997           && (bl->loc_type == bp_loc_software_breakpoint
3998               && (bl->shlib_disabled
3999                   || solib_name_from_address (bl->pspace, bl->address)
4000                   || shared_objfile_contains_address_p (bl->pspace,
4001                                                         bl->address))))
4002         val = 0;
4003
4004       if (val)
4005         return val;
4006       bl->inserted = (is == mark_inserted);
4007     }
4008   else if (bl->loc_type == bp_loc_hardware_watchpoint)
4009     {
4010       gdb_assert (bl->owner->ops != NULL
4011                   && bl->owner->ops->remove_location != NULL);
4012
4013       bl->inserted = (is == mark_inserted);
4014       bl->owner->ops->remove_location (bl);
4015
4016       /* Failure to remove any of the hardware watchpoints comes here.  */
4017       if ((is == mark_uninserted) && (bl->inserted))
4018         warning (_("Could not remove hardware watchpoint %d."),
4019                  bl->owner->number);
4020     }
4021   else if (bl->owner->type == bp_catchpoint
4022            && breakpoint_enabled (bl->owner)
4023            && !bl->duplicate)
4024     {
4025       gdb_assert (bl->owner->ops != NULL
4026                   && bl->owner->ops->remove_location != NULL);
4027
4028       val = bl->owner->ops->remove_location (bl);
4029       if (val)
4030         return val;
4031
4032       bl->inserted = (is == mark_inserted);
4033     }
4034
4035   return 0;
4036 }
4037
4038 static int
4039 remove_breakpoint (struct bp_location *bl, insertion_state_t is)
4040 {
4041   int ret;
4042   struct cleanup *old_chain;
4043
4044   /* BL is never in moribund_locations by our callers.  */
4045   gdb_assert (bl->owner != NULL);
4046
4047   if (bl->permanent)
4048     /* Permanent breakpoints cannot be inserted or removed.  */
4049     return 0;
4050
4051   /* The type of none suggests that owner is actually deleted.
4052      This should not ever happen.  */
4053   gdb_assert (bl->owner->type != bp_none);
4054
4055   old_chain = save_current_space_and_thread ();
4056
4057   switch_to_program_space_and_thread (bl->pspace);
4058
4059   ret = remove_breakpoint_1 (bl, is);
4060
4061   do_cleanups (old_chain);
4062   return ret;
4063 }
4064
4065 /* Clear the "inserted" flag in all breakpoints.  */
4066
4067 void
4068 mark_breakpoints_out (void)
4069 {
4070   struct bp_location *bl, **blp_tmp;
4071
4072   ALL_BP_LOCATIONS (bl, blp_tmp)
4073     if (bl->pspace == current_program_space
4074         && !bl->permanent)
4075       bl->inserted = 0;
4076 }
4077
4078 /* Clear the "inserted" flag in all breakpoints and delete any
4079    breakpoints which should go away between runs of the program.
4080
4081    Plus other such housekeeping that has to be done for breakpoints
4082    between runs.
4083
4084    Note: this function gets called at the end of a run (by
4085    generic_mourn_inferior) and when a run begins (by
4086    init_wait_for_inferior).  */
4087
4088
4089
4090 void
4091 breakpoint_init_inferior (enum inf_context context)
4092 {
4093   struct breakpoint *b, *b_tmp;
4094   struct bp_location *bl, **blp_tmp;
4095   int ix;
4096   struct program_space *pspace = current_program_space;
4097
4098   /* If breakpoint locations are shared across processes, then there's
4099      nothing to do.  */
4100   if (gdbarch_has_global_breakpoints (target_gdbarch ()))
4101     return;
4102
4103   mark_breakpoints_out ();
4104
4105   ALL_BREAKPOINTS_SAFE (b, b_tmp)
4106   {
4107     if (b->loc && b->loc->pspace != pspace)
4108       continue;
4109
4110     switch (b->type)
4111       {
4112       case bp_call_dummy:
4113       case bp_longjmp_call_dummy:
4114
4115         /* If the call dummy breakpoint is at the entry point it will
4116            cause problems when the inferior is rerun, so we better get
4117            rid of it.  */
4118
4119       case bp_watchpoint_scope:
4120
4121         /* Also get rid of scope breakpoints.  */
4122
4123       case bp_shlib_event:
4124
4125         /* Also remove solib event breakpoints.  Their addresses may
4126            have changed since the last time we ran the program.
4127            Actually we may now be debugging against different target;
4128            and so the solib backend that installed this breakpoint may
4129            not be used in by the target.  E.g.,
4130
4131            (gdb) file prog-linux
4132            (gdb) run               # native linux target
4133            ...
4134            (gdb) kill
4135            (gdb) file prog-win.exe
4136            (gdb) tar rem :9999     # remote Windows gdbserver.
4137         */
4138
4139       case bp_step_resume:
4140
4141         /* Also remove step-resume breakpoints.  */
4142
4143       case bp_single_step:
4144
4145         /* Also remove single-step breakpoints.  */
4146
4147         delete_breakpoint (b);
4148         break;
4149
4150       case bp_watchpoint:
4151       case bp_hardware_watchpoint:
4152       case bp_read_watchpoint:
4153       case bp_access_watchpoint:
4154         {
4155           struct watchpoint *w = (struct watchpoint *) b;
4156
4157           /* Likewise for watchpoints on local expressions.  */
4158           if (w->exp_valid_block != NULL)
4159             delete_breakpoint (b);
4160           else if (context == inf_starting)
4161             {
4162               /* Reset val field to force reread of starting value in
4163                  insert_breakpoints.  */
4164               if (w->val)
4165                 value_free (w->val);
4166               w->val = NULL;
4167               w->val_valid = 0;
4168           }
4169         }
4170         break;
4171       default:
4172         break;
4173       }
4174   }
4175
4176   /* Get rid of the moribund locations.  */
4177   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, bl); ++ix)
4178     decref_bp_location (&bl);
4179   VEC_free (bp_location_p, moribund_locations);
4180 }
4181
4182 /* These functions concern about actual breakpoints inserted in the
4183    target --- to e.g. check if we need to do decr_pc adjustment or if
4184    we need to hop over the bkpt --- so we check for address space
4185    match, not program space.  */
4186
4187 /* breakpoint_here_p (PC) returns non-zero if an enabled breakpoint
4188    exists at PC.  It returns ordinary_breakpoint_here if it's an
4189    ordinary breakpoint, or permanent_breakpoint_here if it's a
4190    permanent breakpoint.
4191    - When continuing from a location with an ordinary breakpoint, we
4192      actually single step once before calling insert_breakpoints.
4193    - When continuing from a location with a permanent breakpoint, we
4194      need to use the `SKIP_PERMANENT_BREAKPOINT' macro, provided by
4195      the target, to advance the PC past the breakpoint.  */
4196
4197 enum breakpoint_here
4198 breakpoint_here_p (struct address_space *aspace, CORE_ADDR pc)
4199 {
4200   struct bp_location *bl, **blp_tmp;
4201   int any_breakpoint_here = 0;
4202
4203   ALL_BP_LOCATIONS (bl, blp_tmp)
4204     {
4205       if (bl->loc_type != bp_loc_software_breakpoint
4206           && bl->loc_type != bp_loc_hardware_breakpoint)
4207         continue;
4208
4209       /* ALL_BP_LOCATIONS bp_location has BL->OWNER always non-NULL.  */
4210       if ((breakpoint_enabled (bl->owner)
4211            || bl->permanent)
4212           && breakpoint_location_address_match (bl, aspace, pc))
4213         {
4214           if (overlay_debugging 
4215               && section_is_overlay (bl->section)
4216               && !section_is_mapped (bl->section))
4217             continue;           /* unmapped overlay -- can't be a match */
4218           else if (bl->permanent)
4219             return permanent_breakpoint_here;
4220           else
4221             any_breakpoint_here = 1;
4222         }
4223     }
4224
4225   return any_breakpoint_here ? ordinary_breakpoint_here : 0;
4226 }
4227
4228 /* Return true if there's a moribund breakpoint at PC.  */
4229
4230 int
4231 moribund_breakpoint_here_p (struct address_space *aspace, CORE_ADDR pc)
4232 {
4233   struct bp_location *loc;
4234   int ix;
4235
4236   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
4237     if (breakpoint_location_address_match (loc, aspace, pc))
4238       return 1;
4239
4240   return 0;
4241 }
4242
4243 /* Returns non-zero iff BL is inserted at PC, in address space
4244    ASPACE.  */
4245
4246 static int
4247 bp_location_inserted_here_p (struct bp_location *bl,
4248                              struct address_space *aspace, CORE_ADDR pc)
4249 {
4250   if (bl->inserted
4251       && breakpoint_address_match (bl->pspace->aspace, bl->address,
4252                                    aspace, pc))
4253     {
4254       if (overlay_debugging
4255           && section_is_overlay (bl->section)
4256           && !section_is_mapped (bl->section))
4257         return 0;               /* unmapped overlay -- can't be a match */
4258       else
4259         return 1;
4260     }
4261   return 0;
4262 }
4263
4264 /* Returns non-zero iff there's a breakpoint inserted at PC.  */
4265
4266 int
4267 breakpoint_inserted_here_p (struct address_space *aspace, CORE_ADDR pc)
4268 {
4269   struct bp_location **blp, **blp_tmp = NULL;
4270   struct bp_location *bl;
4271
4272   ALL_BP_LOCATIONS_AT_ADDR (blp, blp_tmp, pc)
4273     {
4274       struct bp_location *bl = *blp;
4275
4276       if (bl->loc_type != bp_loc_software_breakpoint
4277           && bl->loc_type != bp_loc_hardware_breakpoint)
4278         continue;
4279
4280       if (bp_location_inserted_here_p (bl, aspace, pc))
4281         return 1;
4282     }
4283   return 0;
4284 }
4285
4286 /* This function returns non-zero iff there is a software breakpoint
4287    inserted at PC.  */
4288
4289 int
4290 software_breakpoint_inserted_here_p (struct address_space *aspace,
4291                                      CORE_ADDR pc)
4292 {
4293   struct bp_location **blp, **blp_tmp = NULL;
4294   struct bp_location *bl;
4295
4296   ALL_BP_LOCATIONS_AT_ADDR (blp, blp_tmp, pc)
4297     {
4298       struct bp_location *bl = *blp;
4299
4300       if (bl->loc_type != bp_loc_software_breakpoint)
4301         continue;
4302
4303       if (bp_location_inserted_here_p (bl, aspace, pc))
4304         return 1;
4305     }
4306
4307   return 0;
4308 }
4309
4310 /* See breakpoint.h.  */
4311
4312 int
4313 hardware_breakpoint_inserted_here_p (struct address_space *aspace,
4314                                      CORE_ADDR pc)
4315 {
4316   struct bp_location **blp, **blp_tmp = NULL;
4317   struct bp_location *bl;
4318
4319   ALL_BP_LOCATIONS_AT_ADDR (blp, blp_tmp, pc)
4320     {
4321       struct bp_location *bl = *blp;
4322
4323       if (bl->loc_type != bp_loc_hardware_breakpoint)
4324         continue;
4325
4326       if (bp_location_inserted_here_p (bl, aspace, pc))
4327         return 1;
4328     }
4329
4330   return 0;
4331 }
4332
4333 int
4334 hardware_watchpoint_inserted_in_range (struct address_space *aspace,
4335                                        CORE_ADDR addr, ULONGEST len)
4336 {
4337   struct breakpoint *bpt;
4338
4339   ALL_BREAKPOINTS (bpt)
4340     {
4341       struct bp_location *loc;
4342
4343       if (bpt->type != bp_hardware_watchpoint
4344           && bpt->type != bp_access_watchpoint)
4345         continue;
4346
4347       if (!breakpoint_enabled (bpt))
4348         continue;
4349
4350       for (loc = bpt->loc; loc; loc = loc->next)
4351         if (loc->pspace->aspace == aspace && loc->inserted)
4352           {
4353             CORE_ADDR l, h;
4354
4355             /* Check for intersection.  */
4356             l = max (loc->address, addr);
4357             h = min (loc->address + loc->length, addr + len);
4358             if (l < h)
4359               return 1;
4360           }
4361     }
4362   return 0;
4363 }
4364 \f
4365
4366 /* bpstat stuff.  External routines' interfaces are documented
4367    in breakpoint.h.  */
4368
4369 int
4370 is_catchpoint (struct breakpoint *ep)
4371 {
4372   return (ep->type == bp_catchpoint);
4373 }
4374
4375 /* Frees any storage that is part of a bpstat.  Does not walk the
4376    'next' chain.  */
4377
4378 static void
4379 bpstat_free (bpstat bs)
4380 {
4381   if (bs->old_val != NULL)
4382     value_free (bs->old_val);
4383   decref_counted_command_line (&bs->commands);
4384   decref_bp_location (&bs->bp_location_at);
4385   xfree (bs);
4386 }
4387
4388 /* Clear a bpstat so that it says we are not at any breakpoint.
4389    Also free any storage that is part of a bpstat.  */
4390
4391 void
4392 bpstat_clear (bpstat *bsp)
4393 {
4394   bpstat p;
4395   bpstat q;
4396
4397   if (bsp == 0)
4398     return;
4399   p = *bsp;
4400   while (p != NULL)
4401     {
4402       q = p->next;
4403       bpstat_free (p);
4404       p = q;
4405     }
4406   *bsp = NULL;
4407 }
4408
4409 /* Return a copy of a bpstat.  Like "bs1 = bs2" but all storage that
4410    is part of the bpstat is copied as well.  */
4411
4412 bpstat
4413 bpstat_copy (bpstat bs)
4414 {
4415   bpstat p = NULL;
4416   bpstat tmp;
4417   bpstat retval = NULL;
4418
4419   if (bs == NULL)
4420     return bs;
4421
4422   for (; bs != NULL; bs = bs->next)
4423     {
4424       tmp = (bpstat) xmalloc (sizeof (*tmp));
4425       memcpy (tmp, bs, sizeof (*tmp));
4426       incref_counted_command_line (tmp->commands);
4427       incref_bp_location (tmp->bp_location_at);
4428       if (bs->old_val != NULL)
4429         {
4430           tmp->old_val = value_copy (bs->old_val);
4431           release_value (tmp->old_val);
4432         }
4433
4434       if (p == NULL)
4435         /* This is the first thing in the chain.  */
4436         retval = tmp;
4437       else
4438         p->next = tmp;
4439       p = tmp;
4440     }
4441   p->next = NULL;
4442   return retval;
4443 }
4444
4445 /* Find the bpstat associated with this breakpoint.  */
4446
4447 bpstat
4448 bpstat_find_breakpoint (bpstat bsp, struct breakpoint *breakpoint)
4449 {
4450   if (bsp == NULL)
4451     return NULL;
4452
4453   for (; bsp != NULL; bsp = bsp->next)
4454     {
4455       if (bsp->breakpoint_at == breakpoint)
4456         return bsp;
4457     }
4458   return NULL;
4459 }
4460
4461 /* See breakpoint.h.  */
4462
4463 int
4464 bpstat_explains_signal (bpstat bsp, enum gdb_signal sig)
4465 {
4466   for (; bsp != NULL; bsp = bsp->next)
4467     {
4468       if (bsp->breakpoint_at == NULL)
4469         {
4470           /* A moribund location can never explain a signal other than
4471              GDB_SIGNAL_TRAP.  */
4472           if (sig == GDB_SIGNAL_TRAP)
4473             return 1;
4474         }
4475       else
4476         {
4477           if (bsp->breakpoint_at->ops->explains_signal (bsp->breakpoint_at,
4478                                                         sig))
4479             return 1;
4480         }
4481     }
4482
4483   return 0;
4484 }
4485
4486 /* Put in *NUM the breakpoint number of the first breakpoint we are
4487    stopped at.  *BSP upon return is a bpstat which points to the
4488    remaining breakpoints stopped at (but which is not guaranteed to be
4489    good for anything but further calls to bpstat_num).
4490
4491    Return 0 if passed a bpstat which does not indicate any breakpoints.
4492    Return -1 if stopped at a breakpoint that has been deleted since
4493    we set it.
4494    Return 1 otherwise.  */
4495
4496 int
4497 bpstat_num (bpstat *bsp, int *num)
4498 {
4499   struct breakpoint *b;
4500
4501   if ((*bsp) == NULL)
4502     return 0;                   /* No more breakpoint values */
4503
4504   /* We assume we'll never have several bpstats that correspond to a
4505      single breakpoint -- otherwise, this function might return the
4506      same number more than once and this will look ugly.  */
4507   b = (*bsp)->breakpoint_at;
4508   *bsp = (*bsp)->next;
4509   if (b == NULL)
4510     return -1;                  /* breakpoint that's been deleted since */
4511
4512   *num = b->number;             /* We have its number */
4513   return 1;
4514 }
4515
4516 /* See breakpoint.h.  */
4517
4518 void
4519 bpstat_clear_actions (void)
4520 {
4521   struct thread_info *tp;
4522   bpstat bs;
4523
4524   if (ptid_equal (inferior_ptid, null_ptid))
4525     return;
4526
4527   tp = find_thread_ptid (inferior_ptid);
4528   if (tp == NULL)
4529     return;
4530
4531   for (bs = tp->control.stop_bpstat; bs != NULL; bs = bs->next)
4532     {
4533       decref_counted_command_line (&bs->commands);
4534
4535       if (bs->old_val != NULL)
4536         {
4537           value_free (bs->old_val);
4538           bs->old_val = NULL;
4539         }
4540     }
4541 }
4542
4543 /* Called when a command is about to proceed the inferior.  */
4544
4545 static void
4546 breakpoint_about_to_proceed (void)
4547 {
4548   if (!ptid_equal (inferior_ptid, null_ptid))
4549     {
4550       struct thread_info *tp = inferior_thread ();
4551
4552       /* Allow inferior function calls in breakpoint commands to not
4553          interrupt the command list.  When the call finishes
4554          successfully, the inferior will be standing at the same
4555          breakpoint as if nothing happened.  */
4556       if (tp->control.in_infcall)
4557         return;
4558     }
4559
4560   breakpoint_proceeded = 1;
4561 }
4562
4563 /* Stub for cleaning up our state if we error-out of a breakpoint
4564    command.  */
4565 static void
4566 cleanup_executing_breakpoints (void *ignore)
4567 {
4568   executing_breakpoint_commands = 0;
4569 }
4570
4571 /* Return non-zero iff CMD as the first line of a command sequence is `silent'
4572    or its equivalent.  */
4573
4574 static int
4575 command_line_is_silent (struct command_line *cmd)
4576 {
4577   return cmd && (strcmp ("silent", cmd->line) == 0
4578                  || (xdb_commands && strcmp ("Q", cmd->line) == 0));
4579 }
4580
4581 /* Execute all the commands associated with all the breakpoints at
4582    this location.  Any of these commands could cause the process to
4583    proceed beyond this point, etc.  We look out for such changes by
4584    checking the global "breakpoint_proceeded" after each command.
4585
4586    Returns true if a breakpoint command resumed the inferior.  In that
4587    case, it is the caller's responsibility to recall it again with the
4588    bpstat of the current thread.  */
4589
4590 static int
4591 bpstat_do_actions_1 (bpstat *bsp)
4592 {
4593   bpstat bs;
4594   struct cleanup *old_chain;
4595   int again = 0;
4596
4597   /* Avoid endless recursion if a `source' command is contained
4598      in bs->commands.  */
4599   if (executing_breakpoint_commands)
4600     return 0;
4601
4602   executing_breakpoint_commands = 1;
4603   old_chain = make_cleanup (cleanup_executing_breakpoints, 0);
4604
4605   prevent_dont_repeat ();
4606
4607   /* This pointer will iterate over the list of bpstat's.  */
4608   bs = *bsp;
4609
4610   breakpoint_proceeded = 0;
4611   for (; bs != NULL; bs = bs->next)
4612     {
4613       struct counted_command_line *ccmd;
4614       struct command_line *cmd;
4615       struct cleanup *this_cmd_tree_chain;
4616
4617       /* Take ownership of the BSP's command tree, if it has one.
4618
4619          The command tree could legitimately contain commands like
4620          'step' and 'next', which call clear_proceed_status, which
4621          frees stop_bpstat's command tree.  To make sure this doesn't
4622          free the tree we're executing out from under us, we need to
4623          take ownership of the tree ourselves.  Since a given bpstat's
4624          commands are only executed once, we don't need to copy it; we
4625          can clear the pointer in the bpstat, and make sure we free
4626          the tree when we're done.  */
4627       ccmd = bs->commands;
4628       bs->commands = NULL;
4629       this_cmd_tree_chain = make_cleanup_decref_counted_command_line (&ccmd);
4630       cmd = ccmd ? ccmd->commands : NULL;
4631       if (command_line_is_silent (cmd))
4632         {
4633           /* The action has been already done by bpstat_stop_status.  */
4634           cmd = cmd->next;
4635         }
4636
4637       while (cmd != NULL)
4638         {
4639           execute_control_command (cmd);
4640
4641           if (breakpoint_proceeded)
4642             break;
4643           else
4644             cmd = cmd->next;
4645         }
4646
4647       /* We can free this command tree now.  */
4648       do_cleanups (this_cmd_tree_chain);
4649
4650       if (breakpoint_proceeded)
4651         {
4652           if (interpreter_async && target_can_async_p ())
4653             /* If we are in async mode, then the target might be still
4654                running, not stopped at any breakpoint, so nothing for
4655                us to do here -- just return to the event loop.  */
4656             ;
4657           else
4658             /* In sync mode, when execute_control_command returns
4659                we're already standing on the next breakpoint.
4660                Breakpoint commands for that stop were not run, since
4661                execute_command does not run breakpoint commands --
4662                only command_line_handler does, but that one is not
4663                involved in execution of breakpoint commands.  So, we
4664                can now execute breakpoint commands.  It should be
4665                noted that making execute_command do bpstat actions is
4666                not an option -- in this case we'll have recursive
4667                invocation of bpstat for each breakpoint with a
4668                command, and can easily blow up GDB stack.  Instead, we
4669                return true, which will trigger the caller to recall us
4670                with the new stop_bpstat.  */
4671             again = 1;
4672           break;
4673         }
4674     }
4675   do_cleanups (old_chain);
4676   return again;
4677 }
4678
4679 void
4680 bpstat_do_actions (void)
4681 {
4682   struct cleanup *cleanup_if_error = make_bpstat_clear_actions_cleanup ();
4683
4684   /* Do any commands attached to breakpoint we are stopped at.  */
4685   while (!ptid_equal (inferior_ptid, null_ptid)
4686          && target_has_execution
4687          && !is_exited (inferior_ptid)
4688          && !is_executing (inferior_ptid))
4689     /* Since in sync mode, bpstat_do_actions may resume the inferior,
4690        and only return when it is stopped at the next breakpoint, we
4691        keep doing breakpoint actions until it returns false to
4692        indicate the inferior was not resumed.  */
4693     if (!bpstat_do_actions_1 (&inferior_thread ()->control.stop_bpstat))
4694       break;
4695
4696   discard_cleanups (cleanup_if_error);
4697 }
4698
4699 /* Print out the (old or new) value associated with a watchpoint.  */
4700
4701 static void
4702 watchpoint_value_print (struct value *val, struct ui_file *stream)
4703 {
4704   if (val == NULL)
4705     fprintf_unfiltered (stream, _("<unreadable>"));
4706   else
4707     {
4708       struct value_print_options opts;
4709       get_user_print_options (&opts);
4710       value_print (val, stream, &opts);
4711     }
4712 }
4713
4714 /* Generic routine for printing messages indicating why we
4715    stopped.  The behavior of this function depends on the value
4716    'print_it' in the bpstat structure.  Under some circumstances we
4717    may decide not to print anything here and delegate the task to
4718    normal_stop().  */
4719
4720 static enum print_stop_action
4721 print_bp_stop_message (bpstat bs)
4722 {
4723   switch (bs->print_it)
4724     {
4725     case print_it_noop:
4726       /* Nothing should be printed for this bpstat entry.  */
4727       return PRINT_UNKNOWN;
4728       break;
4729
4730     case print_it_done:
4731       /* We still want to print the frame, but we already printed the
4732          relevant messages.  */
4733       return PRINT_SRC_AND_LOC;
4734       break;
4735
4736     case print_it_normal:
4737       {
4738         struct breakpoint *b = bs->breakpoint_at;
4739
4740         /* bs->breakpoint_at can be NULL if it was a momentary breakpoint
4741            which has since been deleted.  */
4742         if (b == NULL)
4743           return PRINT_UNKNOWN;
4744
4745         /* Normal case.  Call the breakpoint's print_it method.  */
4746         return b->ops->print_it (bs);
4747       }
4748       break;
4749
4750     default:
4751       internal_error (__FILE__, __LINE__,
4752                       _("print_bp_stop_message: unrecognized enum value"));
4753       break;
4754     }
4755 }
4756
4757 /* A helper function that prints a shared library stopped event.  */
4758
4759 static void
4760 print_solib_event (int is_catchpoint)
4761 {
4762   int any_deleted
4763     = !VEC_empty (char_ptr, current_program_space->deleted_solibs);
4764   int any_added
4765     = !VEC_empty (so_list_ptr, current_program_space->added_solibs);
4766
4767   if (!is_catchpoint)
4768     {
4769       if (any_added || any_deleted)
4770         ui_out_text (current_uiout,
4771                      _("Stopped due to shared library event:\n"));
4772       else
4773         ui_out_text (current_uiout,
4774                      _("Stopped due to shared library event (no "
4775                        "libraries added or removed)\n"));
4776     }
4777
4778   if (ui_out_is_mi_like_p (current_uiout))
4779     ui_out_field_string (current_uiout, "reason",
4780                          async_reason_lookup (EXEC_ASYNC_SOLIB_EVENT));
4781
4782   if (any_deleted)
4783     {
4784       struct cleanup *cleanup;
4785       char *name;
4786       int ix;
4787
4788       ui_out_text (current_uiout, _("  Inferior unloaded "));
4789       cleanup = make_cleanup_ui_out_list_begin_end (current_uiout,
4790                                                     "removed");
4791       for (ix = 0;
4792            VEC_iterate (char_ptr, current_program_space->deleted_solibs,
4793                         ix, name);
4794            ++ix)
4795         {
4796           if (ix > 0)
4797             ui_out_text (current_uiout, "    ");
4798           ui_out_field_string (current_uiout, "library", name);
4799           ui_out_text (current_uiout, "\n");
4800         }
4801
4802       do_cleanups (cleanup);
4803     }
4804
4805   if (any_added)
4806     {
4807       struct so_list *iter;
4808       int ix;
4809       struct cleanup *cleanup;
4810
4811       ui_out_text (current_uiout, _("  Inferior loaded "));
4812       cleanup = make_cleanup_ui_out_list_begin_end (current_uiout,
4813                                                     "added");
4814       for (ix = 0;
4815            VEC_iterate (so_list_ptr, current_program_space->added_solibs,
4816                         ix, iter);
4817            ++ix)
4818         {
4819           if (ix > 0)
4820             ui_out_text (current_uiout, "    ");
4821           ui_out_field_string (current_uiout, "library", iter->so_name);
4822           ui_out_text (current_uiout, "\n");
4823         }
4824
4825       do_cleanups (cleanup);
4826     }
4827 }
4828
4829 /* Print a message indicating what happened.  This is called from
4830    normal_stop().  The input to this routine is the head of the bpstat
4831    list - a list of the eventpoints that caused this stop.  KIND is
4832    the target_waitkind for the stopping event.  This
4833    routine calls the generic print routine for printing a message
4834    about reasons for stopping.  This will print (for example) the
4835    "Breakpoint n," part of the output.  The return value of this
4836    routine is one of:
4837
4838    PRINT_UNKNOWN: Means we printed nothing.
4839    PRINT_SRC_AND_LOC: Means we printed something, and expect subsequent
4840    code to print the location.  An example is 
4841    "Breakpoint 1, " which should be followed by
4842    the location.
4843    PRINT_SRC_ONLY: Means we printed something, but there is no need
4844    to also print the location part of the message.
4845    An example is the catch/throw messages, which
4846    don't require a location appended to the end.
4847    PRINT_NOTHING: We have done some printing and we don't need any 
4848    further info to be printed.  */
4849
4850 enum print_stop_action
4851 bpstat_print (bpstat bs, int kind)
4852 {
4853   int val;
4854
4855   /* Maybe another breakpoint in the chain caused us to stop.
4856      (Currently all watchpoints go on the bpstat whether hit or not.
4857      That probably could (should) be changed, provided care is taken
4858      with respect to bpstat_explains_signal).  */
4859   for (; bs; bs = bs->next)
4860     {
4861       val = print_bp_stop_message (bs);
4862       if (val == PRINT_SRC_ONLY 
4863           || val == PRINT_SRC_AND_LOC 
4864           || val == PRINT_NOTHING)
4865         return val;
4866     }
4867
4868   /* If we had hit a shared library event breakpoint,
4869      print_bp_stop_message would print out this message.  If we hit an
4870      OS-level shared library event, do the same thing.  */
4871   if (kind == TARGET_WAITKIND_LOADED)
4872     {
4873       print_solib_event (0);
4874       return PRINT_NOTHING;
4875     }
4876
4877   /* We reached the end of the chain, or we got a null BS to start
4878      with and nothing was printed.  */
4879   return PRINT_UNKNOWN;
4880 }
4881
4882 /* Evaluate the expression EXP and return 1 if value is zero.
4883    This returns the inverse of the condition because it is called
4884    from catch_errors which returns 0 if an exception happened, and if an
4885    exception happens we want execution to stop.
4886    The argument is a "struct expression *" that has been cast to a
4887    "void *" to make it pass through catch_errors.  */
4888
4889 static int
4890 breakpoint_cond_eval (void *exp)
4891 {
4892   struct value *mark = value_mark ();
4893   int i = !value_true (evaluate_expression ((struct expression *) exp));
4894
4895   value_free_to_mark (mark);
4896   return i;
4897 }
4898
4899 /* Allocate a new bpstat.  Link it to the FIFO list by BS_LINK_POINTER.  */
4900
4901 static bpstat
4902 bpstat_alloc (struct bp_location *bl, bpstat **bs_link_pointer)
4903 {
4904   bpstat bs;
4905
4906   bs = (bpstat) xmalloc (sizeof (*bs));
4907   bs->next = NULL;
4908   **bs_link_pointer = bs;
4909   *bs_link_pointer = &bs->next;
4910   bs->breakpoint_at = bl->owner;
4911   bs->bp_location_at = bl;
4912   incref_bp_location (bl);
4913   /* If the condition is false, etc., don't do the commands.  */
4914   bs->commands = NULL;
4915   bs->old_val = NULL;
4916   bs->print_it = print_it_normal;
4917   return bs;
4918 }
4919 \f
4920 /* The target has stopped with waitstatus WS.  Check if any hardware
4921    watchpoints have triggered, according to the target.  */
4922
4923 int
4924 watchpoints_triggered (struct target_waitstatus *ws)
4925 {
4926   int stopped_by_watchpoint = target_stopped_by_watchpoint ();
4927   CORE_ADDR addr;
4928   struct breakpoint *b;
4929
4930   if (!stopped_by_watchpoint)
4931     {
4932       /* We were not stopped by a watchpoint.  Mark all watchpoints
4933          as not triggered.  */
4934       ALL_BREAKPOINTS (b)
4935         if (is_hardware_watchpoint (b))
4936           {
4937             struct watchpoint *w = (struct watchpoint *) b;
4938
4939             w->watchpoint_triggered = watch_triggered_no;
4940           }
4941
4942       return 0;
4943     }
4944
4945   if (!target_stopped_data_address (&current_target, &addr))
4946     {
4947       /* We were stopped by a watchpoint, but we don't know where.
4948          Mark all watchpoints as unknown.  */
4949       ALL_BREAKPOINTS (b)
4950         if (is_hardware_watchpoint (b))
4951           {
4952             struct watchpoint *w = (struct watchpoint *) b;
4953
4954             w->watchpoint_triggered = watch_triggered_unknown;
4955           }
4956
4957       return 1;
4958     }
4959
4960   /* The target could report the data address.  Mark watchpoints
4961      affected by this data address as triggered, and all others as not
4962      triggered.  */
4963
4964   ALL_BREAKPOINTS (b)
4965     if (is_hardware_watchpoint (b))
4966       {
4967         struct watchpoint *w = (struct watchpoint *) b;
4968         struct bp_location *loc;
4969
4970         w->watchpoint_triggered = watch_triggered_no;
4971         for (loc = b->loc; loc; loc = loc->next)
4972           {
4973             if (is_masked_watchpoint (b))
4974               {
4975                 CORE_ADDR newaddr = addr & w->hw_wp_mask;
4976                 CORE_ADDR start = loc->address & w->hw_wp_mask;
4977
4978                 if (newaddr == start)
4979                   {
4980                     w->watchpoint_triggered = watch_triggered_yes;
4981                     break;
4982                   }
4983               }
4984             /* Exact match not required.  Within range is sufficient.  */
4985             else if (target_watchpoint_addr_within_range (&current_target,
4986                                                          addr, loc->address,
4987                                                          loc->length))
4988               {
4989                 w->watchpoint_triggered = watch_triggered_yes;
4990                 break;
4991               }
4992           }
4993       }
4994
4995   return 1;
4996 }
4997
4998 /* Possible return values for watchpoint_check (this can't be an enum
4999    because of check_errors).  */
5000 /* The watchpoint has been deleted.  */
5001 #define WP_DELETED 1
5002 /* The value has changed.  */
5003 #define WP_VALUE_CHANGED 2
5004 /* The value has not changed.  */
5005 #define WP_VALUE_NOT_CHANGED 3
5006 /* Ignore this watchpoint, no matter if the value changed or not.  */
5007 #define WP_IGNORE 4
5008
5009 #define BP_TEMPFLAG 1
5010 #define BP_HARDWAREFLAG 2
5011
5012 /* Evaluate watchpoint condition expression and check if its value
5013    changed.
5014
5015    P should be a pointer to struct bpstat, but is defined as a void *
5016    in order for this function to be usable with catch_errors.  */
5017
5018 static int
5019 watchpoint_check (void *p)
5020 {
5021   bpstat bs = (bpstat) p;
5022   struct watchpoint *b;
5023   struct frame_info *fr;
5024   int within_current_scope;
5025
5026   /* BS is built from an existing struct breakpoint.  */
5027   gdb_assert (bs->breakpoint_at != NULL);
5028   b = (struct watchpoint *) bs->breakpoint_at;
5029
5030   /* If this is a local watchpoint, we only want to check if the
5031      watchpoint frame is in scope if the current thread is the thread
5032      that was used to create the watchpoint.  */
5033   if (!watchpoint_in_thread_scope (b))
5034     return WP_IGNORE;
5035
5036   if (b->exp_valid_block == NULL)
5037     within_current_scope = 1;
5038   else
5039     {
5040       struct frame_info *frame = get_current_frame ();
5041       struct gdbarch *frame_arch = get_frame_arch (frame);
5042       CORE_ADDR frame_pc = get_frame_pc (frame);
5043
5044       /* in_function_epilogue_p() returns a non-zero value if we're
5045          still in the function but the stack frame has already been
5046          invalidated.  Since we can't rely on the values of local
5047          variables after the stack has been destroyed, we are treating
5048          the watchpoint in that state as `not changed' without further
5049          checking.  Don't mark watchpoints as changed if the current
5050          frame is in an epilogue - even if they are in some other
5051          frame, our view of the stack is likely to be wrong and
5052          frame_find_by_id could error out.  */
5053       if (gdbarch_in_function_epilogue_p (frame_arch, frame_pc))
5054         return WP_IGNORE;
5055
5056       fr = frame_find_by_id (b->watchpoint_frame);
5057       within_current_scope = (fr != NULL);
5058
5059       /* If we've gotten confused in the unwinder, we might have
5060          returned a frame that can't describe this variable.  */
5061       if (within_current_scope)
5062         {
5063           struct symbol *function;
5064
5065           function = get_frame_function (fr);
5066           if (function == NULL
5067               || !contained_in (b->exp_valid_block,
5068                                 SYMBOL_BLOCK_VALUE (function)))
5069             within_current_scope = 0;
5070         }
5071
5072       if (within_current_scope)
5073         /* If we end up stopping, the current frame will get selected
5074            in normal_stop.  So this call to select_frame won't affect
5075            the user.  */
5076         select_frame (fr);
5077     }
5078
5079   if (within_current_scope)
5080     {
5081       /* We use value_{,free_to_}mark because it could be a *long*
5082          time before we return to the command level and call
5083          free_all_values.  We can't call free_all_values because we
5084          might be in the middle of evaluating a function call.  */
5085
5086       int pc = 0;
5087       struct value *mark;
5088       struct value *new_val;
5089
5090       if (is_masked_watchpoint (&b->base))
5091         /* Since we don't know the exact trigger address (from
5092            stopped_data_address), just tell the user we've triggered
5093            a mask watchpoint.  */
5094         return WP_VALUE_CHANGED;
5095
5096       mark = value_mark ();
5097       fetch_subexp_value (b->exp, &pc, &new_val, NULL, NULL, 0);
5098
5099       if (b->val_bitsize != 0)
5100         new_val = extract_bitfield_from_watchpoint_value (b, new_val);
5101
5102       /* We use value_equal_contents instead of value_equal because
5103          the latter coerces an array to a pointer, thus comparing just
5104          the address of the array instead of its contents.  This is
5105          not what we want.  */
5106       if ((b->val != NULL) != (new_val != NULL)
5107           || (b->val != NULL && !value_equal_contents (b->val, new_val)))
5108         {
5109           if (new_val != NULL)
5110             {
5111               release_value (new_val);
5112               value_free_to_mark (mark);
5113             }
5114           bs->old_val = b->val;
5115           b->val = new_val;
5116           b->val_valid = 1;
5117           return WP_VALUE_CHANGED;
5118         }
5119       else
5120         {
5121           /* Nothing changed.  */
5122           value_free_to_mark (mark);
5123           return WP_VALUE_NOT_CHANGED;
5124         }
5125     }
5126   else
5127     {
5128       struct ui_out *uiout = current_uiout;
5129
5130       /* This seems like the only logical thing to do because
5131          if we temporarily ignored the watchpoint, then when
5132          we reenter the block in which it is valid it contains
5133          garbage (in the case of a function, it may have two
5134          garbage values, one before and one after the prologue).
5135          So we can't even detect the first assignment to it and
5136          watch after that (since the garbage may or may not equal
5137          the first value assigned).  */
5138       /* We print all the stop information in
5139          breakpoint_ops->print_it, but in this case, by the time we
5140          call breakpoint_ops->print_it this bp will be deleted
5141          already.  So we have no choice but print the information
5142          here.  */
5143       if (ui_out_is_mi_like_p (uiout))
5144         ui_out_field_string
5145           (uiout, "reason", async_reason_lookup (EXEC_ASYNC_WATCHPOINT_SCOPE));
5146       ui_out_text (uiout, "\nWatchpoint ");
5147       ui_out_field_int (uiout, "wpnum", b->base.number);
5148       ui_out_text (uiout,
5149                    " deleted because the program has left the block in\n\
5150 which its expression is valid.\n");     
5151
5152       /* Make sure the watchpoint's commands aren't executed.  */
5153       decref_counted_command_line (&b->base.commands);
5154       watchpoint_del_at_next_stop (b);
5155
5156       return WP_DELETED;
5157     }
5158 }
5159
5160 /* Return true if it looks like target has stopped due to hitting
5161    breakpoint location BL.  This function does not check if we should
5162    stop, only if BL explains the stop.  */
5163
5164 static int
5165 bpstat_check_location (const struct bp_location *bl,
5166                        struct address_space *aspace, CORE_ADDR bp_addr,
5167                        const struct target_waitstatus *ws)
5168 {
5169   struct breakpoint *b = bl->owner;
5170
5171   /* BL is from an existing breakpoint.  */
5172   gdb_assert (b != NULL);
5173
5174   return b->ops->breakpoint_hit (bl, aspace, bp_addr, ws);
5175 }
5176
5177 /* Determine if the watched values have actually changed, and we
5178    should stop.  If not, set BS->stop to 0.  */
5179
5180 static void
5181 bpstat_check_watchpoint (bpstat bs)
5182 {
5183   const struct bp_location *bl;
5184   struct watchpoint *b;
5185
5186   /* BS is built for existing struct breakpoint.  */
5187   bl = bs->bp_location_at;
5188   gdb_assert (bl != NULL);
5189   b = (struct watchpoint *) bs->breakpoint_at;
5190   gdb_assert (b != NULL);
5191
5192     {
5193       int must_check_value = 0;
5194       
5195       if (b->base.type == bp_watchpoint)
5196         /* For a software watchpoint, we must always check the
5197            watched value.  */
5198         must_check_value = 1;
5199       else if (b->watchpoint_triggered == watch_triggered_yes)
5200         /* We have a hardware watchpoint (read, write, or access)
5201            and the target earlier reported an address watched by
5202            this watchpoint.  */
5203         must_check_value = 1;
5204       else if (b->watchpoint_triggered == watch_triggered_unknown
5205                && b->base.type == bp_hardware_watchpoint)
5206         /* We were stopped by a hardware watchpoint, but the target could
5207            not report the data address.  We must check the watchpoint's
5208            value.  Access and read watchpoints are out of luck; without
5209            a data address, we can't figure it out.  */
5210         must_check_value = 1;
5211
5212       if (must_check_value)
5213         {
5214           char *message
5215             = xstrprintf ("Error evaluating expression for watchpoint %d\n",
5216                           b->base.number);
5217           struct cleanup *cleanups = make_cleanup (xfree, message);
5218           int e = catch_errors (watchpoint_check, bs, message,
5219                                 RETURN_MASK_ALL);
5220           do_cleanups (cleanups);
5221           switch (e)
5222             {
5223             case WP_DELETED:
5224               /* We've already printed what needs to be printed.  */
5225               bs->print_it = print_it_done;
5226               /* Stop.  */
5227               break;
5228             case WP_IGNORE:
5229               bs->print_it = print_it_noop;
5230               bs->stop = 0;
5231               break;
5232             case WP_VALUE_CHANGED:
5233               if (b->base.type == bp_read_watchpoint)
5234                 {
5235                   /* There are two cases to consider here:
5236
5237                      1. We're watching the triggered memory for reads.
5238                      In that case, trust the target, and always report
5239                      the watchpoint hit to the user.  Even though
5240                      reads don't cause value changes, the value may
5241                      have changed since the last time it was read, and
5242                      since we're not trapping writes, we will not see
5243                      those, and as such we should ignore our notion of
5244                      old value.
5245
5246                      2. We're watching the triggered memory for both
5247                      reads and writes.  There are two ways this may
5248                      happen:
5249
5250                      2.1. This is a target that can't break on data
5251                      reads only, but can break on accesses (reads or
5252                      writes), such as e.g., x86.  We detect this case
5253                      at the time we try to insert read watchpoints.
5254
5255                      2.2. Otherwise, the target supports read
5256                      watchpoints, but, the user set an access or write
5257                      watchpoint watching the same memory as this read
5258                      watchpoint.
5259
5260                      If we're watching memory writes as well as reads,
5261                      ignore watchpoint hits when we find that the
5262                      value hasn't changed, as reads don't cause
5263                      changes.  This still gives false positives when
5264                      the program writes the same value to memory as
5265                      what there was already in memory (we will confuse
5266                      it for a read), but it's much better than
5267                      nothing.  */
5268
5269                   int other_write_watchpoint = 0;
5270
5271                   if (bl->watchpoint_type == hw_read)
5272                     {
5273                       struct breakpoint *other_b;
5274
5275                       ALL_BREAKPOINTS (other_b)
5276                         if (other_b->type == bp_hardware_watchpoint
5277                             || other_b->type == bp_access_watchpoint)
5278                           {
5279                             struct watchpoint *other_w =
5280                               (struct watchpoint *) other_b;
5281
5282                             if (other_w->watchpoint_triggered
5283                                 == watch_triggered_yes)
5284                               {
5285                                 other_write_watchpoint = 1;
5286                                 break;
5287                               }
5288                           }
5289                     }
5290
5291                   if (other_write_watchpoint
5292                       || bl->watchpoint_type == hw_access)
5293                     {
5294                       /* We're watching the same memory for writes,
5295                          and the value changed since the last time we
5296                          updated it, so this trap must be for a write.
5297                          Ignore it.  */
5298                       bs->print_it = print_it_noop;
5299                       bs->stop = 0;
5300                     }
5301                 }
5302               break;
5303             case WP_VALUE_NOT_CHANGED:
5304               if (b->base.type == bp_hardware_watchpoint
5305                   || b->base.type == bp_watchpoint)
5306                 {
5307                   /* Don't stop: write watchpoints shouldn't fire if
5308                      the value hasn't changed.  */
5309                   bs->print_it = print_it_noop;
5310                   bs->stop = 0;
5311                 }
5312               /* Stop.  */
5313               break;
5314             default:
5315               /* Can't happen.  */
5316             case 0:
5317               /* Error from catch_errors.  */
5318               printf_filtered (_("Watchpoint %d deleted.\n"), b->base.number);
5319               watchpoint_del_at_next_stop (b);
5320               /* We've already printed what needs to be printed.  */
5321               bs->print_it = print_it_done;
5322               break;
5323             }
5324         }
5325       else      /* must_check_value == 0 */
5326         {
5327           /* This is a case where some watchpoint(s) triggered, but
5328              not at the address of this watchpoint, or else no
5329              watchpoint triggered after all.  So don't print
5330              anything for this watchpoint.  */
5331           bs->print_it = print_it_noop;
5332           bs->stop = 0;
5333         }
5334     }
5335 }
5336
5337 /* For breakpoints that are currently marked as telling gdb to stop,
5338    check conditions (condition proper, frame, thread and ignore count)
5339    of breakpoint referred to by BS.  If we should not stop for this
5340    breakpoint, set BS->stop to 0.  */
5341
5342 static void
5343 bpstat_check_breakpoint_conditions (bpstat bs, ptid_t ptid)
5344 {
5345   const struct bp_location *bl;
5346   struct breakpoint *b;
5347   int value_is_zero = 0;
5348   struct expression *cond;
5349
5350   gdb_assert (bs->stop);
5351
5352   /* BS is built for existing struct breakpoint.  */
5353   bl = bs->bp_location_at;
5354   gdb_assert (bl != NULL);
5355   b = bs->breakpoint_at;
5356   gdb_assert (b != NULL);
5357
5358   /* Even if the target evaluated the condition on its end and notified GDB, we
5359      need to do so again since GDB does not know if we stopped due to a
5360      breakpoint or a single step breakpoint.  */
5361
5362   if (frame_id_p (b->frame_id)
5363       && !frame_id_eq (b->frame_id, get_stack_frame_id (get_current_frame ())))
5364     {
5365       bs->stop = 0;
5366       return;
5367     }
5368
5369   /* If this is a thread/task-specific breakpoint, don't waste cpu
5370      evaluating the condition if this isn't the specified
5371      thread/task.  */
5372   if ((b->thread != -1 && b->thread != pid_to_thread_id (ptid))
5373       || (b->task != 0 && b->task != ada_get_task_number (ptid)))
5374
5375     {
5376       bs->stop = 0;
5377       return;
5378     }
5379
5380   /* Evaluate extension language breakpoints that have a "stop" method
5381      implemented.  */
5382   bs->stop = breakpoint_ext_lang_cond_says_stop (b);
5383
5384   if (is_watchpoint (b))
5385     {
5386       struct watchpoint *w = (struct watchpoint *) b;
5387
5388       cond = w->cond_exp;
5389     }
5390   else
5391     cond = bl->cond;
5392
5393   if (cond && b->disposition != disp_del_at_next_stop)
5394     {
5395       int within_current_scope = 1;
5396       struct watchpoint * w;
5397
5398       /* We use value_mark and value_free_to_mark because it could
5399          be a long time before we return to the command level and
5400          call free_all_values.  We can't call free_all_values
5401          because we might be in the middle of evaluating a
5402          function call.  */
5403       struct value *mark = value_mark ();
5404
5405       if (is_watchpoint (b))
5406         w = (struct watchpoint *) b;
5407       else
5408         w = NULL;
5409
5410       /* Need to select the frame, with all that implies so that
5411          the conditions will have the right context.  Because we
5412          use the frame, we will not see an inlined function's
5413          variables when we arrive at a breakpoint at the start
5414          of the inlined function; the current frame will be the
5415          call site.  */
5416       if (w == NULL || w->cond_exp_valid_block == NULL)
5417         select_frame (get_current_frame ());
5418       else
5419         {
5420           struct frame_info *frame;
5421
5422           /* For local watchpoint expressions, which particular
5423              instance of a local is being watched matters, so we
5424              keep track of the frame to evaluate the expression
5425              in.  To evaluate the condition however, it doesn't
5426              really matter which instantiation of the function
5427              where the condition makes sense triggers the
5428              watchpoint.  This allows an expression like "watch
5429              global if q > 10" set in `func', catch writes to
5430              global on all threads that call `func', or catch
5431              writes on all recursive calls of `func' by a single
5432              thread.  We simply always evaluate the condition in
5433              the innermost frame that's executing where it makes
5434              sense to evaluate the condition.  It seems
5435              intuitive.  */
5436           frame = block_innermost_frame (w->cond_exp_valid_block);
5437           if (frame != NULL)
5438             select_frame (frame);
5439           else
5440             within_current_scope = 0;
5441         }
5442       if (within_current_scope)
5443         value_is_zero
5444           = catch_errors (breakpoint_cond_eval, cond,
5445                           "Error in testing breakpoint condition:\n",
5446                           RETURN_MASK_ALL);
5447       else
5448         {
5449           warning (_("Watchpoint condition cannot be tested "
5450                      "in the current scope"));
5451           /* If we failed to set the right context for this
5452              watchpoint, unconditionally report it.  */
5453           value_is_zero = 0;
5454         }
5455       /* FIXME-someday, should give breakpoint #.  */
5456       value_free_to_mark (mark);
5457     }
5458
5459   if (cond && value_is_zero)
5460     {
5461       bs->stop = 0;
5462     }
5463   else if (b->ignore_count > 0)
5464     {
5465       b->ignore_count--;
5466       bs->stop = 0;
5467       /* Increase the hit count even though we don't stop.  */
5468       ++(b->hit_count);
5469       observer_notify_breakpoint_modified (b);
5470     }   
5471 }
5472
5473 /* Returns true if we need to track moribund locations of LOC's type
5474    on the current target.  */
5475
5476 static int
5477 need_moribund_for_location_type (struct bp_location *loc)
5478 {
5479   return ((loc->loc_type == bp_loc_software_breakpoint
5480            && !target_supports_stopped_by_sw_breakpoint ())
5481           || (loc->loc_type == bp_loc_hardware_breakpoint
5482               && !target_supports_stopped_by_hw_breakpoint ()));
5483 }
5484
5485
5486 /* Get a bpstat associated with having just stopped at address
5487    BP_ADDR in thread PTID.
5488
5489    Determine whether we stopped at a breakpoint, etc, or whether we
5490    don't understand this stop.  Result is a chain of bpstat's such
5491    that:
5492
5493    if we don't understand the stop, the result is a null pointer.
5494
5495    if we understand why we stopped, the result is not null.
5496
5497    Each element of the chain refers to a particular breakpoint or
5498    watchpoint at which we have stopped.  (We may have stopped for
5499    several reasons concurrently.)
5500
5501    Each element of the chain has valid next, breakpoint_at,
5502    commands, FIXME??? fields.  */
5503
5504 bpstat
5505 bpstat_stop_status (struct address_space *aspace,
5506                     CORE_ADDR bp_addr, ptid_t ptid,
5507                     const struct target_waitstatus *ws)
5508 {
5509   struct breakpoint *b = NULL;
5510   struct bp_location *bl;
5511   struct bp_location *loc;
5512   /* First item of allocated bpstat's.  */
5513   bpstat bs_head = NULL, *bs_link = &bs_head;
5514   /* Pointer to the last thing in the chain currently.  */
5515   bpstat bs;
5516   int ix;
5517   int need_remove_insert;
5518   int removed_any;
5519
5520   /* First, build the bpstat chain with locations that explain a
5521      target stop, while being careful to not set the target running,
5522      as that may invalidate locations (in particular watchpoint
5523      locations are recreated).  Resuming will happen here with
5524      breakpoint conditions or watchpoint expressions that include
5525      inferior function calls.  */
5526
5527   ALL_BREAKPOINTS (b)
5528     {
5529       if (!breakpoint_enabled (b))
5530         continue;
5531
5532       for (bl = b->loc; bl != NULL; bl = bl->next)
5533         {
5534           /* For hardware watchpoints, we look only at the first
5535              location.  The watchpoint_check function will work on the
5536              entire expression, not the individual locations.  For
5537              read watchpoints, the watchpoints_triggered function has
5538              checked all locations already.  */
5539           if (b->type == bp_hardware_watchpoint && bl != b->loc)
5540             break;
5541
5542           if (!bl->enabled || bl->shlib_disabled)
5543             continue;
5544
5545           if (!bpstat_check_location (bl, aspace, bp_addr, ws))
5546             continue;
5547
5548           /* Come here if it's a watchpoint, or if the break address
5549              matches.  */
5550
5551           bs = bpstat_alloc (bl, &bs_link);     /* Alloc a bpstat to
5552                                                    explain stop.  */
5553
5554           /* Assume we stop.  Should we find a watchpoint that is not
5555              actually triggered, or if the condition of the breakpoint
5556              evaluates as false, we'll reset 'stop' to 0.  */
5557           bs->stop = 1;
5558           bs->print = 1;
5559
5560           /* If this is a scope breakpoint, mark the associated
5561              watchpoint as triggered so that we will handle the
5562              out-of-scope event.  We'll get to the watchpoint next
5563              iteration.  */
5564           if (b->type == bp_watchpoint_scope && b->related_breakpoint != b)
5565             {
5566               struct watchpoint *w = (struct watchpoint *) b->related_breakpoint;
5567
5568               w->watchpoint_triggered = watch_triggered_yes;
5569             }
5570         }
5571     }
5572
5573   /* Check if a moribund breakpoint explains the stop.  */
5574   if (!target_supports_stopped_by_sw_breakpoint ()
5575       || !target_supports_stopped_by_hw_breakpoint ())
5576     {
5577       for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
5578         {
5579           if (breakpoint_location_address_match (loc, aspace, bp_addr)
5580               && need_moribund_for_location_type (loc))
5581             {
5582               bs = bpstat_alloc (loc, &bs_link);
5583               /* For hits of moribund locations, we should just proceed.  */
5584               bs->stop = 0;
5585               bs->print = 0;
5586               bs->print_it = print_it_noop;
5587             }
5588         }
5589     }
5590
5591   /* A bit of special processing for shlib breakpoints.  We need to
5592      process solib loading here, so that the lists of loaded and
5593      unloaded libraries are correct before we handle "catch load" and
5594      "catch unload".  */
5595   for (bs = bs_head; bs != NULL; bs = bs->next)
5596     {
5597       if (bs->breakpoint_at && bs->breakpoint_at->type == bp_shlib_event)
5598         {
5599           handle_solib_event ();
5600           break;
5601         }
5602     }
5603
5604   /* Now go through the locations that caused the target to stop, and
5605      check whether we're interested in reporting this stop to higher
5606      layers, or whether we should resume the target transparently.  */
5607
5608   removed_any = 0;
5609
5610   for (bs = bs_head; bs != NULL; bs = bs->next)
5611     {
5612       if (!bs->stop)
5613         continue;
5614
5615       b = bs->breakpoint_at;
5616       b->ops->check_status (bs);
5617       if (bs->stop)
5618         {
5619           bpstat_check_breakpoint_conditions (bs, ptid);
5620
5621           if (bs->stop)
5622             {
5623               ++(b->hit_count);
5624               observer_notify_breakpoint_modified (b);
5625
5626               /* We will stop here.  */
5627               if (b->disposition == disp_disable)
5628                 {
5629                   --(b->enable_count);
5630                   if (b->enable_count <= 0)
5631                     b->enable_state = bp_disabled;
5632                   removed_any = 1;
5633                 }
5634               if (b->silent)
5635                 bs->print = 0;
5636               bs->commands = b->commands;
5637               incref_counted_command_line (bs->commands);
5638               if (command_line_is_silent (bs->commands
5639                                           ? bs->commands->commands : NULL))
5640                 bs->print = 0;
5641
5642               b->ops->after_condition_true (bs);
5643             }
5644
5645         }
5646
5647       /* Print nothing for this entry if we don't stop or don't
5648          print.  */
5649       if (!bs->stop || !bs->print)
5650         bs->print_it = print_it_noop;
5651     }
5652
5653   /* If we aren't stopping, the value of some hardware watchpoint may
5654      not have changed, but the intermediate memory locations we are
5655      watching may have.  Don't bother if we're stopping; this will get
5656      done later.  */
5657   need_remove_insert = 0;
5658   if (! bpstat_causes_stop (bs_head))
5659     for (bs = bs_head; bs != NULL; bs = bs->next)
5660       if (!bs->stop
5661           && bs->breakpoint_at
5662           && is_hardware_watchpoint (bs->breakpoint_at))
5663         {
5664           struct watchpoint *w = (struct watchpoint *) bs->breakpoint_at;
5665
5666           update_watchpoint (w, 0 /* don't reparse.  */);
5667           need_remove_insert = 1;
5668         }
5669
5670   if (need_remove_insert)
5671     update_global_location_list (UGLL_MAY_INSERT);
5672   else if (removed_any)
5673     update_global_location_list (UGLL_DONT_INSERT);
5674
5675   return bs_head;
5676 }
5677
5678 static void
5679 handle_jit_event (void)
5680 {
5681   struct frame_info *frame;
5682   struct gdbarch *gdbarch;
5683
5684   /* Switch terminal for any messages produced by
5685      breakpoint_re_set.  */
5686   target_terminal_ours_for_output ();
5687
5688   frame = get_current_frame ();
5689   gdbarch = get_frame_arch (frame);
5690
5691   jit_event_handler (gdbarch);
5692
5693   target_terminal_inferior ();
5694 }
5695
5696 /* Prepare WHAT final decision for infrun.  */
5697
5698 /* Decide what infrun needs to do with this bpstat.  */
5699
5700 struct bpstat_what
5701 bpstat_what (bpstat bs_head)
5702 {
5703   struct bpstat_what retval;
5704   int jit_event = 0;
5705   bpstat bs;
5706
5707   retval.main_action = BPSTAT_WHAT_KEEP_CHECKING;
5708   retval.call_dummy = STOP_NONE;
5709   retval.is_longjmp = 0;
5710
5711   for (bs = bs_head; bs != NULL; bs = bs->next)
5712     {
5713       /* Extract this BS's action.  After processing each BS, we check
5714          if its action overrides all we've seem so far.  */
5715       enum bpstat_what_main_action this_action = BPSTAT_WHAT_KEEP_CHECKING;
5716       enum bptype bptype;
5717
5718       if (bs->breakpoint_at == NULL)
5719         {
5720           /* I suspect this can happen if it was a momentary
5721              breakpoint which has since been deleted.  */
5722           bptype = bp_none;
5723         }
5724       else
5725         bptype = bs->breakpoint_at->type;
5726
5727       switch (bptype)
5728         {
5729         case bp_none:
5730           break;
5731         case bp_breakpoint:
5732         case bp_hardware_breakpoint:
5733         case bp_single_step:
5734         case bp_until:
5735         case bp_finish:
5736         case bp_shlib_event:
5737           if (bs->stop)
5738             {
5739               if (bs->print)
5740                 this_action = BPSTAT_WHAT_STOP_NOISY;
5741               else
5742                 this_action = BPSTAT_WHAT_STOP_SILENT;
5743             }
5744           else
5745             this_action = BPSTAT_WHAT_SINGLE;
5746           break;
5747         case bp_watchpoint:
5748         case bp_hardware_watchpoint:
5749         case bp_read_watchpoint:
5750         case bp_access_watchpoint:
5751           if (bs->stop)
5752             {
5753               if (bs->print)
5754                 this_action = BPSTAT_WHAT_STOP_NOISY;
5755               else
5756                 this_action = BPSTAT_WHAT_STOP_SILENT;
5757             }
5758           else
5759             {
5760               /* There was a watchpoint, but we're not stopping.
5761                  This requires no further action.  */
5762             }
5763           break;
5764         case bp_longjmp:
5765         case bp_longjmp_call_dummy:
5766         case bp_exception:
5767           this_action = BPSTAT_WHAT_SET_LONGJMP_RESUME;
5768           retval.is_longjmp = bptype != bp_exception;
5769           break;
5770         case bp_longjmp_resume:
5771         case bp_exception_resume:
5772           this_action = BPSTAT_WHAT_CLEAR_LONGJMP_RESUME;
5773           retval.is_longjmp = bptype == bp_longjmp_resume;
5774           break;
5775         case bp_step_resume:
5776           if (bs->stop)
5777             this_action = BPSTAT_WHAT_STEP_RESUME;
5778           else
5779             {
5780               /* It is for the wrong frame.  */
5781               this_action = BPSTAT_WHAT_SINGLE;
5782             }
5783           break;
5784         case bp_hp_step_resume:
5785           if (bs->stop)
5786             this_action = BPSTAT_WHAT_HP_STEP_RESUME;
5787           else
5788             {
5789               /* It is for the wrong frame.  */
5790               this_action = BPSTAT_WHAT_SINGLE;
5791             }
5792           break;
5793         case bp_watchpoint_scope:
5794         case bp_thread_event:
5795         case bp_overlay_event:
5796         case bp_longjmp_master:
5797         case bp_std_terminate_master:
5798         case bp_exception_master:
5799           this_action = BPSTAT_WHAT_SINGLE;
5800           break;
5801         case bp_catchpoint:
5802           if (bs->stop)
5803             {
5804               if (bs->print)
5805                 this_action = BPSTAT_WHAT_STOP_NOISY;
5806               else
5807                 this_action = BPSTAT_WHAT_STOP_SILENT;
5808             }
5809           else
5810             {
5811               /* There was a catchpoint, but we're not stopping.
5812                  This requires no further action.  */
5813             }
5814           break;
5815         case bp_jit_event:
5816           jit_event = 1;
5817           this_action = BPSTAT_WHAT_SINGLE;
5818           break;
5819         case bp_call_dummy:
5820           /* Make sure the action is stop (silent or noisy),
5821              so infrun.c pops the dummy frame.  */
5822           retval.call_dummy = STOP_STACK_DUMMY;
5823           this_action = BPSTAT_WHAT_STOP_SILENT;
5824           break;
5825         case bp_std_terminate:
5826           /* Make sure the action is stop (silent or noisy),
5827              so infrun.c pops the dummy frame.  */
5828           retval.call_dummy = STOP_STD_TERMINATE;
5829           this_action = BPSTAT_WHAT_STOP_SILENT;
5830           break;
5831         case bp_tracepoint:
5832         case bp_fast_tracepoint:
5833         case bp_static_tracepoint:
5834           /* Tracepoint hits should not be reported back to GDB, and
5835              if one got through somehow, it should have been filtered
5836              out already.  */
5837           internal_error (__FILE__, __LINE__,
5838                           _("bpstat_what: tracepoint encountered"));
5839           break;
5840         case bp_gnu_ifunc_resolver:
5841           /* Step over it (and insert bp_gnu_ifunc_resolver_return).  */
5842           this_action = BPSTAT_WHAT_SINGLE;
5843           break;
5844         case bp_gnu_ifunc_resolver_return:
5845           /* The breakpoint will be removed, execution will restart from the
5846              PC of the former breakpoint.  */
5847           this_action = BPSTAT_WHAT_KEEP_CHECKING;
5848           break;
5849
5850         case bp_dprintf:
5851           if (bs->stop)
5852             this_action = BPSTAT_WHAT_STOP_SILENT;
5853           else
5854             this_action = BPSTAT_WHAT_SINGLE;
5855           break;
5856
5857         default:
5858           internal_error (__FILE__, __LINE__,
5859                           _("bpstat_what: unhandled bptype %d"), (int) bptype);
5860         }
5861
5862       retval.main_action = max (retval.main_action, this_action);
5863     }
5864
5865   /* These operations may affect the bs->breakpoint_at state so they are
5866      delayed after MAIN_ACTION is decided above.  */
5867
5868   if (jit_event)
5869     {
5870       if (debug_infrun)
5871         fprintf_unfiltered (gdb_stdlog, "bpstat_what: bp_jit_event\n");
5872
5873       handle_jit_event ();
5874     }
5875
5876   for (bs = bs_head; bs != NULL; bs = bs->next)
5877     {
5878       struct breakpoint *b = bs->breakpoint_at;
5879
5880       if (b == NULL)
5881         continue;
5882       switch (b->type)
5883         {
5884         case bp_gnu_ifunc_resolver:
5885           gnu_ifunc_resolver_stop (b);
5886           break;
5887         case bp_gnu_ifunc_resolver_return:
5888           gnu_ifunc_resolver_return_stop (b);
5889           break;
5890         }
5891     }
5892
5893   return retval;
5894 }
5895
5896 /* Nonzero if we should step constantly (e.g. watchpoints on machines
5897    without hardware support).  This isn't related to a specific bpstat,
5898    just to things like whether watchpoints are set.  */
5899
5900 int
5901 bpstat_should_step (void)
5902 {
5903   struct breakpoint *b;
5904
5905   ALL_BREAKPOINTS (b)
5906     if (breakpoint_enabled (b) && b->type == bp_watchpoint && b->loc != NULL)
5907       return 1;
5908   return 0;
5909 }
5910
5911 int
5912 bpstat_causes_stop (bpstat bs)
5913 {
5914   for (; bs != NULL; bs = bs->next)
5915     if (bs->stop)
5916       return 1;
5917
5918   return 0;
5919 }
5920
5921 \f
5922
5923 /* Compute a string of spaces suitable to indent the next line
5924    so it starts at the position corresponding to the table column
5925    named COL_NAME in the currently active table of UIOUT.  */
5926
5927 static char *
5928 wrap_indent_at_field (struct ui_out *uiout, const char *col_name)
5929 {
5930   static char wrap_indent[80];
5931   int i, total_width, width, align;
5932   char *text;
5933
5934   total_width = 0;
5935   for (i = 1; ui_out_query_field (uiout, i, &width, &align, &text); i++)
5936     {
5937       if (strcmp (text, col_name) == 0)
5938         {
5939           gdb_assert (total_width < sizeof wrap_indent);
5940           memset (wrap_indent, ' ', total_width);
5941           wrap_indent[total_width] = 0;
5942
5943           return wrap_indent;
5944         }
5945
5946       total_width += width + 1;
5947     }
5948
5949   return NULL;
5950 }
5951
5952 /* Determine if the locations of this breakpoint will have their conditions
5953    evaluated by the target, host or a mix of both.  Returns the following:
5954
5955     "host": Host evals condition.
5956     "host or target": Host or Target evals condition.
5957     "target": Target evals condition.
5958 */
5959
5960 static const char *
5961 bp_condition_evaluator (struct breakpoint *b)
5962 {
5963   struct bp_location *bl;
5964   char host_evals = 0;
5965   char target_evals = 0;
5966
5967   if (!b)
5968     return NULL;
5969
5970   if (!is_breakpoint (b))
5971     return NULL;
5972
5973   if (gdb_evaluates_breakpoint_condition_p ()
5974       || !target_supports_evaluation_of_breakpoint_conditions ())
5975     return condition_evaluation_host;
5976
5977   for (bl = b->loc; bl; bl = bl->next)
5978     {
5979       if (bl->cond_bytecode)
5980         target_evals++;
5981       else
5982         host_evals++;
5983     }
5984
5985   if (host_evals && target_evals)
5986     return condition_evaluation_both;
5987   else if (target_evals)
5988     return condition_evaluation_target;
5989   else
5990     return condition_evaluation_host;
5991 }
5992
5993 /* Determine the breakpoint location's condition evaluator.  This is
5994    similar to bp_condition_evaluator, but for locations.  */
5995
5996 static const char *
5997 bp_location_condition_evaluator (struct bp_location *bl)
5998 {
5999   if (bl && !is_breakpoint (bl->owner))
6000     return NULL;
6001
6002   if (gdb_evaluates_breakpoint_condition_p ()
6003       || !target_supports_evaluation_of_breakpoint_conditions ())
6004     return condition_evaluation_host;
6005
6006   if (bl && bl->cond_bytecode)
6007     return condition_evaluation_target;
6008   else
6009     return condition_evaluation_host;
6010 }
6011
6012 /* Print the LOC location out of the list of B->LOC locations.  */
6013
6014 static void
6015 print_breakpoint_location (struct breakpoint *b,
6016                            struct bp_location *loc)
6017 {
6018   struct ui_out *uiout = current_uiout;
6019   struct cleanup *old_chain = save_current_program_space ();
6020
6021   if (loc != NULL && loc->shlib_disabled)
6022     loc = NULL;
6023
6024   if (loc != NULL)
6025     set_current_program_space (loc->pspace);
6026
6027   if (b->display_canonical)
6028     ui_out_field_string (uiout, "what", b->addr_string);
6029   else if (loc && loc->symtab)
6030     {
6031       struct symbol *sym 
6032         = find_pc_sect_function (loc->address, loc->section);
6033       if (sym)
6034         {
6035           ui_out_text (uiout, "in ");
6036           ui_out_field_string (uiout, "func",
6037                                SYMBOL_PRINT_NAME (sym));
6038           ui_out_text (uiout, " ");
6039           ui_out_wrap_hint (uiout, wrap_indent_at_field (uiout, "what"));
6040           ui_out_text (uiout, "at ");
6041         }
6042       ui_out_field_string (uiout, "file",
6043                            symtab_to_filename_for_display (loc->symtab));
6044       ui_out_text (uiout, ":");
6045
6046       if (ui_out_is_mi_like_p (uiout))
6047         ui_out_field_string (uiout, "fullname",
6048                              symtab_to_fullname (loc->symtab));
6049       
6050       ui_out_field_int (uiout, "line", loc->line_number);
6051     }
6052   else if (loc)
6053     {
6054       struct ui_file *stb = mem_fileopen ();
6055       struct cleanup *stb_chain = make_cleanup_ui_file_delete (stb);
6056
6057       print_address_symbolic (loc->gdbarch, loc->address, stb,
6058                               demangle, "");
6059       ui_out_field_stream (uiout, "at", stb);
6060
6061       do_cleanups (stb_chain);
6062     }
6063   else
6064     ui_out_field_string (uiout, "pending", b->addr_string);
6065
6066   if (loc && is_breakpoint (b)
6067       && breakpoint_condition_evaluation_mode () == condition_evaluation_target
6068       && bp_condition_evaluator (b) == condition_evaluation_both)
6069     {
6070       ui_out_text (uiout, " (");
6071       ui_out_field_string (uiout, "evaluated-by",
6072                            bp_location_condition_evaluator (loc));
6073       ui_out_text (uiout, ")");
6074     }
6075
6076   do_cleanups (old_chain);
6077 }
6078
6079 static const char *
6080 bptype_string (enum bptype type)
6081 {
6082   struct ep_type_description
6083     {
6084       enum bptype type;
6085       char *description;
6086     };
6087   static struct ep_type_description bptypes[] =
6088   {
6089     {bp_none, "?deleted?"},
6090     {bp_breakpoint, "breakpoint"},
6091     {bp_hardware_breakpoint, "hw breakpoint"},
6092     {bp_single_step, "sw single-step"},
6093     {bp_until, "until"},
6094     {bp_finish, "finish"},
6095     {bp_watchpoint, "watchpoint"},
6096     {bp_hardware_watchpoint, "hw watchpoint"},
6097     {bp_read_watchpoint, "read watchpoint"},
6098     {bp_access_watchpoint, "acc watchpoint"},
6099     {bp_longjmp, "longjmp"},
6100     {bp_longjmp_resume, "longjmp resume"},
6101     {bp_longjmp_call_dummy, "longjmp for call dummy"},
6102     {bp_exception, "exception"},
6103     {bp_exception_resume, "exception resume"},
6104     {bp_step_resume, "step resume"},
6105     {bp_hp_step_resume, "high-priority step resume"},
6106     {bp_watchpoint_scope, "watchpoint scope"},
6107     {bp_call_dummy, "call dummy"},
6108     {bp_std_terminate, "std::terminate"},
6109     {bp_shlib_event, "shlib events"},
6110     {bp_thread_event, "thread events"},
6111     {bp_overlay_event, "overlay events"},
6112     {bp_longjmp_master, "longjmp master"},
6113     {bp_std_terminate_master, "std::terminate master"},
6114     {bp_exception_master, "exception master"},
6115     {bp_catchpoint, "catchpoint"},
6116     {bp_tracepoint, "tracepoint"},
6117     {bp_fast_tracepoint, "fast tracepoint"},
6118     {bp_static_tracepoint, "static tracepoint"},
6119     {bp_dprintf, "dprintf"},
6120     {bp_jit_event, "jit events"},
6121     {bp_gnu_ifunc_resolver, "STT_GNU_IFUNC resolver"},
6122     {bp_gnu_ifunc_resolver_return, "STT_GNU_IFUNC resolver return"},
6123   };
6124
6125   if (((int) type >= (sizeof (bptypes) / sizeof (bptypes[0])))
6126       || ((int) type != bptypes[(int) type].type))
6127     internal_error (__FILE__, __LINE__,
6128                     _("bptypes table does not describe type #%d."),
6129                     (int) type);
6130
6131   return bptypes[(int) type].description;
6132 }
6133
6134 /* For MI, output a field named 'thread-groups' with a list as the value.
6135    For CLI, prefix the list with the string 'inf'. */
6136
6137 static void
6138 output_thread_groups (struct ui_out *uiout,
6139                       const char *field_name,
6140                       VEC(int) *inf_num,
6141                       int mi_only)
6142 {
6143   struct cleanup *back_to;
6144   int is_mi = ui_out_is_mi_like_p (uiout);
6145   int inf;
6146   int i;
6147
6148   /* For backward compatibility, don't display inferiors in CLI unless
6149      there are several.  Always display them for MI. */
6150   if (!is_mi && mi_only)
6151     return;
6152
6153   back_to = make_cleanup_ui_out_list_begin_end (uiout, field_name);
6154
6155   for (i = 0; VEC_iterate (int, inf_num, i, inf); ++i)
6156     {
6157       if (is_mi)
6158         {
6159           char mi_group[10];
6160
6161           xsnprintf (mi_group, sizeof (mi_group), "i%d", inf);
6162           ui_out_field_string (uiout, NULL, mi_group);
6163         }
6164       else
6165         {
6166           if (i == 0)
6167             ui_out_text (uiout, " inf ");
6168           else
6169             ui_out_text (uiout, ", ");
6170         
6171           ui_out_text (uiout, plongest (inf));
6172         }
6173     }
6174
6175   do_cleanups (back_to);
6176 }
6177
6178 /* Print B to gdb_stdout.  */
6179
6180 static void
6181 print_one_breakpoint_location (struct breakpoint *b,
6182                                struct bp_location *loc,
6183                                int loc_number,
6184                                struct bp_location **last_loc,
6185                                int allflag)
6186 {
6187   struct command_line *l;
6188   static char bpenables[] = "nynny";
6189
6190   struct ui_out *uiout = current_uiout;
6191   int header_of_multiple = 0;
6192   int part_of_multiple = (loc != NULL);
6193   struct value_print_options opts;
6194
6195   get_user_print_options (&opts);
6196
6197   gdb_assert (!loc || loc_number != 0);
6198   /* See comment in print_one_breakpoint concerning treatment of
6199      breakpoints with single disabled location.  */
6200   if (loc == NULL 
6201       && (b->loc != NULL 
6202           && (b->loc->next != NULL || !b->loc->enabled)))
6203     header_of_multiple = 1;
6204   if (loc == NULL)
6205     loc = b->loc;
6206
6207   annotate_record ();
6208
6209   /* 1 */
6210   annotate_field (0);
6211   if (part_of_multiple)
6212     {
6213       char *formatted;
6214       formatted = xstrprintf ("%d.%d", b->number, loc_number);
6215       ui_out_field_string (uiout, "number", formatted);
6216       xfree (formatted);
6217     }
6218   else
6219     {
6220       ui_out_field_int (uiout, "number", b->number);
6221     }
6222
6223   /* 2 */
6224   annotate_field (1);
6225   if (part_of_multiple)
6226     ui_out_field_skip (uiout, "type");
6227   else
6228     ui_out_field_string (uiout, "type", bptype_string (b->type));
6229
6230   /* 3 */
6231   annotate_field (2);
6232   if (part_of_multiple)
6233     ui_out_field_skip (uiout, "disp");
6234   else
6235     ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
6236
6237
6238   /* 4 */
6239   annotate_field (3);
6240   if (part_of_multiple)
6241     ui_out_field_string (uiout, "enabled", loc->enabled ? "y" : "n");
6242   else
6243     ui_out_field_fmt (uiout, "enabled", "%c", 
6244                       bpenables[(int) b->enable_state]);
6245   ui_out_spaces (uiout, 2);
6246
6247   
6248   /* 5 and 6 */
6249   if (b->ops != NULL && b->ops->print_one != NULL)
6250     {
6251       /* Although the print_one can possibly print all locations,
6252          calling it here is not likely to get any nice result.  So,
6253          make sure there's just one location.  */
6254       gdb_assert (b->loc == NULL || b->loc->next == NULL);
6255       b->ops->print_one (b, last_loc);
6256     }
6257   else
6258     switch (b->type)
6259       {
6260       case bp_none:
6261         internal_error (__FILE__, __LINE__,
6262                         _("print_one_breakpoint: bp_none encountered\n"));
6263         break;
6264
6265       case bp_watchpoint:
6266       case bp_hardware_watchpoint:
6267       case bp_read_watchpoint:
6268       case bp_access_watchpoint:
6269         {
6270           struct watchpoint *w = (struct watchpoint *) b;
6271
6272           /* Field 4, the address, is omitted (which makes the columns
6273              not line up too nicely with the headers, but the effect
6274              is relatively readable).  */
6275           if (opts.addressprint)
6276             ui_out_field_skip (uiout, "addr");
6277           annotate_field (5);
6278           ui_out_field_string (uiout, "what", w->exp_string);
6279         }
6280         break;
6281
6282       case bp_breakpoint:
6283       case bp_hardware_breakpoint:
6284       case bp_single_step:
6285       case bp_until:
6286       case bp_finish:
6287       case bp_longjmp:
6288       case bp_longjmp_resume:
6289       case bp_longjmp_call_dummy:
6290       case bp_exception:
6291       case bp_exception_resume:
6292       case bp_step_resume:
6293       case bp_hp_step_resume:
6294       case bp_watchpoint_scope:
6295       case bp_call_dummy:
6296       case bp_std_terminate:
6297       case bp_shlib_event:
6298       case bp_thread_event:
6299       case bp_overlay_event:
6300       case bp_longjmp_master:
6301       case bp_std_terminate_master:
6302       case bp_exception_master:
6303       case bp_tracepoint:
6304       case bp_fast_tracepoint:
6305       case bp_static_tracepoint:
6306       case bp_dprintf:
6307       case bp_jit_event:
6308       case bp_gnu_ifunc_resolver:
6309       case bp_gnu_ifunc_resolver_return:
6310         if (opts.addressprint)
6311           {
6312             annotate_field (4);
6313             if (header_of_multiple)
6314               ui_out_field_string (uiout, "addr", "<MULTIPLE>");
6315             else if (b->loc == NULL || loc->shlib_disabled)
6316               ui_out_field_string (uiout, "addr", "<PENDING>");
6317             else
6318               ui_out_field_core_addr (uiout, "addr",
6319                                       loc->gdbarch, loc->address);
6320           }
6321         annotate_field (5);
6322         if (!header_of_multiple)
6323           print_breakpoint_location (b, loc);
6324         if (b->loc)
6325           *last_loc = b->loc;
6326         break;
6327       }
6328
6329
6330   if (loc != NULL && !header_of_multiple)
6331     {
6332       struct inferior *inf;
6333       VEC(int) *inf_num = NULL;
6334       int mi_only = 1;
6335
6336       ALL_INFERIORS (inf)
6337         {
6338           if (inf->pspace == loc->pspace)
6339             VEC_safe_push (int, inf_num, inf->num);
6340         }
6341
6342         /* For backward compatibility, don't display inferiors in CLI unless
6343            there are several.  Always display for MI. */
6344         if (allflag
6345             || (!gdbarch_has_global_breakpoints (target_gdbarch ())
6346                 && (number_of_program_spaces () > 1
6347                     || number_of_inferiors () > 1)
6348                 /* LOC is for existing B, it cannot be in
6349                    moribund_locations and thus having NULL OWNER.  */
6350                 && loc->owner->type != bp_catchpoint))
6351         mi_only = 0;
6352       output_thread_groups (uiout, "thread-groups", inf_num, mi_only);
6353       VEC_free (int, inf_num);
6354     }
6355
6356   if (!part_of_multiple)
6357     {
6358       if (b->thread != -1)
6359         {
6360           /* FIXME: This seems to be redundant and lost here; see the
6361              "stop only in" line a little further down.  */
6362           ui_out_text (uiout, " thread ");
6363           ui_out_field_int (uiout, "thread", b->thread);
6364         }
6365       else if (b->task != 0)
6366         {
6367           ui_out_text (uiout, " task ");
6368           ui_out_field_int (uiout, "task", b->task);
6369         }
6370     }
6371
6372   ui_out_text (uiout, "\n");
6373
6374   if (!part_of_multiple)
6375     b->ops->print_one_detail (b, uiout);
6376
6377   if (part_of_multiple && frame_id_p (b->frame_id))
6378     {
6379       annotate_field (6);
6380       ui_out_text (uiout, "\tstop only in stack frame at ");
6381       /* FIXME: cagney/2002-12-01: Shouldn't be poking around inside
6382          the frame ID.  */
6383       ui_out_field_core_addr (uiout, "frame",
6384                               b->gdbarch, b->frame_id.stack_addr);
6385       ui_out_text (uiout, "\n");
6386     }
6387   
6388   if (!part_of_multiple && b->cond_string)
6389     {
6390       annotate_field (7);
6391       if (is_tracepoint (b))
6392         ui_out_text (uiout, "\ttrace only if ");
6393       else
6394         ui_out_text (uiout, "\tstop only if ");
6395       ui_out_field_string (uiout, "cond", b->cond_string);
6396
6397       /* Print whether the target is doing the breakpoint's condition
6398          evaluation.  If GDB is doing the evaluation, don't print anything.  */
6399       if (is_breakpoint (b)
6400           && breakpoint_condition_evaluation_mode ()
6401           == condition_evaluation_target)
6402         {
6403           ui_out_text (uiout, " (");
6404           ui_out_field_string (uiout, "evaluated-by",
6405                                bp_condition_evaluator (b));
6406           ui_out_text (uiout, " evals)");
6407         }
6408       ui_out_text (uiout, "\n");
6409     }
6410
6411   if (!part_of_multiple && b->thread != -1)
6412     {
6413       /* FIXME should make an annotation for this.  */
6414       ui_out_text (uiout, "\tstop only in thread ");
6415       ui_out_field_int (uiout, "thread", b->thread);
6416       ui_out_text (uiout, "\n");
6417     }
6418   
6419   if (!part_of_multiple)
6420     {
6421       if (b->hit_count)
6422         {
6423           /* FIXME should make an annotation for this.  */
6424           if (is_catchpoint (b))
6425             ui_out_text (uiout, "\tcatchpoint");
6426           else if (is_tracepoint (b))
6427             ui_out_text (uiout, "\ttracepoint");
6428           else
6429             ui_out_text (uiout, "\tbreakpoint");
6430           ui_out_text (uiout, " already hit ");
6431           ui_out_field_int (uiout, "times", b->hit_count);
6432           if (b->hit_count == 1)
6433             ui_out_text (uiout, " time\n");
6434           else
6435             ui_out_text (uiout, " times\n");
6436         }
6437       else
6438         {
6439           /* Output the count also if it is zero, but only if this is mi.  */
6440           if (ui_out_is_mi_like_p (uiout))
6441             ui_out_field_int (uiout, "times", b->hit_count);
6442         }
6443     }
6444
6445   if (!part_of_multiple && b->ignore_count)
6446     {
6447       annotate_field (8);
6448       ui_out_text (uiout, "\tignore next ");
6449       ui_out_field_int (uiout, "ignore", b->ignore_count);
6450       ui_out_text (uiout, " hits\n");
6451     }
6452
6453   /* Note that an enable count of 1 corresponds to "enable once"
6454      behavior, which is reported by the combination of enablement and
6455      disposition, so we don't need to mention it here.  */
6456   if (!part_of_multiple && b->enable_count > 1)
6457     {
6458       annotate_field (8);
6459       ui_out_text (uiout, "\tdisable after ");
6460       /* Tweak the wording to clarify that ignore and enable counts
6461          are distinct, and have additive effect.  */
6462       if (b->ignore_count)
6463         ui_out_text (uiout, "additional ");
6464       else
6465         ui_out_text (uiout, "next ");
6466       ui_out_field_int (uiout, "enable", b->enable_count);
6467       ui_out_text (uiout, " hits\n");
6468     }
6469
6470   if (!part_of_multiple && is_tracepoint (b))
6471     {
6472       struct tracepoint *tp = (struct tracepoint *) b;
6473
6474       if (tp->traceframe_usage)
6475         {
6476           ui_out_text (uiout, "\ttrace buffer usage ");
6477           ui_out_field_int (uiout, "traceframe-usage", tp->traceframe_usage);
6478           ui_out_text (uiout, " bytes\n");
6479         }
6480     }
6481
6482   l = b->commands ? b->commands->commands : NULL;
6483   if (!part_of_multiple && l)
6484     {
6485       struct cleanup *script_chain;
6486
6487       annotate_field (9);
6488       script_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "script");
6489       print_command_lines (uiout, l, 4);
6490       do_cleanups (script_chain);
6491     }
6492
6493   if (is_tracepoint (b))
6494     {
6495       struct tracepoint *t = (struct tracepoint *) b;
6496
6497       if (!part_of_multiple && t->pass_count)
6498         {
6499           annotate_field (10);
6500           ui_out_text (uiout, "\tpass count ");
6501           ui_out_field_int (uiout, "pass", t->pass_count);
6502           ui_out_text (uiout, " \n");
6503         }
6504
6505       /* Don't display it when tracepoint or tracepoint location is
6506          pending.   */
6507       if (!header_of_multiple && loc != NULL && !loc->shlib_disabled)
6508         {
6509           annotate_field (11);
6510
6511           if (ui_out_is_mi_like_p (uiout))
6512             ui_out_field_string (uiout, "installed",
6513                                  loc->inserted ? "y" : "n");
6514           else
6515             {
6516               if (loc->inserted)
6517                 ui_out_text (uiout, "\t");
6518               else
6519                 ui_out_text (uiout, "\tnot ");
6520               ui_out_text (uiout, "installed on target\n");
6521             }
6522         }
6523     }
6524
6525   if (ui_out_is_mi_like_p (uiout) && !part_of_multiple)
6526     {
6527       if (is_watchpoint (b))
6528         {
6529           struct watchpoint *w = (struct watchpoint *) b;
6530
6531           ui_out_field_string (uiout, "original-location", w->exp_string);
6532         }
6533       else if (b->addr_string)
6534         ui_out_field_string (uiout, "original-location", b->addr_string);
6535     }
6536 }
6537
6538 static void
6539 print_one_breakpoint (struct breakpoint *b,
6540                       struct bp_location **last_loc, 
6541                       int allflag)
6542 {
6543   struct cleanup *bkpt_chain;
6544   struct ui_out *uiout = current_uiout;
6545
6546   bkpt_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "bkpt");
6547
6548   print_one_breakpoint_location (b, NULL, 0, last_loc, allflag);
6549   do_cleanups (bkpt_chain);
6550
6551   /* If this breakpoint has custom print function,
6552      it's already printed.  Otherwise, print individual
6553      locations, if any.  */
6554   if (b->ops == NULL || b->ops->print_one == NULL)
6555     {
6556       /* If breakpoint has a single location that is disabled, we
6557          print it as if it had several locations, since otherwise it's
6558          hard to represent "breakpoint enabled, location disabled"
6559          situation.
6560
6561          Note that while hardware watchpoints have several locations
6562          internally, that's not a property exposed to user.  */
6563       if (b->loc 
6564           && !is_hardware_watchpoint (b)
6565           && (b->loc->next || !b->loc->enabled))
6566         {
6567           struct bp_location *loc;
6568           int n = 1;
6569
6570           for (loc = b->loc; loc; loc = loc->next, ++n)
6571             {
6572               struct cleanup *inner2 =
6573                 make_cleanup_ui_out_tuple_begin_end (uiout, NULL);
6574               print_one_breakpoint_location (b, loc, n, last_loc, allflag);
6575               do_cleanups (inner2);
6576             }
6577         }
6578     }
6579 }
6580
6581 static int
6582 breakpoint_address_bits (struct breakpoint *b)
6583 {
6584   int print_address_bits = 0;
6585   struct bp_location *loc;
6586
6587   for (loc = b->loc; loc; loc = loc->next)
6588     {
6589       int addr_bit;
6590
6591       /* Software watchpoints that aren't watching memory don't have
6592          an address to print.  */
6593       if (b->type == bp_watchpoint && loc->watchpoint_type == -1)
6594         continue;
6595
6596       addr_bit = gdbarch_addr_bit (loc->gdbarch);
6597       if (addr_bit > print_address_bits)
6598         print_address_bits = addr_bit;
6599     }
6600
6601   return print_address_bits;
6602 }
6603
6604 struct captured_breakpoint_query_args
6605   {
6606     int bnum;
6607   };
6608
6609 static int
6610 do_captured_breakpoint_query (struct ui_out *uiout, void *data)
6611 {
6612   struct captured_breakpoint_query_args *args = data;
6613   struct breakpoint *b;
6614   struct bp_location *dummy_loc = NULL;
6615
6616   ALL_BREAKPOINTS (b)
6617     {
6618       if (args->bnum == b->number)
6619         {
6620           print_one_breakpoint (b, &dummy_loc, 0);
6621           return GDB_RC_OK;
6622         }
6623     }
6624   return GDB_RC_NONE;
6625 }
6626
6627 enum gdb_rc
6628 gdb_breakpoint_query (struct ui_out *uiout, int bnum, 
6629                       char **error_message)
6630 {
6631   struct captured_breakpoint_query_args args;
6632
6633   args.bnum = bnum;
6634   /* For the moment we don't trust print_one_breakpoint() to not throw
6635      an error.  */
6636   if (catch_exceptions_with_msg (uiout, do_captured_breakpoint_query, &args,
6637                                  error_message, RETURN_MASK_ALL) < 0)
6638     return GDB_RC_FAIL;
6639   else
6640     return GDB_RC_OK;
6641 }
6642
6643 /* Return true if this breakpoint was set by the user, false if it is
6644    internal or momentary.  */
6645
6646 int
6647 user_breakpoint_p (struct breakpoint *b)
6648 {
6649   return b->number > 0;
6650 }
6651
6652 /* Print information on user settable breakpoint (watchpoint, etc)
6653    number BNUM.  If BNUM is -1 print all user-settable breakpoints.
6654    If ALLFLAG is non-zero, include non-user-settable breakpoints.  If
6655    FILTER is non-NULL, call it on each breakpoint and only include the
6656    ones for which it returns non-zero.  Return the total number of
6657    breakpoints listed.  */
6658
6659 static int
6660 breakpoint_1 (char *args, int allflag, 
6661               int (*filter) (const struct breakpoint *))
6662 {
6663   struct breakpoint *b;
6664   struct bp_location *last_loc = NULL;
6665   int nr_printable_breakpoints;
6666   struct cleanup *bkpttbl_chain;
6667   struct value_print_options opts;
6668   int print_address_bits = 0;
6669   int print_type_col_width = 14;
6670   struct ui_out *uiout = current_uiout;
6671
6672   get_user_print_options (&opts);
6673
6674   /* Compute the number of rows in the table, as well as the size
6675      required for address fields.  */
6676   nr_printable_breakpoints = 0;
6677   ALL_BREAKPOINTS (b)
6678     {
6679       /* If we have a filter, only list the breakpoints it accepts.  */
6680       if (filter && !filter (b))
6681         continue;
6682
6683       /* If we have an "args" string, it is a list of breakpoints to 
6684          accept.  Skip the others.  */
6685       if (args != NULL && *args != '\0')
6686         {
6687           if (allflag && parse_and_eval_long (args) != b->number)
6688             continue;
6689           if (!allflag && !number_is_in_list (args, b->number))
6690             continue;
6691         }
6692
6693       if (allflag || user_breakpoint_p (b))
6694         {
6695           int addr_bit, type_len;
6696
6697           addr_bit = breakpoint_address_bits (b);
6698           if (addr_bit > print_address_bits)
6699             print_address_bits = addr_bit;
6700
6701           type_len = strlen (bptype_string (b->type));
6702           if (type_len > print_type_col_width)
6703             print_type_col_width = type_len;
6704
6705           nr_printable_breakpoints++;
6706         }
6707     }
6708
6709   if (opts.addressprint)
6710     bkpttbl_chain 
6711       = make_cleanup_ui_out_table_begin_end (uiout, 6,
6712                                              nr_printable_breakpoints,
6713                                              "BreakpointTable");
6714   else
6715     bkpttbl_chain 
6716       = make_cleanup_ui_out_table_begin_end (uiout, 5,
6717                                              nr_printable_breakpoints,
6718                                              "BreakpointTable");
6719
6720   if (nr_printable_breakpoints > 0)
6721     annotate_breakpoints_headers ();
6722   if (nr_printable_breakpoints > 0)
6723     annotate_field (0);
6724   ui_out_table_header (uiout, 7, ui_left, "number", "Num");     /* 1 */
6725   if (nr_printable_breakpoints > 0)
6726     annotate_field (1);
6727   ui_out_table_header (uiout, print_type_col_width, ui_left,
6728                        "type", "Type");                         /* 2 */
6729   if (nr_printable_breakpoints > 0)
6730     annotate_field (2);
6731   ui_out_table_header (uiout, 4, ui_left, "disp", "Disp");      /* 3 */
6732   if (nr_printable_breakpoints > 0)
6733     annotate_field (3);
6734   ui_out_table_header (uiout, 3, ui_left, "enabled", "Enb");    /* 4 */
6735   if (opts.addressprint)
6736     {
6737       if (nr_printable_breakpoints > 0)
6738         annotate_field (4);
6739       if (print_address_bits <= 32)
6740         ui_out_table_header (uiout, 10, ui_left, 
6741                              "addr", "Address");                /* 5 */
6742       else
6743         ui_out_table_header (uiout, 18, ui_left, 
6744                              "addr", "Address");                /* 5 */
6745     }
6746   if (nr_printable_breakpoints > 0)
6747     annotate_field (5);
6748   ui_out_table_header (uiout, 40, ui_noalign, "what", "What");  /* 6 */
6749   ui_out_table_body (uiout);
6750   if (nr_printable_breakpoints > 0)
6751     annotate_breakpoints_table ();
6752
6753   ALL_BREAKPOINTS (b)
6754     {
6755       QUIT;
6756       /* If we have a filter, only list the breakpoints it accepts.  */
6757       if (filter && !filter (b))
6758         continue;
6759
6760       /* If we have an "args" string, it is a list of breakpoints to 
6761          accept.  Skip the others.  */
6762
6763       if (args != NULL && *args != '\0')
6764         {
6765           if (allflag)  /* maintenance info breakpoint */
6766             {
6767               if (parse_and_eval_long (args) != b->number)
6768                 continue;
6769             }
6770           else          /* all others */
6771             {
6772               if (!number_is_in_list (args, b->number))
6773                 continue;
6774             }
6775         }
6776       /* We only print out user settable breakpoints unless the
6777          allflag is set.  */
6778       if (allflag || user_breakpoint_p (b))
6779         print_one_breakpoint (b, &last_loc, allflag);
6780     }
6781
6782   do_cleanups (bkpttbl_chain);
6783
6784   if (nr_printable_breakpoints == 0)
6785     {
6786       /* If there's a filter, let the caller decide how to report
6787          empty list.  */
6788       if (!filter)
6789         {
6790           if (args == NULL || *args == '\0')
6791             ui_out_message (uiout, 0, "No breakpoints or watchpoints.\n");
6792           else
6793             ui_out_message (uiout, 0, 
6794                             "No breakpoint or watchpoint matching '%s'.\n",
6795                             args);
6796         }
6797     }
6798   else
6799     {
6800       if (last_loc && !server_command)
6801         set_next_address (last_loc->gdbarch, last_loc->address);
6802     }
6803
6804   /* FIXME?  Should this be moved up so that it is only called when
6805      there have been breakpoints? */
6806   annotate_breakpoints_table_end ();
6807
6808   return nr_printable_breakpoints;
6809 }
6810
6811 /* Display the value of default-collect in a way that is generally
6812    compatible with the breakpoint list.  */
6813
6814 static void
6815 default_collect_info (void)
6816 {
6817   struct ui_out *uiout = current_uiout;
6818
6819   /* If it has no value (which is frequently the case), say nothing; a
6820      message like "No default-collect." gets in user's face when it's
6821      not wanted.  */
6822   if (!*default_collect)
6823     return;
6824
6825   /* The following phrase lines up nicely with per-tracepoint collect
6826      actions.  */
6827   ui_out_text (uiout, "default collect ");
6828   ui_out_field_string (uiout, "default-collect", default_collect);
6829   ui_out_text (uiout, " \n");
6830 }
6831   
6832 static void
6833 breakpoints_info (char *args, int from_tty)
6834 {
6835   breakpoint_1 (args, 0, NULL);
6836
6837   default_collect_info ();
6838 }
6839
6840 static void
6841 watchpoints_info (char *args, int from_tty)
6842 {
6843   int num_printed = breakpoint_1 (args, 0, is_watchpoint);
6844   struct ui_out *uiout = current_uiout;
6845
6846   if (num_printed == 0)
6847     {
6848       if (args == NULL || *args == '\0')
6849         ui_out_message (uiout, 0, "No watchpoints.\n");
6850       else
6851         ui_out_message (uiout, 0, "No watchpoint matching '%s'.\n", args);
6852     }
6853 }
6854
6855 static void
6856 maintenance_info_breakpoints (char *args, int from_tty)
6857 {
6858   breakpoint_1 (args, 1, NULL);
6859
6860   default_collect_info ();
6861 }
6862
6863 static int
6864 breakpoint_has_pc (struct breakpoint *b,
6865                    struct program_space *pspace,
6866                    CORE_ADDR pc, struct obj_section *section)
6867 {
6868   struct bp_location *bl = b->loc;
6869
6870   for (; bl; bl = bl->next)
6871     {
6872       if (bl->pspace == pspace
6873           && bl->address == pc
6874           && (!overlay_debugging || bl->section == section))
6875         return 1;         
6876     }
6877   return 0;
6878 }
6879
6880 /* Print a message describing any user-breakpoints set at PC.  This
6881    concerns with logical breakpoints, so we match program spaces, not
6882    address spaces.  */
6883
6884 static void
6885 describe_other_breakpoints (struct gdbarch *gdbarch,
6886                             struct program_space *pspace, CORE_ADDR pc,
6887                             struct obj_section *section, int thread)
6888 {
6889   int others = 0;
6890   struct breakpoint *b;
6891
6892   ALL_BREAKPOINTS (b)
6893     others += (user_breakpoint_p (b)
6894                && breakpoint_has_pc (b, pspace, pc, section));
6895   if (others > 0)
6896     {
6897       if (others == 1)
6898         printf_filtered (_("Note: breakpoint "));
6899       else /* if (others == ???) */
6900         printf_filtered (_("Note: breakpoints "));
6901       ALL_BREAKPOINTS (b)
6902         if (user_breakpoint_p (b) && breakpoint_has_pc (b, pspace, pc, section))
6903           {
6904             others--;
6905             printf_filtered ("%d", b->number);
6906             if (b->thread == -1 && thread != -1)
6907               printf_filtered (" (all threads)");
6908             else if (b->thread != -1)
6909               printf_filtered (" (thread %d)", b->thread);
6910             printf_filtered ("%s%s ",
6911                              ((b->enable_state == bp_disabled
6912                                || b->enable_state == bp_call_disabled)
6913                               ? " (disabled)"
6914                               : ""),
6915                              (others > 1) ? "," 
6916                              : ((others == 1) ? " and" : ""));
6917           }
6918       printf_filtered (_("also set at pc "));
6919       fputs_filtered (paddress (gdbarch, pc), gdb_stdout);
6920       printf_filtered (".\n");
6921     }
6922 }
6923 \f
6924
6925 /* Return true iff it is meaningful to use the address member of
6926    BPT.  For some breakpoint types, the address member is irrelevant
6927    and it makes no sense to attempt to compare it to other addresses
6928    (or use it for any other purpose either).
6929
6930    More specifically, each of the following breakpoint types will
6931    always have a zero valued address and we don't want to mark
6932    breakpoints of any of these types to be a duplicate of an actual
6933    breakpoint at address zero:
6934
6935       bp_watchpoint
6936       bp_catchpoint
6937
6938 */
6939
6940 static int
6941 breakpoint_address_is_meaningful (struct breakpoint *bpt)
6942 {
6943   enum bptype type = bpt->type;
6944
6945   return (type != bp_watchpoint && type != bp_catchpoint);
6946 }
6947
6948 /* Assuming LOC1 and LOC2's owners are hardware watchpoints, returns
6949    true if LOC1 and LOC2 represent the same watchpoint location.  */
6950
6951 static int
6952 watchpoint_locations_match (struct bp_location *loc1, 
6953                             struct bp_location *loc2)
6954 {
6955   struct watchpoint *w1 = (struct watchpoint *) loc1->owner;
6956   struct watchpoint *w2 = (struct watchpoint *) loc2->owner;
6957
6958   /* Both of them must exist.  */
6959   gdb_assert (w1 != NULL);
6960   gdb_assert (w2 != NULL);
6961
6962   /* If the target can evaluate the condition expression in hardware,
6963      then we we need to insert both watchpoints even if they are at
6964      the same place.  Otherwise the watchpoint will only trigger when
6965      the condition of whichever watchpoint was inserted evaluates to
6966      true, not giving a chance for GDB to check the condition of the
6967      other watchpoint.  */
6968   if ((w1->cond_exp
6969        && target_can_accel_watchpoint_condition (loc1->address, 
6970                                                  loc1->length,
6971                                                  loc1->watchpoint_type,
6972                                                  w1->cond_exp))
6973       || (w2->cond_exp
6974           && target_can_accel_watchpoint_condition (loc2->address, 
6975                                                     loc2->length,
6976                                                     loc2->watchpoint_type,
6977                                                     w2->cond_exp)))
6978     return 0;
6979
6980   /* Note that this checks the owner's type, not the location's.  In
6981      case the target does not support read watchpoints, but does
6982      support access watchpoints, we'll have bp_read_watchpoint
6983      watchpoints with hw_access locations.  Those should be considered
6984      duplicates of hw_read locations.  The hw_read locations will
6985      become hw_access locations later.  */
6986   return (loc1->owner->type == loc2->owner->type
6987           && loc1->pspace->aspace == loc2->pspace->aspace
6988           && loc1->address == loc2->address
6989           && loc1->length == loc2->length);
6990 }
6991
6992 /* See breakpoint.h.  */
6993
6994 int
6995 breakpoint_address_match (struct address_space *aspace1, CORE_ADDR addr1,
6996                           struct address_space *aspace2, CORE_ADDR addr2)
6997 {
6998   return ((gdbarch_has_global_breakpoints (target_gdbarch ())
6999            || aspace1 == aspace2)
7000           && addr1 == addr2);
7001 }
7002
7003 /* Returns true if {ASPACE2,ADDR2} falls within the range determined by
7004    {ASPACE1,ADDR1,LEN1}.  In most targets, this can only be true if ASPACE1
7005    matches ASPACE2.  On targets that have global breakpoints, the address
7006    space doesn't really matter.  */
7007
7008 static int
7009 breakpoint_address_match_range (struct address_space *aspace1, CORE_ADDR addr1,
7010                                 int len1, struct address_space *aspace2,
7011                                 CORE_ADDR addr2)
7012 {
7013   return ((gdbarch_has_global_breakpoints (target_gdbarch ())
7014            || aspace1 == aspace2)
7015           && addr2 >= addr1 && addr2 < addr1 + len1);
7016 }
7017
7018 /* Returns true if {ASPACE,ADDR} matches the breakpoint BL.  BL may be
7019    a ranged breakpoint.  In most targets, a match happens only if ASPACE
7020    matches the breakpoint's address space.  On targets that have global
7021    breakpoints, the address space doesn't really matter.  */
7022
7023 static int
7024 breakpoint_location_address_match (struct bp_location *bl,
7025                                    struct address_space *aspace,
7026                                    CORE_ADDR addr)
7027 {
7028   return (breakpoint_address_match (bl->pspace->aspace, bl->address,
7029                                     aspace, addr)
7030           || (bl->length
7031               && breakpoint_address_match_range (bl->pspace->aspace,
7032                                                  bl->address, bl->length,
7033                                                  aspace, addr)));
7034 }
7035
7036 /* If LOC1 and LOC2's owners are not tracepoints, returns false directly.
7037    Then, if LOC1 and LOC2 represent the same tracepoint location, returns
7038    true, otherwise returns false.  */
7039
7040 static int
7041 tracepoint_locations_match (struct bp_location *loc1,
7042                             struct bp_location *loc2)
7043 {
7044   if (is_tracepoint (loc1->owner) && is_tracepoint (loc2->owner))
7045     /* Since tracepoint locations are never duplicated with others', tracepoint
7046        locations at the same address of different tracepoints are regarded as
7047        different locations.  */
7048     return (loc1->address == loc2->address && loc1->owner == loc2->owner);
7049   else
7050     return 0;
7051 }
7052
7053 /* Assuming LOC1 and LOC2's types' have meaningful target addresses
7054    (breakpoint_address_is_meaningful), returns true if LOC1 and LOC2
7055    represent the same location.  */
7056
7057 static int
7058 breakpoint_locations_match (struct bp_location *loc1, 
7059                             struct bp_location *loc2)
7060 {
7061   int hw_point1, hw_point2;
7062
7063   /* Both of them must not be in moribund_locations.  */
7064   gdb_assert (loc1->owner != NULL);
7065   gdb_assert (loc2->owner != NULL);
7066
7067   hw_point1 = is_hardware_watchpoint (loc1->owner);
7068   hw_point2 = is_hardware_watchpoint (loc2->owner);
7069
7070   if (hw_point1 != hw_point2)
7071     return 0;
7072   else if (hw_point1)
7073     return watchpoint_locations_match (loc1, loc2);
7074   else if (is_tracepoint (loc1->owner) || is_tracepoint (loc2->owner))
7075     return tracepoint_locations_match (loc1, loc2);
7076   else
7077     /* We compare bp_location.length in order to cover ranged breakpoints.  */
7078     return (breakpoint_address_match (loc1->pspace->aspace, loc1->address,
7079                                      loc2->pspace->aspace, loc2->address)
7080             && loc1->length == loc2->length);
7081 }
7082
7083 static void
7084 breakpoint_adjustment_warning (CORE_ADDR from_addr, CORE_ADDR to_addr,
7085                                int bnum, int have_bnum)
7086 {
7087   /* The longest string possibly returned by hex_string_custom
7088      is 50 chars.  These must be at least that big for safety.  */
7089   char astr1[64];
7090   char astr2[64];
7091
7092   strcpy (astr1, hex_string_custom ((unsigned long) from_addr, 8));
7093   strcpy (astr2, hex_string_custom ((unsigned long) to_addr, 8));
7094   if (have_bnum)
7095     warning (_("Breakpoint %d address previously adjusted from %s to %s."),
7096              bnum, astr1, astr2);
7097   else
7098     warning (_("Breakpoint address adjusted from %s to %s."), astr1, astr2);
7099 }
7100
7101 /* Adjust a breakpoint's address to account for architectural
7102    constraints on breakpoint placement.  Return the adjusted address.
7103    Note: Very few targets require this kind of adjustment.  For most
7104    targets, this function is simply the identity function.  */
7105
7106 static CORE_ADDR
7107 adjust_breakpoint_address (struct gdbarch *gdbarch,
7108                            CORE_ADDR bpaddr, enum bptype bptype)
7109 {
7110   if (!gdbarch_adjust_breakpoint_address_p (gdbarch))
7111     {
7112       /* Very few targets need any kind of breakpoint adjustment.  */
7113       return bpaddr;
7114     }
7115   else if (bptype == bp_watchpoint
7116            || bptype == bp_hardware_watchpoint
7117            || bptype == bp_read_watchpoint
7118            || bptype == bp_access_watchpoint
7119            || bptype == bp_catchpoint)
7120     {
7121       /* Watchpoints and the various bp_catch_* eventpoints should not
7122          have their addresses modified.  */
7123       return bpaddr;
7124     }
7125   else if (bptype == bp_single_step)
7126     {
7127       /* Single-step breakpoints should not have their addresses
7128          modified.  If there's any architectural constrain that
7129          applies to this address, then it should have already been
7130          taken into account when the breakpoint was created in the
7131          first place.  If we didn't do this, stepping through e.g.,
7132          Thumb-2 IT blocks would break.  */
7133       return bpaddr;
7134     }
7135   else
7136     {
7137       CORE_ADDR adjusted_bpaddr;
7138
7139       /* Some targets have architectural constraints on the placement
7140          of breakpoint instructions.  Obtain the adjusted address.  */
7141       adjusted_bpaddr = gdbarch_adjust_breakpoint_address (gdbarch, bpaddr);
7142
7143       /* An adjusted breakpoint address can significantly alter
7144          a user's expectations.  Print a warning if an adjustment
7145          is required.  */
7146       if (adjusted_bpaddr != bpaddr)
7147         breakpoint_adjustment_warning (bpaddr, adjusted_bpaddr, 0, 0);
7148
7149       return adjusted_bpaddr;
7150     }
7151 }
7152
7153 void
7154 init_bp_location (struct bp_location *loc, const struct bp_location_ops *ops,
7155                   struct breakpoint *owner)
7156 {
7157   memset (loc, 0, sizeof (*loc));
7158
7159   gdb_assert (ops != NULL);
7160
7161   loc->ops = ops;
7162   loc->owner = owner;
7163   loc->cond = NULL;
7164   loc->cond_bytecode = NULL;
7165   loc->shlib_disabled = 0;
7166   loc->enabled = 1;
7167
7168   switch (owner->type)
7169     {
7170     case bp_breakpoint:
7171     case bp_single_step:
7172     case bp_until:
7173     case bp_finish:
7174     case bp_longjmp:
7175     case bp_longjmp_resume:
7176     case bp_longjmp_call_dummy:
7177     case bp_exception:
7178     case bp_exception_resume:
7179     case bp_step_resume:
7180     case bp_hp_step_resume:
7181     case bp_watchpoint_scope:
7182     case bp_call_dummy:
7183     case bp_std_terminate:
7184     case bp_shlib_event:
7185     case bp_thread_event:
7186     case bp_overlay_event:
7187     case bp_jit_event:
7188     case bp_longjmp_master:
7189     case bp_std_terminate_master:
7190     case bp_exception_master:
7191     case bp_gnu_ifunc_resolver:
7192     case bp_gnu_ifunc_resolver_return:
7193     case bp_dprintf:
7194       loc->loc_type = bp_loc_software_breakpoint;
7195       mark_breakpoint_location_modified (loc);
7196       break;
7197     case bp_hardware_breakpoint:
7198       loc->loc_type = bp_loc_hardware_breakpoint;
7199       mark_breakpoint_location_modified (loc);
7200       break;
7201     case bp_hardware_watchpoint:
7202     case bp_read_watchpoint:
7203     case bp_access_watchpoint:
7204       loc->loc_type = bp_loc_hardware_watchpoint;
7205       break;
7206     case bp_watchpoint:
7207     case bp_catchpoint:
7208     case bp_tracepoint:
7209     case bp_fast_tracepoint:
7210     case bp_static_tracepoint:
7211       loc->loc_type = bp_loc_other;
7212       break;
7213     default:
7214       internal_error (__FILE__, __LINE__, _("unknown breakpoint type"));
7215     }
7216
7217   loc->refc = 1;
7218 }
7219
7220 /* Allocate a struct bp_location.  */
7221
7222 static struct bp_location *
7223 allocate_bp_location (struct breakpoint *bpt)
7224 {
7225   return bpt->ops->allocate_location (bpt);
7226 }
7227
7228 static void
7229 free_bp_location (struct bp_location *loc)
7230 {
7231   loc->ops->dtor (loc);
7232   xfree (loc);
7233 }
7234
7235 /* Increment reference count.  */
7236
7237 static void
7238 incref_bp_location (struct bp_location *bl)
7239 {
7240   ++bl->refc;
7241 }
7242
7243 /* Decrement reference count.  If the reference count reaches 0,
7244    destroy the bp_location.  Sets *BLP to NULL.  */
7245
7246 static void
7247 decref_bp_location (struct bp_location **blp)
7248 {
7249   gdb_assert ((*blp)->refc > 0);
7250
7251   if (--(*blp)->refc == 0)
7252     free_bp_location (*blp);
7253   *blp = NULL;
7254 }
7255
7256 /* Add breakpoint B at the end of the global breakpoint chain.  */
7257
7258 static void
7259 add_to_breakpoint_chain (struct breakpoint *b)
7260 {
7261   struct breakpoint *b1;
7262
7263   /* Add this breakpoint to the end of the chain so that a list of
7264      breakpoints will come out in order of increasing numbers.  */
7265
7266   b1 = breakpoint_chain;
7267   if (b1 == 0)
7268     breakpoint_chain = b;
7269   else
7270     {
7271       while (b1->next)
7272         b1 = b1->next;
7273       b1->next = b;
7274     }
7275 }
7276
7277 /* Initializes breakpoint B with type BPTYPE and no locations yet.  */
7278
7279 static void
7280 init_raw_breakpoint_without_location (struct breakpoint *b,
7281                                       struct gdbarch *gdbarch,
7282                                       enum bptype bptype,
7283                                       const struct breakpoint_ops *ops)
7284 {
7285   memset (b, 0, sizeof (*b));
7286
7287   gdb_assert (ops != NULL);
7288
7289   b->ops = ops;
7290   b->type = bptype;
7291   b->gdbarch = gdbarch;
7292   b->language = current_language->la_language;
7293   b->input_radix = input_radix;
7294   b->thread = -1;
7295   b->enable_state = bp_enabled;
7296   b->next = 0;
7297   b->silent = 0;
7298   b->ignore_count = 0;
7299   b->commands = NULL;
7300   b->frame_id = null_frame_id;
7301   b->condition_not_parsed = 0;
7302   b->py_bp_object = NULL;
7303   b->related_breakpoint = b;
7304 }
7305
7306 /* Helper to set_raw_breakpoint below.  Creates a breakpoint
7307    that has type BPTYPE and has no locations as yet.  */
7308
7309 static struct breakpoint *
7310 set_raw_breakpoint_without_location (struct gdbarch *gdbarch,
7311                                      enum bptype bptype,
7312                                      const struct breakpoint_ops *ops)
7313 {
7314   struct breakpoint *b = XNEW (struct breakpoint);
7315
7316   init_raw_breakpoint_without_location (b, gdbarch, bptype, ops);
7317   add_to_breakpoint_chain (b);
7318   return b;
7319 }
7320
7321 /* Initialize loc->function_name.  EXPLICIT_LOC says no indirect function
7322    resolutions should be made as the user specified the location explicitly
7323    enough.  */
7324
7325 static void
7326 set_breakpoint_location_function (struct bp_location *loc, int explicit_loc)
7327 {
7328   gdb_assert (loc->owner != NULL);
7329
7330   if (loc->owner->type == bp_breakpoint
7331       || loc->owner->type == bp_hardware_breakpoint
7332       || is_tracepoint (loc->owner))
7333     {
7334       int is_gnu_ifunc;
7335       const char *function_name;
7336       CORE_ADDR func_addr;
7337
7338       find_pc_partial_function_gnu_ifunc (loc->address, &function_name,
7339                                           &func_addr, NULL, &is_gnu_ifunc);
7340
7341       if (is_gnu_ifunc && !explicit_loc)
7342         {
7343           struct breakpoint *b = loc->owner;
7344
7345           gdb_assert (loc->pspace == current_program_space);
7346           if (gnu_ifunc_resolve_name (function_name,
7347                                       &loc->requested_address))
7348             {
7349               /* Recalculate ADDRESS based on new REQUESTED_ADDRESS.  */
7350               loc->address = adjust_breakpoint_address (loc->gdbarch,
7351                                                         loc->requested_address,
7352                                                         b->type);
7353             }
7354           else if (b->type == bp_breakpoint && b->loc == loc
7355                    && loc->next == NULL && b->related_breakpoint == b)
7356             {
7357               /* Create only the whole new breakpoint of this type but do not
7358                  mess more complicated breakpoints with multiple locations.  */
7359               b->type = bp_gnu_ifunc_resolver;
7360               /* Remember the resolver's address for use by the return
7361                  breakpoint.  */
7362               loc->related_address = func_addr;
7363             }
7364         }
7365
7366       if (function_name)
7367         loc->function_name = xstrdup (function_name);
7368     }
7369 }
7370
7371 /* Attempt to determine architecture of location identified by SAL.  */
7372 struct gdbarch *
7373 get_sal_arch (struct symtab_and_line sal)
7374 {
7375   if (sal.section)
7376     return get_objfile_arch (sal.section->objfile);
7377   if (sal.symtab)
7378     return get_objfile_arch (SYMTAB_OBJFILE (sal.symtab));
7379
7380   return NULL;
7381 }
7382
7383 /* Low level routine for partially initializing a breakpoint of type
7384    BPTYPE.  The newly created breakpoint's address, section, source
7385    file name, and line number are provided by SAL.
7386
7387    It is expected that the caller will complete the initialization of
7388    the newly created breakpoint struct as well as output any status
7389    information regarding the creation of a new breakpoint.  */
7390
7391 static void
7392 init_raw_breakpoint (struct breakpoint *b, struct gdbarch *gdbarch,
7393                      struct symtab_and_line sal, enum bptype bptype,
7394                      const struct breakpoint_ops *ops)
7395 {
7396   init_raw_breakpoint_without_location (b, gdbarch, bptype, ops);
7397
7398   add_location_to_breakpoint (b, &sal);
7399
7400   if (bptype != bp_catchpoint)
7401     gdb_assert (sal.pspace != NULL);
7402
7403   /* Store the program space that was used to set the breakpoint,
7404      except for ordinary breakpoints, which are independent of the
7405      program space.  */
7406   if (bptype != bp_breakpoint && bptype != bp_hardware_breakpoint)
7407     b->pspace = sal.pspace;
7408 }
7409
7410 /* set_raw_breakpoint is a low level routine for allocating and
7411    partially initializing a breakpoint of type BPTYPE.  The newly
7412    created breakpoint's address, section, source file name, and line
7413    number are provided by SAL.  The newly created and partially
7414    initialized breakpoint is added to the breakpoint chain and
7415    is also returned as the value of this function.
7416
7417    It is expected that the caller will complete the initialization of
7418    the newly created breakpoint struct as well as output any status
7419    information regarding the creation of a new breakpoint.  In
7420    particular, set_raw_breakpoint does NOT set the breakpoint
7421    number!  Care should be taken to not allow an error to occur
7422    prior to completing the initialization of the breakpoint.  If this
7423    should happen, a bogus breakpoint will be left on the chain.  */
7424
7425 struct breakpoint *
7426 set_raw_breakpoint (struct gdbarch *gdbarch,
7427                     struct symtab_and_line sal, enum bptype bptype,
7428                     const struct breakpoint_ops *ops)
7429 {
7430   struct breakpoint *b = XNEW (struct breakpoint);
7431
7432   init_raw_breakpoint (b, gdbarch, sal, bptype, ops);
7433   add_to_breakpoint_chain (b);
7434   return b;
7435 }
7436
7437
7438 /* Note that the breakpoint object B describes a permanent breakpoint
7439    instruction, hard-wired into the inferior's code.  */
7440 void
7441 make_breakpoint_permanent (struct breakpoint *b)
7442 {
7443   struct bp_location *bl;
7444
7445   /* By definition, permanent breakpoints are already present in the
7446      code.  Mark all locations as inserted.  For now,
7447      make_breakpoint_permanent is called in just one place, so it's
7448      hard to say if it's reasonable to have permanent breakpoint with
7449      multiple locations or not, but it's easy to implement.  */
7450   for (bl = b->loc; bl; bl = bl->next)
7451     {
7452       bl->permanent = 1;
7453       bl->inserted = 1;
7454     }
7455 }
7456
7457 /* Call this routine when stepping and nexting to enable a breakpoint
7458    if we do a longjmp() or 'throw' in TP.  FRAME is the frame which
7459    initiated the operation.  */
7460
7461 void
7462 set_longjmp_breakpoint (struct thread_info *tp, struct frame_id frame)
7463 {
7464   struct breakpoint *b, *b_tmp;
7465   int thread = tp->num;
7466
7467   /* To avoid having to rescan all objfile symbols at every step,
7468      we maintain a list of continually-inserted but always disabled
7469      longjmp "master" breakpoints.  Here, we simply create momentary
7470      clones of those and enable them for the requested thread.  */
7471   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7472     if (b->pspace == current_program_space
7473         && (b->type == bp_longjmp_master
7474             || b->type == bp_exception_master))
7475       {
7476         enum bptype type = b->type == bp_longjmp_master ? bp_longjmp : bp_exception;
7477         struct breakpoint *clone;
7478
7479         /* longjmp_breakpoint_ops ensures INITIATING_FRAME is cleared again
7480            after their removal.  */
7481         clone = momentary_breakpoint_from_master (b, type,
7482                                                   &longjmp_breakpoint_ops, 1);
7483         clone->thread = thread;
7484       }
7485
7486   tp->initiating_frame = frame;
7487 }
7488
7489 /* Delete all longjmp breakpoints from THREAD.  */
7490 void
7491 delete_longjmp_breakpoint (int thread)
7492 {
7493   struct breakpoint *b, *b_tmp;
7494
7495   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7496     if (b->type == bp_longjmp || b->type == bp_exception)
7497       {
7498         if (b->thread == thread)
7499           delete_breakpoint (b);
7500       }
7501 }
7502
7503 void
7504 delete_longjmp_breakpoint_at_next_stop (int thread)
7505 {
7506   struct breakpoint *b, *b_tmp;
7507
7508   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7509     if (b->type == bp_longjmp || b->type == bp_exception)
7510       {
7511         if (b->thread == thread)
7512           b->disposition = disp_del_at_next_stop;
7513       }
7514 }
7515
7516 /* Place breakpoints of type bp_longjmp_call_dummy to catch longjmp for
7517    INFERIOR_PTID thread.  Chain them all by RELATED_BREAKPOINT and return
7518    pointer to any of them.  Return NULL if this system cannot place longjmp
7519    breakpoints.  */
7520
7521 struct breakpoint *
7522 set_longjmp_breakpoint_for_call_dummy (void)
7523 {
7524   struct breakpoint *b, *retval = NULL;
7525
7526   ALL_BREAKPOINTS (b)
7527     if (b->pspace == current_program_space && b->type == bp_longjmp_master)
7528       {
7529         struct breakpoint *new_b;
7530
7531         new_b = momentary_breakpoint_from_master (b, bp_longjmp_call_dummy,
7532                                                   &momentary_breakpoint_ops,
7533                                                   1);
7534         new_b->thread = pid_to_thread_id (inferior_ptid);
7535
7536         /* Link NEW_B into the chain of RETVAL breakpoints.  */
7537
7538         gdb_assert (new_b->related_breakpoint == new_b);
7539         if (retval == NULL)
7540           retval = new_b;
7541         new_b->related_breakpoint = retval;
7542         while (retval->related_breakpoint != new_b->related_breakpoint)
7543           retval = retval->related_breakpoint;
7544         retval->related_breakpoint = new_b;
7545       }
7546
7547   return retval;
7548 }
7549
7550 /* Verify all existing dummy frames and their associated breakpoints for
7551    TP.  Remove those which can no longer be found in the current frame
7552    stack.
7553
7554    You should call this function only at places where it is safe to currently
7555    unwind the whole stack.  Failed stack unwind would discard live dummy
7556    frames.  */
7557
7558 void
7559 check_longjmp_breakpoint_for_call_dummy (struct thread_info *tp)
7560 {
7561   struct breakpoint *b, *b_tmp;
7562
7563   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7564     if (b->type == bp_longjmp_call_dummy && b->thread == tp->num)
7565       {
7566         struct breakpoint *dummy_b = b->related_breakpoint;
7567
7568         while (dummy_b != b && dummy_b->type != bp_call_dummy)
7569           dummy_b = dummy_b->related_breakpoint;
7570         if (dummy_b->type != bp_call_dummy
7571             || frame_find_by_id (dummy_b->frame_id) != NULL)
7572           continue;
7573         
7574         dummy_frame_discard (dummy_b->frame_id, tp->ptid);
7575
7576         while (b->related_breakpoint != b)
7577           {
7578             if (b_tmp == b->related_breakpoint)
7579               b_tmp = b->related_breakpoint->next;
7580             delete_breakpoint (b->related_breakpoint);
7581           }
7582         delete_breakpoint (b);
7583       }
7584 }
7585
7586 void
7587 enable_overlay_breakpoints (void)
7588 {
7589   struct breakpoint *b;
7590
7591   ALL_BREAKPOINTS (b)
7592     if (b->type == bp_overlay_event)
7593     {
7594       b->enable_state = bp_enabled;
7595       update_global_location_list (UGLL_MAY_INSERT);
7596       overlay_events_enabled = 1;
7597     }
7598 }
7599
7600 void
7601 disable_overlay_breakpoints (void)
7602 {
7603   struct breakpoint *b;
7604
7605   ALL_BREAKPOINTS (b)
7606     if (b->type == bp_overlay_event)
7607     {
7608       b->enable_state = bp_disabled;
7609       update_global_location_list (UGLL_DONT_INSERT);
7610       overlay_events_enabled = 0;
7611     }
7612 }
7613
7614 /* Set an active std::terminate breakpoint for each std::terminate
7615    master breakpoint.  */
7616 void
7617 set_std_terminate_breakpoint (void)
7618 {
7619   struct breakpoint *b, *b_tmp;
7620
7621   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7622     if (b->pspace == current_program_space
7623         && b->type == bp_std_terminate_master)
7624       {
7625         momentary_breakpoint_from_master (b, bp_std_terminate,
7626                                           &momentary_breakpoint_ops, 1);
7627       }
7628 }
7629
7630 /* Delete all the std::terminate breakpoints.  */
7631 void
7632 delete_std_terminate_breakpoint (void)
7633 {
7634   struct breakpoint *b, *b_tmp;
7635
7636   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7637     if (b->type == bp_std_terminate)
7638       delete_breakpoint (b);
7639 }
7640
7641 struct breakpoint *
7642 create_thread_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7643 {
7644   struct breakpoint *b;
7645
7646   b = create_internal_breakpoint (gdbarch, address, bp_thread_event,
7647                                   &internal_breakpoint_ops);
7648
7649   b->enable_state = bp_enabled;
7650   /* addr_string has to be used or breakpoint_re_set will delete me.  */
7651   b->addr_string
7652     = xstrprintf ("*%s", paddress (b->loc->gdbarch, b->loc->address));
7653
7654   update_global_location_list_nothrow (UGLL_MAY_INSERT);
7655
7656   return b;
7657 }
7658
7659 void
7660 remove_thread_event_breakpoints (void)
7661 {
7662   struct breakpoint *b, *b_tmp;
7663
7664   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7665     if (b->type == bp_thread_event
7666         && b->loc->pspace == current_program_space)
7667       delete_breakpoint (b);
7668 }
7669
7670 struct lang_and_radix
7671   {
7672     enum language lang;
7673     int radix;
7674   };
7675
7676 /* Create a breakpoint for JIT code registration and unregistration.  */
7677
7678 struct breakpoint *
7679 create_jit_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7680 {
7681   struct breakpoint *b;
7682
7683   b = create_internal_breakpoint (gdbarch, address, bp_jit_event,
7684                                   &internal_breakpoint_ops);
7685   update_global_location_list_nothrow (UGLL_MAY_INSERT);
7686   return b;
7687 }
7688
7689 /* Remove JIT code registration and unregistration breakpoint(s).  */
7690
7691 void
7692 remove_jit_event_breakpoints (void)
7693 {
7694   struct breakpoint *b, *b_tmp;
7695
7696   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7697     if (b->type == bp_jit_event
7698         && b->loc->pspace == current_program_space)
7699       delete_breakpoint (b);
7700 }
7701
7702 void
7703 remove_solib_event_breakpoints (void)
7704 {
7705   struct breakpoint *b, *b_tmp;
7706
7707   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7708     if (b->type == bp_shlib_event
7709         && b->loc->pspace == current_program_space)
7710       delete_breakpoint (b);
7711 }
7712
7713 /* See breakpoint.h.  */
7714
7715 void
7716 remove_solib_event_breakpoints_at_next_stop (void)
7717 {
7718   struct breakpoint *b, *b_tmp;
7719
7720   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7721     if (b->type == bp_shlib_event
7722         && b->loc->pspace == current_program_space)
7723       b->disposition = disp_del_at_next_stop;
7724 }
7725
7726 /* Helper for create_solib_event_breakpoint /
7727    create_and_insert_solib_event_breakpoint.  Allows specifying which
7728    INSERT_MODE to pass through to update_global_location_list.  */
7729
7730 static struct breakpoint *
7731 create_solib_event_breakpoint_1 (struct gdbarch *gdbarch, CORE_ADDR address,
7732                                  enum ugll_insert_mode insert_mode)
7733 {
7734   struct breakpoint *b;
7735
7736   b = create_internal_breakpoint (gdbarch, address, bp_shlib_event,
7737                                   &internal_breakpoint_ops);
7738   update_global_location_list_nothrow (insert_mode);
7739   return b;
7740 }
7741
7742 struct breakpoint *
7743 create_solib_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7744 {
7745   return create_solib_event_breakpoint_1 (gdbarch, address, UGLL_MAY_INSERT);
7746 }
7747
7748 /* See breakpoint.h.  */
7749
7750 struct breakpoint *
7751 create_and_insert_solib_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7752 {
7753   struct breakpoint *b;
7754
7755   /* Explicitly tell update_global_location_list to insert
7756      locations.  */
7757   b = create_solib_event_breakpoint_1 (gdbarch, address, UGLL_INSERT);
7758   if (!b->loc->inserted)
7759     {
7760       delete_breakpoint (b);
7761       return NULL;
7762     }
7763   return b;
7764 }
7765
7766 /* Disable any breakpoints that are on code in shared libraries.  Only
7767    apply to enabled breakpoints, disabled ones can just stay disabled.  */
7768
7769 void
7770 disable_breakpoints_in_shlibs (void)
7771 {
7772   struct bp_location *loc, **locp_tmp;
7773
7774   ALL_BP_LOCATIONS (loc, locp_tmp)
7775   {
7776     /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
7777     struct breakpoint *b = loc->owner;
7778
7779     /* We apply the check to all breakpoints, including disabled for
7780        those with loc->duplicate set.  This is so that when breakpoint
7781        becomes enabled, or the duplicate is removed, gdb will try to
7782        insert all breakpoints.  If we don't set shlib_disabled here,
7783        we'll try to insert those breakpoints and fail.  */
7784     if (((b->type == bp_breakpoint)
7785          || (b->type == bp_jit_event)
7786          || (b->type == bp_hardware_breakpoint)
7787          || (is_tracepoint (b)))
7788         && loc->pspace == current_program_space
7789         && !loc->shlib_disabled
7790         && solib_name_from_address (loc->pspace, loc->address)
7791         )
7792       {
7793         loc->shlib_disabled = 1;
7794       }
7795   }
7796 }
7797
7798 /* Disable any breakpoints and tracepoints that are in SOLIB upon
7799    notification of unloaded_shlib.  Only apply to enabled breakpoints,
7800    disabled ones can just stay disabled.  */
7801
7802 static void
7803 disable_breakpoints_in_unloaded_shlib (struct so_list *solib)
7804 {
7805   struct bp_location *loc, **locp_tmp;
7806   int disabled_shlib_breaks = 0;
7807
7808   /* SunOS a.out shared libraries are always mapped, so do not
7809      disable breakpoints; they will only be reported as unloaded
7810      through clear_solib when GDB discards its shared library
7811      list.  See clear_solib for more information.  */
7812   if (exec_bfd != NULL
7813       && bfd_get_flavour (exec_bfd) == bfd_target_aout_flavour)
7814     return;
7815
7816   ALL_BP_LOCATIONS (loc, locp_tmp)
7817   {
7818     /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
7819     struct breakpoint *b = loc->owner;
7820
7821     if (solib->pspace == loc->pspace
7822         && !loc->shlib_disabled
7823         && (((b->type == bp_breakpoint
7824               || b->type == bp_jit_event
7825               || b->type == bp_hardware_breakpoint)
7826              && (loc->loc_type == bp_loc_hardware_breakpoint
7827                  || loc->loc_type == bp_loc_software_breakpoint))
7828             || is_tracepoint (b))
7829         && solib_contains_address_p (solib, loc->address))
7830       {
7831         loc->shlib_disabled = 1;
7832         /* At this point, we cannot rely on remove_breakpoint
7833            succeeding so we must mark the breakpoint as not inserted
7834            to prevent future errors occurring in remove_breakpoints.  */
7835         loc->inserted = 0;
7836
7837         /* This may cause duplicate notifications for the same breakpoint.  */
7838         observer_notify_breakpoint_modified (b);
7839
7840         if (!disabled_shlib_breaks)
7841           {
7842             target_terminal_ours_for_output ();
7843             warning (_("Temporarily disabling breakpoints "
7844                        "for unloaded shared library \"%s\""),
7845                      solib->so_name);
7846           }
7847         disabled_shlib_breaks = 1;
7848       }
7849   }
7850 }
7851
7852 /* Disable any breakpoints and tracepoints in OBJFILE upon
7853    notification of free_objfile.  Only apply to enabled breakpoints,
7854    disabled ones can just stay disabled.  */
7855
7856 static void
7857 disable_breakpoints_in_freed_objfile (struct objfile *objfile)
7858 {
7859   struct breakpoint *b;
7860
7861   if (objfile == NULL)
7862     return;
7863
7864   /* OBJF_SHARED|OBJF_USERLOADED objfiles are dynamic modules manually
7865      managed by the user with add-symbol-file/remove-symbol-file.
7866      Similarly to how breakpoints in shared libraries are handled in
7867      response to "nosharedlibrary", mark breakpoints in such modules
7868      shlib_disabled so they end up uninserted on the next global
7869      location list update.  Shared libraries not loaded by the user
7870      aren't handled here -- they're already handled in
7871      disable_breakpoints_in_unloaded_shlib, called by solib.c's
7872      solib_unloaded observer.  We skip objfiles that are not
7873      OBJF_SHARED as those aren't considered dynamic objects (e.g. the
7874      main objfile).  */
7875   if ((objfile->flags & OBJF_SHARED) == 0
7876       || (objfile->flags & OBJF_USERLOADED) == 0)
7877     return;
7878
7879   ALL_BREAKPOINTS (b)
7880     {
7881       struct bp_location *loc;
7882       int bp_modified = 0;
7883
7884       if (!is_breakpoint (b) && !is_tracepoint (b))
7885         continue;
7886
7887       for (loc = b->loc; loc != NULL; loc = loc->next)
7888         {
7889           CORE_ADDR loc_addr = loc->address;
7890
7891           if (loc->loc_type != bp_loc_hardware_breakpoint
7892               && loc->loc_type != bp_loc_software_breakpoint)
7893             continue;
7894
7895           if (loc->shlib_disabled != 0)
7896             continue;
7897
7898           if (objfile->pspace != loc->pspace)
7899             continue;
7900
7901           if (loc->loc_type != bp_loc_hardware_breakpoint
7902               && loc->loc_type != bp_loc_software_breakpoint)
7903             continue;
7904
7905           if (is_addr_in_objfile (loc_addr, objfile))
7906             {
7907               loc->shlib_disabled = 1;
7908               /* At this point, we don't know whether the object was
7909                  unmapped from the inferior or not, so leave the
7910                  inserted flag alone.  We'll handle failure to
7911                  uninsert quietly, in case the object was indeed
7912                  unmapped.  */
7913
7914               mark_breakpoint_location_modified (loc);
7915
7916               bp_modified = 1;
7917             }
7918         }
7919
7920       if (bp_modified)
7921         observer_notify_breakpoint_modified (b);
7922     }
7923 }
7924
7925 /* FORK & VFORK catchpoints.  */
7926
7927 /* An instance of this type is used to represent a fork or vfork
7928    catchpoint.  It includes a "struct breakpoint" as a kind of base
7929    class; users downcast to "struct breakpoint *" when needed.  A
7930    breakpoint is really of this type iff its ops pointer points to
7931    CATCH_FORK_BREAKPOINT_OPS.  */
7932
7933 struct fork_catchpoint
7934 {
7935   /* The base class.  */
7936   struct breakpoint base;
7937
7938   /* Process id of a child process whose forking triggered this
7939      catchpoint.  This field is only valid immediately after this
7940      catchpoint has triggered.  */
7941   ptid_t forked_inferior_pid;
7942 };
7943
7944 /* Implement the "insert" breakpoint_ops method for fork
7945    catchpoints.  */
7946
7947 static int
7948 insert_catch_fork (struct bp_location *bl)
7949 {
7950   return target_insert_fork_catchpoint (ptid_get_pid (inferior_ptid));
7951 }
7952
7953 /* Implement the "remove" breakpoint_ops method for fork
7954    catchpoints.  */
7955
7956 static int
7957 remove_catch_fork (struct bp_location *bl)
7958 {
7959   return target_remove_fork_catchpoint (ptid_get_pid (inferior_ptid));
7960 }
7961
7962 /* Implement the "breakpoint_hit" breakpoint_ops method for fork
7963    catchpoints.  */
7964
7965 static int
7966 breakpoint_hit_catch_fork (const struct bp_location *bl,
7967                            struct address_space *aspace, CORE_ADDR bp_addr,
7968                            const struct target_waitstatus *ws)
7969 {
7970   struct fork_catchpoint *c = (struct fork_catchpoint *) bl->owner;
7971
7972   if (ws->kind != TARGET_WAITKIND_FORKED)
7973     return 0;
7974
7975   c->forked_inferior_pid = ws->value.related_pid;
7976   return 1;
7977 }
7978
7979 /* Implement the "print_it" breakpoint_ops method for fork
7980    catchpoints.  */
7981
7982 static enum print_stop_action
7983 print_it_catch_fork (bpstat bs)
7984 {
7985   struct ui_out *uiout = current_uiout;
7986   struct breakpoint *b = bs->breakpoint_at;
7987   struct fork_catchpoint *c = (struct fork_catchpoint *) bs->breakpoint_at;
7988
7989   annotate_catchpoint (b->number);
7990   if (b->disposition == disp_del)
7991     ui_out_text (uiout, "\nTemporary catchpoint ");
7992   else
7993     ui_out_text (uiout, "\nCatchpoint ");
7994   if (ui_out_is_mi_like_p (uiout))
7995     {
7996       ui_out_field_string (uiout, "reason",
7997                            async_reason_lookup (EXEC_ASYNC_FORK));
7998       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
7999     }
8000   ui_out_field_int (uiout, "bkptno", b->number);
8001   ui_out_text (uiout, " (forked process ");
8002   ui_out_field_int (uiout, "newpid", ptid_get_pid (c->forked_inferior_pid));
8003   ui_out_text (uiout, "), ");
8004   return PRINT_SRC_AND_LOC;
8005 }
8006
8007 /* Implement the "print_one" breakpoint_ops method for fork
8008    catchpoints.  */
8009
8010 static void
8011 print_one_catch_fork (struct breakpoint *b, struct bp_location **last_loc)
8012 {
8013   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
8014   struct value_print_options opts;
8015   struct ui_out *uiout = current_uiout;
8016
8017   get_user_print_options (&opts);
8018
8019   /* Field 4, the address, is omitted (which makes the columns not
8020      line up too nicely with the headers, but the effect is relatively
8021      readable).  */
8022   if (opts.addressprint)
8023     ui_out_field_skip (uiout, "addr");
8024   annotate_field (5);
8025   ui_out_text (uiout, "fork");
8026   if (!ptid_equal (c->forked_inferior_pid, null_ptid))
8027     {
8028       ui_out_text (uiout, ", process ");
8029       ui_out_field_int (uiout, "what",
8030                         ptid_get_pid (c->forked_inferior_pid));
8031       ui_out_spaces (uiout, 1);
8032     }
8033
8034   if (ui_out_is_mi_like_p (uiout))
8035     ui_out_field_string (uiout, "catch-type", "fork");
8036 }
8037
8038 /* Implement the "print_mention" breakpoint_ops method for fork
8039    catchpoints.  */
8040
8041 static void
8042 print_mention_catch_fork (struct breakpoint *b)
8043 {
8044   printf_filtered (_("Catchpoint %d (fork)"), b->number);
8045 }
8046
8047 /* Implement the "print_recreate" breakpoint_ops method for fork
8048    catchpoints.  */
8049
8050 static void
8051 print_recreate_catch_fork (struct breakpoint *b, struct ui_file *fp)
8052 {
8053   fprintf_unfiltered (fp, "catch fork");
8054   print_recreate_thread (b, fp);
8055 }
8056
8057 /* The breakpoint_ops structure to be used in fork catchpoints.  */
8058
8059 static struct breakpoint_ops catch_fork_breakpoint_ops;
8060
8061 /* Implement the "insert" breakpoint_ops method for vfork
8062    catchpoints.  */
8063
8064 static int
8065 insert_catch_vfork (struct bp_location *bl)
8066 {
8067   return target_insert_vfork_catchpoint (ptid_get_pid (inferior_ptid));
8068 }
8069
8070 /* Implement the "remove" breakpoint_ops method for vfork
8071    catchpoints.  */
8072
8073 static int
8074 remove_catch_vfork (struct bp_location *bl)
8075 {
8076   return target_remove_vfork_catchpoint (ptid_get_pid (inferior_ptid));
8077 }
8078
8079 /* Implement the "breakpoint_hit" breakpoint_ops method for vfork
8080    catchpoints.  */
8081
8082 static int
8083 breakpoint_hit_catch_vfork (const struct bp_location *bl,
8084                             struct address_space *aspace, CORE_ADDR bp_addr,
8085                             const struct target_waitstatus *ws)
8086 {
8087   struct fork_catchpoint *c = (struct fork_catchpoint *) bl->owner;
8088
8089   if (ws->kind != TARGET_WAITKIND_VFORKED)
8090     return 0;
8091
8092   c->forked_inferior_pid = ws->value.related_pid;
8093   return 1;
8094 }
8095
8096 /* Implement the "print_it" breakpoint_ops method for vfork
8097    catchpoints.  */
8098
8099 static enum print_stop_action
8100 print_it_catch_vfork (bpstat bs)
8101 {
8102   struct ui_out *uiout = current_uiout;
8103   struct breakpoint *b = bs->breakpoint_at;
8104   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
8105
8106   annotate_catchpoint (b->number);
8107   if (b->disposition == disp_del)
8108     ui_out_text (uiout, "\nTemporary catchpoint ");
8109   else
8110     ui_out_text (uiout, "\nCatchpoint ");
8111   if (ui_out_is_mi_like_p (uiout))
8112     {
8113       ui_out_field_string (uiout, "reason",
8114                            async_reason_lookup (EXEC_ASYNC_VFORK));
8115       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
8116     }
8117   ui_out_field_int (uiout, "bkptno", b->number);
8118   ui_out_text (uiout, " (vforked process ");
8119   ui_out_field_int (uiout, "newpid", ptid_get_pid (c->forked_inferior_pid));
8120   ui_out_text (uiout, "), ");
8121   return PRINT_SRC_AND_LOC;
8122 }
8123
8124 /* Implement the "print_one" breakpoint_ops method for vfork
8125    catchpoints.  */
8126
8127 static void
8128 print_one_catch_vfork (struct breakpoint *b, struct bp_location **last_loc)
8129 {
8130   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
8131   struct value_print_options opts;
8132   struct ui_out *uiout = current_uiout;
8133
8134   get_user_print_options (&opts);
8135   /* Field 4, the address, is omitted (which makes the columns not
8136      line up too nicely with the headers, but the effect is relatively
8137      readable).  */
8138   if (opts.addressprint)
8139     ui_out_field_skip (uiout, "addr");
8140   annotate_field (5);
8141   ui_out_text (uiout, "vfork");
8142   if (!ptid_equal (c->forked_inferior_pid, null_ptid))
8143     {
8144       ui_out_text (uiout, ", process ");
8145       ui_out_field_int (uiout, "what",
8146                         ptid_get_pid (c->forked_inferior_pid));
8147       ui_out_spaces (uiout, 1);
8148     }
8149
8150   if (ui_out_is_mi_like_p (uiout))
8151     ui_out_field_string (uiout, "catch-type", "vfork");
8152 }
8153
8154 /* Implement the "print_mention" breakpoint_ops method for vfork
8155    catchpoints.  */
8156
8157 static void
8158 print_mention_catch_vfork (struct breakpoint *b)
8159 {
8160   printf_filtered (_("Catchpoint %d (vfork)"), b->number);
8161 }
8162
8163 /* Implement the "print_recreate" breakpoint_ops method for vfork
8164    catchpoints.  */
8165
8166 static void
8167 print_recreate_catch_vfork (struct breakpoint *b, struct ui_file *fp)
8168 {
8169   fprintf_unfiltered (fp, "catch vfork");
8170   print_recreate_thread (b, fp);
8171 }
8172
8173 /* The breakpoint_ops structure to be used in vfork catchpoints.  */
8174
8175 static struct breakpoint_ops catch_vfork_breakpoint_ops;
8176
8177 /* An instance of this type is used to represent an solib catchpoint.
8178    It includes a "struct breakpoint" as a kind of base class; users
8179    downcast to "struct breakpoint *" when needed.  A breakpoint is
8180    really of this type iff its ops pointer points to
8181    CATCH_SOLIB_BREAKPOINT_OPS.  */
8182
8183 struct solib_catchpoint
8184 {
8185   /* The base class.  */
8186   struct breakpoint base;
8187
8188   /* True for "catch load", false for "catch unload".  */
8189   unsigned char is_load;
8190
8191   /* Regular expression to match, if any.  COMPILED is only valid when
8192      REGEX is non-NULL.  */
8193   char *regex;
8194   regex_t compiled;
8195 };
8196
8197 static void
8198 dtor_catch_solib (struct breakpoint *b)
8199 {
8200   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8201
8202   if (self->regex)
8203     regfree (&self->compiled);
8204   xfree (self->regex);
8205
8206   base_breakpoint_ops.dtor (b);
8207 }
8208
8209 static int
8210 insert_catch_solib (struct bp_location *ignore)
8211 {
8212   return 0;
8213 }
8214
8215 static int
8216 remove_catch_solib (struct bp_location *ignore)
8217 {
8218   return 0;
8219 }
8220
8221 static int
8222 breakpoint_hit_catch_solib (const struct bp_location *bl,
8223                             struct address_space *aspace,
8224                             CORE_ADDR bp_addr,
8225                             const struct target_waitstatus *ws)
8226 {
8227   struct solib_catchpoint *self = (struct solib_catchpoint *) bl->owner;
8228   struct breakpoint *other;
8229
8230   if (ws->kind == TARGET_WAITKIND_LOADED)
8231     return 1;
8232
8233   ALL_BREAKPOINTS (other)
8234   {
8235     struct bp_location *other_bl;
8236
8237     if (other == bl->owner)
8238       continue;
8239
8240     if (other->type != bp_shlib_event)
8241       continue;
8242
8243     if (self->base.pspace != NULL && other->pspace != self->base.pspace)
8244       continue;
8245
8246     for (other_bl = other->loc; other_bl != NULL; other_bl = other_bl->next)
8247       {
8248         if (other->ops->breakpoint_hit (other_bl, aspace, bp_addr, ws))
8249           return 1;
8250       }
8251   }
8252
8253   return 0;
8254 }
8255
8256 static void
8257 check_status_catch_solib (struct bpstats *bs)
8258 {
8259   struct solib_catchpoint *self
8260     = (struct solib_catchpoint *) bs->breakpoint_at;
8261   int ix;
8262
8263   if (self->is_load)
8264     {
8265       struct so_list *iter;
8266
8267       for (ix = 0;
8268            VEC_iterate (so_list_ptr, current_program_space->added_solibs,
8269                         ix, iter);
8270            ++ix)
8271         {
8272           if (!self->regex
8273               || regexec (&self->compiled, iter->so_name, 0, NULL, 0) == 0)
8274             return;
8275         }
8276     }
8277   else
8278     {
8279       char *iter;
8280
8281       for (ix = 0;
8282            VEC_iterate (char_ptr, current_program_space->deleted_solibs,
8283                         ix, iter);
8284            ++ix)
8285         {
8286           if (!self->regex
8287               || regexec (&self->compiled, iter, 0, NULL, 0) == 0)
8288             return;
8289         }
8290     }
8291
8292   bs->stop = 0;
8293   bs->print_it = print_it_noop;
8294 }
8295
8296 static enum print_stop_action
8297 print_it_catch_solib (bpstat bs)
8298 {
8299   struct breakpoint *b = bs->breakpoint_at;
8300   struct ui_out *uiout = current_uiout;
8301
8302   annotate_catchpoint (b->number);
8303   if (b->disposition == disp_del)
8304     ui_out_text (uiout, "\nTemporary catchpoint ");
8305   else
8306     ui_out_text (uiout, "\nCatchpoint ");
8307   ui_out_field_int (uiout, "bkptno", b->number);
8308   ui_out_text (uiout, "\n");
8309   if (ui_out_is_mi_like_p (uiout))
8310     ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
8311   print_solib_event (1);
8312   return PRINT_SRC_AND_LOC;
8313 }
8314
8315 static void
8316 print_one_catch_solib (struct breakpoint *b, struct bp_location **locs)
8317 {
8318   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8319   struct value_print_options opts;
8320   struct ui_out *uiout = current_uiout;
8321   char *msg;
8322
8323   get_user_print_options (&opts);
8324   /* Field 4, the address, is omitted (which makes the columns not
8325      line up too nicely with the headers, but the effect is relatively
8326      readable).  */
8327   if (opts.addressprint)
8328     {
8329       annotate_field (4);
8330       ui_out_field_skip (uiout, "addr");
8331     }
8332
8333   annotate_field (5);
8334   if (self->is_load)
8335     {
8336       if (self->regex)
8337         msg = xstrprintf (_("load of library matching %s"), self->regex);
8338       else
8339         msg = xstrdup (_("load of library"));
8340     }
8341   else
8342     {
8343       if (self->regex)
8344         msg = xstrprintf (_("unload of library matching %s"), self->regex);
8345       else
8346         msg = xstrdup (_("unload of library"));
8347     }
8348   ui_out_field_string (uiout, "what", msg);
8349   xfree (msg);
8350
8351   if (ui_out_is_mi_like_p (uiout))
8352     ui_out_field_string (uiout, "catch-type",
8353                          self->is_load ? "load" : "unload");
8354 }
8355
8356 static void
8357 print_mention_catch_solib (struct breakpoint *b)
8358 {
8359   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8360
8361   printf_filtered (_("Catchpoint %d (%s)"), b->number,
8362                    self->is_load ? "load" : "unload");
8363 }
8364
8365 static void
8366 print_recreate_catch_solib (struct breakpoint *b, struct ui_file *fp)
8367 {
8368   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8369
8370   fprintf_unfiltered (fp, "%s %s",
8371                       b->disposition == disp_del ? "tcatch" : "catch",
8372                       self->is_load ? "load" : "unload");
8373   if (self->regex)
8374     fprintf_unfiltered (fp, " %s", self->regex);
8375   fprintf_unfiltered (fp, "\n");
8376 }
8377
8378 static struct breakpoint_ops catch_solib_breakpoint_ops;
8379
8380 /* Shared helper function (MI and CLI) for creating and installing
8381    a shared object event catchpoint.  If IS_LOAD is non-zero then
8382    the events to be caught are load events, otherwise they are
8383    unload events.  If IS_TEMP is non-zero the catchpoint is a
8384    temporary one.  If ENABLED is non-zero the catchpoint is
8385    created in an enabled state.  */
8386
8387 void
8388 add_solib_catchpoint (char *arg, int is_load, int is_temp, int enabled)
8389 {
8390   struct solib_catchpoint *c;
8391   struct gdbarch *gdbarch = get_current_arch ();
8392   struct cleanup *cleanup;
8393
8394   if (!arg)
8395     arg = "";
8396   arg = skip_spaces (arg);
8397
8398   c = XCNEW (struct solib_catchpoint);
8399   cleanup = make_cleanup (xfree, c);
8400
8401   if (*arg != '\0')
8402     {
8403       int errcode;
8404
8405       errcode = regcomp (&c->compiled, arg, REG_NOSUB);
8406       if (errcode != 0)
8407         {
8408           char *err = get_regcomp_error (errcode, &c->compiled);
8409
8410           make_cleanup (xfree, err);
8411           error (_("Invalid regexp (%s): %s"), err, arg);
8412         }
8413       c->regex = xstrdup (arg);
8414     }
8415
8416   c->is_load = is_load;
8417   init_catchpoint (&c->base, gdbarch, is_temp, NULL,
8418                    &catch_solib_breakpoint_ops);
8419
8420   c->base.enable_state = enabled ? bp_enabled : bp_disabled;
8421
8422   discard_cleanups (cleanup);
8423   install_breakpoint (0, &c->base, 1);
8424 }
8425
8426 /* A helper function that does all the work for "catch load" and
8427    "catch unload".  */
8428
8429 static void
8430 catch_load_or_unload (char *arg, int from_tty, int is_load,
8431                       struct cmd_list_element *command)
8432 {
8433   int tempflag;
8434   const int enabled = 1;
8435
8436   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
8437
8438   add_solib_catchpoint (arg, is_load, tempflag, enabled);
8439 }
8440
8441 static void
8442 catch_load_command_1 (char *arg, int from_tty,
8443                       struct cmd_list_element *command)
8444 {
8445   catch_load_or_unload (arg, from_tty, 1, command);
8446 }
8447
8448 static void
8449 catch_unload_command_1 (char *arg, int from_tty,
8450                         struct cmd_list_element *command)
8451 {
8452   catch_load_or_unload (arg, from_tty, 0, command);
8453 }
8454
8455 /* An instance of this type is used to represent a syscall catchpoint.
8456    It includes a "struct breakpoint" as a kind of base class; users
8457    downcast to "struct breakpoint *" when needed.  A breakpoint is
8458    really of this type iff its ops pointer points to
8459    CATCH_SYSCALL_BREAKPOINT_OPS.  */
8460
8461 struct syscall_catchpoint
8462 {
8463   /* The base class.  */
8464   struct breakpoint base;
8465
8466   /* Syscall numbers used for the 'catch syscall' feature.  If no
8467      syscall has been specified for filtering, its value is NULL.
8468      Otherwise, it holds a list of all syscalls to be caught.  The
8469      list elements are allocated with xmalloc.  */
8470   VEC(int) *syscalls_to_be_caught;
8471 };
8472
8473 /* Implement the "dtor" breakpoint_ops method for syscall
8474    catchpoints.  */
8475
8476 static void
8477 dtor_catch_syscall (struct breakpoint *b)
8478 {
8479   struct syscall_catchpoint *c = (struct syscall_catchpoint *) b;
8480
8481   VEC_free (int, c->syscalls_to_be_caught);
8482
8483   base_breakpoint_ops.dtor (b);
8484 }
8485
8486 static const struct inferior_data *catch_syscall_inferior_data = NULL;
8487
8488 struct catch_syscall_inferior_data
8489 {
8490   /* We keep a count of the number of times the user has requested a
8491      particular syscall to be tracked, and pass this information to the
8492      target.  This lets capable targets implement filtering directly.  */
8493
8494   /* Number of times that "any" syscall is requested.  */
8495   int any_syscall_count;
8496
8497   /* Count of each system call.  */
8498   VEC(int) *syscalls_counts;
8499
8500   /* This counts all syscall catch requests, so we can readily determine
8501      if any catching is necessary.  */
8502   int total_syscalls_count;
8503 };
8504
8505 static struct catch_syscall_inferior_data*
8506 get_catch_syscall_inferior_data (struct inferior *inf)
8507 {
8508   struct catch_syscall_inferior_data *inf_data;
8509
8510   inf_data = inferior_data (inf, catch_syscall_inferior_data);
8511   if (inf_data == NULL)
8512     {
8513       inf_data = XCNEW (struct catch_syscall_inferior_data);
8514       set_inferior_data (inf, catch_syscall_inferior_data, inf_data);
8515     }
8516
8517   return inf_data;
8518 }
8519
8520 static void
8521 catch_syscall_inferior_data_cleanup (struct inferior *inf, void *arg)
8522 {
8523   xfree (arg);
8524 }
8525
8526
8527 /* Implement the "insert" breakpoint_ops method for syscall
8528    catchpoints.  */
8529
8530 static int
8531 insert_catch_syscall (struct bp_location *bl)
8532 {
8533   struct syscall_catchpoint *c = (struct syscall_catchpoint *) bl->owner;
8534   struct inferior *inf = current_inferior ();
8535   struct catch_syscall_inferior_data *inf_data
8536     = get_catch_syscall_inferior_data (inf);
8537
8538   ++inf_data->total_syscalls_count;
8539   if (!c->syscalls_to_be_caught)
8540     ++inf_data->any_syscall_count;
8541   else
8542     {
8543       int i, iter;
8544
8545       for (i = 0;
8546            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
8547            i++)
8548         {
8549           int elem;
8550
8551           if (iter >= VEC_length (int, inf_data->syscalls_counts))
8552             {
8553               int old_size = VEC_length (int, inf_data->syscalls_counts);
8554               uintptr_t vec_addr_offset
8555                 = old_size * ((uintptr_t) sizeof (int));
8556               uintptr_t vec_addr;
8557               VEC_safe_grow (int, inf_data->syscalls_counts, iter + 1);
8558               vec_addr = ((uintptr_t) VEC_address (int,
8559                                                   inf_data->syscalls_counts)
8560                           + vec_addr_offset);
8561               memset ((void *) vec_addr, 0,
8562                       (iter + 1 - old_size) * sizeof (int));
8563             }
8564           elem = VEC_index (int, inf_data->syscalls_counts, iter);
8565           VEC_replace (int, inf_data->syscalls_counts, iter, ++elem);
8566         }
8567     }
8568
8569   return target_set_syscall_catchpoint (ptid_get_pid (inferior_ptid),
8570                                         inf_data->total_syscalls_count != 0,
8571                                         inf_data->any_syscall_count,
8572                                         VEC_length (int,
8573                                                     inf_data->syscalls_counts),
8574                                         VEC_address (int,
8575                                                      inf_data->syscalls_counts));
8576 }
8577
8578 /* Implement the "remove" breakpoint_ops method for syscall
8579    catchpoints.  */
8580
8581 static int
8582 remove_catch_syscall (struct bp_location *bl)
8583 {
8584   struct syscall_catchpoint *c = (struct syscall_catchpoint *) bl->owner;
8585   struct inferior *inf = current_inferior ();
8586   struct catch_syscall_inferior_data *inf_data
8587     = get_catch_syscall_inferior_data (inf);
8588
8589   --inf_data->total_syscalls_count;
8590   if (!c->syscalls_to_be_caught)
8591     --inf_data->any_syscall_count;
8592   else
8593     {
8594       int i, iter;
8595
8596       for (i = 0;
8597            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
8598            i++)
8599         {
8600           int elem;
8601           if (iter >= VEC_length (int, inf_data->syscalls_counts))
8602             /* Shouldn't happen.  */
8603             continue;
8604           elem = VEC_index (int, inf_data->syscalls_counts, iter);
8605           VEC_replace (int, inf_data->syscalls_counts, iter, --elem);
8606         }
8607     }
8608
8609   return target_set_syscall_catchpoint (ptid_get_pid (inferior_ptid),
8610                                         inf_data->total_syscalls_count != 0,
8611                                         inf_data->any_syscall_count,
8612                                         VEC_length (int,
8613                                                     inf_data->syscalls_counts),
8614                                         VEC_address (int,
8615                                                      inf_data->syscalls_counts));
8616 }
8617
8618 /* Implement the "breakpoint_hit" breakpoint_ops method for syscall
8619    catchpoints.  */
8620
8621 static int
8622 breakpoint_hit_catch_syscall (const struct bp_location *bl,
8623                               struct address_space *aspace, CORE_ADDR bp_addr,
8624                               const struct target_waitstatus *ws)
8625 {
8626   /* We must check if we are catching specific syscalls in this
8627      breakpoint.  If we are, then we must guarantee that the called
8628      syscall is the same syscall we are catching.  */
8629   int syscall_number = 0;
8630   const struct syscall_catchpoint *c
8631     = (const struct syscall_catchpoint *) bl->owner;
8632
8633   if (ws->kind != TARGET_WAITKIND_SYSCALL_ENTRY
8634       && ws->kind != TARGET_WAITKIND_SYSCALL_RETURN)
8635     return 0;
8636
8637   syscall_number = ws->value.syscall_number;
8638
8639   /* Now, checking if the syscall is the same.  */
8640   if (c->syscalls_to_be_caught)
8641     {
8642       int i, iter;
8643
8644       for (i = 0;
8645            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
8646            i++)
8647         if (syscall_number == iter)
8648           return 1;
8649
8650       return 0;
8651     }
8652
8653   return 1;
8654 }
8655
8656 /* Implement the "print_it" breakpoint_ops method for syscall
8657    catchpoints.  */
8658
8659 static enum print_stop_action
8660 print_it_catch_syscall (bpstat bs)
8661 {
8662   struct ui_out *uiout = current_uiout;
8663   struct breakpoint *b = bs->breakpoint_at;
8664   /* These are needed because we want to know in which state a
8665      syscall is.  It can be in the TARGET_WAITKIND_SYSCALL_ENTRY
8666      or TARGET_WAITKIND_SYSCALL_RETURN, and depending on it we
8667      must print "called syscall" or "returned from syscall".  */
8668   ptid_t ptid;
8669   struct target_waitstatus last;
8670   struct syscall s;
8671   struct gdbarch *gdbarch = bs->bp_location_at->gdbarch;
8672
8673   get_last_target_status (&ptid, &last);
8674
8675   get_syscall_by_number (gdbarch, last.value.syscall_number, &s);
8676
8677   annotate_catchpoint (b->number);
8678
8679   if (b->disposition == disp_del)
8680     ui_out_text (uiout, "\nTemporary catchpoint ");
8681   else
8682     ui_out_text (uiout, "\nCatchpoint ");
8683   if (ui_out_is_mi_like_p (uiout))
8684     {
8685       ui_out_field_string (uiout, "reason",
8686                            async_reason_lookup (last.kind == TARGET_WAITKIND_SYSCALL_ENTRY
8687                                                 ? EXEC_ASYNC_SYSCALL_ENTRY
8688                                                 : EXEC_ASYNC_SYSCALL_RETURN));
8689       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
8690     }
8691   ui_out_field_int (uiout, "bkptno", b->number);
8692
8693   if (last.kind == TARGET_WAITKIND_SYSCALL_ENTRY)
8694     ui_out_text (uiout, " (call to syscall ");
8695   else
8696     ui_out_text (uiout, " (returned from syscall ");
8697
8698   if (s.name == NULL || ui_out_is_mi_like_p (uiout))
8699     ui_out_field_int (uiout, "syscall-number", last.value.syscall_number);
8700   if (s.name != NULL)
8701     ui_out_field_string (uiout, "syscall-name", s.name);
8702
8703   ui_out_text (uiout, "), ");
8704
8705   return PRINT_SRC_AND_LOC;
8706 }
8707
8708 /* Implement the "print_one" breakpoint_ops method for syscall
8709    catchpoints.  */
8710
8711 static void
8712 print_one_catch_syscall (struct breakpoint *b,
8713                          struct bp_location **last_loc)
8714 {
8715   struct syscall_catchpoint *c = (struct syscall_catchpoint *) b;
8716   struct value_print_options opts;
8717   struct ui_out *uiout = current_uiout;
8718   struct gdbarch *gdbarch = b->loc->gdbarch;
8719
8720   get_user_print_options (&opts);
8721   /* Field 4, the address, is omitted (which makes the columns not
8722      line up too nicely with the headers, but the effect is relatively
8723      readable).  */
8724   if (opts.addressprint)
8725     ui_out_field_skip (uiout, "addr");
8726   annotate_field (5);
8727
8728   if (c->syscalls_to_be_caught
8729       && VEC_length (int, c->syscalls_to_be_caught) > 1)
8730     ui_out_text (uiout, "syscalls \"");
8731   else
8732     ui_out_text (uiout, "syscall \"");
8733
8734   if (c->syscalls_to_be_caught)
8735     {
8736       int i, iter;
8737       char *text = xstrprintf ("%s", "");
8738
8739       for (i = 0;
8740            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
8741            i++)
8742         {
8743           char *x = text;
8744           struct syscall s;
8745           get_syscall_by_number (gdbarch, iter, &s);
8746
8747           if (s.name != NULL)
8748             text = xstrprintf ("%s%s, ", text, s.name);
8749           else
8750             text = xstrprintf ("%s%d, ", text, iter);
8751
8752           /* We have to xfree the last 'text' (now stored at 'x')
8753              because xstrprintf dynamically allocates new space for it
8754              on every call.  */
8755           xfree (x);
8756         }
8757       /* Remove the last comma.  */
8758       text[strlen (text) - 2] = '\0';
8759       ui_out_field_string (uiout, "what", text);
8760     }
8761   else
8762     ui_out_field_string (uiout, "what", "<any syscall>");
8763   ui_out_text (uiout, "\" ");
8764
8765   if (ui_out_is_mi_like_p (uiout))
8766     ui_out_field_string (uiout, "catch-type", "syscall");
8767 }
8768
8769 /* Implement the "print_mention" breakpoint_ops method for syscall
8770    catchpoints.  */
8771
8772 static void
8773 print_mention_catch_syscall (struct breakpoint *b)
8774 {
8775   struct syscall_catchpoint *c = (struct syscall_catchpoint *) b;
8776   struct gdbarch *gdbarch = b->loc->gdbarch;
8777
8778   if (c->syscalls_to_be_caught)
8779     {
8780       int i, iter;
8781
8782       if (VEC_length (int, c->syscalls_to_be_caught) > 1)
8783         printf_filtered (_("Catchpoint %d (syscalls"), b->number);
8784       else
8785         printf_filtered (_("Catchpoint %d (syscall"), b->number);
8786
8787       for (i = 0;
8788            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
8789            i++)
8790         {
8791           struct syscall s;
8792           get_syscall_by_number (gdbarch, iter, &s);
8793
8794           if (s.name)
8795             printf_filtered (" '%s' [%d]", s.name, s.number);
8796           else
8797             printf_filtered (" %d", s.number);
8798         }
8799       printf_filtered (")");
8800     }
8801   else
8802     printf_filtered (_("Catchpoint %d (any syscall)"),
8803                      b->number);
8804 }
8805
8806 /* Implement the "print_recreate" breakpoint_ops method for syscall
8807    catchpoints.  */
8808
8809 static void
8810 print_recreate_catch_syscall (struct breakpoint *b, struct ui_file *fp)
8811 {
8812   struct syscall_catchpoint *c = (struct syscall_catchpoint *) b;
8813   struct gdbarch *gdbarch = b->loc->gdbarch;
8814
8815   fprintf_unfiltered (fp, "catch syscall");
8816
8817   if (c->syscalls_to_be_caught)
8818     {
8819       int i, iter;
8820
8821       for (i = 0;
8822            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
8823            i++)
8824         {
8825           struct syscall s;
8826
8827           get_syscall_by_number (gdbarch, iter, &s);
8828           if (s.name)
8829             fprintf_unfiltered (fp, " %s", s.name);
8830           else
8831             fprintf_unfiltered (fp, " %d", s.number);
8832         }
8833     }
8834   print_recreate_thread (b, fp);
8835 }
8836
8837 /* The breakpoint_ops structure to be used in syscall catchpoints.  */
8838
8839 static struct breakpoint_ops catch_syscall_breakpoint_ops;
8840
8841 /* Returns non-zero if 'b' is a syscall catchpoint.  */
8842
8843 static int
8844 syscall_catchpoint_p (struct breakpoint *b)
8845 {
8846   return (b->ops == &catch_syscall_breakpoint_ops);
8847 }
8848
8849 /* Initialize a new breakpoint of the bp_catchpoint kind.  If TEMPFLAG
8850    is non-zero, then make the breakpoint temporary.  If COND_STRING is
8851    not NULL, then store it in the breakpoint.  OPS, if not NULL, is
8852    the breakpoint_ops structure associated to the catchpoint.  */
8853
8854 void
8855 init_catchpoint (struct breakpoint *b,
8856                  struct gdbarch *gdbarch, int tempflag,
8857                  char *cond_string,
8858                  const struct breakpoint_ops *ops)
8859 {
8860   struct symtab_and_line sal;
8861
8862   init_sal (&sal);
8863   sal.pspace = current_program_space;
8864
8865   init_raw_breakpoint (b, gdbarch, sal, bp_catchpoint, ops);
8866
8867   b->cond_string = (cond_string == NULL) ? NULL : xstrdup (cond_string);
8868   b->disposition = tempflag ? disp_del : disp_donttouch;
8869 }
8870
8871 void
8872 install_breakpoint (int internal, struct breakpoint *b, int update_gll)
8873 {
8874   add_to_breakpoint_chain (b);
8875   set_breakpoint_number (internal, b);
8876   if (is_tracepoint (b))
8877     set_tracepoint_count (breakpoint_count);
8878   if (!internal)
8879     mention (b);
8880   observer_notify_breakpoint_created (b);
8881
8882   if (update_gll)
8883     update_global_location_list (UGLL_MAY_INSERT);
8884 }
8885
8886 static void
8887 create_fork_vfork_event_catchpoint (struct gdbarch *gdbarch,
8888                                     int tempflag, char *cond_string,
8889                                     const struct breakpoint_ops *ops)
8890 {
8891   struct fork_catchpoint *c = XNEW (struct fork_catchpoint);
8892
8893   init_catchpoint (&c->base, gdbarch, tempflag, cond_string, ops);
8894
8895   c->forked_inferior_pid = null_ptid;
8896
8897   install_breakpoint (0, &c->base, 1);
8898 }
8899
8900 /* Exec catchpoints.  */
8901
8902 /* An instance of this type is used to represent an exec catchpoint.
8903    It includes a "struct breakpoint" as a kind of base class; users
8904    downcast to "struct breakpoint *" when needed.  A breakpoint is
8905    really of this type iff its ops pointer points to
8906    CATCH_EXEC_BREAKPOINT_OPS.  */
8907
8908 struct exec_catchpoint
8909 {
8910   /* The base class.  */
8911   struct breakpoint base;
8912
8913   /* Filename of a program whose exec triggered this catchpoint.
8914      This field is only valid immediately after this catchpoint has
8915      triggered.  */
8916   char *exec_pathname;
8917 };
8918
8919 /* Implement the "dtor" breakpoint_ops method for exec
8920    catchpoints.  */
8921
8922 static void
8923 dtor_catch_exec (struct breakpoint *b)
8924 {
8925   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
8926
8927   xfree (c->exec_pathname);
8928
8929   base_breakpoint_ops.dtor (b);
8930 }
8931
8932 static int
8933 insert_catch_exec (struct bp_location *bl)
8934 {
8935   return target_insert_exec_catchpoint (ptid_get_pid (inferior_ptid));
8936 }
8937
8938 static int
8939 remove_catch_exec (struct bp_location *bl)
8940 {
8941   return target_remove_exec_catchpoint (ptid_get_pid (inferior_ptid));
8942 }
8943
8944 static int
8945 breakpoint_hit_catch_exec (const struct bp_location *bl,
8946                            struct address_space *aspace, CORE_ADDR bp_addr,
8947                            const struct target_waitstatus *ws)
8948 {
8949   struct exec_catchpoint *c = (struct exec_catchpoint *) bl->owner;
8950
8951   if (ws->kind != TARGET_WAITKIND_EXECD)
8952     return 0;
8953
8954   c->exec_pathname = xstrdup (ws->value.execd_pathname);
8955   return 1;
8956 }
8957
8958 static enum print_stop_action
8959 print_it_catch_exec (bpstat bs)
8960 {
8961   struct ui_out *uiout = current_uiout;
8962   struct breakpoint *b = bs->breakpoint_at;
8963   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
8964
8965   annotate_catchpoint (b->number);
8966   if (b->disposition == disp_del)
8967     ui_out_text (uiout, "\nTemporary catchpoint ");
8968   else
8969     ui_out_text (uiout, "\nCatchpoint ");
8970   if (ui_out_is_mi_like_p (uiout))
8971     {
8972       ui_out_field_string (uiout, "reason",
8973                            async_reason_lookup (EXEC_ASYNC_EXEC));
8974       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
8975     }
8976   ui_out_field_int (uiout, "bkptno", b->number);
8977   ui_out_text (uiout, " (exec'd ");
8978   ui_out_field_string (uiout, "new-exec", c->exec_pathname);
8979   ui_out_text (uiout, "), ");
8980
8981   return PRINT_SRC_AND_LOC;
8982 }
8983
8984 static void
8985 print_one_catch_exec (struct breakpoint *b, struct bp_location **last_loc)
8986 {
8987   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
8988   struct value_print_options opts;
8989   struct ui_out *uiout = current_uiout;
8990
8991   get_user_print_options (&opts);
8992
8993   /* Field 4, the address, is omitted (which makes the columns
8994      not line up too nicely with the headers, but the effect
8995      is relatively readable).  */
8996   if (opts.addressprint)
8997     ui_out_field_skip (uiout, "addr");
8998   annotate_field (5);
8999   ui_out_text (uiout, "exec");
9000   if (c->exec_pathname != NULL)
9001     {
9002       ui_out_text (uiout, ", program \"");
9003       ui_out_field_string (uiout, "what", c->exec_pathname);
9004       ui_out_text (uiout, "\" ");
9005     }
9006
9007   if (ui_out_is_mi_like_p (uiout))
9008     ui_out_field_string (uiout, "catch-type", "exec");
9009 }
9010
9011 static void
9012 print_mention_catch_exec (struct breakpoint *b)
9013 {
9014   printf_filtered (_("Catchpoint %d (exec)"), b->number);
9015 }
9016
9017 /* Implement the "print_recreate" breakpoint_ops method for exec
9018    catchpoints.  */
9019
9020 static void
9021 print_recreate_catch_exec (struct breakpoint *b, struct ui_file *fp)
9022 {
9023   fprintf_unfiltered (fp, "catch exec");
9024   print_recreate_thread (b, fp);
9025 }
9026
9027 static struct breakpoint_ops catch_exec_breakpoint_ops;
9028
9029 static void
9030 create_syscall_event_catchpoint (int tempflag, VEC(int) *filter,
9031                                  const struct breakpoint_ops *ops)
9032 {
9033   struct syscall_catchpoint *c;
9034   struct gdbarch *gdbarch = get_current_arch ();
9035
9036   c = XNEW (struct syscall_catchpoint);
9037   init_catchpoint (&c->base, gdbarch, tempflag, NULL, ops);
9038   c->syscalls_to_be_caught = filter;
9039
9040   install_breakpoint (0, &c->base, 1);
9041 }
9042
9043 static int
9044 hw_breakpoint_used_count (void)
9045 {
9046   int i = 0;
9047   struct breakpoint *b;
9048   struct bp_location *bl;
9049
9050   ALL_BREAKPOINTS (b)
9051   {
9052     if (b->type == bp_hardware_breakpoint && breakpoint_enabled (b))
9053       for (bl = b->loc; bl; bl = bl->next)
9054         {
9055           /* Special types of hardware breakpoints may use more than
9056              one register.  */
9057           i += b->ops->resources_needed (bl);
9058         }
9059   }
9060
9061   return i;
9062 }
9063
9064 /* Returns the resources B would use if it were a hardware
9065    watchpoint.  */
9066
9067 static int
9068 hw_watchpoint_use_count (struct breakpoint *b)
9069 {
9070   int i = 0;
9071   struct bp_location *bl;
9072
9073   if (!breakpoint_enabled (b))
9074     return 0;
9075
9076   for (bl = b->loc; bl; bl = bl->next)
9077     {
9078       /* Special types of hardware watchpoints may use more than
9079          one register.  */
9080       i += b->ops->resources_needed (bl);
9081     }
9082
9083   return i;
9084 }
9085
9086 /* Returns the sum the used resources of all hardware watchpoints of
9087    type TYPE in the breakpoints list.  Also returns in OTHER_TYPE_USED
9088    the sum of the used resources of all hardware watchpoints of other
9089    types _not_ TYPE.  */
9090
9091 static int
9092 hw_watchpoint_used_count_others (struct breakpoint *except,
9093                                  enum bptype type, int *other_type_used)
9094 {
9095   int i = 0;
9096   struct breakpoint *b;
9097
9098   *other_type_used = 0;
9099   ALL_BREAKPOINTS (b)
9100     {
9101       if (b == except)
9102         continue;
9103       if (!breakpoint_enabled (b))
9104         continue;
9105
9106       if (b->type == type)
9107         i += hw_watchpoint_use_count (b);
9108       else if (is_hardware_watchpoint (b))
9109         *other_type_used = 1;
9110     }
9111
9112   return i;
9113 }
9114
9115 void
9116 disable_watchpoints_before_interactive_call_start (void)
9117 {
9118   struct breakpoint *b;
9119
9120   ALL_BREAKPOINTS (b)
9121   {
9122     if (is_watchpoint (b) && breakpoint_enabled (b))
9123       {
9124         b->enable_state = bp_call_disabled;
9125         update_global_location_list (UGLL_DONT_INSERT);
9126       }
9127   }
9128 }
9129
9130 void
9131 enable_watchpoints_after_interactive_call_stop (void)
9132 {
9133   struct breakpoint *b;
9134
9135   ALL_BREAKPOINTS (b)
9136   {
9137     if (is_watchpoint (b) && b->enable_state == bp_call_disabled)
9138       {
9139         b->enable_state = bp_enabled;
9140         update_global_location_list (UGLL_MAY_INSERT);
9141       }
9142   }
9143 }
9144
9145 void
9146 disable_breakpoints_before_startup (void)
9147 {
9148   current_program_space->executing_startup = 1;
9149   update_global_location_list (UGLL_DONT_INSERT);
9150 }
9151
9152 void
9153 enable_breakpoints_after_startup (void)
9154 {
9155   current_program_space->executing_startup = 0;
9156   breakpoint_re_set ();
9157 }
9158
9159 /* Create a new single-step breakpoint for thread THREAD, with no
9160    locations.  */
9161
9162 static struct breakpoint *
9163 new_single_step_breakpoint (int thread, struct gdbarch *gdbarch)
9164 {
9165   struct breakpoint *b = XNEW (struct breakpoint);
9166
9167   init_raw_breakpoint_without_location (b, gdbarch, bp_single_step,
9168                                         &momentary_breakpoint_ops);
9169
9170   b->disposition = disp_donttouch;
9171   b->frame_id = null_frame_id;
9172
9173   b->thread = thread;
9174   gdb_assert (b->thread != 0);
9175
9176   add_to_breakpoint_chain (b);
9177
9178   return b;
9179 }
9180
9181 /* Set a momentary breakpoint of type TYPE at address specified by
9182    SAL.  If FRAME_ID is valid, the breakpoint is restricted to that
9183    frame.  */
9184
9185 struct breakpoint *
9186 set_momentary_breakpoint (struct gdbarch *gdbarch, struct symtab_and_line sal,
9187                           struct frame_id frame_id, enum bptype type)
9188 {
9189   struct breakpoint *b;
9190
9191   /* If FRAME_ID is valid, it should be a real frame, not an inlined or
9192      tail-called one.  */
9193   gdb_assert (!frame_id_artificial_p (frame_id));
9194
9195   b = set_raw_breakpoint (gdbarch, sal, type, &momentary_breakpoint_ops);
9196   b->enable_state = bp_enabled;
9197   b->disposition = disp_donttouch;
9198   b->frame_id = frame_id;
9199
9200   /* If we're debugging a multi-threaded program, then we want
9201      momentary breakpoints to be active in only a single thread of
9202      control.  */
9203   if (in_thread_list (inferior_ptid))
9204     b->thread = pid_to_thread_id (inferior_ptid);
9205
9206   update_global_location_list_nothrow (UGLL_MAY_INSERT);
9207
9208   return b;
9209 }
9210
9211 /* Make a momentary breakpoint based on the master breakpoint ORIG.
9212    The new breakpoint will have type TYPE, use OPS as its
9213    breakpoint_ops, and will set enabled to LOC_ENABLED.  */
9214
9215 static struct breakpoint *
9216 momentary_breakpoint_from_master (struct breakpoint *orig,
9217                                   enum bptype type,
9218                                   const struct breakpoint_ops *ops,
9219                                   int loc_enabled)
9220 {
9221   struct breakpoint *copy;
9222
9223   copy = set_raw_breakpoint_without_location (orig->gdbarch, type, ops);
9224   copy->loc = allocate_bp_location (copy);
9225   set_breakpoint_location_function (copy->loc, 1);
9226
9227   copy->loc->gdbarch = orig->loc->gdbarch;
9228   copy->loc->requested_address = orig->loc->requested_address;
9229   copy->loc->address = orig->loc->address;
9230   copy->loc->section = orig->loc->section;
9231   copy->loc->pspace = orig->loc->pspace;
9232   copy->loc->probe = orig->loc->probe;
9233   copy->loc->line_number = orig->loc->line_number;
9234   copy->loc->symtab = orig->loc->symtab;
9235   copy->loc->enabled = loc_enabled;
9236   copy->frame_id = orig->frame_id;
9237   copy->thread = orig->thread;
9238   copy->pspace = orig->pspace;
9239
9240   copy->enable_state = bp_enabled;
9241   copy->disposition = disp_donttouch;
9242   copy->number = internal_breakpoint_number--;
9243
9244   update_global_location_list_nothrow (UGLL_DONT_INSERT);
9245   return copy;
9246 }
9247
9248 /* Make a deep copy of momentary breakpoint ORIG.  Returns NULL if
9249    ORIG is NULL.  */
9250
9251 struct breakpoint *
9252 clone_momentary_breakpoint (struct breakpoint *orig)
9253 {
9254   /* If there's nothing to clone, then return nothing.  */
9255   if (orig == NULL)
9256     return NULL;
9257
9258   return momentary_breakpoint_from_master (orig, orig->type, orig->ops, 0);
9259 }
9260
9261 struct breakpoint *
9262 set_momentary_breakpoint_at_pc (struct gdbarch *gdbarch, CORE_ADDR pc,
9263                                 enum bptype type)
9264 {
9265   struct symtab_and_line sal;
9266
9267   sal = find_pc_line (pc, 0);
9268   sal.pc = pc;
9269   sal.section = find_pc_overlay (pc);
9270   sal.explicit_pc = 1;
9271
9272   return set_momentary_breakpoint (gdbarch, sal, null_frame_id, type);
9273 }
9274 \f
9275
9276 /* Tell the user we have just set a breakpoint B.  */
9277
9278 static void
9279 mention (struct breakpoint *b)
9280 {
9281   b->ops->print_mention (b);
9282   if (ui_out_is_mi_like_p (current_uiout))
9283     return;
9284   printf_filtered ("\n");
9285 }
9286 \f
9287
9288 static int bp_loc_is_permanent (struct bp_location *loc);
9289
9290 static struct bp_location *
9291 add_location_to_breakpoint (struct breakpoint *b,
9292                             const struct symtab_and_line *sal)
9293 {
9294   struct bp_location *loc, **tmp;
9295   CORE_ADDR adjusted_address;
9296   struct gdbarch *loc_gdbarch = get_sal_arch (*sal);
9297
9298   if (loc_gdbarch == NULL)
9299     loc_gdbarch = b->gdbarch;
9300
9301   /* Adjust the breakpoint's address prior to allocating a location.
9302      Once we call allocate_bp_location(), that mostly uninitialized
9303      location will be placed on the location chain.  Adjustment of the
9304      breakpoint may cause target_read_memory() to be called and we do
9305      not want its scan of the location chain to find a breakpoint and
9306      location that's only been partially initialized.  */
9307   adjusted_address = adjust_breakpoint_address (loc_gdbarch,
9308                                                 sal->pc, b->type);
9309
9310   /* Sort the locations by their ADDRESS.  */
9311   loc = allocate_bp_location (b);
9312   for (tmp = &(b->loc); *tmp != NULL && (*tmp)->address <= adjusted_address;
9313        tmp = &((*tmp)->next))
9314     ;
9315   loc->next = *tmp;
9316   *tmp = loc;
9317
9318   loc->requested_address = sal->pc;
9319   loc->address = adjusted_address;
9320   loc->pspace = sal->pspace;
9321   loc->probe.probe = sal->probe;
9322   loc->probe.objfile = sal->objfile;
9323   gdb_assert (loc->pspace != NULL);
9324   loc->section = sal->section;
9325   loc->gdbarch = loc_gdbarch;
9326   loc->line_number = sal->line;
9327   loc->symtab = sal->symtab;
9328
9329   set_breakpoint_location_function (loc,
9330                                     sal->explicit_pc || sal->explicit_line);
9331
9332   if (bp_loc_is_permanent (loc))
9333     {
9334       loc->inserted = 1;
9335       loc->permanent = 1;
9336     }
9337
9338   return loc;
9339 }
9340 \f
9341
9342 /* See breakpoint.h.  */
9343
9344 int
9345 program_breakpoint_here_p (struct gdbarch *gdbarch, CORE_ADDR address)
9346 {
9347   int len;
9348   CORE_ADDR addr;
9349   const gdb_byte *bpoint;
9350   gdb_byte *target_mem;
9351   struct cleanup *cleanup;
9352   int retval = 0;
9353
9354   addr = address;
9355   bpoint = gdbarch_breakpoint_from_pc (gdbarch, &addr, &len);
9356
9357   /* Software breakpoints unsupported?  */
9358   if (bpoint == NULL)
9359     return 0;
9360
9361   target_mem = alloca (len);
9362
9363   /* Enable the automatic memory restoration from breakpoints while
9364      we read the memory.  Otherwise we could say about our temporary
9365      breakpoints they are permanent.  */
9366   cleanup = make_show_memory_breakpoints_cleanup (0);
9367
9368   if (target_read_memory (address, target_mem, len) == 0
9369       && memcmp (target_mem, bpoint, len) == 0)
9370     retval = 1;
9371
9372   do_cleanups (cleanup);
9373
9374   return retval;
9375 }
9376
9377 /* Return 1 if LOC is pointing to a permanent breakpoint,
9378    return 0 otherwise.  */
9379
9380 static int
9381 bp_loc_is_permanent (struct bp_location *loc)
9382 {
9383   struct cleanup *cleanup;
9384   int retval;
9385
9386   gdb_assert (loc != NULL);
9387
9388   /* bp_call_dummy breakpoint locations are usually memory locations
9389      where GDB just wrote a breakpoint instruction, making it look
9390      as if there is a permanent breakpoint at that location.  Considering
9391      it permanent makes GDB rely on that breakpoint instruction to stop
9392      the program, thus removing the need to insert its own breakpoint
9393      there.  This is normally expected to work, except that some versions
9394      of QEMU (Eg: QEMU 2.0.0 for SPARC) just report a fatal problem (Trap
9395      0x02 while interrupts disabled, Error state) instead of reporting
9396      a SIGTRAP.  QEMU should probably be fixed, but in the interest of
9397      compatibility with versions that behave this way, we always consider
9398      bp_call_dummy breakpoint locations as non-permanent.  */
9399   if (loc->owner->type == bp_call_dummy)
9400     return 0;
9401
9402   cleanup = save_current_space_and_thread ();
9403   switch_to_program_space_and_thread (loc->pspace);
9404
9405   retval = program_breakpoint_here_p (loc->gdbarch, loc->address);
9406
9407   do_cleanups (cleanup);
9408
9409   return retval;
9410 }
9411
9412 /* Build a command list for the dprintf corresponding to the current
9413    settings of the dprintf style options.  */
9414
9415 static void
9416 update_dprintf_command_list (struct breakpoint *b)
9417 {
9418   char *dprintf_args = b->extra_string;
9419   char *printf_line = NULL;
9420
9421   if (!dprintf_args)
9422     return;
9423
9424   dprintf_args = skip_spaces (dprintf_args);
9425
9426   /* Allow a comma, as it may have terminated a location, but don't
9427      insist on it.  */
9428   if (*dprintf_args == ',')
9429     ++dprintf_args;
9430   dprintf_args = skip_spaces (dprintf_args);
9431
9432   if (*dprintf_args != '"')
9433     error (_("Bad format string, missing '\"'."));
9434
9435   if (strcmp (dprintf_style, dprintf_style_gdb) == 0)
9436     printf_line = xstrprintf ("printf %s", dprintf_args);
9437   else if (strcmp (dprintf_style, dprintf_style_call) == 0)
9438     {
9439       if (!dprintf_function)
9440         error (_("No function supplied for dprintf call"));
9441
9442       if (dprintf_channel && strlen (dprintf_channel) > 0)
9443         printf_line = xstrprintf ("call (void) %s (%s,%s)",
9444                                   dprintf_function,
9445                                   dprintf_channel,
9446                                   dprintf_args);
9447       else
9448         printf_line = xstrprintf ("call (void) %s (%s)",
9449                                   dprintf_function,
9450                                   dprintf_args);
9451     }
9452   else if (strcmp (dprintf_style, dprintf_style_agent) == 0)
9453     {
9454       if (target_can_run_breakpoint_commands ())
9455         printf_line = xstrprintf ("agent-printf %s", dprintf_args);
9456       else
9457         {
9458           warning (_("Target cannot run dprintf commands, falling back to GDB printf"));
9459           printf_line = xstrprintf ("printf %s", dprintf_args);
9460         }
9461     }
9462   else
9463     internal_error (__FILE__, __LINE__,
9464                     _("Invalid dprintf style."));
9465
9466   gdb_assert (printf_line != NULL);
9467   /* Manufacture a printf sequence.  */
9468   {
9469     struct command_line *printf_cmd_line
9470       = xmalloc (sizeof (struct command_line));
9471
9472     printf_cmd_line = xmalloc (sizeof (struct command_line));
9473     printf_cmd_line->control_type = simple_control;
9474     printf_cmd_line->body_count = 0;
9475     printf_cmd_line->body_list = NULL;
9476     printf_cmd_line->next = NULL;
9477     printf_cmd_line->line = printf_line;
9478
9479     breakpoint_set_commands (b, printf_cmd_line);
9480   }
9481 }
9482
9483 /* Update all dprintf commands, making their command lists reflect
9484    current style settings.  */
9485
9486 static void
9487 update_dprintf_commands (char *args, int from_tty,
9488                          struct cmd_list_element *c)
9489 {
9490   struct breakpoint *b;
9491
9492   ALL_BREAKPOINTS (b)
9493     {
9494       if (b->type == bp_dprintf)
9495         update_dprintf_command_list (b);
9496     }
9497 }
9498
9499 /* Create a breakpoint with SAL as location.  Use ADDR_STRING
9500    as textual description of the location, and COND_STRING
9501    as condition expression.  */
9502
9503 static void
9504 init_breakpoint_sal (struct breakpoint *b, struct gdbarch *gdbarch,
9505                      struct symtabs_and_lines sals, char *addr_string,
9506                      char *filter, char *cond_string,
9507                      char *extra_string,
9508                      enum bptype type, enum bpdisp disposition,
9509                      int thread, int task, int ignore_count,
9510                      const struct breakpoint_ops *ops, int from_tty,
9511                      int enabled, int internal, unsigned flags,
9512                      int display_canonical)
9513 {
9514   int i;
9515
9516   if (type == bp_hardware_breakpoint)
9517     {
9518       int target_resources_ok;
9519
9520       i = hw_breakpoint_used_count ();
9521       target_resources_ok =
9522         target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
9523                                             i + 1, 0);
9524       if (target_resources_ok == 0)
9525         error (_("No hardware breakpoint support in the target."));
9526       else if (target_resources_ok < 0)
9527         error (_("Hardware breakpoints used exceeds limit."));
9528     }
9529
9530   gdb_assert (sals.nelts > 0);
9531
9532   for (i = 0; i < sals.nelts; ++i)
9533     {
9534       struct symtab_and_line sal = sals.sals[i];
9535       struct bp_location *loc;
9536
9537       if (from_tty)
9538         {
9539           struct gdbarch *loc_gdbarch = get_sal_arch (sal);
9540           if (!loc_gdbarch)
9541             loc_gdbarch = gdbarch;
9542
9543           describe_other_breakpoints (loc_gdbarch,
9544                                       sal.pspace, sal.pc, sal.section, thread);
9545         }
9546
9547       if (i == 0)
9548         {
9549           init_raw_breakpoint (b, gdbarch, sal, type, ops);
9550           b->thread = thread;
9551           b->task = task;
9552
9553           b->cond_string = cond_string;
9554           b->extra_string = extra_string;
9555           b->ignore_count = ignore_count;
9556           b->enable_state = enabled ? bp_enabled : bp_disabled;
9557           b->disposition = disposition;
9558
9559           if ((flags & CREATE_BREAKPOINT_FLAGS_INSERTED) != 0)
9560             b->loc->inserted = 1;
9561
9562           if (type == bp_static_tracepoint)
9563             {
9564               struct tracepoint *t = (struct tracepoint *) b;
9565               struct static_tracepoint_marker marker;
9566
9567               if (strace_marker_p (b))
9568                 {
9569                   /* We already know the marker exists, otherwise, we
9570                      wouldn't see a sal for it.  */
9571                   char *p = &addr_string[3];
9572                   char *endp;
9573                   char *marker_str;
9574
9575                   p = skip_spaces (p);
9576
9577                   endp = skip_to_space (p);
9578
9579                   marker_str = savestring (p, endp - p);
9580                   t->static_trace_marker_id = marker_str;
9581
9582                   printf_filtered (_("Probed static tracepoint "
9583                                      "marker \"%s\"\n"),
9584                                    t->static_trace_marker_id);
9585                 }
9586               else if (target_static_tracepoint_marker_at (sal.pc, &marker))
9587                 {
9588                   t->static_trace_marker_id = xstrdup (marker.str_id);
9589                   release_static_tracepoint_marker (&marker);
9590
9591                   printf_filtered (_("Probed static tracepoint "
9592                                      "marker \"%s\"\n"),
9593                                    t->static_trace_marker_id);
9594                 }
9595               else
9596                 warning (_("Couldn't determine the static "
9597                            "tracepoint marker to probe"));
9598             }
9599
9600           loc = b->loc;
9601         }
9602       else
9603         {
9604           loc = add_location_to_breakpoint (b, &sal);
9605           if ((flags & CREATE_BREAKPOINT_FLAGS_INSERTED) != 0)
9606             loc->inserted = 1;
9607         }
9608
9609       if (b->cond_string)
9610         {
9611           const char *arg = b->cond_string;
9612
9613           loc->cond = parse_exp_1 (&arg, loc->address,
9614                                    block_for_pc (loc->address), 0);
9615           if (*arg)
9616               error (_("Garbage '%s' follows condition"), arg);
9617         }
9618
9619       /* Dynamic printf requires and uses additional arguments on the
9620          command line, otherwise it's an error.  */
9621       if (type == bp_dprintf)
9622         {
9623           if (b->extra_string)
9624             update_dprintf_command_list (b);
9625           else
9626             error (_("Format string required"));
9627         }
9628       else if (b->extra_string)
9629         error (_("Garbage '%s' at end of command"), b->extra_string);
9630     }
9631
9632   b->display_canonical = display_canonical;
9633   if (addr_string)
9634     b->addr_string = addr_string;
9635   else
9636     /* addr_string has to be used or breakpoint_re_set will delete
9637        me.  */
9638     b->addr_string
9639       = xstrprintf ("*%s", paddress (b->loc->gdbarch, b->loc->address));
9640   b->filter = filter;
9641 }
9642
9643 static void
9644 create_breakpoint_sal (struct gdbarch *gdbarch,
9645                        struct symtabs_and_lines sals, char *addr_string,
9646                        char *filter, char *cond_string,
9647                        char *extra_string,
9648                        enum bptype type, enum bpdisp disposition,
9649                        int thread, int task, int ignore_count,
9650                        const struct breakpoint_ops *ops, int from_tty,
9651                        int enabled, int internal, unsigned flags,
9652                        int display_canonical)
9653 {
9654   struct breakpoint *b;
9655   struct cleanup *old_chain;
9656
9657   if (is_tracepoint_type (type))
9658     {
9659       struct tracepoint *t;
9660
9661       t = XCNEW (struct tracepoint);
9662       b = &t->base;
9663     }
9664   else
9665     b = XNEW (struct breakpoint);
9666
9667   old_chain = make_cleanup (xfree, b);
9668
9669   init_breakpoint_sal (b, gdbarch,
9670                        sals, addr_string,
9671                        filter, cond_string, extra_string,
9672                        type, disposition,
9673                        thread, task, ignore_count,
9674                        ops, from_tty,
9675                        enabled, internal, flags,
9676                        display_canonical);
9677   discard_cleanups (old_chain);
9678
9679   install_breakpoint (internal, b, 0);
9680 }
9681
9682 /* Add SALS.nelts breakpoints to the breakpoint table.  For each
9683    SALS.sal[i] breakpoint, include the corresponding ADDR_STRING[i]
9684    value.  COND_STRING, if not NULL, specified the condition to be
9685    used for all breakpoints.  Essentially the only case where
9686    SALS.nelts is not 1 is when we set a breakpoint on an overloaded
9687    function.  In that case, it's still not possible to specify
9688    separate conditions for different overloaded functions, so
9689    we take just a single condition string.
9690    
9691    NOTE: If the function succeeds, the caller is expected to cleanup
9692    the arrays ADDR_STRING, COND_STRING, and SALS (but not the
9693    array contents).  If the function fails (error() is called), the
9694    caller is expected to cleanups both the ADDR_STRING, COND_STRING,
9695    COND and SALS arrays and each of those arrays contents.  */
9696
9697 static void
9698 create_breakpoints_sal (struct gdbarch *gdbarch,
9699                         struct linespec_result *canonical,
9700                         char *cond_string, char *extra_string,
9701                         enum bptype type, enum bpdisp disposition,
9702                         int thread, int task, int ignore_count,
9703                         const struct breakpoint_ops *ops, int from_tty,
9704                         int enabled, int internal, unsigned flags)
9705 {
9706   int i;
9707   struct linespec_sals *lsal;
9708
9709   if (canonical->pre_expanded)
9710     gdb_assert (VEC_length (linespec_sals, canonical->sals) == 1);
9711
9712   for (i = 0; VEC_iterate (linespec_sals, canonical->sals, i, lsal); ++i)
9713     {
9714       /* Note that 'addr_string' can be NULL in the case of a plain
9715          'break', without arguments.  */
9716       char *addr_string = (canonical->addr_string
9717                            ? xstrdup (canonical->addr_string)
9718                            : NULL);
9719       char *filter_string = lsal->canonical ? xstrdup (lsal->canonical) : NULL;
9720       struct cleanup *inner = make_cleanup (xfree, addr_string);
9721
9722       make_cleanup (xfree, filter_string);
9723       create_breakpoint_sal (gdbarch, lsal->sals,
9724                              addr_string,
9725                              filter_string,
9726                              cond_string, extra_string,
9727                              type, disposition,
9728                              thread, task, ignore_count, ops,
9729                              from_tty, enabled, internal, flags,
9730                              canonical->special_display);
9731       discard_cleanups (inner);
9732     }
9733 }
9734
9735 /* Parse ADDRESS which is assumed to be a SAL specification possibly
9736    followed by conditionals.  On return, SALS contains an array of SAL
9737    addresses found.  ADDR_STRING contains a vector of (canonical)
9738    address strings.  ADDRESS points to the end of the SAL.
9739
9740    The array and the line spec strings are allocated on the heap, it is
9741    the caller's responsibility to free them.  */
9742
9743 static void
9744 parse_breakpoint_sals (char **address,
9745                        struct linespec_result *canonical)
9746 {
9747   /* If no arg given, or if first arg is 'if ', use the default
9748      breakpoint.  */
9749   if ((*address) == NULL
9750       || (startswith ((*address), "if") && isspace ((*address)[2])))
9751     {
9752       /* The last displayed codepoint, if it's valid, is our default breakpoint
9753          address.  */
9754       if (last_displayed_sal_is_valid ())
9755         {
9756           struct linespec_sals lsal;
9757           struct symtab_and_line sal;
9758           CORE_ADDR pc;
9759
9760           init_sal (&sal);              /* Initialize to zeroes.  */
9761           lsal.sals.sals = (struct symtab_and_line *)
9762             xmalloc (sizeof (struct symtab_and_line));
9763
9764           /* Set sal's pspace, pc, symtab, and line to the values
9765              corresponding to the last call to print_frame_info.
9766              Be sure to reinitialize LINE with NOTCURRENT == 0
9767              as the breakpoint line number is inappropriate otherwise.
9768              find_pc_line would adjust PC, re-set it back.  */
9769           get_last_displayed_sal (&sal);
9770           pc = sal.pc;
9771           sal = find_pc_line (pc, 0);
9772
9773           /* "break" without arguments is equivalent to "break *PC"
9774              where PC is the last displayed codepoint's address.  So
9775              make sure to set sal.explicit_pc to prevent GDB from
9776              trying to expand the list of sals to include all other
9777              instances with the same symtab and line.  */
9778           sal.pc = pc;
9779           sal.explicit_pc = 1;
9780
9781           lsal.sals.sals[0] = sal;
9782           lsal.sals.nelts = 1;
9783           lsal.canonical = NULL;
9784
9785           VEC_safe_push (linespec_sals, canonical->sals, &lsal);
9786         }
9787       else
9788         error (_("No default breakpoint address now."));
9789     }
9790   else
9791     {
9792       struct symtab_and_line cursal = get_current_source_symtab_and_line ();
9793
9794       /* Force almost all breakpoints to be in terms of the
9795          current_source_symtab (which is decode_line_1's default).
9796          This should produce the results we want almost all of the
9797          time while leaving default_breakpoint_* alone.
9798
9799          ObjC: However, don't match an Objective-C method name which
9800          may have a '+' or '-' succeeded by a '['.  */
9801       if (last_displayed_sal_is_valid ()
9802           && (!cursal.symtab
9803               || ((strchr ("+-", (*address)[0]) != NULL)
9804                   && ((*address)[1] != '['))))
9805         decode_line_full (address, DECODE_LINE_FUNFIRSTLINE,
9806                           get_last_displayed_symtab (),
9807                           get_last_displayed_line (),
9808                           canonical, NULL, NULL);
9809       else
9810         decode_line_full (address, DECODE_LINE_FUNFIRSTLINE,
9811                           cursal.symtab, cursal.line, canonical, NULL, NULL);
9812     }
9813 }
9814
9815
9816 /* Convert each SAL into a real PC.  Verify that the PC can be
9817    inserted as a breakpoint.  If it can't throw an error.  */
9818
9819 static void
9820 breakpoint_sals_to_pc (struct symtabs_and_lines *sals)
9821 {    
9822   int i;
9823
9824   for (i = 0; i < sals->nelts; i++)
9825     resolve_sal_pc (&sals->sals[i]);
9826 }
9827
9828 /* Fast tracepoints may have restrictions on valid locations.  For
9829    instance, a fast tracepoint using a jump instead of a trap will
9830    likely have to overwrite more bytes than a trap would, and so can
9831    only be placed where the instruction is longer than the jump, or a
9832    multi-instruction sequence does not have a jump into the middle of
9833    it, etc.  */
9834
9835 static void
9836 check_fast_tracepoint_sals (struct gdbarch *gdbarch,
9837                             struct symtabs_and_lines *sals)
9838 {
9839   int i, rslt;
9840   struct symtab_and_line *sal;
9841   char *msg;
9842   struct cleanup *old_chain;
9843
9844   for (i = 0; i < sals->nelts; i++)
9845     {
9846       struct gdbarch *sarch;
9847
9848       sal = &sals->sals[i];
9849
9850       sarch = get_sal_arch (*sal);
9851       /* We fall back to GDBARCH if there is no architecture
9852          associated with SAL.  */
9853       if (sarch == NULL)
9854         sarch = gdbarch;
9855       rslt = gdbarch_fast_tracepoint_valid_at (sarch, sal->pc,
9856                                                NULL, &msg);
9857       old_chain = make_cleanup (xfree, msg);
9858
9859       if (!rslt)
9860         error (_("May not have a fast tracepoint at 0x%s%s"),
9861                paddress (sarch, sal->pc), (msg ? msg : ""));
9862
9863       do_cleanups (old_chain);
9864     }
9865 }
9866
9867 /* Issue an invalid thread ID error.  */
9868
9869 static void ATTRIBUTE_NORETURN
9870 invalid_thread_id_error (int id)
9871 {
9872   error (_("Unknown thread %d."), id);
9873 }
9874
9875 /* Given TOK, a string specification of condition and thread, as
9876    accepted by the 'break' command, extract the condition
9877    string and thread number and set *COND_STRING and *THREAD.
9878    PC identifies the context at which the condition should be parsed.
9879    If no condition is found, *COND_STRING is set to NULL.
9880    If no thread is found, *THREAD is set to -1.  */
9881
9882 static void
9883 find_condition_and_thread (const char *tok, CORE_ADDR pc,
9884                            char **cond_string, int *thread, int *task,
9885                            char **rest)
9886 {
9887   *cond_string = NULL;
9888   *thread = -1;
9889   *task = 0;
9890   *rest = NULL;
9891
9892   while (tok && *tok)
9893     {
9894       const char *end_tok;
9895       int toklen;
9896       const char *cond_start = NULL;
9897       const char *cond_end = NULL;
9898
9899       tok = skip_spaces_const (tok);
9900
9901       if ((*tok == '"' || *tok == ',') && rest)
9902         {
9903           *rest = savestring (tok, strlen (tok));
9904           return;
9905         }
9906
9907       end_tok = skip_to_space_const (tok);
9908
9909       toklen = end_tok - tok;
9910
9911       if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
9912         {
9913           struct expression *expr;
9914
9915           tok = cond_start = end_tok + 1;
9916           expr = parse_exp_1 (&tok, pc, block_for_pc (pc), 0);
9917           xfree (expr);
9918           cond_end = tok;
9919           *cond_string = savestring (cond_start, cond_end - cond_start);
9920         }
9921       else if (toklen >= 1 && strncmp (tok, "thread", toklen) == 0)
9922         {
9923           char *tmptok;
9924
9925           tok = end_tok + 1;
9926           *thread = strtol (tok, &tmptok, 0);
9927           if (tok == tmptok)
9928             error (_("Junk after thread keyword."));
9929           if (!valid_thread_id (*thread))
9930             invalid_thread_id_error (*thread);
9931           tok = tmptok;
9932         }
9933       else if (toklen >= 1 && strncmp (tok, "task", toklen) == 0)
9934         {
9935           char *tmptok;
9936
9937           tok = end_tok + 1;
9938           *task = strtol (tok, &tmptok, 0);
9939           if (tok == tmptok)
9940             error (_("Junk after task keyword."));
9941           if (!valid_task_id (*task))
9942             error (_("Unknown task %d."), *task);
9943           tok = tmptok;
9944         }
9945       else if (rest)
9946         {
9947           *rest = savestring (tok, strlen (tok));
9948           return;
9949         }
9950       else
9951         error (_("Junk at end of arguments."));
9952     }
9953 }
9954
9955 /* Decode a static tracepoint marker spec.  */
9956
9957 static struct symtabs_and_lines
9958 decode_static_tracepoint_spec (char **arg_p)
9959 {
9960   VEC(static_tracepoint_marker_p) *markers = NULL;
9961   struct symtabs_and_lines sals;
9962   struct cleanup *old_chain;
9963   char *p = &(*arg_p)[3];
9964   char *endp;
9965   char *marker_str;
9966   int i;
9967
9968   p = skip_spaces (p);
9969
9970   endp = skip_to_space (p);
9971
9972   marker_str = savestring (p, endp - p);
9973   old_chain = make_cleanup (xfree, marker_str);
9974
9975   markers = target_static_tracepoint_markers_by_strid (marker_str);
9976   if (VEC_empty(static_tracepoint_marker_p, markers))
9977     error (_("No known static tracepoint marker named %s"), marker_str);
9978
9979   sals.nelts = VEC_length(static_tracepoint_marker_p, markers);
9980   sals.sals = xmalloc (sizeof *sals.sals * sals.nelts);
9981
9982   for (i = 0; i < sals.nelts; i++)
9983     {
9984       struct static_tracepoint_marker *marker;
9985
9986       marker = VEC_index (static_tracepoint_marker_p, markers, i);
9987
9988       init_sal (&sals.sals[i]);
9989
9990       sals.sals[i] = find_pc_line (marker->address, 0);
9991       sals.sals[i].pc = marker->address;
9992
9993       release_static_tracepoint_marker (marker);
9994     }
9995
9996   do_cleanups (old_chain);
9997
9998   *arg_p = endp;
9999   return sals;
10000 }
10001
10002 /* Set a breakpoint.  This function is shared between CLI and MI
10003    functions for setting a breakpoint.  This function has two major
10004    modes of operations, selected by the PARSE_ARG parameter.  If
10005    non-zero, the function will parse ARG, extracting location,
10006    condition, thread and extra string.  Otherwise, ARG is just the
10007    breakpoint's location, with condition, thread, and extra string
10008    specified by the COND_STRING, THREAD and EXTRA_STRING parameters.
10009    If INTERNAL is non-zero, the breakpoint number will be allocated
10010    from the internal breakpoint count.  Returns true if any breakpoint
10011    was created; false otherwise.  */
10012
10013 int
10014 create_breakpoint (struct gdbarch *gdbarch,
10015                    char *arg, char *cond_string,
10016                    int thread, char *extra_string,
10017                    int parse_arg,
10018                    int tempflag, enum bptype type_wanted,
10019                    int ignore_count,
10020                    enum auto_boolean pending_break_support,
10021                    const struct breakpoint_ops *ops,
10022                    int from_tty, int enabled, int internal,
10023                    unsigned flags)
10024 {
10025   char *copy_arg = NULL;
10026   char *addr_start = arg;
10027   struct linespec_result canonical;
10028   struct cleanup *old_chain;
10029   struct cleanup *bkpt_chain = NULL;
10030   int pending = 0;
10031   int task = 0;
10032   int prev_bkpt_count = breakpoint_count;
10033
10034   gdb_assert (ops != NULL);
10035
10036   init_linespec_result (&canonical);
10037
10038   TRY
10039     {
10040       ops->create_sals_from_address (&arg, &canonical, type_wanted,
10041                                      addr_start, &copy_arg);
10042     }
10043   CATCH (e, RETURN_MASK_ERROR)
10044     {
10045       /* If caller is interested in rc value from parse, set
10046          value.  */
10047       if (e.error == NOT_FOUND_ERROR)
10048         {
10049           /* If pending breakpoint support is turned off, throw
10050              error.  */
10051
10052           if (pending_break_support == AUTO_BOOLEAN_FALSE)
10053             throw_exception (e);
10054
10055           exception_print (gdb_stderr, e);
10056
10057           /* If pending breakpoint support is auto query and the user
10058              selects no, then simply return the error code.  */
10059           if (pending_break_support == AUTO_BOOLEAN_AUTO
10060               && !nquery (_("Make %s pending on future shared library load? "),
10061                           bptype_string (type_wanted)))
10062             return 0;
10063
10064           /* At this point, either the user was queried about setting
10065              a pending breakpoint and selected yes, or pending
10066              breakpoint behavior is on and thus a pending breakpoint
10067              is defaulted on behalf of the user.  */
10068           {
10069             struct linespec_sals lsal;
10070
10071             copy_arg = xstrdup (addr_start);
10072             lsal.canonical = xstrdup (copy_arg);
10073             lsal.sals.nelts = 1;
10074             lsal.sals.sals = XNEW (struct symtab_and_line);
10075             init_sal (&lsal.sals.sals[0]);
10076             pending = 1;
10077             VEC_safe_push (linespec_sals, canonical.sals, &lsal);
10078           }
10079         }
10080       else
10081         throw_exception (e);
10082     }
10083   END_CATCH
10084
10085   if (VEC_empty (linespec_sals, canonical.sals))
10086     return 0;
10087
10088   /* Create a chain of things that always need to be cleaned up.  */
10089   old_chain = make_cleanup_destroy_linespec_result (&canonical);
10090
10091   /* ----------------------------- SNIP -----------------------------
10092      Anything added to the cleanup chain beyond this point is assumed
10093      to be part of a breakpoint.  If the breakpoint create succeeds
10094      then the memory is not reclaimed.  */
10095   bkpt_chain = make_cleanup (null_cleanup, 0);
10096
10097   /* Resolve all line numbers to PC's and verify that the addresses
10098      are ok for the target.  */
10099   if (!pending)
10100     {
10101       int ix;
10102       struct linespec_sals *iter;
10103
10104       for (ix = 0; VEC_iterate (linespec_sals, canonical.sals, ix, iter); ++ix)
10105         breakpoint_sals_to_pc (&iter->sals);
10106     }
10107
10108   /* Fast tracepoints may have additional restrictions on location.  */
10109   if (!pending && type_wanted == bp_fast_tracepoint)
10110     {
10111       int ix;
10112       struct linespec_sals *iter;
10113
10114       for (ix = 0; VEC_iterate (linespec_sals, canonical.sals, ix, iter); ++ix)
10115         check_fast_tracepoint_sals (gdbarch, &iter->sals);
10116     }
10117
10118   /* Verify that condition can be parsed, before setting any
10119      breakpoints.  Allocate a separate condition expression for each
10120      breakpoint.  */
10121   if (!pending)
10122     {
10123       if (parse_arg)
10124         {
10125           char *rest;
10126           struct linespec_sals *lsal;
10127
10128           lsal = VEC_index (linespec_sals, canonical.sals, 0);
10129
10130           /* Here we only parse 'arg' to separate condition
10131              from thread number, so parsing in context of first
10132              sal is OK.  When setting the breakpoint we'll
10133              re-parse it in context of each sal.  */
10134
10135           find_condition_and_thread (arg, lsal->sals.sals[0].pc, &cond_string,
10136                                      &thread, &task, &rest);
10137           if (cond_string)
10138             make_cleanup (xfree, cond_string);
10139           if (rest)
10140             make_cleanup (xfree, rest);
10141           if (rest)
10142             extra_string = rest;
10143         }
10144       else
10145         {
10146           if (*arg != '\0')
10147             error (_("Garbage '%s' at end of location"), arg);
10148
10149           /* Create a private copy of condition string.  */
10150           if (cond_string)
10151             {
10152               cond_string = xstrdup (cond_string);
10153               make_cleanup (xfree, cond_string);
10154             }
10155           /* Create a private copy of any extra string.  */
10156           if (extra_string)
10157             {
10158               extra_string = xstrdup (extra_string);
10159               make_cleanup (xfree, extra_string);
10160             }
10161         }
10162
10163       ops->create_breakpoints_sal (gdbarch, &canonical,
10164                                    cond_string, extra_string, type_wanted,
10165                                    tempflag ? disp_del : disp_donttouch,
10166                                    thread, task, ignore_count, ops,
10167                                    from_tty, enabled, internal, flags);
10168     }
10169   else
10170     {
10171       struct breakpoint *b;
10172
10173       make_cleanup (xfree, copy_arg);
10174
10175       if (is_tracepoint_type (type_wanted))
10176         {
10177           struct tracepoint *t;
10178
10179           t = XCNEW (struct tracepoint);
10180           b = &t->base;
10181         }
10182       else
10183         b = XNEW (struct breakpoint);
10184
10185       init_raw_breakpoint_without_location (b, gdbarch, type_wanted, ops);
10186
10187       b->addr_string = copy_arg;
10188       if (parse_arg)
10189         b->cond_string = NULL;
10190       else
10191         {
10192           /* Create a private copy of condition string.  */
10193           if (cond_string)
10194             {
10195               cond_string = xstrdup (cond_string);
10196               make_cleanup (xfree, cond_string);
10197             }
10198           b->cond_string = cond_string;
10199         }
10200       b->extra_string = NULL;
10201       b->ignore_count = ignore_count;
10202       b->disposition = tempflag ? disp_del : disp_donttouch;
10203       b->condition_not_parsed = 1;
10204       b->enable_state = enabled ? bp_enabled : bp_disabled;
10205       if ((type_wanted != bp_breakpoint
10206            && type_wanted != bp_hardware_breakpoint) || thread != -1)
10207         b->pspace = current_program_space;
10208
10209       install_breakpoint (internal, b, 0);
10210     }
10211   
10212   if (VEC_length (linespec_sals, canonical.sals) > 1)
10213     {
10214       warning (_("Multiple breakpoints were set.\nUse the "
10215                  "\"delete\" command to delete unwanted breakpoints."));
10216       prev_breakpoint_count = prev_bkpt_count;
10217     }
10218
10219   /* That's it.  Discard the cleanups for data inserted into the
10220      breakpoint.  */
10221   discard_cleanups (bkpt_chain);
10222   /* But cleanup everything else.  */
10223   do_cleanups (old_chain);
10224
10225   /* error call may happen here - have BKPT_CHAIN already discarded.  */
10226   update_global_location_list (UGLL_MAY_INSERT);
10227
10228   return 1;
10229 }
10230
10231 /* Set a breakpoint.
10232    ARG is a string describing breakpoint address,
10233    condition, and thread.
10234    FLAG specifies if a breakpoint is hardware on,
10235    and if breakpoint is temporary, using BP_HARDWARE_FLAG
10236    and BP_TEMPFLAG.  */
10237
10238 static void
10239 break_command_1 (char *arg, int flag, int from_tty)
10240 {
10241   int tempflag = flag & BP_TEMPFLAG;
10242   enum bptype type_wanted = (flag & BP_HARDWAREFLAG
10243                              ? bp_hardware_breakpoint
10244                              : bp_breakpoint);
10245   struct breakpoint_ops *ops;
10246   const char *arg_cp = arg;
10247
10248   /* Matching breakpoints on probes.  */
10249   if (arg && probe_linespec_to_ops (&arg_cp) != NULL)
10250     ops = &bkpt_probe_breakpoint_ops;
10251   else
10252     ops = &bkpt_breakpoint_ops;
10253
10254   create_breakpoint (get_current_arch (),
10255                      arg,
10256                      NULL, 0, NULL, 1 /* parse arg */,
10257                      tempflag, type_wanted,
10258                      0 /* Ignore count */,
10259                      pending_break_support,
10260                      ops,
10261                      from_tty,
10262                      1 /* enabled */,
10263                      0 /* internal */,
10264                      0);
10265 }
10266
10267 /* Helper function for break_command_1 and disassemble_command.  */
10268
10269 void
10270 resolve_sal_pc (struct symtab_and_line *sal)
10271 {
10272   CORE_ADDR pc;
10273
10274   if (sal->pc == 0 && sal->symtab != NULL)
10275     {
10276       if (!find_line_pc (sal->symtab, sal->line, &pc))
10277         error (_("No line %d in file \"%s\"."),
10278                sal->line, symtab_to_filename_for_display (sal->symtab));
10279       sal->pc = pc;
10280
10281       /* If this SAL corresponds to a breakpoint inserted using a line
10282          number, then skip the function prologue if necessary.  */
10283       if (sal->explicit_line)
10284         skip_prologue_sal (sal);
10285     }
10286
10287   if (sal->section == 0 && sal->symtab != NULL)
10288     {
10289       const struct blockvector *bv;
10290       const struct block *b;
10291       struct symbol *sym;
10292
10293       bv = blockvector_for_pc_sect (sal->pc, 0, &b,
10294                                     SYMTAB_COMPUNIT (sal->symtab));
10295       if (bv != NULL)
10296         {
10297           sym = block_linkage_function (b);
10298           if (sym != NULL)
10299             {
10300               fixup_symbol_section (sym, SYMTAB_OBJFILE (sal->symtab));
10301               sal->section = SYMBOL_OBJ_SECTION (SYMTAB_OBJFILE (sal->symtab),
10302                                                  sym);
10303             }
10304           else
10305             {
10306               /* It really is worthwhile to have the section, so we'll
10307                  just have to look harder. This case can be executed
10308                  if we have line numbers but no functions (as can
10309                  happen in assembly source).  */
10310
10311               struct bound_minimal_symbol msym;
10312               struct cleanup *old_chain = save_current_space_and_thread ();
10313
10314               switch_to_program_space_and_thread (sal->pspace);
10315
10316               msym = lookup_minimal_symbol_by_pc (sal->pc);
10317               if (msym.minsym)
10318                 sal->section = MSYMBOL_OBJ_SECTION (msym.objfile, msym.minsym);
10319
10320               do_cleanups (old_chain);
10321             }
10322         }
10323     }
10324 }
10325
10326 void
10327 break_command (char *arg, int from_tty)
10328 {
10329   break_command_1 (arg, 0, from_tty);
10330 }
10331
10332 void
10333 tbreak_command (char *arg, int from_tty)
10334 {
10335   break_command_1 (arg, BP_TEMPFLAG, from_tty);
10336 }
10337
10338 static void
10339 hbreak_command (char *arg, int from_tty)
10340 {
10341   break_command_1 (arg, BP_HARDWAREFLAG, from_tty);
10342 }
10343
10344 static void
10345 thbreak_command (char *arg, int from_tty)
10346 {
10347   break_command_1 (arg, (BP_TEMPFLAG | BP_HARDWAREFLAG), from_tty);
10348 }
10349
10350 static void
10351 stop_command (char *arg, int from_tty)
10352 {
10353   printf_filtered (_("Specify the type of breakpoint to set.\n\
10354 Usage: stop in <function | address>\n\
10355        stop at <line>\n"));
10356 }
10357
10358 static void
10359 stopin_command (char *arg, int from_tty)
10360 {
10361   int badInput = 0;
10362
10363   if (arg == (char *) NULL)
10364     badInput = 1;
10365   else if (*arg != '*')
10366     {
10367       char *argptr = arg;
10368       int hasColon = 0;
10369
10370       /* Look for a ':'.  If this is a line number specification, then
10371          say it is bad, otherwise, it should be an address or
10372          function/method name.  */
10373       while (*argptr && !hasColon)
10374         {
10375           hasColon = (*argptr == ':');
10376           argptr++;
10377         }
10378
10379       if (hasColon)
10380         badInput = (*argptr != ':');    /* Not a class::method */
10381       else
10382         badInput = isdigit (*arg);      /* a simple line number */
10383     }
10384
10385   if (badInput)
10386     printf_filtered (_("Usage: stop in <function | address>\n"));
10387   else
10388     break_command_1 (arg, 0, from_tty);
10389 }
10390
10391 static void
10392 stopat_command (char *arg, int from_tty)
10393 {
10394   int badInput = 0;
10395
10396   if (arg == (char *) NULL || *arg == '*')      /* no line number */
10397     badInput = 1;
10398   else
10399     {
10400       char *argptr = arg;
10401       int hasColon = 0;
10402
10403       /* Look for a ':'.  If there is a '::' then get out, otherwise
10404          it is probably a line number.  */
10405       while (*argptr && !hasColon)
10406         {
10407           hasColon = (*argptr == ':');
10408           argptr++;
10409         }
10410
10411       if (hasColon)
10412         badInput = (*argptr == ':');    /* we have class::method */
10413       else
10414         badInput = !isdigit (*arg);     /* not a line number */
10415     }
10416
10417   if (badInput)
10418     printf_filtered (_("Usage: stop at <line>\n"));
10419   else
10420     break_command_1 (arg, 0, from_tty);
10421 }
10422
10423 /* The dynamic printf command is mostly like a regular breakpoint, but
10424    with a prewired command list consisting of a single output command,
10425    built from extra arguments supplied on the dprintf command
10426    line.  */
10427
10428 static void
10429 dprintf_command (char *arg, int from_tty)
10430 {
10431   create_breakpoint (get_current_arch (),
10432                      arg,
10433                      NULL, 0, NULL, 1 /* parse arg */,
10434                      0, bp_dprintf,
10435                      0 /* Ignore count */,
10436                      pending_break_support,
10437                      &dprintf_breakpoint_ops,
10438                      from_tty,
10439                      1 /* enabled */,
10440                      0 /* internal */,
10441                      0);
10442 }
10443
10444 static void
10445 agent_printf_command (char *arg, int from_tty)
10446 {
10447   error (_("May only run agent-printf on the target"));
10448 }
10449
10450 /* Implement the "breakpoint_hit" breakpoint_ops method for
10451    ranged breakpoints.  */
10452
10453 static int
10454 breakpoint_hit_ranged_breakpoint (const struct bp_location *bl,
10455                                   struct address_space *aspace,
10456                                   CORE_ADDR bp_addr,
10457                                   const struct target_waitstatus *ws)
10458 {
10459   if (ws->kind != TARGET_WAITKIND_STOPPED
10460       || ws->value.sig != GDB_SIGNAL_TRAP)
10461     return 0;
10462
10463   return breakpoint_address_match_range (bl->pspace->aspace, bl->address,
10464                                          bl->length, aspace, bp_addr);
10465 }
10466
10467 /* Implement the "resources_needed" breakpoint_ops method for
10468    ranged breakpoints.  */
10469
10470 static int
10471 resources_needed_ranged_breakpoint (const struct bp_location *bl)
10472 {
10473   return target_ranged_break_num_registers ();
10474 }
10475
10476 /* Implement the "print_it" breakpoint_ops method for
10477    ranged breakpoints.  */
10478
10479 static enum print_stop_action
10480 print_it_ranged_breakpoint (bpstat bs)
10481 {
10482   struct breakpoint *b = bs->breakpoint_at;
10483   struct bp_location *bl = b->loc;
10484   struct ui_out *uiout = current_uiout;
10485
10486   gdb_assert (b->type == bp_hardware_breakpoint);
10487
10488   /* Ranged breakpoints have only one location.  */
10489   gdb_assert (bl && bl->next == NULL);
10490
10491   annotate_breakpoint (b->number);
10492   if (b->disposition == disp_del)
10493     ui_out_text (uiout, "\nTemporary ranged breakpoint ");
10494   else
10495     ui_out_text (uiout, "\nRanged breakpoint ");
10496   if (ui_out_is_mi_like_p (uiout))
10497     {
10498       ui_out_field_string (uiout, "reason",
10499                       async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
10500       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
10501     }
10502   ui_out_field_int (uiout, "bkptno", b->number);
10503   ui_out_text (uiout, ", ");
10504
10505   return PRINT_SRC_AND_LOC;
10506 }
10507
10508 /* Implement the "print_one" breakpoint_ops method for
10509    ranged breakpoints.  */
10510
10511 static void
10512 print_one_ranged_breakpoint (struct breakpoint *b,
10513                              struct bp_location **last_loc)
10514 {
10515   struct bp_location *bl = b->loc;
10516   struct value_print_options opts;
10517   struct ui_out *uiout = current_uiout;
10518
10519   /* Ranged breakpoints have only one location.  */
10520   gdb_assert (bl && bl->next == NULL);
10521
10522   get_user_print_options (&opts);
10523
10524   if (opts.addressprint)
10525     /* We don't print the address range here, it will be printed later
10526        by print_one_detail_ranged_breakpoint.  */
10527     ui_out_field_skip (uiout, "addr");
10528   annotate_field (5);
10529   print_breakpoint_location (b, bl);
10530   *last_loc = bl;
10531 }
10532
10533 /* Implement the "print_one_detail" breakpoint_ops method for
10534    ranged breakpoints.  */
10535
10536 static void
10537 print_one_detail_ranged_breakpoint (const struct breakpoint *b,
10538                                     struct ui_out *uiout)
10539 {
10540   CORE_ADDR address_start, address_end;
10541   struct bp_location *bl = b->loc;
10542   struct ui_file *stb = mem_fileopen ();
10543   struct cleanup *cleanup = make_cleanup_ui_file_delete (stb);
10544
10545   gdb_assert (bl);
10546
10547   address_start = bl->address;
10548   address_end = address_start + bl->length - 1;
10549
10550   ui_out_text (uiout, "\taddress range: ");
10551   fprintf_unfiltered (stb, "[%s, %s]",
10552                       print_core_address (bl->gdbarch, address_start),
10553                       print_core_address (bl->gdbarch, address_end));
10554   ui_out_field_stream (uiout, "addr", stb);
10555   ui_out_text (uiout, "\n");
10556
10557   do_cleanups (cleanup);
10558 }
10559
10560 /* Implement the "print_mention" breakpoint_ops method for
10561    ranged breakpoints.  */
10562
10563 static void
10564 print_mention_ranged_breakpoint (struct breakpoint *b)
10565 {
10566   struct bp_location *bl = b->loc;
10567   struct ui_out *uiout = current_uiout;
10568
10569   gdb_assert (bl);
10570   gdb_assert (b->type == bp_hardware_breakpoint);
10571
10572   if (ui_out_is_mi_like_p (uiout))
10573     return;
10574
10575   printf_filtered (_("Hardware assisted ranged breakpoint %d from %s to %s."),
10576                    b->number, paddress (bl->gdbarch, bl->address),
10577                    paddress (bl->gdbarch, bl->address + bl->length - 1));
10578 }
10579
10580 /* Implement the "print_recreate" breakpoint_ops method for
10581    ranged breakpoints.  */
10582
10583 static void
10584 print_recreate_ranged_breakpoint (struct breakpoint *b, struct ui_file *fp)
10585 {
10586   fprintf_unfiltered (fp, "break-range %s, %s", b->addr_string,
10587                       b->addr_string_range_end);
10588   print_recreate_thread (b, fp);
10589 }
10590
10591 /* The breakpoint_ops structure to be used in ranged breakpoints.  */
10592
10593 static struct breakpoint_ops ranged_breakpoint_ops;
10594
10595 /* Find the address where the end of the breakpoint range should be
10596    placed, given the SAL of the end of the range.  This is so that if
10597    the user provides a line number, the end of the range is set to the
10598    last instruction of the given line.  */
10599
10600 static CORE_ADDR
10601 find_breakpoint_range_end (struct symtab_and_line sal)
10602 {
10603   CORE_ADDR end;
10604
10605   /* If the user provided a PC value, use it.  Otherwise,
10606      find the address of the end of the given location.  */
10607   if (sal.explicit_pc)
10608     end = sal.pc;
10609   else
10610     {
10611       int ret;
10612       CORE_ADDR start;
10613
10614       ret = find_line_pc_range (sal, &start, &end);
10615       if (!ret)
10616         error (_("Could not find location of the end of the range."));
10617
10618       /* find_line_pc_range returns the start of the next line.  */
10619       end--;
10620     }
10621
10622   return end;
10623 }
10624
10625 /* Implement the "break-range" CLI command.  */
10626
10627 static void
10628 break_range_command (char *arg, int from_tty)
10629 {
10630   char *arg_start, *addr_string_start, *addr_string_end;
10631   struct linespec_result canonical_start, canonical_end;
10632   int bp_count, can_use_bp, length;
10633   CORE_ADDR end;
10634   struct breakpoint *b;
10635   struct symtab_and_line sal_start, sal_end;
10636   struct cleanup *cleanup_bkpt;
10637   struct linespec_sals *lsal_start, *lsal_end;
10638
10639   /* We don't support software ranged breakpoints.  */
10640   if (target_ranged_break_num_registers () < 0)
10641     error (_("This target does not support hardware ranged breakpoints."));
10642
10643   bp_count = hw_breakpoint_used_count ();
10644   bp_count += target_ranged_break_num_registers ();
10645   can_use_bp = target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
10646                                                    bp_count, 0);
10647   if (can_use_bp < 0)
10648     error (_("Hardware breakpoints used exceeds limit."));
10649
10650   arg = skip_spaces (arg);
10651   if (arg == NULL || arg[0] == '\0')
10652     error(_("No address range specified."));
10653
10654   init_linespec_result (&canonical_start);
10655
10656   arg_start = arg;
10657   parse_breakpoint_sals (&arg, &canonical_start);
10658
10659   cleanup_bkpt = make_cleanup_destroy_linespec_result (&canonical_start);
10660
10661   if (arg[0] != ',')
10662     error (_("Too few arguments."));
10663   else if (VEC_empty (linespec_sals, canonical_start.sals))
10664     error (_("Could not find location of the beginning of the range."));
10665
10666   lsal_start = VEC_index (linespec_sals, canonical_start.sals, 0);
10667
10668   if (VEC_length (linespec_sals, canonical_start.sals) > 1
10669       || lsal_start->sals.nelts != 1)
10670     error (_("Cannot create a ranged breakpoint with multiple locations."));
10671
10672   sal_start = lsal_start->sals.sals[0];
10673   addr_string_start = savestring (arg_start, arg - arg_start);
10674   make_cleanup (xfree, addr_string_start);
10675
10676   arg++;        /* Skip the comma.  */
10677   arg = skip_spaces (arg);
10678
10679   /* Parse the end location.  */
10680
10681   init_linespec_result (&canonical_end);
10682   arg_start = arg;
10683
10684   /* We call decode_line_full directly here instead of using
10685      parse_breakpoint_sals because we need to specify the start location's
10686      symtab and line as the default symtab and line for the end of the
10687      range.  This makes it possible to have ranges like "foo.c:27, +14",
10688      where +14 means 14 lines from the start location.  */
10689   decode_line_full (&arg, DECODE_LINE_FUNFIRSTLINE,
10690                     sal_start.symtab, sal_start.line,
10691                     &canonical_end, NULL, NULL);
10692
10693   make_cleanup_destroy_linespec_result (&canonical_end);
10694
10695   if (VEC_empty (linespec_sals, canonical_end.sals))
10696     error (_("Could not find location of the end of the range."));
10697
10698   lsal_end = VEC_index (linespec_sals, canonical_end.sals, 0);
10699   if (VEC_length (linespec_sals, canonical_end.sals) > 1
10700       || lsal_end->sals.nelts != 1)
10701     error (_("Cannot create a ranged breakpoint with multiple locations."));
10702
10703   sal_end = lsal_end->sals.sals[0];
10704   addr_string_end = savestring (arg_start, arg - arg_start);
10705   make_cleanup (xfree, addr_string_end);
10706
10707   end = find_breakpoint_range_end (sal_end);
10708   if (sal_start.pc > end)
10709     error (_("Invalid address range, end precedes start."));
10710
10711   length = end - sal_start.pc + 1;
10712   if (length < 0)
10713     /* Length overflowed.  */
10714     error (_("Address range too large."));
10715   else if (length == 1)
10716     {
10717       /* This range is simple enough to be handled by
10718          the `hbreak' command.  */
10719       hbreak_command (addr_string_start, 1);
10720
10721       do_cleanups (cleanup_bkpt);
10722
10723       return;
10724     }
10725
10726   /* Now set up the breakpoint.  */
10727   b = set_raw_breakpoint (get_current_arch (), sal_start,
10728                           bp_hardware_breakpoint, &ranged_breakpoint_ops);
10729   set_breakpoint_count (breakpoint_count + 1);
10730   b->number = breakpoint_count;
10731   b->disposition = disp_donttouch;
10732   b->addr_string = xstrdup (addr_string_start);
10733   b->addr_string_range_end = xstrdup (addr_string_end);
10734   b->loc->length = length;
10735
10736   do_cleanups (cleanup_bkpt);
10737
10738   mention (b);
10739   observer_notify_breakpoint_created (b);
10740   update_global_location_list (UGLL_MAY_INSERT);
10741 }
10742
10743 /*  Return non-zero if EXP is verified as constant.  Returned zero
10744     means EXP is variable.  Also the constant detection may fail for
10745     some constant expressions and in such case still falsely return
10746     zero.  */
10747
10748 static int
10749 watchpoint_exp_is_const (const struct expression *exp)
10750 {
10751   int i = exp->nelts;
10752
10753   while (i > 0)
10754     {
10755       int oplenp, argsp;
10756
10757       /* We are only interested in the descriptor of each element.  */
10758       operator_length (exp, i, &oplenp, &argsp);
10759       i -= oplenp;
10760
10761       switch (exp->elts[i].opcode)
10762         {
10763         case BINOP_ADD:
10764         case BINOP_SUB:
10765         case BINOP_MUL:
10766         case BINOP_DIV:
10767         case BINOP_REM:
10768         case BINOP_MOD:
10769         case BINOP_LSH:
10770         case BINOP_RSH:
10771         case BINOP_LOGICAL_AND:
10772         case BINOP_LOGICAL_OR:
10773         case BINOP_BITWISE_AND:
10774         case BINOP_BITWISE_IOR:
10775         case BINOP_BITWISE_XOR:
10776         case BINOP_EQUAL:
10777         case BINOP_NOTEQUAL:
10778         case BINOP_LESS:
10779         case BINOP_GTR:
10780         case BINOP_LEQ:
10781         case BINOP_GEQ:
10782         case BINOP_REPEAT:
10783         case BINOP_COMMA:
10784         case BINOP_EXP:
10785         case BINOP_MIN:
10786         case BINOP_MAX:
10787         case BINOP_INTDIV:
10788         case BINOP_CONCAT:
10789         case TERNOP_COND:
10790         case TERNOP_SLICE:
10791
10792         case OP_LONG:
10793         case OP_DOUBLE:
10794         case OP_DECFLOAT:
10795         case OP_LAST:
10796         case OP_COMPLEX:
10797         case OP_STRING:
10798         case OP_ARRAY:
10799         case OP_TYPE:
10800         case OP_TYPEOF:
10801         case OP_DECLTYPE:
10802         case OP_TYPEID:
10803         case OP_NAME:
10804         case OP_OBJC_NSSTRING:
10805
10806         case UNOP_NEG:
10807         case UNOP_LOGICAL_NOT:
10808         case UNOP_COMPLEMENT:
10809         case UNOP_ADDR:
10810         case UNOP_HIGH:
10811         case UNOP_CAST:
10812
10813         case UNOP_CAST_TYPE:
10814         case UNOP_REINTERPRET_CAST:
10815         case UNOP_DYNAMIC_CAST:
10816           /* Unary, binary and ternary operators: We have to check
10817              their operands.  If they are constant, then so is the
10818              result of that operation.  For instance, if A and B are
10819              determined to be constants, then so is "A + B".
10820
10821              UNOP_IND is one exception to the rule above, because the
10822              value of *ADDR is not necessarily a constant, even when
10823              ADDR is.  */
10824           break;
10825
10826         case OP_VAR_VALUE:
10827           /* Check whether the associated symbol is a constant.
10828
10829              We use SYMBOL_CLASS rather than TYPE_CONST because it's
10830              possible that a buggy compiler could mark a variable as
10831              constant even when it is not, and TYPE_CONST would return
10832              true in this case, while SYMBOL_CLASS wouldn't.
10833
10834              We also have to check for function symbols because they
10835              are always constant.  */
10836           {
10837             struct symbol *s = exp->elts[i + 2].symbol;
10838
10839             if (SYMBOL_CLASS (s) != LOC_BLOCK
10840                 && SYMBOL_CLASS (s) != LOC_CONST
10841                 && SYMBOL_CLASS (s) != LOC_CONST_BYTES)
10842               return 0;
10843             break;
10844           }
10845
10846         /* The default action is to return 0 because we are using
10847            the optimistic approach here: If we don't know something,
10848            then it is not a constant.  */
10849         default:
10850           return 0;
10851         }
10852     }
10853
10854   return 1;
10855 }
10856
10857 /* Implement the "dtor" breakpoint_ops method for watchpoints.  */
10858
10859 static void
10860 dtor_watchpoint (struct breakpoint *self)
10861 {
10862   struct watchpoint *w = (struct watchpoint *) self;
10863
10864   xfree (w->cond_exp);
10865   xfree (w->exp);
10866   xfree (w->exp_string);
10867   xfree (w->exp_string_reparse);
10868   value_free (w->val);
10869
10870   base_breakpoint_ops.dtor (self);
10871 }
10872
10873 /* Implement the "re_set" breakpoint_ops method for watchpoints.  */
10874
10875 static void
10876 re_set_watchpoint (struct breakpoint *b)
10877 {
10878   struct watchpoint *w = (struct watchpoint *) b;
10879
10880   /* Watchpoint can be either on expression using entirely global
10881      variables, or it can be on local variables.
10882
10883      Watchpoints of the first kind are never auto-deleted, and even
10884      persist across program restarts.  Since they can use variables
10885      from shared libraries, we need to reparse expression as libraries
10886      are loaded and unloaded.
10887
10888      Watchpoints on local variables can also change meaning as result
10889      of solib event.  For example, if a watchpoint uses both a local
10890      and a global variables in expression, it's a local watchpoint,
10891      but unloading of a shared library will make the expression
10892      invalid.  This is not a very common use case, but we still
10893      re-evaluate expression, to avoid surprises to the user.
10894
10895      Note that for local watchpoints, we re-evaluate it only if
10896      watchpoints frame id is still valid.  If it's not, it means the
10897      watchpoint is out of scope and will be deleted soon.  In fact,
10898      I'm not sure we'll ever be called in this case.
10899
10900      If a local watchpoint's frame id is still valid, then
10901      w->exp_valid_block is likewise valid, and we can safely use it.
10902
10903      Don't do anything about disabled watchpoints, since they will be
10904      reevaluated again when enabled.  */
10905   update_watchpoint (w, 1 /* reparse */);
10906 }
10907
10908 /* Implement the "insert" breakpoint_ops method for hardware watchpoints.  */
10909
10910 static int
10911 insert_watchpoint (struct bp_location *bl)
10912 {
10913   struct watchpoint *w = (struct watchpoint *) bl->owner;
10914   int length = w->exact ? 1 : bl->length;
10915
10916   return target_insert_watchpoint (bl->address, length, bl->watchpoint_type,
10917                                    w->cond_exp);
10918 }
10919
10920 /* Implement the "remove" breakpoint_ops method for hardware watchpoints.  */
10921
10922 static int
10923 remove_watchpoint (struct bp_location *bl)
10924 {
10925   struct watchpoint *w = (struct watchpoint *) bl->owner;
10926   int length = w->exact ? 1 : bl->length;
10927
10928   return target_remove_watchpoint (bl->address, length, bl->watchpoint_type,
10929                                    w->cond_exp);
10930 }
10931
10932 static int
10933 breakpoint_hit_watchpoint (const struct bp_location *bl,
10934                            struct address_space *aspace, CORE_ADDR bp_addr,
10935                            const struct target_waitstatus *ws)
10936 {
10937   struct breakpoint *b = bl->owner;
10938   struct watchpoint *w = (struct watchpoint *) b;
10939
10940   /* Continuable hardware watchpoints are treated as non-existent if the
10941      reason we stopped wasn't a hardware watchpoint (we didn't stop on
10942      some data address).  Otherwise gdb won't stop on a break instruction
10943      in the code (not from a breakpoint) when a hardware watchpoint has
10944      been defined.  Also skip watchpoints which we know did not trigger
10945      (did not match the data address).  */
10946   if (is_hardware_watchpoint (b)
10947       && w->watchpoint_triggered == watch_triggered_no)
10948     return 0;
10949
10950   return 1;
10951 }
10952
10953 static void
10954 check_status_watchpoint (bpstat bs)
10955 {
10956   gdb_assert (is_watchpoint (bs->breakpoint_at));
10957
10958   bpstat_check_watchpoint (bs);
10959 }
10960
10961 /* Implement the "resources_needed" breakpoint_ops method for
10962    hardware watchpoints.  */
10963
10964 static int
10965 resources_needed_watchpoint (const struct bp_location *bl)
10966 {
10967   struct watchpoint *w = (struct watchpoint *) bl->owner;
10968   int length = w->exact? 1 : bl->length;
10969
10970   return target_region_ok_for_hw_watchpoint (bl->address, length);
10971 }
10972
10973 /* Implement the "works_in_software_mode" breakpoint_ops method for
10974    hardware watchpoints.  */
10975
10976 static int
10977 works_in_software_mode_watchpoint (const struct breakpoint *b)
10978 {
10979   /* Read and access watchpoints only work with hardware support.  */
10980   return b->type == bp_watchpoint || b->type == bp_hardware_watchpoint;
10981 }
10982
10983 static enum print_stop_action
10984 print_it_watchpoint (bpstat bs)
10985 {
10986   struct cleanup *old_chain;
10987   struct breakpoint *b;
10988   struct ui_file *stb;
10989   enum print_stop_action result;
10990   struct watchpoint *w;
10991   struct ui_out *uiout = current_uiout;
10992
10993   gdb_assert (bs->bp_location_at != NULL);
10994
10995   b = bs->breakpoint_at;
10996   w = (struct watchpoint *) b;
10997
10998   stb = mem_fileopen ();
10999   old_chain = make_cleanup_ui_file_delete (stb);
11000
11001   switch (b->type)
11002     {
11003     case bp_watchpoint:
11004     case bp_hardware_watchpoint:
11005       annotate_watchpoint (b->number);
11006       if (ui_out_is_mi_like_p (uiout))
11007         ui_out_field_string
11008           (uiout, "reason",
11009            async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
11010       mention (b);
11011       make_cleanup_ui_out_tuple_begin_end (uiout, "value");
11012       ui_out_text (uiout, "\nOld value = ");
11013       watchpoint_value_print (bs->old_val, stb);
11014       ui_out_field_stream (uiout, "old", stb);
11015       ui_out_text (uiout, "\nNew value = ");
11016       watchpoint_value_print (w->val, stb);
11017       ui_out_field_stream (uiout, "new", stb);
11018       ui_out_text (uiout, "\n");
11019       /* More than one watchpoint may have been triggered.  */
11020       result = PRINT_UNKNOWN;
11021       break;
11022
11023     case bp_read_watchpoint:
11024       if (ui_out_is_mi_like_p (uiout))
11025         ui_out_field_string
11026           (uiout, "reason",
11027            async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
11028       mention (b);
11029       make_cleanup_ui_out_tuple_begin_end (uiout, "value");
11030       ui_out_text (uiout, "\nValue = ");
11031       watchpoint_value_print (w->val, stb);
11032       ui_out_field_stream (uiout, "value", stb);
11033       ui_out_text (uiout, "\n");
11034       result = PRINT_UNKNOWN;
11035       break;
11036
11037     case bp_access_watchpoint:
11038       if (bs->old_val != NULL)
11039         {
11040           annotate_watchpoint (b->number);
11041           if (ui_out_is_mi_like_p (uiout))
11042             ui_out_field_string
11043               (uiout, "reason",
11044                async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
11045           mention (b);
11046           make_cleanup_ui_out_tuple_begin_end (uiout, "value");
11047           ui_out_text (uiout, "\nOld value = ");
11048           watchpoint_value_print (bs->old_val, stb);
11049           ui_out_field_stream (uiout, "old", stb);
11050           ui_out_text (uiout, "\nNew value = ");
11051         }
11052       else
11053         {
11054           mention (b);
11055           if (ui_out_is_mi_like_p (uiout))
11056             ui_out_field_string
11057               (uiout, "reason",
11058                async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
11059           make_cleanup_ui_out_tuple_begin_end (uiout, "value");
11060           ui_out_text (uiout, "\nValue = ");
11061         }
11062       watchpoint_value_print (w->val, stb);
11063       ui_out_field_stream (uiout, "new", stb);
11064       ui_out_text (uiout, "\n");
11065       result = PRINT_UNKNOWN;
11066       break;
11067     default:
11068       result = PRINT_UNKNOWN;
11069     }
11070
11071   do_cleanups (old_chain);
11072   return result;
11073 }
11074
11075 /* Implement the "print_mention" breakpoint_ops method for hardware
11076    watchpoints.  */
11077
11078 static void
11079 print_mention_watchpoint (struct breakpoint *b)
11080 {
11081   struct cleanup *ui_out_chain;
11082   struct watchpoint *w = (struct watchpoint *) b;
11083   struct ui_out *uiout = current_uiout;
11084
11085   switch (b->type)
11086     {
11087     case bp_watchpoint:
11088       ui_out_text (uiout, "Watchpoint ");
11089       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "wpt");
11090       break;
11091     case bp_hardware_watchpoint:
11092       ui_out_text (uiout, "Hardware watchpoint ");
11093       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "wpt");
11094       break;
11095     case bp_read_watchpoint:
11096       ui_out_text (uiout, "Hardware read watchpoint ");
11097       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-rwpt");
11098       break;
11099     case bp_access_watchpoint:
11100       ui_out_text (uiout, "Hardware access (read/write) watchpoint ");
11101       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-awpt");
11102       break;
11103     default:
11104       internal_error (__FILE__, __LINE__,
11105                       _("Invalid hardware watchpoint type."));
11106     }
11107
11108   ui_out_field_int (uiout, "number", b->number);
11109   ui_out_text (uiout, ": ");
11110   ui_out_field_string (uiout, "exp", w->exp_string);
11111   do_cleanups (ui_out_chain);
11112 }
11113
11114 /* Implement the "print_recreate" breakpoint_ops method for
11115    watchpoints.  */
11116
11117 static void
11118 print_recreate_watchpoint (struct breakpoint *b, struct ui_file *fp)
11119 {
11120   struct watchpoint *w = (struct watchpoint *) b;
11121
11122   switch (b->type)
11123     {
11124     case bp_watchpoint:
11125     case bp_hardware_watchpoint:
11126       fprintf_unfiltered (fp, "watch");
11127       break;
11128     case bp_read_watchpoint:
11129       fprintf_unfiltered (fp, "rwatch");
11130       break;
11131     case bp_access_watchpoint:
11132       fprintf_unfiltered (fp, "awatch");
11133       break;
11134     default:
11135       internal_error (__FILE__, __LINE__,
11136                       _("Invalid watchpoint type."));
11137     }
11138
11139   fprintf_unfiltered (fp, " %s", w->exp_string);
11140   print_recreate_thread (b, fp);
11141 }
11142
11143 /* Implement the "explains_signal" breakpoint_ops method for
11144    watchpoints.  */
11145
11146 static int
11147 explains_signal_watchpoint (struct breakpoint *b, enum gdb_signal sig)
11148 {
11149   /* A software watchpoint cannot cause a signal other than
11150      GDB_SIGNAL_TRAP.  */
11151   if (b->type == bp_watchpoint && sig != GDB_SIGNAL_TRAP)
11152     return 0;
11153
11154   return 1;
11155 }
11156
11157 /* The breakpoint_ops structure to be used in hardware watchpoints.  */
11158
11159 static struct breakpoint_ops watchpoint_breakpoint_ops;
11160
11161 /* Implement the "insert" breakpoint_ops method for
11162    masked hardware watchpoints.  */
11163
11164 static int
11165 insert_masked_watchpoint (struct bp_location *bl)
11166 {
11167   struct watchpoint *w = (struct watchpoint *) bl->owner;
11168
11169   return target_insert_mask_watchpoint (bl->address, w->hw_wp_mask,
11170                                         bl->watchpoint_type);
11171 }
11172
11173 /* Implement the "remove" breakpoint_ops method for
11174    masked hardware watchpoints.  */
11175
11176 static int
11177 remove_masked_watchpoint (struct bp_location *bl)
11178 {
11179   struct watchpoint *w = (struct watchpoint *) bl->owner;
11180
11181   return target_remove_mask_watchpoint (bl->address, w->hw_wp_mask,
11182                                         bl->watchpoint_type);
11183 }
11184
11185 /* Implement the "resources_needed" breakpoint_ops method for
11186    masked hardware watchpoints.  */
11187
11188 static int
11189 resources_needed_masked_watchpoint (const struct bp_location *bl)
11190 {
11191   struct watchpoint *w = (struct watchpoint *) bl->owner;
11192
11193   return target_masked_watch_num_registers (bl->address, w->hw_wp_mask);
11194 }
11195
11196 /* Implement the "works_in_software_mode" breakpoint_ops method for
11197    masked hardware watchpoints.  */
11198
11199 static int
11200 works_in_software_mode_masked_watchpoint (const struct breakpoint *b)
11201 {
11202   return 0;
11203 }
11204
11205 /* Implement the "print_it" breakpoint_ops method for
11206    masked hardware watchpoints.  */
11207
11208 static enum print_stop_action
11209 print_it_masked_watchpoint (bpstat bs)
11210 {
11211   struct breakpoint *b = bs->breakpoint_at;
11212   struct ui_out *uiout = current_uiout;
11213
11214   /* Masked watchpoints have only one location.  */
11215   gdb_assert (b->loc && b->loc->next == NULL);
11216
11217   switch (b->type)
11218     {
11219     case bp_hardware_watchpoint:
11220       annotate_watchpoint (b->number);
11221       if (ui_out_is_mi_like_p (uiout))
11222         ui_out_field_string
11223           (uiout, "reason",
11224            async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
11225       break;
11226
11227     case bp_read_watchpoint:
11228       if (ui_out_is_mi_like_p (uiout))
11229         ui_out_field_string
11230           (uiout, "reason",
11231            async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
11232       break;
11233
11234     case bp_access_watchpoint:
11235       if (ui_out_is_mi_like_p (uiout))
11236         ui_out_field_string
11237           (uiout, "reason",
11238            async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
11239       break;
11240     default:
11241       internal_error (__FILE__, __LINE__,
11242                       _("Invalid hardware watchpoint type."));
11243     }
11244
11245   mention (b);
11246   ui_out_text (uiout, _("\n\
11247 Check the underlying instruction at PC for the memory\n\
11248 address and value which triggered this watchpoint.\n"));
11249   ui_out_text (uiout, "\n");
11250
11251   /* More than one watchpoint may have been triggered.  */
11252   return PRINT_UNKNOWN;
11253 }
11254
11255 /* Implement the "print_one_detail" breakpoint_ops method for
11256    masked hardware watchpoints.  */
11257
11258 static void
11259 print_one_detail_masked_watchpoint (const struct breakpoint *b,
11260                                     struct ui_out *uiout)
11261 {
11262   struct watchpoint *w = (struct watchpoint *) b;
11263
11264   /* Masked watchpoints have only one location.  */
11265   gdb_assert (b->loc && b->loc->next == NULL);
11266
11267   ui_out_text (uiout, "\tmask ");
11268   ui_out_field_core_addr (uiout, "mask", b->loc->gdbarch, w->hw_wp_mask);
11269   ui_out_text (uiout, "\n");
11270 }
11271
11272 /* Implement the "print_mention" breakpoint_ops method for
11273    masked hardware watchpoints.  */
11274
11275 static void
11276 print_mention_masked_watchpoint (struct breakpoint *b)
11277 {
11278   struct watchpoint *w = (struct watchpoint *) b;
11279   struct ui_out *uiout = current_uiout;
11280   struct cleanup *ui_out_chain;
11281
11282   switch (b->type)
11283     {
11284     case bp_hardware_watchpoint:
11285       ui_out_text (uiout, "Masked hardware watchpoint ");
11286       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "wpt");
11287       break;
11288     case bp_read_watchpoint:
11289       ui_out_text (uiout, "Masked hardware read watchpoint ");
11290       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-rwpt");
11291       break;
11292     case bp_access_watchpoint:
11293       ui_out_text (uiout, "Masked hardware access (read/write) watchpoint ");
11294       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-awpt");
11295       break;
11296     default:
11297       internal_error (__FILE__, __LINE__,
11298                       _("Invalid hardware watchpoint type."));
11299     }
11300
11301   ui_out_field_int (uiout, "number", b->number);
11302   ui_out_text (uiout, ": ");
11303   ui_out_field_string (uiout, "exp", w->exp_string);
11304   do_cleanups (ui_out_chain);
11305 }
11306
11307 /* Implement the "print_recreate" breakpoint_ops method for
11308    masked hardware watchpoints.  */
11309
11310 static void
11311 print_recreate_masked_watchpoint (struct breakpoint *b, struct ui_file *fp)
11312 {
11313   struct watchpoint *w = (struct watchpoint *) b;
11314   char tmp[40];
11315
11316   switch (b->type)
11317     {
11318     case bp_hardware_watchpoint:
11319       fprintf_unfiltered (fp, "watch");
11320       break;
11321     case bp_read_watchpoint:
11322       fprintf_unfiltered (fp, "rwatch");
11323       break;
11324     case bp_access_watchpoint:
11325       fprintf_unfiltered (fp, "awatch");
11326       break;
11327     default:
11328       internal_error (__FILE__, __LINE__,
11329                       _("Invalid hardware watchpoint type."));
11330     }
11331
11332   sprintf_vma (tmp, w->hw_wp_mask);
11333   fprintf_unfiltered (fp, " %s mask 0x%s", w->exp_string, tmp);
11334   print_recreate_thread (b, fp);
11335 }
11336
11337 /* The breakpoint_ops structure to be used in masked hardware watchpoints.  */
11338
11339 static struct breakpoint_ops masked_watchpoint_breakpoint_ops;
11340
11341 /* Tell whether the given watchpoint is a masked hardware watchpoint.  */
11342
11343 static int
11344 is_masked_watchpoint (const struct breakpoint *b)
11345 {
11346   return b->ops == &masked_watchpoint_breakpoint_ops;
11347 }
11348
11349 /* accessflag:  hw_write:  watch write, 
11350                 hw_read:   watch read, 
11351                 hw_access: watch access (read or write) */
11352 static void
11353 watch_command_1 (const char *arg, int accessflag, int from_tty,
11354                  int just_location, int internal)
11355 {
11356   struct breakpoint *b, *scope_breakpoint = NULL;
11357   struct expression *exp;
11358   const struct block *exp_valid_block = NULL, *cond_exp_valid_block = NULL;
11359   struct value *val, *mark, *result;
11360   int saved_bitpos = 0, saved_bitsize = 0;
11361   struct frame_info *frame;
11362   const char *exp_start = NULL;
11363   const char *exp_end = NULL;
11364   const char *tok, *end_tok;
11365   int toklen = -1;
11366   const char *cond_start = NULL;
11367   const char *cond_end = NULL;
11368   enum bptype bp_type;
11369   int thread = -1;
11370   int pc = 0;
11371   /* Flag to indicate whether we are going to use masks for
11372      the hardware watchpoint.  */
11373   int use_mask = 0;
11374   CORE_ADDR mask = 0;
11375   struct watchpoint *w;
11376   char *expression;
11377   struct cleanup *back_to;
11378
11379   /* Make sure that we actually have parameters to parse.  */
11380   if (arg != NULL && arg[0] != '\0')
11381     {
11382       const char *value_start;
11383
11384       exp_end = arg + strlen (arg);
11385
11386       /* Look for "parameter value" pairs at the end
11387          of the arguments string.  */
11388       for (tok = exp_end - 1; tok > arg; tok--)
11389         {
11390           /* Skip whitespace at the end of the argument list.  */
11391           while (tok > arg && (*tok == ' ' || *tok == '\t'))
11392             tok--;
11393
11394           /* Find the beginning of the last token.
11395              This is the value of the parameter.  */
11396           while (tok > arg && (*tok != ' ' && *tok != '\t'))
11397             tok--;
11398           value_start = tok + 1;
11399
11400           /* Skip whitespace.  */
11401           while (tok > arg && (*tok == ' ' || *tok == '\t'))
11402             tok--;
11403
11404           end_tok = tok;
11405
11406           /* Find the beginning of the second to last token.
11407              This is the parameter itself.  */
11408           while (tok > arg && (*tok != ' ' && *tok != '\t'))
11409             tok--;
11410           tok++;
11411           toklen = end_tok - tok + 1;
11412
11413           if (toklen == 6 && startswith (tok, "thread"))
11414             {
11415               /* At this point we've found a "thread" token, which means
11416                  the user is trying to set a watchpoint that triggers
11417                  only in a specific thread.  */
11418               char *endp;
11419
11420               if (thread != -1)
11421                 error(_("You can specify only one thread."));
11422
11423               /* Extract the thread ID from the next token.  */
11424               thread = strtol (value_start, &endp, 0);
11425
11426               /* Check if the user provided a valid numeric value for the
11427                  thread ID.  */
11428               if (*endp != ' ' && *endp != '\t' && *endp != '\0')
11429                 error (_("Invalid thread ID specification %s."), value_start);
11430
11431               /* Check if the thread actually exists.  */
11432               if (!valid_thread_id (thread))
11433                 invalid_thread_id_error (thread);
11434             }
11435           else if (toklen == 4 && startswith (tok, "mask"))
11436             {
11437               /* We've found a "mask" token, which means the user wants to
11438                  create a hardware watchpoint that is going to have the mask
11439                  facility.  */
11440               struct value *mask_value, *mark;
11441
11442               if (use_mask)
11443                 error(_("You can specify only one mask."));
11444
11445               use_mask = just_location = 1;
11446
11447               mark = value_mark ();
11448               mask_value = parse_to_comma_and_eval (&value_start);
11449               mask = value_as_address (mask_value);
11450               value_free_to_mark (mark);
11451             }
11452           else
11453             /* We didn't recognize what we found.  We should stop here.  */
11454             break;
11455
11456           /* Truncate the string and get rid of the "parameter value" pair before
11457              the arguments string is parsed by the parse_exp_1 function.  */
11458           exp_end = tok;
11459         }
11460     }
11461   else
11462     exp_end = arg;
11463
11464   /* Parse the rest of the arguments.  From here on out, everything
11465      is in terms of a newly allocated string instead of the original
11466      ARG.  */
11467   innermost_block = NULL;
11468   expression = savestring (arg, exp_end - arg);
11469   back_to = make_cleanup (xfree, expression);
11470   exp_start = arg = expression;
11471   exp = parse_exp_1 (&arg, 0, 0, 0);
11472   exp_end = arg;
11473   /* Remove trailing whitespace from the expression before saving it.
11474      This makes the eventual display of the expression string a bit
11475      prettier.  */
11476   while (exp_end > exp_start && (exp_end[-1] == ' ' || exp_end[-1] == '\t'))
11477     --exp_end;
11478
11479   /* Checking if the expression is not constant.  */
11480   if (watchpoint_exp_is_const (exp))
11481     {
11482       int len;
11483
11484       len = exp_end - exp_start;
11485       while (len > 0 && isspace (exp_start[len - 1]))
11486         len--;
11487       error (_("Cannot watch constant value `%.*s'."), len, exp_start);
11488     }
11489
11490   exp_valid_block = innermost_block;
11491   mark = value_mark ();
11492   fetch_subexp_value (exp, &pc, &val, &result, NULL, just_location);
11493
11494   if (val != NULL && just_location)
11495     {
11496       saved_bitpos = value_bitpos (val);
11497       saved_bitsize = value_bitsize (val);
11498     }
11499
11500   if (just_location)
11501     {
11502       int ret;
11503
11504       exp_valid_block = NULL;
11505       val = value_addr (result);
11506       release_value (val);
11507       value_free_to_mark (mark);
11508
11509       if (use_mask)
11510         {
11511           ret = target_masked_watch_num_registers (value_as_address (val),
11512                                                    mask);
11513           if (ret == -1)
11514             error (_("This target does not support masked watchpoints."));
11515           else if (ret == -2)
11516             error (_("Invalid mask or memory region."));
11517         }
11518     }
11519   else if (val != NULL)
11520     release_value (val);
11521
11522   tok = skip_spaces_const (arg);
11523   end_tok = skip_to_space_const (tok);
11524
11525   toklen = end_tok - tok;
11526   if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
11527     {
11528       struct expression *cond;
11529
11530       innermost_block = NULL;
11531       tok = cond_start = end_tok + 1;
11532       cond = parse_exp_1 (&tok, 0, 0, 0);
11533
11534       /* The watchpoint expression may not be local, but the condition
11535          may still be.  E.g.: `watch global if local > 0'.  */
11536       cond_exp_valid_block = innermost_block;
11537
11538       xfree (cond);
11539       cond_end = tok;
11540     }
11541   if (*tok)
11542     error (_("Junk at end of command."));
11543
11544   frame = block_innermost_frame (exp_valid_block);
11545
11546   /* If the expression is "local", then set up a "watchpoint scope"
11547      breakpoint at the point where we've left the scope of the watchpoint
11548      expression.  Create the scope breakpoint before the watchpoint, so
11549      that we will encounter it first in bpstat_stop_status.  */
11550   if (exp_valid_block && frame)
11551     {
11552       if (frame_id_p (frame_unwind_caller_id (frame)))
11553         {
11554           scope_breakpoint
11555             = create_internal_breakpoint (frame_unwind_caller_arch (frame),
11556                                           frame_unwind_caller_pc (frame),
11557                                           bp_watchpoint_scope,
11558                                           &momentary_breakpoint_ops);
11559
11560           scope_breakpoint->enable_state = bp_enabled;
11561
11562           /* Automatically delete the breakpoint when it hits.  */
11563           scope_breakpoint->disposition = disp_del;
11564
11565           /* Only break in the proper frame (help with recursion).  */
11566           scope_breakpoint->frame_id = frame_unwind_caller_id (frame);
11567
11568           /* Set the address at which we will stop.  */
11569           scope_breakpoint->loc->gdbarch
11570             = frame_unwind_caller_arch (frame);
11571           scope_breakpoint->loc->requested_address
11572             = frame_unwind_caller_pc (frame);
11573           scope_breakpoint->loc->address
11574             = adjust_breakpoint_address (scope_breakpoint->loc->gdbarch,
11575                                          scope_breakpoint->loc->requested_address,
11576                                          scope_breakpoint->type);
11577         }
11578     }
11579
11580   /* Now set up the breakpoint.  We create all watchpoints as hardware
11581      watchpoints here even if hardware watchpoints are turned off, a call
11582      to update_watchpoint later in this function will cause the type to
11583      drop back to bp_watchpoint (software watchpoint) if required.  */
11584
11585   if (accessflag == hw_read)
11586     bp_type = bp_read_watchpoint;
11587   else if (accessflag == hw_access)
11588     bp_type = bp_access_watchpoint;
11589   else
11590     bp_type = bp_hardware_watchpoint;
11591
11592   w = XCNEW (struct watchpoint);
11593   b = &w->base;
11594   if (use_mask)
11595     init_raw_breakpoint_without_location (b, NULL, bp_type,
11596                                           &masked_watchpoint_breakpoint_ops);
11597   else
11598     init_raw_breakpoint_without_location (b, NULL, bp_type,
11599                                           &watchpoint_breakpoint_ops);
11600   b->thread = thread;
11601   b->disposition = disp_donttouch;
11602   b->pspace = current_program_space;
11603   w->exp = exp;
11604   w->exp_valid_block = exp_valid_block;
11605   w->cond_exp_valid_block = cond_exp_valid_block;
11606   if (just_location)
11607     {
11608       struct type *t = value_type (val);
11609       CORE_ADDR addr = value_as_address (val);
11610       char *name;
11611
11612       t = check_typedef (TYPE_TARGET_TYPE (check_typedef (t)));
11613       name = type_to_string (t);
11614
11615       w->exp_string_reparse = xstrprintf ("* (%s *) %s", name,
11616                                           core_addr_to_string (addr));
11617       xfree (name);
11618
11619       w->exp_string = xstrprintf ("-location %.*s",
11620                                   (int) (exp_end - exp_start), exp_start);
11621
11622       /* The above expression is in C.  */
11623       b->language = language_c;
11624     }
11625   else
11626     w->exp_string = savestring (exp_start, exp_end - exp_start);
11627
11628   if (use_mask)
11629     {
11630       w->hw_wp_mask = mask;
11631     }
11632   else
11633     {
11634       w->val = val;
11635       w->val_bitpos = saved_bitpos;
11636       w->val_bitsize = saved_bitsize;
11637       w->val_valid = 1;
11638     }
11639
11640   if (cond_start)
11641     b->cond_string = savestring (cond_start, cond_end - cond_start);
11642   else
11643     b->cond_string = 0;
11644
11645   if (frame)
11646     {
11647       w->watchpoint_frame = get_frame_id (frame);
11648       w->watchpoint_thread = inferior_ptid;
11649     }
11650   else
11651     {
11652       w->watchpoint_frame = null_frame_id;
11653       w->watchpoint_thread = null_ptid;
11654     }
11655
11656   if (scope_breakpoint != NULL)
11657     {
11658       /* The scope breakpoint is related to the watchpoint.  We will
11659          need to act on them together.  */
11660       b->related_breakpoint = scope_breakpoint;
11661       scope_breakpoint->related_breakpoint = b;
11662     }
11663
11664   if (!just_location)
11665     value_free_to_mark (mark);
11666
11667   TRY
11668     {
11669       /* Finally update the new watchpoint.  This creates the locations
11670          that should be inserted.  */
11671       update_watchpoint (w, 1);
11672     }
11673   CATCH (e, RETURN_MASK_ALL)
11674     {
11675       delete_breakpoint (b);
11676       throw_exception (e);
11677     }
11678   END_CATCH
11679
11680   install_breakpoint (internal, b, 1);
11681   do_cleanups (back_to);
11682 }
11683
11684 /* Return count of debug registers needed to watch the given expression.
11685    If the watchpoint cannot be handled in hardware return zero.  */
11686
11687 static int
11688 can_use_hardware_watchpoint (struct value *v)
11689 {
11690   int found_memory_cnt = 0;
11691   struct value *head = v;
11692
11693   /* Did the user specifically forbid us to use hardware watchpoints? */
11694   if (!can_use_hw_watchpoints)
11695     return 0;
11696
11697   /* Make sure that the value of the expression depends only upon
11698      memory contents, and values computed from them within GDB.  If we
11699      find any register references or function calls, we can't use a
11700      hardware watchpoint.
11701
11702      The idea here is that evaluating an expression generates a series
11703      of values, one holding the value of every subexpression.  (The
11704      expression a*b+c has five subexpressions: a, b, a*b, c, and
11705      a*b+c.)  GDB's values hold almost enough information to establish
11706      the criteria given above --- they identify memory lvalues,
11707      register lvalues, computed values, etcetera.  So we can evaluate
11708      the expression, and then scan the chain of values that leaves
11709      behind to decide whether we can detect any possible change to the
11710      expression's final value using only hardware watchpoints.
11711
11712      However, I don't think that the values returned by inferior
11713      function calls are special in any way.  So this function may not
11714      notice that an expression involving an inferior function call
11715      can't be watched with hardware watchpoints.  FIXME.  */
11716   for (; v; v = value_next (v))
11717     {
11718       if (VALUE_LVAL (v) == lval_memory)
11719         {
11720           if (v != head && value_lazy (v))
11721             /* A lazy memory lvalue in the chain is one that GDB never
11722                needed to fetch; we either just used its address (e.g.,
11723                `a' in `a.b') or we never needed it at all (e.g., `a'
11724                in `a,b').  This doesn't apply to HEAD; if that is
11725                lazy then it was not readable, but watch it anyway.  */
11726             ;
11727           else
11728             {
11729               /* Ahh, memory we actually used!  Check if we can cover
11730                  it with hardware watchpoints.  */
11731               struct type *vtype = check_typedef (value_type (v));
11732
11733               /* We only watch structs and arrays if user asked for it
11734                  explicitly, never if they just happen to appear in a
11735                  middle of some value chain.  */
11736               if (v == head
11737                   || (TYPE_CODE (vtype) != TYPE_CODE_STRUCT
11738                       && TYPE_CODE (vtype) != TYPE_CODE_ARRAY))
11739                 {
11740                   CORE_ADDR vaddr = value_address (v);
11741                   int len;
11742                   int num_regs;
11743
11744                   len = (target_exact_watchpoints
11745                          && is_scalar_type_recursive (vtype))?
11746                     1 : TYPE_LENGTH (value_type (v));
11747
11748                   num_regs = target_region_ok_for_hw_watchpoint (vaddr, len);
11749                   if (!num_regs)
11750                     return 0;
11751                   else
11752                     found_memory_cnt += num_regs;
11753                 }
11754             }
11755         }
11756       else if (VALUE_LVAL (v) != not_lval
11757                && deprecated_value_modifiable (v) == 0)
11758         return 0;       /* These are values from the history (e.g., $1).  */
11759       else if (VALUE_LVAL (v) == lval_register)
11760         return 0;       /* Cannot watch a register with a HW watchpoint.  */
11761     }
11762
11763   /* The expression itself looks suitable for using a hardware
11764      watchpoint, but give the target machine a chance to reject it.  */
11765   return found_memory_cnt;
11766 }
11767
11768 void
11769 watch_command_wrapper (char *arg, int from_tty, int internal)
11770 {
11771   watch_command_1 (arg, hw_write, from_tty, 0, internal);
11772 }
11773
11774 /* A helper function that looks for the "-location" argument and then
11775    calls watch_command_1.  */
11776
11777 static void
11778 watch_maybe_just_location (char *arg, int accessflag, int from_tty)
11779 {
11780   int just_location = 0;
11781
11782   if (arg
11783       && (check_for_argument (&arg, "-location", sizeof ("-location") - 1)
11784           || check_for_argument (&arg, "-l", sizeof ("-l") - 1)))
11785     {
11786       arg = skip_spaces (arg);
11787       just_location = 1;
11788     }
11789
11790   watch_command_1 (arg, accessflag, from_tty, just_location, 0);
11791 }
11792
11793 static void
11794 watch_command (char *arg, int from_tty)
11795 {
11796   watch_maybe_just_location (arg, hw_write, from_tty);
11797 }
11798
11799 void
11800 rwatch_command_wrapper (char *arg, int from_tty, int internal)
11801 {
11802   watch_command_1 (arg, hw_read, from_tty, 0, internal);
11803 }
11804
11805 static void
11806 rwatch_command (char *arg, int from_tty)
11807 {
11808   watch_maybe_just_location (arg, hw_read, from_tty);
11809 }
11810
11811 void
11812 awatch_command_wrapper (char *arg, int from_tty, int internal)
11813 {
11814   watch_command_1 (arg, hw_access, from_tty, 0, internal);
11815 }
11816
11817 static void
11818 awatch_command (char *arg, int from_tty)
11819 {
11820   watch_maybe_just_location (arg, hw_access, from_tty);
11821 }
11822 \f
11823
11824 /* Helper routines for the until_command routine in infcmd.c.  Here
11825    because it uses the mechanisms of breakpoints.  */
11826
11827 struct until_break_command_continuation_args
11828 {
11829   struct breakpoint *breakpoint;
11830   struct breakpoint *breakpoint2;
11831   int thread_num;
11832 };
11833
11834 /* This function is called by fetch_inferior_event via the
11835    cmd_continuation pointer, to complete the until command.  It takes
11836    care of cleaning up the temporary breakpoints set up by the until
11837    command.  */
11838 static void
11839 until_break_command_continuation (void *arg, int err)
11840 {
11841   struct until_break_command_continuation_args *a = arg;
11842
11843   delete_breakpoint (a->breakpoint);
11844   if (a->breakpoint2)
11845     delete_breakpoint (a->breakpoint2);
11846   delete_longjmp_breakpoint (a->thread_num);
11847 }
11848
11849 void
11850 until_break_command (char *arg, int from_tty, int anywhere)
11851 {
11852   struct symtabs_and_lines sals;
11853   struct symtab_and_line sal;
11854   struct frame_info *frame;
11855   struct gdbarch *frame_gdbarch;
11856   struct frame_id stack_frame_id;
11857   struct frame_id caller_frame_id;
11858   struct breakpoint *breakpoint;
11859   struct breakpoint *breakpoint2 = NULL;
11860   struct cleanup *old_chain;
11861   int thread;
11862   struct thread_info *tp;
11863
11864   clear_proceed_status (0);
11865
11866   /* Set a breakpoint where the user wants it and at return from
11867      this function.  */
11868
11869   if (last_displayed_sal_is_valid ())
11870     sals = decode_line_1 (&arg, DECODE_LINE_FUNFIRSTLINE,
11871                           get_last_displayed_symtab (),
11872                           get_last_displayed_line ());
11873   else
11874     sals = decode_line_1 (&arg, DECODE_LINE_FUNFIRSTLINE,
11875                           (struct symtab *) NULL, 0);
11876
11877   if (sals.nelts != 1)
11878     error (_("Couldn't get information on specified line."));
11879
11880   sal = sals.sals[0];
11881   xfree (sals.sals);    /* malloc'd, so freed.  */
11882
11883   if (*arg)
11884     error (_("Junk at end of arguments."));
11885
11886   resolve_sal_pc (&sal);
11887
11888   tp = inferior_thread ();
11889   thread = tp->num;
11890
11891   old_chain = make_cleanup (null_cleanup, NULL);
11892
11893   /* Note linespec handling above invalidates the frame chain.
11894      Installing a breakpoint also invalidates the frame chain (as it
11895      may need to switch threads), so do any frame handling before
11896      that.  */
11897
11898   frame = get_selected_frame (NULL);
11899   frame_gdbarch = get_frame_arch (frame);
11900   stack_frame_id = get_stack_frame_id (frame);
11901   caller_frame_id = frame_unwind_caller_id (frame);
11902
11903   /* Keep within the current frame, or in frames called by the current
11904      one.  */
11905
11906   if (frame_id_p (caller_frame_id))
11907     {
11908       struct symtab_and_line sal2;
11909
11910       sal2 = find_pc_line (frame_unwind_caller_pc (frame), 0);
11911       sal2.pc = frame_unwind_caller_pc (frame);
11912       breakpoint2 = set_momentary_breakpoint (frame_unwind_caller_arch (frame),
11913                                               sal2,
11914                                               caller_frame_id,
11915                                               bp_until);
11916       make_cleanup_delete_breakpoint (breakpoint2);
11917
11918       set_longjmp_breakpoint (tp, caller_frame_id);
11919       make_cleanup (delete_longjmp_breakpoint_cleanup, &thread);
11920     }
11921
11922   /* set_momentary_breakpoint could invalidate FRAME.  */
11923   frame = NULL;
11924
11925   if (anywhere)
11926     /* If the user told us to continue until a specified location,
11927        we don't specify a frame at which we need to stop.  */
11928     breakpoint = set_momentary_breakpoint (frame_gdbarch, sal,
11929                                            null_frame_id, bp_until);
11930   else
11931     /* Otherwise, specify the selected frame, because we want to stop
11932        only at the very same frame.  */
11933     breakpoint = set_momentary_breakpoint (frame_gdbarch, sal,
11934                                            stack_frame_id, bp_until);
11935   make_cleanup_delete_breakpoint (breakpoint);
11936
11937   proceed (-1, GDB_SIGNAL_DEFAULT, 0);
11938
11939   /* If we are running asynchronously, and proceed call above has
11940      actually managed to start the target, arrange for breakpoints to
11941      be deleted when the target stops.  Otherwise, we're already
11942      stopped and delete breakpoints via cleanup chain.  */
11943
11944   if (target_can_async_p () && is_running (inferior_ptid))
11945     {
11946       struct until_break_command_continuation_args *args;
11947       args = xmalloc (sizeof (*args));
11948
11949       args->breakpoint = breakpoint;
11950       args->breakpoint2 = breakpoint2;
11951       args->thread_num = thread;
11952
11953       discard_cleanups (old_chain);
11954       add_continuation (inferior_thread (),
11955                         until_break_command_continuation, args,
11956                         xfree);
11957     }
11958   else
11959     do_cleanups (old_chain);
11960 }
11961
11962 /* This function attempts to parse an optional "if <cond>" clause
11963    from the arg string.  If one is not found, it returns NULL.
11964
11965    Else, it returns a pointer to the condition string.  (It does not
11966    attempt to evaluate the string against a particular block.)  And,
11967    it updates arg to point to the first character following the parsed
11968    if clause in the arg string.  */
11969
11970 char *
11971 ep_parse_optional_if_clause (char **arg)
11972 {
11973   char *cond_string;
11974
11975   if (((*arg)[0] != 'i') || ((*arg)[1] != 'f') || !isspace ((*arg)[2]))
11976     return NULL;
11977
11978   /* Skip the "if" keyword.  */
11979   (*arg) += 2;
11980
11981   /* Skip any extra leading whitespace, and record the start of the
11982      condition string.  */
11983   *arg = skip_spaces (*arg);
11984   cond_string = *arg;
11985
11986   /* Assume that the condition occupies the remainder of the arg
11987      string.  */
11988   (*arg) += strlen (cond_string);
11989
11990   return cond_string;
11991 }
11992
11993 /* Commands to deal with catching events, such as signals, exceptions,
11994    process start/exit, etc.  */
11995
11996 typedef enum
11997 {
11998   catch_fork_temporary, catch_vfork_temporary,
11999   catch_fork_permanent, catch_vfork_permanent
12000 }
12001 catch_fork_kind;
12002
12003 static void
12004 catch_fork_command_1 (char *arg, int from_tty, 
12005                       struct cmd_list_element *command)
12006 {
12007   struct gdbarch *gdbarch = get_current_arch ();
12008   char *cond_string = NULL;
12009   catch_fork_kind fork_kind;
12010   int tempflag;
12011
12012   fork_kind = (catch_fork_kind) (uintptr_t) get_cmd_context (command);
12013   tempflag = (fork_kind == catch_fork_temporary
12014               || fork_kind == catch_vfork_temporary);
12015
12016   if (!arg)
12017     arg = "";
12018   arg = skip_spaces (arg);
12019
12020   /* The allowed syntax is:
12021      catch [v]fork
12022      catch [v]fork if <cond>
12023
12024      First, check if there's an if clause.  */
12025   cond_string = ep_parse_optional_if_clause (&arg);
12026
12027   if ((*arg != '\0') && !isspace (*arg))
12028     error (_("Junk at end of arguments."));
12029
12030   /* If this target supports it, create a fork or vfork catchpoint
12031      and enable reporting of such events.  */
12032   switch (fork_kind)
12033     {
12034     case catch_fork_temporary:
12035     case catch_fork_permanent:
12036       create_fork_vfork_event_catchpoint (gdbarch, tempflag, cond_string,
12037                                           &catch_fork_breakpoint_ops);
12038       break;
12039     case catch_vfork_temporary:
12040     case catch_vfork_permanent:
12041       create_fork_vfork_event_catchpoint (gdbarch, tempflag, cond_string,
12042                                           &catch_vfork_breakpoint_ops);
12043       break;
12044     default:
12045       error (_("unsupported or unknown fork kind; cannot catch it"));
12046       break;
12047     }
12048 }
12049
12050 static void
12051 catch_exec_command_1 (char *arg, int from_tty, 
12052                       struct cmd_list_element *command)
12053 {
12054   struct exec_catchpoint *c;
12055   struct gdbarch *gdbarch = get_current_arch ();
12056   int tempflag;
12057   char *cond_string = NULL;
12058
12059   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
12060
12061   if (!arg)
12062     arg = "";
12063   arg = skip_spaces (arg);
12064
12065   /* The allowed syntax is:
12066      catch exec
12067      catch exec if <cond>
12068
12069      First, check if there's an if clause.  */
12070   cond_string = ep_parse_optional_if_clause (&arg);
12071
12072   if ((*arg != '\0') && !isspace (*arg))
12073     error (_("Junk at end of arguments."));
12074
12075   c = XNEW (struct exec_catchpoint);
12076   init_catchpoint (&c->base, gdbarch, tempflag, cond_string,
12077                    &catch_exec_breakpoint_ops);
12078   c->exec_pathname = NULL;
12079
12080   install_breakpoint (0, &c->base, 1);
12081 }
12082
12083 void
12084 init_ada_exception_breakpoint (struct breakpoint *b,
12085                                struct gdbarch *gdbarch,
12086                                struct symtab_and_line sal,
12087                                char *addr_string,
12088                                const struct breakpoint_ops *ops,
12089                                int tempflag,
12090                                int enabled,
12091                                int from_tty)
12092 {
12093   if (from_tty)
12094     {
12095       struct gdbarch *loc_gdbarch = get_sal_arch (sal);
12096       if (!loc_gdbarch)
12097         loc_gdbarch = gdbarch;
12098
12099       describe_other_breakpoints (loc_gdbarch,
12100                                   sal.pspace, sal.pc, sal.section, -1);
12101       /* FIXME: brobecker/2006-12-28: Actually, re-implement a special
12102          version for exception catchpoints, because two catchpoints
12103          used for different exception names will use the same address.
12104          In this case, a "breakpoint ... also set at..." warning is
12105          unproductive.  Besides, the warning phrasing is also a bit
12106          inappropriate, we should use the word catchpoint, and tell
12107          the user what type of catchpoint it is.  The above is good
12108          enough for now, though.  */
12109     }
12110
12111   init_raw_breakpoint (b, gdbarch, sal, bp_breakpoint, ops);
12112
12113   b->enable_state = enabled ? bp_enabled : bp_disabled;
12114   b->disposition = tempflag ? disp_del : disp_donttouch;
12115   b->addr_string = addr_string;
12116   b->language = language_ada;
12117 }
12118
12119 /* Splits the argument using space as delimiter.  Returns an xmalloc'd
12120    filter list, or NULL if no filtering is required.  */
12121 static VEC(int) *
12122 catch_syscall_split_args (char *arg)
12123 {
12124   VEC(int) *result = NULL;
12125   struct cleanup *cleanup = make_cleanup (VEC_cleanup (int), &result);
12126   struct gdbarch *gdbarch = target_gdbarch ();
12127
12128   while (*arg != '\0')
12129     {
12130       int i, syscall_number;
12131       char *endptr;
12132       char cur_name[128];
12133       struct syscall s;
12134
12135       /* Skip whitespace.  */
12136       arg = skip_spaces (arg);
12137
12138       for (i = 0; i < 127 && arg[i] && !isspace (arg[i]); ++i)
12139         cur_name[i] = arg[i];
12140       cur_name[i] = '\0';
12141       arg += i;
12142
12143       /* Check if the user provided a syscall name or a number.  */
12144       syscall_number = (int) strtol (cur_name, &endptr, 0);
12145       if (*endptr == '\0')
12146         get_syscall_by_number (gdbarch, syscall_number, &s);
12147       else
12148         {
12149           /* We have a name.  Let's check if it's valid and convert it
12150              to a number.  */
12151           get_syscall_by_name (gdbarch, cur_name, &s);
12152
12153           if (s.number == UNKNOWN_SYSCALL)
12154             /* Here we have to issue an error instead of a warning,
12155                because GDB cannot do anything useful if there's no
12156                syscall number to be caught.  */
12157             error (_("Unknown syscall name '%s'."), cur_name);
12158         }
12159
12160       /* Ok, it's valid.  */
12161       VEC_safe_push (int, result, s.number);
12162     }
12163
12164   discard_cleanups (cleanup);
12165   return result;
12166 }
12167
12168 /* Implement the "catch syscall" command.  */
12169
12170 static void
12171 catch_syscall_command_1 (char *arg, int from_tty, 
12172                          struct cmd_list_element *command)
12173 {
12174   int tempflag;
12175   VEC(int) *filter;
12176   struct syscall s;
12177   struct gdbarch *gdbarch = get_current_arch ();
12178
12179   /* Checking if the feature if supported.  */
12180   if (gdbarch_get_syscall_number_p (gdbarch) == 0)
12181     error (_("The feature 'catch syscall' is not supported on \
12182 this architecture yet."));
12183
12184   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
12185
12186   arg = skip_spaces (arg);
12187
12188   /* We need to do this first "dummy" translation in order
12189      to get the syscall XML file loaded or, most important,
12190      to display a warning to the user if there's no XML file
12191      for his/her architecture.  */
12192   get_syscall_by_number (gdbarch, 0, &s);
12193
12194   /* The allowed syntax is:
12195      catch syscall
12196      catch syscall <name | number> [<name | number> ... <name | number>]
12197
12198      Let's check if there's a syscall name.  */
12199
12200   if (arg != NULL)
12201     filter = catch_syscall_split_args (arg);
12202   else
12203     filter = NULL;
12204
12205   create_syscall_event_catchpoint (tempflag, filter,
12206                                    &catch_syscall_breakpoint_ops);
12207 }
12208
12209 static void
12210 catch_command (char *arg, int from_tty)
12211 {
12212   error (_("Catch requires an event name."));
12213 }
12214 \f
12215
12216 static void
12217 tcatch_command (char *arg, int from_tty)
12218 {
12219   error (_("Catch requires an event name."));
12220 }
12221
12222 /* A qsort comparison function that sorts breakpoints in order.  */
12223
12224 static int
12225 compare_breakpoints (const void *a, const void *b)
12226 {
12227   const breakpoint_p *ba = a;
12228   uintptr_t ua = (uintptr_t) *ba;
12229   const breakpoint_p *bb = b;
12230   uintptr_t ub = (uintptr_t) *bb;
12231
12232   if ((*ba)->number < (*bb)->number)
12233     return -1;
12234   else if ((*ba)->number > (*bb)->number)
12235     return 1;
12236
12237   /* Now sort by address, in case we see, e..g, two breakpoints with
12238      the number 0.  */
12239   if (ua < ub)
12240     return -1;
12241   return ua > ub ? 1 : 0;
12242 }
12243
12244 /* Delete breakpoints by address or line.  */
12245
12246 static void
12247 clear_command (char *arg, int from_tty)
12248 {
12249   struct breakpoint *b, *prev;
12250   VEC(breakpoint_p) *found = 0;
12251   int ix;
12252   int default_match;
12253   struct symtabs_and_lines sals;
12254   struct symtab_and_line sal;
12255   int i;
12256   struct cleanup *cleanups = make_cleanup (null_cleanup, NULL);
12257
12258   if (arg)
12259     {
12260       sals = decode_line_with_current_source (arg,
12261                                               (DECODE_LINE_FUNFIRSTLINE
12262                                                | DECODE_LINE_LIST_MODE));
12263       make_cleanup (xfree, sals.sals);
12264       default_match = 0;
12265     }
12266   else
12267     {
12268       sals.sals = (struct symtab_and_line *)
12269         xmalloc (sizeof (struct symtab_and_line));
12270       make_cleanup (xfree, sals.sals);
12271       init_sal (&sal);          /* Initialize to zeroes.  */
12272
12273       /* Set sal's line, symtab, pc, and pspace to the values
12274          corresponding to the last call to print_frame_info.  If the
12275          codepoint is not valid, this will set all the fields to 0.  */
12276       get_last_displayed_sal (&sal);
12277       if (sal.symtab == 0)
12278         error (_("No source file specified."));
12279
12280       sals.sals[0] = sal;
12281       sals.nelts = 1;
12282
12283       default_match = 1;
12284     }
12285
12286   /* We don't call resolve_sal_pc here.  That's not as bad as it
12287      seems, because all existing breakpoints typically have both
12288      file/line and pc set.  So, if clear is given file/line, we can
12289      match this to existing breakpoint without obtaining pc at all.
12290
12291      We only support clearing given the address explicitly 
12292      present in breakpoint table.  Say, we've set breakpoint 
12293      at file:line.  There were several PC values for that file:line,
12294      due to optimization, all in one block.
12295
12296      We've picked one PC value.  If "clear" is issued with another
12297      PC corresponding to the same file:line, the breakpoint won't
12298      be cleared.  We probably can still clear the breakpoint, but 
12299      since the other PC value is never presented to user, user
12300      can only find it by guessing, and it does not seem important
12301      to support that.  */
12302
12303   /* For each line spec given, delete bps which correspond to it.  Do
12304      it in two passes, solely to preserve the current behavior that
12305      from_tty is forced true if we delete more than one
12306      breakpoint.  */
12307
12308   found = NULL;
12309   make_cleanup (VEC_cleanup (breakpoint_p), &found);
12310   for (i = 0; i < sals.nelts; i++)
12311     {
12312       const char *sal_fullname;
12313
12314       /* If exact pc given, clear bpts at that pc.
12315          If line given (pc == 0), clear all bpts on specified line.
12316          If defaulting, clear all bpts on default line
12317          or at default pc.
12318
12319          defaulting    sal.pc != 0    tests to do
12320
12321          0              1             pc
12322          1              1             pc _and_ line
12323          0              0             line
12324          1              0             <can't happen> */
12325
12326       sal = sals.sals[i];
12327       sal_fullname = (sal.symtab == NULL
12328                       ? NULL : symtab_to_fullname (sal.symtab));
12329
12330       /* Find all matching breakpoints and add them to 'found'.  */
12331       ALL_BREAKPOINTS (b)
12332         {
12333           int match = 0;
12334           /* Are we going to delete b?  */
12335           if (b->type != bp_none && !is_watchpoint (b))
12336             {
12337               struct bp_location *loc = b->loc;
12338               for (; loc; loc = loc->next)
12339                 {
12340                   /* If the user specified file:line, don't allow a PC
12341                      match.  This matches historical gdb behavior.  */
12342                   int pc_match = (!sal.explicit_line
12343                                   && sal.pc
12344                                   && (loc->pspace == sal.pspace)
12345                                   && (loc->address == sal.pc)
12346                                   && (!section_is_overlay (loc->section)
12347                                       || loc->section == sal.section));
12348                   int line_match = 0;
12349
12350                   if ((default_match || sal.explicit_line)
12351                       && loc->symtab != NULL
12352                       && sal_fullname != NULL
12353                       && sal.pspace == loc->pspace
12354                       && loc->line_number == sal.line
12355                       && filename_cmp (symtab_to_fullname (loc->symtab),
12356                                        sal_fullname) == 0)
12357                     line_match = 1;
12358
12359                   if (pc_match || line_match)
12360                     {
12361                       match = 1;
12362                       break;
12363                     }
12364                 }
12365             }
12366
12367           if (match)
12368             VEC_safe_push(breakpoint_p, found, b);
12369         }
12370     }
12371
12372   /* Now go thru the 'found' chain and delete them.  */
12373   if (VEC_empty(breakpoint_p, found))
12374     {
12375       if (arg)
12376         error (_("No breakpoint at %s."), arg);
12377       else
12378         error (_("No breakpoint at this line."));
12379     }
12380
12381   /* Remove duplicates from the vec.  */
12382   qsort (VEC_address (breakpoint_p, found),
12383          VEC_length (breakpoint_p, found),
12384          sizeof (breakpoint_p),
12385          compare_breakpoints);
12386   prev = VEC_index (breakpoint_p, found, 0);
12387   for (ix = 1; VEC_iterate (breakpoint_p, found, ix, b); ++ix)
12388     {
12389       if (b == prev)
12390         {
12391           VEC_ordered_remove (breakpoint_p, found, ix);
12392           --ix;
12393         }
12394     }
12395
12396   if (VEC_length(breakpoint_p, found) > 1)
12397     from_tty = 1;       /* Always report if deleted more than one.  */
12398   if (from_tty)
12399     {
12400       if (VEC_length(breakpoint_p, found) == 1)
12401         printf_unfiltered (_("Deleted breakpoint "));
12402       else
12403         printf_unfiltered (_("Deleted breakpoints "));
12404     }
12405
12406   for (ix = 0; VEC_iterate(breakpoint_p, found, ix, b); ix++)
12407     {
12408       if (from_tty)
12409         printf_unfiltered ("%d ", b->number);
12410       delete_breakpoint (b);
12411     }
12412   if (from_tty)
12413     putchar_unfiltered ('\n');
12414
12415   do_cleanups (cleanups);
12416 }
12417 \f
12418 /* Delete breakpoint in BS if they are `delete' breakpoints and
12419    all breakpoints that are marked for deletion, whether hit or not.
12420    This is called after any breakpoint is hit, or after errors.  */
12421
12422 void
12423 breakpoint_auto_delete (bpstat bs)
12424 {
12425   struct breakpoint *b, *b_tmp;
12426
12427   for (; bs; bs = bs->next)
12428     if (bs->breakpoint_at
12429         && bs->breakpoint_at->disposition == disp_del
12430         && bs->stop)
12431       delete_breakpoint (bs->breakpoint_at);
12432
12433   ALL_BREAKPOINTS_SAFE (b, b_tmp)
12434   {
12435     if (b->disposition == disp_del_at_next_stop)
12436       delete_breakpoint (b);
12437   }
12438 }
12439
12440 /* A comparison function for bp_location AP and BP being interfaced to
12441    qsort.  Sort elements primarily by their ADDRESS (no matter what
12442    does breakpoint_address_is_meaningful say for its OWNER),
12443    secondarily by ordering first permanent elements and
12444    terciarily just ensuring the array is sorted stable way despite
12445    qsort being an unstable algorithm.  */
12446
12447 static int
12448 bp_location_compare (const void *ap, const void *bp)
12449 {
12450   struct bp_location *a = *(void **) ap;
12451   struct bp_location *b = *(void **) bp;
12452
12453   if (a->address != b->address)
12454     return (a->address > b->address) - (a->address < b->address);
12455
12456   /* Sort locations at the same address by their pspace number, keeping
12457      locations of the same inferior (in a multi-inferior environment)
12458      grouped.  */
12459
12460   if (a->pspace->num != b->pspace->num)
12461     return ((a->pspace->num > b->pspace->num)
12462             - (a->pspace->num < b->pspace->num));
12463
12464   /* Sort permanent breakpoints first.  */
12465   if (a->permanent != b->permanent)
12466     return (a->permanent < b->permanent) - (a->permanent > b->permanent);
12467
12468   /* Make the internal GDB representation stable across GDB runs
12469      where A and B memory inside GDB can differ.  Breakpoint locations of
12470      the same type at the same address can be sorted in arbitrary order.  */
12471
12472   if (a->owner->number != b->owner->number)
12473     return ((a->owner->number > b->owner->number)
12474             - (a->owner->number < b->owner->number));
12475
12476   return (a > b) - (a < b);
12477 }
12478
12479 /* Set bp_location_placed_address_before_address_max and
12480    bp_location_shadow_len_after_address_max according to the current
12481    content of the bp_location array.  */
12482
12483 static void
12484 bp_location_target_extensions_update (void)
12485 {
12486   struct bp_location *bl, **blp_tmp;
12487
12488   bp_location_placed_address_before_address_max = 0;
12489   bp_location_shadow_len_after_address_max = 0;
12490
12491   ALL_BP_LOCATIONS (bl, blp_tmp)
12492     {
12493       CORE_ADDR start, end, addr;
12494
12495       if (!bp_location_has_shadow (bl))
12496         continue;
12497
12498       start = bl->target_info.placed_address;
12499       end = start + bl->target_info.shadow_len;
12500
12501       gdb_assert (bl->address >= start);
12502       addr = bl->address - start;
12503       if (addr > bp_location_placed_address_before_address_max)
12504         bp_location_placed_address_before_address_max = addr;
12505
12506       /* Zero SHADOW_LEN would not pass bp_location_has_shadow.  */
12507
12508       gdb_assert (bl->address < end);
12509       addr = end - bl->address;
12510       if (addr > bp_location_shadow_len_after_address_max)
12511         bp_location_shadow_len_after_address_max = addr;
12512     }
12513 }
12514
12515 /* Download tracepoint locations if they haven't been.  */
12516
12517 static void
12518 download_tracepoint_locations (void)
12519 {
12520   struct breakpoint *b;
12521   struct cleanup *old_chain;
12522
12523   if (!target_can_download_tracepoint ())
12524     return;
12525
12526   old_chain = save_current_space_and_thread ();
12527
12528   ALL_TRACEPOINTS (b)
12529     {
12530       struct bp_location *bl;
12531       struct tracepoint *t;
12532       int bp_location_downloaded = 0;
12533
12534       if ((b->type == bp_fast_tracepoint
12535            ? !may_insert_fast_tracepoints
12536            : !may_insert_tracepoints))
12537         continue;
12538
12539       for (bl = b->loc; bl; bl = bl->next)
12540         {
12541           /* In tracepoint, locations are _never_ duplicated, so
12542              should_be_inserted is equivalent to
12543              unduplicated_should_be_inserted.  */
12544           if (!should_be_inserted (bl) || bl->inserted)
12545             continue;
12546
12547           switch_to_program_space_and_thread (bl->pspace);
12548
12549           target_download_tracepoint (bl);
12550
12551           bl->inserted = 1;
12552           bp_location_downloaded = 1;
12553         }
12554       t = (struct tracepoint *) b;
12555       t->number_on_target = b->number;
12556       if (bp_location_downloaded)
12557         observer_notify_breakpoint_modified (b);
12558     }
12559
12560   do_cleanups (old_chain);
12561 }
12562
12563 /* Swap the insertion/duplication state between two locations.  */
12564
12565 static void
12566 swap_insertion (struct bp_location *left, struct bp_location *right)
12567 {
12568   const int left_inserted = left->inserted;
12569   const int left_duplicate = left->duplicate;
12570   const int left_needs_update = left->needs_update;
12571   const struct bp_target_info left_target_info = left->target_info;
12572
12573   /* Locations of tracepoints can never be duplicated.  */
12574   if (is_tracepoint (left->owner))
12575     gdb_assert (!left->duplicate);
12576   if (is_tracepoint (right->owner))
12577     gdb_assert (!right->duplicate);
12578
12579   left->inserted = right->inserted;
12580   left->duplicate = right->duplicate;
12581   left->needs_update = right->needs_update;
12582   left->target_info = right->target_info;
12583   right->inserted = left_inserted;
12584   right->duplicate = left_duplicate;
12585   right->needs_update = left_needs_update;
12586   right->target_info = left_target_info;
12587 }
12588
12589 /* Force the re-insertion of the locations at ADDRESS.  This is called
12590    once a new/deleted/modified duplicate location is found and we are evaluating
12591    conditions on the target's side.  Such conditions need to be updated on
12592    the target.  */
12593
12594 static void
12595 force_breakpoint_reinsertion (struct bp_location *bl)
12596 {
12597   struct bp_location **locp = NULL, **loc2p;
12598   struct bp_location *loc;
12599   CORE_ADDR address = 0;
12600   int pspace_num;
12601
12602   address = bl->address;
12603   pspace_num = bl->pspace->num;
12604
12605   /* This is only meaningful if the target is
12606      evaluating conditions and if the user has
12607      opted for condition evaluation on the target's
12608      side.  */
12609   if (gdb_evaluates_breakpoint_condition_p ()
12610       || !target_supports_evaluation_of_breakpoint_conditions ())
12611     return;
12612
12613   /* Flag all breakpoint locations with this address and
12614      the same program space as the location
12615      as "its condition has changed".  We need to
12616      update the conditions on the target's side.  */
12617   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, address)
12618     {
12619       loc = *loc2p;
12620
12621       if (!is_breakpoint (loc->owner)
12622           || pspace_num != loc->pspace->num)
12623         continue;
12624
12625       /* Flag the location appropriately.  We use a different state to
12626          let everyone know that we already updated the set of locations
12627          with addr bl->address and program space bl->pspace.  This is so
12628          we don't have to keep calling these functions just to mark locations
12629          that have already been marked.  */
12630       loc->condition_changed = condition_updated;
12631
12632       /* Free the agent expression bytecode as well.  We will compute
12633          it later on.  */
12634       if (loc->cond_bytecode)
12635         {
12636           free_agent_expr (loc->cond_bytecode);
12637           loc->cond_bytecode = NULL;
12638         }
12639     }
12640 }
12641 /* Called whether new breakpoints are created, or existing breakpoints
12642    deleted, to update the global location list and recompute which
12643    locations are duplicate of which.
12644
12645    The INSERT_MODE flag determines whether locations may not, may, or
12646    shall be inserted now.  See 'enum ugll_insert_mode' for more
12647    info.  */
12648
12649 static void
12650 update_global_location_list (enum ugll_insert_mode insert_mode)
12651 {
12652   struct breakpoint *b;
12653   struct bp_location **locp, *loc;
12654   struct cleanup *cleanups;
12655   /* Last breakpoint location address that was marked for update.  */
12656   CORE_ADDR last_addr = 0;
12657   /* Last breakpoint location program space that was marked for update.  */
12658   int last_pspace_num = -1;
12659
12660   /* Used in the duplicates detection below.  When iterating over all
12661      bp_locations, points to the first bp_location of a given address.
12662      Breakpoints and watchpoints of different types are never
12663      duplicates of each other.  Keep one pointer for each type of
12664      breakpoint/watchpoint, so we only need to loop over all locations
12665      once.  */
12666   struct bp_location *bp_loc_first;  /* breakpoint */
12667   struct bp_location *wp_loc_first;  /* hardware watchpoint */
12668   struct bp_location *awp_loc_first; /* access watchpoint */
12669   struct bp_location *rwp_loc_first; /* read watchpoint */
12670
12671   /* Saved former bp_location array which we compare against the newly
12672      built bp_location from the current state of ALL_BREAKPOINTS.  */
12673   struct bp_location **old_location, **old_locp;
12674   unsigned old_location_count;
12675
12676   old_location = bp_location;
12677   old_location_count = bp_location_count;
12678   bp_location = NULL;
12679   bp_location_count = 0;
12680   cleanups = make_cleanup (xfree, old_location);
12681
12682   ALL_BREAKPOINTS (b)
12683     for (loc = b->loc; loc; loc = loc->next)
12684       bp_location_count++;
12685
12686   bp_location = xmalloc (sizeof (*bp_location) * bp_location_count);
12687   locp = bp_location;
12688   ALL_BREAKPOINTS (b)
12689     for (loc = b->loc; loc; loc = loc->next)
12690       *locp++ = loc;
12691   qsort (bp_location, bp_location_count, sizeof (*bp_location),
12692          bp_location_compare);
12693
12694   bp_location_target_extensions_update ();
12695
12696   /* Identify bp_location instances that are no longer present in the
12697      new list, and therefore should be freed.  Note that it's not
12698      necessary that those locations should be removed from inferior --
12699      if there's another location at the same address (previously
12700      marked as duplicate), we don't need to remove/insert the
12701      location.
12702      
12703      LOCP is kept in sync with OLD_LOCP, each pointing to the current
12704      and former bp_location array state respectively.  */
12705
12706   locp = bp_location;
12707   for (old_locp = old_location; old_locp < old_location + old_location_count;
12708        old_locp++)
12709     {
12710       struct bp_location *old_loc = *old_locp;
12711       struct bp_location **loc2p;
12712
12713       /* Tells if 'old_loc' is found among the new locations.  If
12714          not, we have to free it.  */
12715       int found_object = 0;
12716       /* Tells if the location should remain inserted in the target.  */
12717       int keep_in_target = 0;
12718       int removed = 0;
12719
12720       /* Skip LOCP entries which will definitely never be needed.
12721          Stop either at or being the one matching OLD_LOC.  */
12722       while (locp < bp_location + bp_location_count
12723              && (*locp)->address < old_loc->address)
12724         locp++;
12725
12726       for (loc2p = locp;
12727            (loc2p < bp_location + bp_location_count
12728             && (*loc2p)->address == old_loc->address);
12729            loc2p++)
12730         {
12731           /* Check if this is a new/duplicated location or a duplicated
12732              location that had its condition modified.  If so, we want to send
12733              its condition to the target if evaluation of conditions is taking
12734              place there.  */
12735           if ((*loc2p)->condition_changed == condition_modified
12736               && (last_addr != old_loc->address
12737                   || last_pspace_num != old_loc->pspace->num))
12738             {
12739               force_breakpoint_reinsertion (*loc2p);
12740               last_pspace_num = old_loc->pspace->num;
12741             }
12742
12743           if (*loc2p == old_loc)
12744             found_object = 1;
12745         }
12746
12747       /* We have already handled this address, update it so that we don't
12748          have to go through updates again.  */
12749       last_addr = old_loc->address;
12750
12751       /* Target-side condition evaluation: Handle deleted locations.  */
12752       if (!found_object)
12753         force_breakpoint_reinsertion (old_loc);
12754
12755       /* If this location is no longer present, and inserted, look if
12756          there's maybe a new location at the same address.  If so,
12757          mark that one inserted, and don't remove this one.  This is
12758          needed so that we don't have a time window where a breakpoint
12759          at certain location is not inserted.  */
12760
12761       if (old_loc->inserted)
12762         {
12763           /* If the location is inserted now, we might have to remove
12764              it.  */
12765
12766           if (found_object && should_be_inserted (old_loc))
12767             {
12768               /* The location is still present in the location list,
12769                  and still should be inserted.  Don't do anything.  */
12770               keep_in_target = 1;
12771             }
12772           else
12773             {
12774               /* This location still exists, but it won't be kept in the
12775                  target since it may have been disabled.  We proceed to
12776                  remove its target-side condition.  */
12777
12778               /* The location is either no longer present, or got
12779                  disabled.  See if there's another location at the
12780                  same address, in which case we don't need to remove
12781                  this one from the target.  */
12782
12783               /* OLD_LOC comes from existing struct breakpoint.  */
12784               if (breakpoint_address_is_meaningful (old_loc->owner))
12785                 {
12786                   for (loc2p = locp;
12787                        (loc2p < bp_location + bp_location_count
12788                         && (*loc2p)->address == old_loc->address);
12789                        loc2p++)
12790                     {
12791                       struct bp_location *loc2 = *loc2p;
12792
12793                       if (breakpoint_locations_match (loc2, old_loc))
12794                         {
12795                           /* Read watchpoint locations are switched to
12796                              access watchpoints, if the former are not
12797                              supported, but the latter are.  */
12798                           if (is_hardware_watchpoint (old_loc->owner))
12799                             {
12800                               gdb_assert (is_hardware_watchpoint (loc2->owner));
12801                               loc2->watchpoint_type = old_loc->watchpoint_type;
12802                             }
12803
12804                           /* loc2 is a duplicated location. We need to check
12805                              if it should be inserted in case it will be
12806                              unduplicated.  */
12807                           if (loc2 != old_loc
12808                               && unduplicated_should_be_inserted (loc2))
12809                             {
12810                               swap_insertion (old_loc, loc2);
12811                               keep_in_target = 1;
12812                               break;
12813                             }
12814                         }
12815                     }
12816                 }
12817             }
12818
12819           if (!keep_in_target)
12820             {
12821               if (remove_breakpoint (old_loc, mark_uninserted))
12822                 {
12823                   /* This is just about all we can do.  We could keep
12824                      this location on the global list, and try to
12825                      remove it next time, but there's no particular
12826                      reason why we will succeed next time.
12827                      
12828                      Note that at this point, old_loc->owner is still
12829                      valid, as delete_breakpoint frees the breakpoint
12830                      only after calling us.  */
12831                   printf_filtered (_("warning: Error removing "
12832                                      "breakpoint %d\n"), 
12833                                    old_loc->owner->number);
12834                 }
12835               removed = 1;
12836             }
12837         }
12838
12839       if (!found_object)
12840         {
12841           if (removed && non_stop
12842               && need_moribund_for_location_type (old_loc))
12843             {
12844               /* This location was removed from the target.  In
12845                  non-stop mode, a race condition is possible where
12846                  we've removed a breakpoint, but stop events for that
12847                  breakpoint are already queued and will arrive later.
12848                  We apply an heuristic to be able to distinguish such
12849                  SIGTRAPs from other random SIGTRAPs: we keep this
12850                  breakpoint location for a bit, and will retire it
12851                  after we see some number of events.  The theory here
12852                  is that reporting of events should, "on the average",
12853                  be fair, so after a while we'll see events from all
12854                  threads that have anything of interest, and no longer
12855                  need to keep this breakpoint location around.  We
12856                  don't hold locations forever so to reduce chances of
12857                  mistaking a non-breakpoint SIGTRAP for a breakpoint
12858                  SIGTRAP.
12859
12860                  The heuristic failing can be disastrous on
12861                  decr_pc_after_break targets.
12862
12863                  On decr_pc_after_break targets, like e.g., x86-linux,
12864                  if we fail to recognize a late breakpoint SIGTRAP,
12865                  because events_till_retirement has reached 0 too
12866                  soon, we'll fail to do the PC adjustment, and report
12867                  a random SIGTRAP to the user.  When the user resumes
12868                  the inferior, it will most likely immediately crash
12869                  with SIGILL/SIGBUS/SIGSEGV, or worse, get silently
12870                  corrupted, because of being resumed e.g., in the
12871                  middle of a multi-byte instruction, or skipped a
12872                  one-byte instruction.  This was actually seen happen
12873                  on native x86-linux, and should be less rare on
12874                  targets that do not support new thread events, like
12875                  remote, due to the heuristic depending on
12876                  thread_count.
12877
12878                  Mistaking a random SIGTRAP for a breakpoint trap
12879                  causes similar symptoms (PC adjustment applied when
12880                  it shouldn't), but then again, playing with SIGTRAPs
12881                  behind the debugger's back is asking for trouble.
12882
12883                  Since hardware watchpoint traps are always
12884                  distinguishable from other traps, so we don't need to
12885                  apply keep hardware watchpoint moribund locations
12886                  around.  We simply always ignore hardware watchpoint
12887                  traps we can no longer explain.  */
12888
12889               old_loc->events_till_retirement = 3 * (thread_count () + 1);
12890               old_loc->owner = NULL;
12891
12892               VEC_safe_push (bp_location_p, moribund_locations, old_loc);
12893             }
12894           else
12895             {
12896               old_loc->owner = NULL;
12897               decref_bp_location (&old_loc);
12898             }
12899         }
12900     }
12901
12902   /* Rescan breakpoints at the same address and section, marking the
12903      first one as "first" and any others as "duplicates".  This is so
12904      that the bpt instruction is only inserted once.  If we have a
12905      permanent breakpoint at the same place as BPT, make that one the
12906      official one, and the rest as duplicates.  Permanent breakpoints
12907      are sorted first for the same address.
12908
12909      Do the same for hardware watchpoints, but also considering the
12910      watchpoint's type (regular/access/read) and length.  */
12911
12912   bp_loc_first = NULL;
12913   wp_loc_first = NULL;
12914   awp_loc_first = NULL;
12915   rwp_loc_first = NULL;
12916   ALL_BP_LOCATIONS (loc, locp)
12917     {
12918       /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always
12919          non-NULL.  */
12920       struct bp_location **loc_first_p;
12921       b = loc->owner;
12922
12923       if (!unduplicated_should_be_inserted (loc)
12924           || !breakpoint_address_is_meaningful (b)
12925           /* Don't detect duplicate for tracepoint locations because they are
12926            never duplicated.  See the comments in field `duplicate' of
12927            `struct bp_location'.  */
12928           || is_tracepoint (b))
12929         {
12930           /* Clear the condition modification flag.  */
12931           loc->condition_changed = condition_unchanged;
12932           continue;
12933         }
12934
12935       /* Permanent breakpoint should always be inserted.  */
12936       if (loc->permanent && ! loc->inserted)
12937         internal_error (__FILE__, __LINE__,
12938                         _("allegedly permanent breakpoint is not "
12939                         "actually inserted"));
12940
12941       if (b->type == bp_hardware_watchpoint)
12942         loc_first_p = &wp_loc_first;
12943       else if (b->type == bp_read_watchpoint)
12944         loc_first_p = &rwp_loc_first;
12945       else if (b->type == bp_access_watchpoint)
12946         loc_first_p = &awp_loc_first;
12947       else
12948         loc_first_p = &bp_loc_first;
12949
12950       if (*loc_first_p == NULL
12951           || (overlay_debugging && loc->section != (*loc_first_p)->section)
12952           || !breakpoint_locations_match (loc, *loc_first_p))
12953         {
12954           *loc_first_p = loc;
12955           loc->duplicate = 0;
12956
12957           if (is_breakpoint (loc->owner) && loc->condition_changed)
12958             {
12959               loc->needs_update = 1;
12960               /* Clear the condition modification flag.  */
12961               loc->condition_changed = condition_unchanged;
12962             }
12963           continue;
12964         }
12965
12966
12967       /* This and the above ensure the invariant that the first location
12968          is not duplicated, and is the inserted one.
12969          All following are marked as duplicated, and are not inserted.  */
12970       if (loc->inserted)
12971         swap_insertion (loc, *loc_first_p);
12972       loc->duplicate = 1;
12973
12974       /* Clear the condition modification flag.  */
12975       loc->condition_changed = condition_unchanged;
12976
12977       if (loc->inserted && !loc->permanent
12978           && (*loc_first_p)->permanent)
12979         internal_error (__FILE__, __LINE__,
12980                         _("another breakpoint was inserted on top of "
12981                         "a permanent breakpoint"));
12982     }
12983
12984   if (insert_mode == UGLL_INSERT || breakpoints_should_be_inserted_now ())
12985     {
12986       if (insert_mode != UGLL_DONT_INSERT)
12987         insert_breakpoint_locations ();
12988       else
12989         {
12990           /* Even though the caller told us to not insert new
12991              locations, we may still need to update conditions on the
12992              target's side of breakpoints that were already inserted
12993              if the target is evaluating breakpoint conditions.  We
12994              only update conditions for locations that are marked
12995              "needs_update".  */
12996           update_inserted_breakpoint_locations ();
12997         }
12998     }
12999
13000   if (insert_mode != UGLL_DONT_INSERT)
13001     download_tracepoint_locations ();
13002
13003   do_cleanups (cleanups);
13004 }
13005
13006 void
13007 breakpoint_retire_moribund (void)
13008 {
13009   struct bp_location *loc;
13010   int ix;
13011
13012   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
13013     if (--(loc->events_till_retirement) == 0)
13014       {
13015         decref_bp_location (&loc);
13016         VEC_unordered_remove (bp_location_p, moribund_locations, ix);
13017         --ix;
13018       }
13019 }
13020
13021 static void
13022 update_global_location_list_nothrow (enum ugll_insert_mode insert_mode)
13023 {
13024
13025   TRY
13026     {
13027       update_global_location_list (insert_mode);
13028     }
13029   CATCH (e, RETURN_MASK_ERROR)
13030     {
13031     }
13032   END_CATCH
13033 }
13034
13035 /* Clear BKP from a BPS.  */
13036
13037 static void
13038 bpstat_remove_bp_location (bpstat bps, struct breakpoint *bpt)
13039 {
13040   bpstat bs;
13041
13042   for (bs = bps; bs; bs = bs->next)
13043     if (bs->breakpoint_at == bpt)
13044       {
13045         bs->breakpoint_at = NULL;
13046         bs->old_val = NULL;
13047         /* bs->commands will be freed later.  */
13048       }
13049 }
13050
13051 /* Callback for iterate_over_threads.  */
13052 static int
13053 bpstat_remove_breakpoint_callback (struct thread_info *th, void *data)
13054 {
13055   struct breakpoint *bpt = data;
13056
13057   bpstat_remove_bp_location (th->control.stop_bpstat, bpt);
13058   return 0;
13059 }
13060
13061 /* Helper for breakpoint and tracepoint breakpoint_ops->mention
13062    callbacks.  */
13063
13064 static void
13065 say_where (struct breakpoint *b)
13066 {
13067   struct value_print_options opts;
13068
13069   get_user_print_options (&opts);
13070
13071   /* i18n: cagney/2005-02-11: Below needs to be merged into a
13072      single string.  */
13073   if (b->loc == NULL)
13074     {
13075       printf_filtered (_(" (%s) pending."), b->addr_string);
13076     }
13077   else
13078     {
13079       if (opts.addressprint || b->loc->symtab == NULL)
13080         {
13081           printf_filtered (" at ");
13082           fputs_filtered (paddress (b->loc->gdbarch, b->loc->address),
13083                           gdb_stdout);
13084         }
13085       if (b->loc->symtab != NULL)
13086         {
13087           /* If there is a single location, we can print the location
13088              more nicely.  */
13089           if (b->loc->next == NULL)
13090             printf_filtered (": file %s, line %d.",
13091                              symtab_to_filename_for_display (b->loc->symtab),
13092                              b->loc->line_number);
13093           else
13094             /* This is not ideal, but each location may have a
13095                different file name, and this at least reflects the
13096                real situation somewhat.  */
13097             printf_filtered (": %s.", b->addr_string);
13098         }
13099
13100       if (b->loc->next)
13101         {
13102           struct bp_location *loc = b->loc;
13103           int n = 0;
13104           for (; loc; loc = loc->next)
13105             ++n;
13106           printf_filtered (" (%d locations)", n);
13107         }
13108     }
13109 }
13110
13111 /* Default bp_location_ops methods.  */
13112
13113 static void
13114 bp_location_dtor (struct bp_location *self)
13115 {
13116   xfree (self->cond);
13117   if (self->cond_bytecode)
13118     free_agent_expr (self->cond_bytecode);
13119   xfree (self->function_name);
13120
13121   VEC_free (agent_expr_p, self->target_info.conditions);
13122   VEC_free (agent_expr_p, self->target_info.tcommands);
13123 }
13124
13125 static const struct bp_location_ops bp_location_ops =
13126 {
13127   bp_location_dtor
13128 };
13129
13130 /* Default breakpoint_ops methods all breakpoint_ops ultimately
13131    inherit from.  */
13132
13133 static void
13134 base_breakpoint_dtor (struct breakpoint *self)
13135 {
13136   decref_counted_command_line (&self->commands);
13137   xfree (self->cond_string);
13138   xfree (self->extra_string);
13139   xfree (self->addr_string);
13140   xfree (self->filter);
13141   xfree (self->addr_string_range_end);
13142 }
13143
13144 static struct bp_location *
13145 base_breakpoint_allocate_location (struct breakpoint *self)
13146 {
13147   struct bp_location *loc;
13148
13149   loc = XNEW (struct bp_location);
13150   init_bp_location (loc, &bp_location_ops, self);
13151   return loc;
13152 }
13153
13154 static void
13155 base_breakpoint_re_set (struct breakpoint *b)
13156 {
13157   /* Nothing to re-set. */
13158 }
13159
13160 #define internal_error_pure_virtual_called() \
13161   gdb_assert_not_reached ("pure virtual function called")
13162
13163 static int
13164 base_breakpoint_insert_location (struct bp_location *bl)
13165 {
13166   internal_error_pure_virtual_called ();
13167 }
13168
13169 static int
13170 base_breakpoint_remove_location (struct bp_location *bl)
13171 {
13172   internal_error_pure_virtual_called ();
13173 }
13174
13175 static int
13176 base_breakpoint_breakpoint_hit (const struct bp_location *bl,
13177                                 struct address_space *aspace,
13178                                 CORE_ADDR bp_addr,
13179                                 const struct target_waitstatus *ws)
13180 {
13181   internal_error_pure_virtual_called ();
13182 }
13183
13184 static void
13185 base_breakpoint_check_status (bpstat bs)
13186 {
13187   /* Always stop.   */
13188 }
13189
13190 /* A "works_in_software_mode" breakpoint_ops method that just internal
13191    errors.  */
13192
13193 static int
13194 base_breakpoint_works_in_software_mode (const struct breakpoint *b)
13195 {
13196   internal_error_pure_virtual_called ();
13197 }
13198
13199 /* A "resources_needed" breakpoint_ops method that just internal
13200    errors.  */
13201
13202 static int
13203 base_breakpoint_resources_needed (const struct bp_location *bl)
13204 {
13205   internal_error_pure_virtual_called ();
13206 }
13207
13208 static enum print_stop_action
13209 base_breakpoint_print_it (bpstat bs)
13210 {
13211   internal_error_pure_virtual_called ();
13212 }
13213
13214 static void
13215 base_breakpoint_print_one_detail (const struct breakpoint *self,
13216                                   struct ui_out *uiout)
13217 {
13218   /* nothing */
13219 }
13220
13221 static void
13222 base_breakpoint_print_mention (struct breakpoint *b)
13223 {
13224   internal_error_pure_virtual_called ();
13225 }
13226
13227 static void
13228 base_breakpoint_print_recreate (struct breakpoint *b, struct ui_file *fp)
13229 {
13230   internal_error_pure_virtual_called ();
13231 }
13232
13233 static void
13234 base_breakpoint_create_sals_from_address (char **arg,
13235                                           struct linespec_result *canonical,
13236                                           enum bptype type_wanted,
13237                                           char *addr_start,
13238                                           char **copy_arg)
13239 {
13240   internal_error_pure_virtual_called ();
13241 }
13242
13243 static void
13244 base_breakpoint_create_breakpoints_sal (struct gdbarch *gdbarch,
13245                                         struct linespec_result *c,
13246                                         char *cond_string,
13247                                         char *extra_string,
13248                                         enum bptype type_wanted,
13249                                         enum bpdisp disposition,
13250                                         int thread,
13251                                         int task, int ignore_count,
13252                                         const struct breakpoint_ops *o,
13253                                         int from_tty, int enabled,
13254                                         int internal, unsigned flags)
13255 {
13256   internal_error_pure_virtual_called ();
13257 }
13258
13259 static void
13260 base_breakpoint_decode_linespec (struct breakpoint *b, char **s,
13261                                  struct symtabs_and_lines *sals)
13262 {
13263   internal_error_pure_virtual_called ();
13264 }
13265
13266 /* The default 'explains_signal' method.  */
13267
13268 static int
13269 base_breakpoint_explains_signal (struct breakpoint *b, enum gdb_signal sig)
13270 {
13271   return 1;
13272 }
13273
13274 /* The default "after_condition_true" method.  */
13275
13276 static void
13277 base_breakpoint_after_condition_true (struct bpstats *bs)
13278 {
13279   /* Nothing to do.   */
13280 }
13281
13282 struct breakpoint_ops base_breakpoint_ops =
13283 {
13284   base_breakpoint_dtor,
13285   base_breakpoint_allocate_location,
13286   base_breakpoint_re_set,
13287   base_breakpoint_insert_location,
13288   base_breakpoint_remove_location,
13289   base_breakpoint_breakpoint_hit,
13290   base_breakpoint_check_status,
13291   base_breakpoint_resources_needed,
13292   base_breakpoint_works_in_software_mode,
13293   base_breakpoint_print_it,
13294   NULL,
13295   base_breakpoint_print_one_detail,
13296   base_breakpoint_print_mention,
13297   base_breakpoint_print_recreate,
13298   base_breakpoint_create_sals_from_address,
13299   base_breakpoint_create_breakpoints_sal,
13300   base_breakpoint_decode_linespec,
13301   base_breakpoint_explains_signal,
13302   base_breakpoint_after_condition_true,
13303 };
13304
13305 /* Default breakpoint_ops methods.  */
13306
13307 static void
13308 bkpt_re_set (struct breakpoint *b)
13309 {
13310   /* FIXME: is this still reachable?  */
13311   if (b->addr_string == NULL)
13312     {
13313       /* Anything without a string can't be re-set.  */
13314       delete_breakpoint (b);
13315       return;
13316     }
13317
13318   breakpoint_re_set_default (b);
13319 }
13320
13321 static int
13322 bkpt_insert_location (struct bp_location *bl)
13323 {
13324   if (bl->loc_type == bp_loc_hardware_breakpoint)
13325     return target_insert_hw_breakpoint (bl->gdbarch, &bl->target_info);
13326   else
13327     return target_insert_breakpoint (bl->gdbarch, &bl->target_info);
13328 }
13329
13330 static int
13331 bkpt_remove_location (struct bp_location *bl)
13332 {
13333   if (bl->loc_type == bp_loc_hardware_breakpoint)
13334     return target_remove_hw_breakpoint (bl->gdbarch, &bl->target_info);
13335   else
13336     return target_remove_breakpoint (bl->gdbarch, &bl->target_info);
13337 }
13338
13339 static int
13340 bkpt_breakpoint_hit (const struct bp_location *bl,
13341                      struct address_space *aspace, CORE_ADDR bp_addr,
13342                      const struct target_waitstatus *ws)
13343 {
13344   if (ws->kind != TARGET_WAITKIND_STOPPED
13345       || ws->value.sig != GDB_SIGNAL_TRAP)
13346     return 0;
13347
13348   if (!breakpoint_address_match (bl->pspace->aspace, bl->address,
13349                                  aspace, bp_addr))
13350     return 0;
13351
13352   if (overlay_debugging         /* unmapped overlay section */
13353       && section_is_overlay (bl->section)
13354       && !section_is_mapped (bl->section))
13355     return 0;
13356
13357   return 1;
13358 }
13359
13360 static int
13361 dprintf_breakpoint_hit (const struct bp_location *bl,
13362                         struct address_space *aspace, CORE_ADDR bp_addr,
13363                         const struct target_waitstatus *ws)
13364 {
13365   if (dprintf_style == dprintf_style_agent
13366       && target_can_run_breakpoint_commands ())
13367     {
13368       /* An agent-style dprintf never causes a stop.  If we see a trap
13369          for this address it must be for a breakpoint that happens to
13370          be set at the same address.  */
13371       return 0;
13372     }
13373
13374   return bkpt_breakpoint_hit (bl, aspace, bp_addr, ws);
13375 }
13376
13377 static int
13378 bkpt_resources_needed (const struct bp_location *bl)
13379 {
13380   gdb_assert (bl->owner->type == bp_hardware_breakpoint);
13381
13382   return 1;
13383 }
13384
13385 static enum print_stop_action
13386 bkpt_print_it (bpstat bs)
13387 {
13388   struct breakpoint *b;
13389   const struct bp_location *bl;
13390   int bp_temp;
13391   struct ui_out *uiout = current_uiout;
13392
13393   gdb_assert (bs->bp_location_at != NULL);
13394
13395   bl = bs->bp_location_at;
13396   b = bs->breakpoint_at;
13397
13398   bp_temp = b->disposition == disp_del;
13399   if (bl->address != bl->requested_address)
13400     breakpoint_adjustment_warning (bl->requested_address,
13401                                    bl->address,
13402                                    b->number, 1);
13403   annotate_breakpoint (b->number);
13404   if (bp_temp)
13405     ui_out_text (uiout, "\nTemporary breakpoint ");
13406   else
13407     ui_out_text (uiout, "\nBreakpoint ");
13408   if (ui_out_is_mi_like_p (uiout))
13409     {
13410       ui_out_field_string (uiout, "reason",
13411                            async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
13412       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
13413     }
13414   ui_out_field_int (uiout, "bkptno", b->number);
13415   ui_out_text (uiout, ", ");
13416
13417   return PRINT_SRC_AND_LOC;
13418 }
13419
13420 static void
13421 bkpt_print_mention (struct breakpoint *b)
13422 {
13423   if (ui_out_is_mi_like_p (current_uiout))
13424     return;
13425
13426   switch (b->type)
13427     {
13428     case bp_breakpoint:
13429     case bp_gnu_ifunc_resolver:
13430       if (b->disposition == disp_del)
13431         printf_filtered (_("Temporary breakpoint"));
13432       else
13433         printf_filtered (_("Breakpoint"));
13434       printf_filtered (_(" %d"), b->number);
13435       if (b->type == bp_gnu_ifunc_resolver)
13436         printf_filtered (_(" at gnu-indirect-function resolver"));
13437       break;
13438     case bp_hardware_breakpoint:
13439       printf_filtered (_("Hardware assisted breakpoint %d"), b->number);
13440       break;
13441     case bp_dprintf:
13442       printf_filtered (_("Dprintf %d"), b->number);
13443       break;
13444     }
13445
13446   say_where (b);
13447 }
13448
13449 static void
13450 bkpt_print_recreate (struct breakpoint *tp, struct ui_file *fp)
13451 {
13452   if (tp->type == bp_breakpoint && tp->disposition == disp_del)
13453     fprintf_unfiltered (fp, "tbreak");
13454   else if (tp->type == bp_breakpoint)
13455     fprintf_unfiltered (fp, "break");
13456   else if (tp->type == bp_hardware_breakpoint
13457            && tp->disposition == disp_del)
13458     fprintf_unfiltered (fp, "thbreak");
13459   else if (tp->type == bp_hardware_breakpoint)
13460     fprintf_unfiltered (fp, "hbreak");
13461   else
13462     internal_error (__FILE__, __LINE__,
13463                     _("unhandled breakpoint type %d"), (int) tp->type);
13464
13465   fprintf_unfiltered (fp, " %s", tp->addr_string);
13466   print_recreate_thread (tp, fp);
13467 }
13468
13469 static void
13470 bkpt_create_sals_from_address (char **arg,
13471                                struct linespec_result *canonical,
13472                                enum bptype type_wanted,
13473                                char *addr_start, char **copy_arg)
13474 {
13475   create_sals_from_address_default (arg, canonical, type_wanted,
13476                                     addr_start, copy_arg);
13477 }
13478
13479 static void
13480 bkpt_create_breakpoints_sal (struct gdbarch *gdbarch,
13481                              struct linespec_result *canonical,
13482                              char *cond_string,
13483                              char *extra_string,
13484                              enum bptype type_wanted,
13485                              enum bpdisp disposition,
13486                              int thread,
13487                              int task, int ignore_count,
13488                              const struct breakpoint_ops *ops,
13489                              int from_tty, int enabled,
13490                              int internal, unsigned flags)
13491 {
13492   create_breakpoints_sal_default (gdbarch, canonical,
13493                                   cond_string, extra_string,
13494                                   type_wanted,
13495                                   disposition, thread, task,
13496                                   ignore_count, ops, from_tty,
13497                                   enabled, internal, flags);
13498 }
13499
13500 static void
13501 bkpt_decode_linespec (struct breakpoint *b, char **s,
13502                       struct symtabs_and_lines *sals)
13503 {
13504   decode_linespec_default (b, s, sals);
13505 }
13506
13507 /* Virtual table for internal breakpoints.  */
13508
13509 static void
13510 internal_bkpt_re_set (struct breakpoint *b)
13511 {
13512   switch (b->type)
13513     {
13514       /* Delete overlay event and longjmp master breakpoints; they
13515          will be reset later by breakpoint_re_set.  */
13516     case bp_overlay_event:
13517     case bp_longjmp_master:
13518     case bp_std_terminate_master:
13519     case bp_exception_master:
13520       delete_breakpoint (b);
13521       break;
13522
13523       /* This breakpoint is special, it's set up when the inferior
13524          starts and we really don't want to touch it.  */
13525     case bp_shlib_event:
13526
13527       /* Like bp_shlib_event, this breakpoint type is special.  Once
13528          it is set up, we do not want to touch it.  */
13529     case bp_thread_event:
13530       break;
13531     }
13532 }
13533
13534 static void
13535 internal_bkpt_check_status (bpstat bs)
13536 {
13537   if (bs->breakpoint_at->type == bp_shlib_event)
13538     {
13539       /* If requested, stop when the dynamic linker notifies GDB of
13540          events.  This allows the user to get control and place
13541          breakpoints in initializer routines for dynamically loaded
13542          objects (among other things).  */
13543       bs->stop = stop_on_solib_events;
13544       bs->print = stop_on_solib_events;
13545     }
13546   else
13547     bs->stop = 0;
13548 }
13549
13550 static enum print_stop_action
13551 internal_bkpt_print_it (bpstat bs)
13552 {
13553   struct breakpoint *b;
13554
13555   b = bs->breakpoint_at;
13556
13557   switch (b->type)
13558     {
13559     case bp_shlib_event:
13560       /* Did we stop because the user set the stop_on_solib_events
13561          variable?  (If so, we report this as a generic, "Stopped due
13562          to shlib event" message.) */
13563       print_solib_event (0);
13564       break;
13565
13566     case bp_thread_event:
13567       /* Not sure how we will get here.
13568          GDB should not stop for these breakpoints.  */
13569       printf_filtered (_("Thread Event Breakpoint: gdb should not stop!\n"));
13570       break;
13571
13572     case bp_overlay_event:
13573       /* By analogy with the thread event, GDB should not stop for these.  */
13574       printf_filtered (_("Overlay Event Breakpoint: gdb should not stop!\n"));
13575       break;
13576
13577     case bp_longjmp_master:
13578       /* These should never be enabled.  */
13579       printf_filtered (_("Longjmp Master Breakpoint: gdb should not stop!\n"));
13580       break;
13581
13582     case bp_std_terminate_master:
13583       /* These should never be enabled.  */
13584       printf_filtered (_("std::terminate Master Breakpoint: "
13585                          "gdb should not stop!\n"));
13586       break;
13587
13588     case bp_exception_master:
13589       /* These should never be enabled.  */
13590       printf_filtered (_("Exception Master Breakpoint: "
13591                          "gdb should not stop!\n"));
13592       break;
13593     }
13594
13595   return PRINT_NOTHING;
13596 }
13597
13598 static void
13599 internal_bkpt_print_mention (struct breakpoint *b)
13600 {
13601   /* Nothing to mention.  These breakpoints are internal.  */
13602 }
13603
13604 /* Virtual table for momentary breakpoints  */
13605
13606 static void
13607 momentary_bkpt_re_set (struct breakpoint *b)
13608 {
13609   /* Keep temporary breakpoints, which can be encountered when we step
13610      over a dlopen call and solib_add is resetting the breakpoints.
13611      Otherwise these should have been blown away via the cleanup chain
13612      or by breakpoint_init_inferior when we rerun the executable.  */
13613 }
13614
13615 static void
13616 momentary_bkpt_check_status (bpstat bs)
13617 {
13618   /* Nothing.  The point of these breakpoints is causing a stop.  */
13619 }
13620
13621 static enum print_stop_action
13622 momentary_bkpt_print_it (bpstat bs)
13623 {
13624   struct ui_out *uiout = current_uiout;
13625
13626   if (ui_out_is_mi_like_p (uiout))
13627     {
13628       struct breakpoint *b = bs->breakpoint_at;
13629
13630       switch (b->type)
13631         {
13632         case bp_finish:
13633           ui_out_field_string
13634             (uiout, "reason",
13635              async_reason_lookup (EXEC_ASYNC_FUNCTION_FINISHED));
13636           break;
13637
13638         case bp_until:
13639           ui_out_field_string
13640             (uiout, "reason",
13641              async_reason_lookup (EXEC_ASYNC_LOCATION_REACHED));
13642           break;
13643         }
13644     }
13645
13646   return PRINT_UNKNOWN;
13647 }
13648
13649 static void
13650 momentary_bkpt_print_mention (struct breakpoint *b)
13651 {
13652   /* Nothing to mention.  These breakpoints are internal.  */
13653 }
13654
13655 /* Ensure INITIATING_FRAME is cleared when no such breakpoint exists.
13656
13657    It gets cleared already on the removal of the first one of such placed
13658    breakpoints.  This is OK as they get all removed altogether.  */
13659
13660 static void
13661 longjmp_bkpt_dtor (struct breakpoint *self)
13662 {
13663   struct thread_info *tp = find_thread_id (self->thread);
13664
13665   if (tp)
13666     tp->initiating_frame = null_frame_id;
13667
13668   momentary_breakpoint_ops.dtor (self);
13669 }
13670
13671 /* Specific methods for probe breakpoints.  */
13672
13673 static int
13674 bkpt_probe_insert_location (struct bp_location *bl)
13675 {
13676   int v = bkpt_insert_location (bl);
13677
13678   if (v == 0)
13679     {
13680       /* The insertion was successful, now let's set the probe's semaphore
13681          if needed.  */
13682       if (bl->probe.probe->pops->set_semaphore != NULL)
13683         bl->probe.probe->pops->set_semaphore (bl->probe.probe,
13684                                               bl->probe.objfile,
13685                                               bl->gdbarch);
13686     }
13687
13688   return v;
13689 }
13690
13691 static int
13692 bkpt_probe_remove_location (struct bp_location *bl)
13693 {
13694   /* Let's clear the semaphore before removing the location.  */
13695   if (bl->probe.probe->pops->clear_semaphore != NULL)
13696     bl->probe.probe->pops->clear_semaphore (bl->probe.probe,
13697                                             bl->probe.objfile,
13698                                             bl->gdbarch);
13699
13700   return bkpt_remove_location (bl);
13701 }
13702
13703 static void
13704 bkpt_probe_create_sals_from_address (char **arg,
13705                                      struct linespec_result *canonical,
13706                                      enum bptype type_wanted,
13707                                      char *addr_start, char **copy_arg)
13708 {
13709   struct linespec_sals lsal;
13710
13711   lsal.sals = parse_probes (arg, canonical);
13712
13713   *copy_arg = xstrdup (canonical->addr_string);
13714   lsal.canonical = xstrdup (*copy_arg);
13715
13716   VEC_safe_push (linespec_sals, canonical->sals, &lsal);
13717 }
13718
13719 static void
13720 bkpt_probe_decode_linespec (struct breakpoint *b, char **s,
13721                             struct symtabs_and_lines *sals)
13722 {
13723   *sals = parse_probes (s, NULL);
13724   if (!sals->sals)
13725     error (_("probe not found"));
13726 }
13727
13728 /* The breakpoint_ops structure to be used in tracepoints.  */
13729
13730 static void
13731 tracepoint_re_set (struct breakpoint *b)
13732 {
13733   breakpoint_re_set_default (b);
13734 }
13735
13736 static int
13737 tracepoint_breakpoint_hit (const struct bp_location *bl,
13738                            struct address_space *aspace, CORE_ADDR bp_addr,
13739                            const struct target_waitstatus *ws)
13740 {
13741   /* By definition, the inferior does not report stops at
13742      tracepoints.  */
13743   return 0;
13744 }
13745
13746 static void
13747 tracepoint_print_one_detail (const struct breakpoint *self,
13748                              struct ui_out *uiout)
13749 {
13750   struct tracepoint *tp = (struct tracepoint *) self;
13751   if (tp->static_trace_marker_id)
13752     {
13753       gdb_assert (self->type == bp_static_tracepoint);
13754
13755       ui_out_text (uiout, "\tmarker id is ");
13756       ui_out_field_string (uiout, "static-tracepoint-marker-string-id",
13757                            tp->static_trace_marker_id);
13758       ui_out_text (uiout, "\n");
13759     }
13760 }
13761
13762 static void
13763 tracepoint_print_mention (struct breakpoint *b)
13764 {
13765   if (ui_out_is_mi_like_p (current_uiout))
13766     return;
13767
13768   switch (b->type)
13769     {
13770     case bp_tracepoint:
13771       printf_filtered (_("Tracepoint"));
13772       printf_filtered (_(" %d"), b->number);
13773       break;
13774     case bp_fast_tracepoint:
13775       printf_filtered (_("Fast tracepoint"));
13776       printf_filtered (_(" %d"), b->number);
13777       break;
13778     case bp_static_tracepoint:
13779       printf_filtered (_("Static tracepoint"));
13780       printf_filtered (_(" %d"), b->number);
13781       break;
13782     default:
13783       internal_error (__FILE__, __LINE__,
13784                       _("unhandled tracepoint type %d"), (int) b->type);
13785     }
13786
13787   say_where (b);
13788 }
13789
13790 static void
13791 tracepoint_print_recreate (struct breakpoint *self, struct ui_file *fp)
13792 {
13793   struct tracepoint *tp = (struct tracepoint *) self;
13794
13795   if (self->type == bp_fast_tracepoint)
13796     fprintf_unfiltered (fp, "ftrace");
13797   if (self->type == bp_static_tracepoint)
13798     fprintf_unfiltered (fp, "strace");
13799   else if (self->type == bp_tracepoint)
13800     fprintf_unfiltered (fp, "trace");
13801   else
13802     internal_error (__FILE__, __LINE__,
13803                     _("unhandled tracepoint type %d"), (int) self->type);
13804
13805   fprintf_unfiltered (fp, " %s", self->addr_string);
13806   print_recreate_thread (self, fp);
13807
13808   if (tp->pass_count)
13809     fprintf_unfiltered (fp, "  passcount %d\n", tp->pass_count);
13810 }
13811
13812 static void
13813 tracepoint_create_sals_from_address (char **arg,
13814                                      struct linespec_result *canonical,
13815                                      enum bptype type_wanted,
13816                                      char *addr_start, char **copy_arg)
13817 {
13818   create_sals_from_address_default (arg, canonical, type_wanted,
13819                                     addr_start, copy_arg);
13820 }
13821
13822 static void
13823 tracepoint_create_breakpoints_sal (struct gdbarch *gdbarch,
13824                                    struct linespec_result *canonical,
13825                                    char *cond_string,
13826                                    char *extra_string,
13827                                    enum bptype type_wanted,
13828                                    enum bpdisp disposition,
13829                                    int thread,
13830                                    int task, int ignore_count,
13831                                    const struct breakpoint_ops *ops,
13832                                    int from_tty, int enabled,
13833                                    int internal, unsigned flags)
13834 {
13835   create_breakpoints_sal_default (gdbarch, canonical,
13836                                   cond_string, extra_string,
13837                                   type_wanted,
13838                                   disposition, thread, task,
13839                                   ignore_count, ops, from_tty,
13840                                   enabled, internal, flags);
13841 }
13842
13843 static void
13844 tracepoint_decode_linespec (struct breakpoint *b, char **s,
13845                             struct symtabs_and_lines *sals)
13846 {
13847   decode_linespec_default (b, s, sals);
13848 }
13849
13850 struct breakpoint_ops tracepoint_breakpoint_ops;
13851
13852 /* The breakpoint_ops structure to be use on tracepoints placed in a
13853    static probe.  */
13854
13855 static void
13856 tracepoint_probe_create_sals_from_address (char **arg,
13857                                            struct linespec_result *canonical,
13858                                            enum bptype type_wanted,
13859                                            char *addr_start, char **copy_arg)
13860 {
13861   /* We use the same method for breakpoint on probes.  */
13862   bkpt_probe_create_sals_from_address (arg, canonical, type_wanted,
13863                                        addr_start, copy_arg);
13864 }
13865
13866 static void
13867 tracepoint_probe_decode_linespec (struct breakpoint *b, char **s,
13868                                   struct symtabs_and_lines *sals)
13869 {
13870   /* We use the same method for breakpoint on probes.  */
13871   bkpt_probe_decode_linespec (b, s, sals);
13872 }
13873
13874 static struct breakpoint_ops tracepoint_probe_breakpoint_ops;
13875
13876 /* Dprintf breakpoint_ops methods.  */
13877
13878 static void
13879 dprintf_re_set (struct breakpoint *b)
13880 {
13881   breakpoint_re_set_default (b);
13882
13883   /* This breakpoint could have been pending, and be resolved now, and
13884      if so, we should now have the extra string.  If we don't, the
13885      dprintf was malformed when created, but we couldn't tell because
13886      we can't extract the extra string until the location is
13887      resolved.  */
13888   if (b->loc != NULL && b->extra_string == NULL)
13889     error (_("Format string required"));
13890
13891   /* 1 - connect to target 1, that can run breakpoint commands.
13892      2 - create a dprintf, which resolves fine.
13893      3 - disconnect from target 1
13894      4 - connect to target 2, that can NOT run breakpoint commands.
13895
13896      After steps #3/#4, you'll want the dprintf command list to
13897      be updated, because target 1 and 2 may well return different
13898      answers for target_can_run_breakpoint_commands().
13899      Given absence of finer grained resetting, we get to do
13900      it all the time.  */
13901   if (b->extra_string != NULL)
13902     update_dprintf_command_list (b);
13903 }
13904
13905 /* Implement the "print_recreate" breakpoint_ops method for dprintf.  */
13906
13907 static void
13908 dprintf_print_recreate (struct breakpoint *tp, struct ui_file *fp)
13909 {
13910   fprintf_unfiltered (fp, "dprintf %s%s", tp->addr_string,
13911                       tp->extra_string);
13912   print_recreate_thread (tp, fp);
13913 }
13914
13915 /* Implement the "after_condition_true" breakpoint_ops method for
13916    dprintf.
13917
13918    dprintf's are implemented with regular commands in their command
13919    list, but we run the commands here instead of before presenting the
13920    stop to the user, as dprintf's don't actually cause a stop.  This
13921    also makes it so that the commands of multiple dprintfs at the same
13922    address are all handled.  */
13923
13924 static void
13925 dprintf_after_condition_true (struct bpstats *bs)
13926 {
13927   struct cleanup *old_chain;
13928   struct bpstats tmp_bs = { NULL };
13929   struct bpstats *tmp_bs_p = &tmp_bs;
13930
13931   /* dprintf's never cause a stop.  This wasn't set in the
13932      check_status hook instead because that would make the dprintf's
13933      condition not be evaluated.  */
13934   bs->stop = 0;
13935
13936   /* Run the command list here.  Take ownership of it instead of
13937      copying.  We never want these commands to run later in
13938      bpstat_do_actions, if a breakpoint that causes a stop happens to
13939      be set at same address as this dprintf, or even if running the
13940      commands here throws.  */
13941   tmp_bs.commands = bs->commands;
13942   bs->commands = NULL;
13943   old_chain = make_cleanup_decref_counted_command_line (&tmp_bs.commands);
13944
13945   bpstat_do_actions_1 (&tmp_bs_p);
13946
13947   /* 'tmp_bs.commands' will usually be NULL by now, but
13948      bpstat_do_actions_1 may return early without processing the whole
13949      list.  */
13950   do_cleanups (old_chain);
13951 }
13952
13953 /* The breakpoint_ops structure to be used on static tracepoints with
13954    markers (`-m').  */
13955
13956 static void
13957 strace_marker_create_sals_from_address (char **arg,
13958                                         struct linespec_result *canonical,
13959                                         enum bptype type_wanted,
13960                                         char *addr_start, char **copy_arg)
13961 {
13962   struct linespec_sals lsal;
13963
13964   lsal.sals = decode_static_tracepoint_spec (arg);
13965
13966   *copy_arg = savestring (addr_start, *arg - addr_start);
13967
13968   canonical->addr_string = xstrdup (*copy_arg);
13969   lsal.canonical = xstrdup (*copy_arg);
13970   VEC_safe_push (linespec_sals, canonical->sals, &lsal);
13971 }
13972
13973 static void
13974 strace_marker_create_breakpoints_sal (struct gdbarch *gdbarch,
13975                                       struct linespec_result *canonical,
13976                                       char *cond_string,
13977                                       char *extra_string,
13978                                       enum bptype type_wanted,
13979                                       enum bpdisp disposition,
13980                                       int thread,
13981                                       int task, int ignore_count,
13982                                       const struct breakpoint_ops *ops,
13983                                       int from_tty, int enabled,
13984                                       int internal, unsigned flags)
13985 {
13986   int i;
13987   struct linespec_sals *lsal = VEC_index (linespec_sals,
13988                                           canonical->sals, 0);
13989
13990   /* If the user is creating a static tracepoint by marker id
13991      (strace -m MARKER_ID), then store the sals index, so that
13992      breakpoint_re_set can try to match up which of the newly
13993      found markers corresponds to this one, and, don't try to
13994      expand multiple locations for each sal, given than SALS
13995      already should contain all sals for MARKER_ID.  */
13996
13997   for (i = 0; i < lsal->sals.nelts; ++i)
13998     {
13999       struct symtabs_and_lines expanded;
14000       struct tracepoint *tp;
14001       struct cleanup *old_chain;
14002       char *addr_string;
14003
14004       expanded.nelts = 1;
14005       expanded.sals = &lsal->sals.sals[i];
14006
14007       addr_string = xstrdup (canonical->addr_string);
14008       old_chain = make_cleanup (xfree, addr_string);
14009
14010       tp = XCNEW (struct tracepoint);
14011       init_breakpoint_sal (&tp->base, gdbarch, expanded,
14012                            addr_string, NULL,
14013                            cond_string, extra_string,
14014                            type_wanted, disposition,
14015                            thread, task, ignore_count, ops,
14016                            from_tty, enabled, internal, flags,
14017                            canonical->special_display);
14018       /* Given that its possible to have multiple markers with
14019          the same string id, if the user is creating a static
14020          tracepoint by marker id ("strace -m MARKER_ID"), then
14021          store the sals index, so that breakpoint_re_set can
14022          try to match up which of the newly found markers
14023          corresponds to this one  */
14024       tp->static_trace_marker_id_idx = i;
14025
14026       install_breakpoint (internal, &tp->base, 0);
14027
14028       discard_cleanups (old_chain);
14029     }
14030 }
14031
14032 static void
14033 strace_marker_decode_linespec (struct breakpoint *b, char **s,
14034                                struct symtabs_and_lines *sals)
14035 {
14036   struct tracepoint *tp = (struct tracepoint *) b;
14037
14038   *sals = decode_static_tracepoint_spec (s);
14039   if (sals->nelts > tp->static_trace_marker_id_idx)
14040     {
14041       sals->sals[0] = sals->sals[tp->static_trace_marker_id_idx];
14042       sals->nelts = 1;
14043     }
14044   else
14045     error (_("marker %s not found"), tp->static_trace_marker_id);
14046 }
14047
14048 static struct breakpoint_ops strace_marker_breakpoint_ops;
14049
14050 static int
14051 strace_marker_p (struct breakpoint *b)
14052 {
14053   return b->ops == &strace_marker_breakpoint_ops;
14054 }
14055
14056 /* Delete a breakpoint and clean up all traces of it in the data
14057    structures.  */
14058
14059 void
14060 delete_breakpoint (struct breakpoint *bpt)
14061 {
14062   struct breakpoint *b;
14063
14064   gdb_assert (bpt != NULL);
14065
14066   /* Has this bp already been deleted?  This can happen because
14067      multiple lists can hold pointers to bp's.  bpstat lists are
14068      especial culprits.
14069
14070      One example of this happening is a watchpoint's scope bp.  When
14071      the scope bp triggers, we notice that the watchpoint is out of
14072      scope, and delete it.  We also delete its scope bp.  But the
14073      scope bp is marked "auto-deleting", and is already on a bpstat.
14074      That bpstat is then checked for auto-deleting bp's, which are
14075      deleted.
14076
14077      A real solution to this problem might involve reference counts in
14078      bp's, and/or giving them pointers back to their referencing
14079      bpstat's, and teaching delete_breakpoint to only free a bp's
14080      storage when no more references were extent.  A cheaper bandaid
14081      was chosen.  */
14082   if (bpt->type == bp_none)
14083     return;
14084
14085   /* At least avoid this stale reference until the reference counting
14086      of breakpoints gets resolved.  */
14087   if (bpt->related_breakpoint != bpt)
14088     {
14089       struct breakpoint *related;
14090       struct watchpoint *w;
14091
14092       if (bpt->type == bp_watchpoint_scope)
14093         w = (struct watchpoint *) bpt->related_breakpoint;
14094       else if (bpt->related_breakpoint->type == bp_watchpoint_scope)
14095         w = (struct watchpoint *) bpt;
14096       else
14097         w = NULL;
14098       if (w != NULL)
14099         watchpoint_del_at_next_stop (w);
14100
14101       /* Unlink bpt from the bpt->related_breakpoint ring.  */
14102       for (related = bpt; related->related_breakpoint != bpt;
14103            related = related->related_breakpoint);
14104       related->related_breakpoint = bpt->related_breakpoint;
14105       bpt->related_breakpoint = bpt;
14106     }
14107
14108   /* watch_command_1 creates a watchpoint but only sets its number if
14109      update_watchpoint succeeds in creating its bp_locations.  If there's
14110      a problem in that process, we'll be asked to delete the half-created
14111      watchpoint.  In that case, don't announce the deletion.  */
14112   if (bpt->number)
14113     observer_notify_breakpoint_deleted (bpt);
14114
14115   if (breakpoint_chain == bpt)
14116     breakpoint_chain = bpt->next;
14117
14118   ALL_BREAKPOINTS (b)
14119     if (b->next == bpt)
14120     {
14121       b->next = bpt->next;
14122       break;
14123     }
14124
14125   /* Be sure no bpstat's are pointing at the breakpoint after it's
14126      been freed.  */
14127   /* FIXME, how can we find all bpstat's?  We just check stop_bpstat
14128      in all threads for now.  Note that we cannot just remove bpstats
14129      pointing at bpt from the stop_bpstat list entirely, as breakpoint
14130      commands are associated with the bpstat; if we remove it here,
14131      then the later call to bpstat_do_actions (&stop_bpstat); in
14132      event-top.c won't do anything, and temporary breakpoints with
14133      commands won't work.  */
14134
14135   iterate_over_threads (bpstat_remove_breakpoint_callback, bpt);
14136
14137   /* Now that breakpoint is removed from breakpoint list, update the
14138      global location list.  This will remove locations that used to
14139      belong to this breakpoint.  Do this before freeing the breakpoint
14140      itself, since remove_breakpoint looks at location's owner.  It
14141      might be better design to have location completely
14142      self-contained, but it's not the case now.  */
14143   update_global_location_list (UGLL_DONT_INSERT);
14144
14145   bpt->ops->dtor (bpt);
14146   /* On the chance that someone will soon try again to delete this
14147      same bp, we mark it as deleted before freeing its storage.  */
14148   bpt->type = bp_none;
14149   xfree (bpt);
14150 }
14151
14152 static void
14153 do_delete_breakpoint_cleanup (void *b)
14154 {
14155   delete_breakpoint (b);
14156 }
14157
14158 struct cleanup *
14159 make_cleanup_delete_breakpoint (struct breakpoint *b)
14160 {
14161   return make_cleanup (do_delete_breakpoint_cleanup, b);
14162 }
14163
14164 /* Iterator function to call a user-provided callback function once
14165    for each of B and its related breakpoints.  */
14166
14167 static void
14168 iterate_over_related_breakpoints (struct breakpoint *b,
14169                                   void (*function) (struct breakpoint *,
14170                                                     void *),
14171                                   void *data)
14172 {
14173   struct breakpoint *related;
14174
14175   related = b;
14176   do
14177     {
14178       struct breakpoint *next;
14179
14180       /* FUNCTION may delete RELATED.  */
14181       next = related->related_breakpoint;
14182
14183       if (next == related)
14184         {
14185           /* RELATED is the last ring entry.  */
14186           function (related, data);
14187
14188           /* FUNCTION may have deleted it, so we'd never reach back to
14189              B.  There's nothing left to do anyway, so just break
14190              out.  */
14191           break;
14192         }
14193       else
14194         function (related, data);
14195
14196       related = next;
14197     }
14198   while (related != b);
14199 }
14200
14201 static void
14202 do_delete_breakpoint (struct breakpoint *b, void *ignore)
14203 {
14204   delete_breakpoint (b);
14205 }
14206
14207 /* A callback for map_breakpoint_numbers that calls
14208    delete_breakpoint.  */
14209
14210 static void
14211 do_map_delete_breakpoint (struct breakpoint *b, void *ignore)
14212 {
14213   iterate_over_related_breakpoints (b, do_delete_breakpoint, NULL);
14214 }
14215
14216 void
14217 delete_command (char *arg, int from_tty)
14218 {
14219   struct breakpoint *b, *b_tmp;
14220
14221   dont_repeat ();
14222
14223   if (arg == 0)
14224     {
14225       int breaks_to_delete = 0;
14226
14227       /* Delete all breakpoints if no argument.  Do not delete
14228          internal breakpoints, these have to be deleted with an
14229          explicit breakpoint number argument.  */
14230       ALL_BREAKPOINTS (b)
14231         if (user_breakpoint_p (b))
14232           {
14233             breaks_to_delete = 1;
14234             break;
14235           }
14236
14237       /* Ask user only if there are some breakpoints to delete.  */
14238       if (!from_tty
14239           || (breaks_to_delete && query (_("Delete all breakpoints? "))))
14240         {
14241           ALL_BREAKPOINTS_SAFE (b, b_tmp)
14242             if (user_breakpoint_p (b))
14243               delete_breakpoint (b);
14244         }
14245     }
14246   else
14247     map_breakpoint_numbers (arg, do_map_delete_breakpoint, NULL);
14248 }
14249
14250 static int
14251 all_locations_are_pending (struct bp_location *loc)
14252 {
14253   for (; loc; loc = loc->next)
14254     if (!loc->shlib_disabled
14255         && !loc->pspace->executing_startup)
14256       return 0;
14257   return 1;
14258 }
14259
14260 /* Subroutine of update_breakpoint_locations to simplify it.
14261    Return non-zero if multiple fns in list LOC have the same name.
14262    Null names are ignored.  */
14263
14264 static int
14265 ambiguous_names_p (struct bp_location *loc)
14266 {
14267   struct bp_location *l;
14268   htab_t htab = htab_create_alloc (13, htab_hash_string,
14269                                    (int (*) (const void *, 
14270                                              const void *)) streq,
14271                                    NULL, xcalloc, xfree);
14272
14273   for (l = loc; l != NULL; l = l->next)
14274     {
14275       const char **slot;
14276       const char *name = l->function_name;
14277
14278       /* Allow for some names to be NULL, ignore them.  */
14279       if (name == NULL)
14280         continue;
14281
14282       slot = (const char **) htab_find_slot (htab, (const void *) name,
14283                                              INSERT);
14284       /* NOTE: We can assume slot != NULL here because xcalloc never
14285          returns NULL.  */
14286       if (*slot != NULL)
14287         {
14288           htab_delete (htab);
14289           return 1;
14290         }
14291       *slot = name;
14292     }
14293
14294   htab_delete (htab);
14295   return 0;
14296 }
14297
14298 /* When symbols change, it probably means the sources changed as well,
14299    and it might mean the static tracepoint markers are no longer at
14300    the same address or line numbers they used to be at last we
14301    checked.  Losing your static tracepoints whenever you rebuild is
14302    undesirable.  This function tries to resync/rematch gdb static
14303    tracepoints with the markers on the target, for static tracepoints
14304    that have not been set by marker id.  Static tracepoint that have
14305    been set by marker id are reset by marker id in breakpoint_re_set.
14306    The heuristic is:
14307
14308    1) For a tracepoint set at a specific address, look for a marker at
14309    the old PC.  If one is found there, assume to be the same marker.
14310    If the name / string id of the marker found is different from the
14311    previous known name, assume that means the user renamed the marker
14312    in the sources, and output a warning.
14313
14314    2) For a tracepoint set at a given line number, look for a marker
14315    at the new address of the old line number.  If one is found there,
14316    assume to be the same marker.  If the name / string id of the
14317    marker found is different from the previous known name, assume that
14318    means the user renamed the marker in the sources, and output a
14319    warning.
14320
14321    3) If a marker is no longer found at the same address or line, it
14322    may mean the marker no longer exists.  But it may also just mean
14323    the code changed a bit.  Maybe the user added a few lines of code
14324    that made the marker move up or down (in line number terms).  Ask
14325    the target for info about the marker with the string id as we knew
14326    it.  If found, update line number and address in the matching
14327    static tracepoint.  This will get confused if there's more than one
14328    marker with the same ID (possible in UST, although unadvised
14329    precisely because it confuses tools).  */
14330
14331 static struct symtab_and_line
14332 update_static_tracepoint (struct breakpoint *b, struct symtab_and_line sal)
14333 {
14334   struct tracepoint *tp = (struct tracepoint *) b;
14335   struct static_tracepoint_marker marker;
14336   CORE_ADDR pc;
14337
14338   pc = sal.pc;
14339   if (sal.line)
14340     find_line_pc (sal.symtab, sal.line, &pc);
14341
14342   if (target_static_tracepoint_marker_at (pc, &marker))
14343     {
14344       if (strcmp (tp->static_trace_marker_id, marker.str_id) != 0)
14345         warning (_("static tracepoint %d changed probed marker from %s to %s"),
14346                  b->number,
14347                  tp->static_trace_marker_id, marker.str_id);
14348
14349       xfree (tp->static_trace_marker_id);
14350       tp->static_trace_marker_id = xstrdup (marker.str_id);
14351       release_static_tracepoint_marker (&marker);
14352
14353       return sal;
14354     }
14355
14356   /* Old marker wasn't found on target at lineno.  Try looking it up
14357      by string ID.  */
14358   if (!sal.explicit_pc
14359       && sal.line != 0
14360       && sal.symtab != NULL
14361       && tp->static_trace_marker_id != NULL)
14362     {
14363       VEC(static_tracepoint_marker_p) *markers;
14364
14365       markers
14366         = target_static_tracepoint_markers_by_strid (tp->static_trace_marker_id);
14367
14368       if (!VEC_empty(static_tracepoint_marker_p, markers))
14369         {
14370           struct symtab_and_line sal2;
14371           struct symbol *sym;
14372           struct static_tracepoint_marker *tpmarker;
14373           struct ui_out *uiout = current_uiout;
14374
14375           tpmarker = VEC_index (static_tracepoint_marker_p, markers, 0);
14376
14377           xfree (tp->static_trace_marker_id);
14378           tp->static_trace_marker_id = xstrdup (tpmarker->str_id);
14379
14380           warning (_("marker for static tracepoint %d (%s) not "
14381                      "found at previous line number"),
14382                    b->number, tp->static_trace_marker_id);
14383
14384           init_sal (&sal2);
14385
14386           sal2.pc = tpmarker->address;
14387
14388           sal2 = find_pc_line (tpmarker->address, 0);
14389           sym = find_pc_sect_function (tpmarker->address, NULL);
14390           ui_out_text (uiout, "Now in ");
14391           if (sym)
14392             {
14393               ui_out_field_string (uiout, "func",
14394                                    SYMBOL_PRINT_NAME (sym));
14395               ui_out_text (uiout, " at ");
14396             }
14397           ui_out_field_string (uiout, "file",
14398                                symtab_to_filename_for_display (sal2.symtab));
14399           ui_out_text (uiout, ":");
14400
14401           if (ui_out_is_mi_like_p (uiout))
14402             {
14403               const char *fullname = symtab_to_fullname (sal2.symtab);
14404
14405               ui_out_field_string (uiout, "fullname", fullname);
14406             }
14407
14408           ui_out_field_int (uiout, "line", sal2.line);
14409           ui_out_text (uiout, "\n");
14410
14411           b->loc->line_number = sal2.line;
14412           b->loc->symtab = sym != NULL ? sal2.symtab : NULL;
14413
14414           xfree (b->addr_string);
14415           b->addr_string = xstrprintf ("%s:%d",
14416                                    symtab_to_filename_for_display (sal2.symtab),
14417                                        b->loc->line_number);
14418
14419           /* Might be nice to check if function changed, and warn if
14420              so.  */
14421
14422           release_static_tracepoint_marker (tpmarker);
14423         }
14424     }
14425   return sal;
14426 }
14427
14428 /* Returns 1 iff locations A and B are sufficiently same that
14429    we don't need to report breakpoint as changed.  */
14430
14431 static int
14432 locations_are_equal (struct bp_location *a, struct bp_location *b)
14433 {
14434   while (a && b)
14435     {
14436       if (a->address != b->address)
14437         return 0;
14438
14439       if (a->shlib_disabled != b->shlib_disabled)
14440         return 0;
14441
14442       if (a->enabled != b->enabled)
14443         return 0;
14444
14445       a = a->next;
14446       b = b->next;
14447     }
14448
14449   if ((a == NULL) != (b == NULL))
14450     return 0;
14451
14452   return 1;
14453 }
14454
14455 /* Create new breakpoint locations for B (a hardware or software breakpoint)
14456    based on SALS and SALS_END.  If SALS_END.NELTS is not zero, then B is
14457    a ranged breakpoint.  */
14458
14459 void
14460 update_breakpoint_locations (struct breakpoint *b,
14461                              struct symtabs_and_lines sals,
14462                              struct symtabs_and_lines sals_end)
14463 {
14464   int i;
14465   struct bp_location *existing_locations = b->loc;
14466
14467   if (sals_end.nelts != 0 && (sals.nelts != 1 || sals_end.nelts != 1))
14468     {
14469       /* Ranged breakpoints have only one start location and one end
14470          location.  */
14471       b->enable_state = bp_disabled;
14472       update_global_location_list (UGLL_MAY_INSERT);
14473       printf_unfiltered (_("Could not reset ranged breakpoint %d: "
14474                            "multiple locations found\n"),
14475                          b->number);
14476       return;
14477     }
14478
14479   /* If there's no new locations, and all existing locations are
14480      pending, don't do anything.  This optimizes the common case where
14481      all locations are in the same shared library, that was unloaded.
14482      We'd like to retain the location, so that when the library is
14483      loaded again, we don't loose the enabled/disabled status of the
14484      individual locations.  */
14485   if (all_locations_are_pending (existing_locations) && sals.nelts == 0)
14486     return;
14487
14488   b->loc = NULL;
14489
14490   for (i = 0; i < sals.nelts; ++i)
14491     {
14492       struct bp_location *new_loc;
14493
14494       switch_to_program_space_and_thread (sals.sals[i].pspace);
14495
14496       new_loc = add_location_to_breakpoint (b, &(sals.sals[i]));
14497
14498       /* Reparse conditions, they might contain references to the
14499          old symtab.  */
14500       if (b->cond_string != NULL)
14501         {
14502           const char *s;
14503
14504           s = b->cond_string;
14505           TRY
14506             {
14507               new_loc->cond = parse_exp_1 (&s, sals.sals[i].pc,
14508                                            block_for_pc (sals.sals[i].pc), 
14509                                            0);
14510             }
14511           CATCH (e, RETURN_MASK_ERROR)
14512             {
14513               warning (_("failed to reevaluate condition "
14514                          "for breakpoint %d: %s"), 
14515                        b->number, e.message);
14516               new_loc->enabled = 0;
14517             }
14518           END_CATCH
14519         }
14520
14521       if (sals_end.nelts)
14522         {
14523           CORE_ADDR end = find_breakpoint_range_end (sals_end.sals[0]);
14524
14525           new_loc->length = end - sals.sals[0].pc + 1;
14526         }
14527     }
14528
14529   /* If possible, carry over 'disable' status from existing
14530      breakpoints.  */
14531   {
14532     struct bp_location *e = existing_locations;
14533     /* If there are multiple breakpoints with the same function name,
14534        e.g. for inline functions, comparing function names won't work.
14535        Instead compare pc addresses; this is just a heuristic as things
14536        may have moved, but in practice it gives the correct answer
14537        often enough until a better solution is found.  */
14538     int have_ambiguous_names = ambiguous_names_p (b->loc);
14539
14540     for (; e; e = e->next)
14541       {
14542         if (!e->enabled && e->function_name)
14543           {
14544             struct bp_location *l = b->loc;
14545             if (have_ambiguous_names)
14546               {
14547                 for (; l; l = l->next)
14548                   if (breakpoint_locations_match (e, l))
14549                     {
14550                       l->enabled = 0;
14551                       break;
14552                     }
14553               }
14554             else
14555               {
14556                 for (; l; l = l->next)
14557                   if (l->function_name
14558                       && strcmp (e->function_name, l->function_name) == 0)
14559                     {
14560                       l->enabled = 0;
14561                       break;
14562                     }
14563               }
14564           }
14565       }
14566   }
14567
14568   if (!locations_are_equal (existing_locations, b->loc))
14569     observer_notify_breakpoint_modified (b);
14570
14571   update_global_location_list (UGLL_MAY_INSERT);
14572 }
14573
14574 /* Find the SaL locations corresponding to the given ADDR_STRING.
14575    On return, FOUND will be 1 if any SaL was found, zero otherwise.  */
14576
14577 static struct symtabs_and_lines
14578 addr_string_to_sals (struct breakpoint *b, char *addr_string, int *found)
14579 {
14580   char *s;
14581   struct symtabs_and_lines sals = {0};
14582   struct gdb_exception exception = exception_none;
14583
14584   gdb_assert (b->ops != NULL);
14585   s = addr_string;
14586
14587   TRY
14588     {
14589       b->ops->decode_linespec (b, &s, &sals);
14590     }
14591   CATCH (e, RETURN_MASK_ERROR)
14592     {
14593       int not_found_and_ok = 0;
14594
14595       exception = e;
14596
14597       /* For pending breakpoints, it's expected that parsing will
14598          fail until the right shared library is loaded.  User has
14599          already told to create pending breakpoints and don't need
14600          extra messages.  If breakpoint is in bp_shlib_disabled
14601          state, then user already saw the message about that
14602          breakpoint being disabled, and don't want to see more
14603          errors.  */
14604       if (e.error == NOT_FOUND_ERROR
14605           && (b->condition_not_parsed 
14606               || (b->loc && b->loc->shlib_disabled)
14607               || (b->loc && b->loc->pspace->executing_startup)
14608               || b->enable_state == bp_disabled))
14609         not_found_and_ok = 1;
14610
14611       if (!not_found_and_ok)
14612         {
14613           /* We surely don't want to warn about the same breakpoint
14614              10 times.  One solution, implemented here, is disable
14615              the breakpoint on error.  Another solution would be to
14616              have separate 'warning emitted' flag.  Since this
14617              happens only when a binary has changed, I don't know
14618              which approach is better.  */
14619           b->enable_state = bp_disabled;
14620           throw_exception (e);
14621         }
14622     }
14623   END_CATCH
14624
14625   if (exception.reason == 0 || exception.error != NOT_FOUND_ERROR)
14626     {
14627       int i;
14628
14629       for (i = 0; i < sals.nelts; ++i)
14630         resolve_sal_pc (&sals.sals[i]);
14631       if (b->condition_not_parsed && s && s[0])
14632         {
14633           char *cond_string, *extra_string;
14634           int thread, task;
14635
14636           find_condition_and_thread (s, sals.sals[0].pc,
14637                                      &cond_string, &thread, &task,
14638                                      &extra_string);
14639           if (cond_string)
14640             b->cond_string = cond_string;
14641           b->thread = thread;
14642           b->task = task;
14643           if (extra_string)
14644             b->extra_string = extra_string;
14645           b->condition_not_parsed = 0;
14646         }
14647
14648       if (b->type == bp_static_tracepoint && !strace_marker_p (b))
14649         sals.sals[0] = update_static_tracepoint (b, sals.sals[0]);
14650
14651       *found = 1;
14652     }
14653   else
14654     *found = 0;
14655
14656   return sals;
14657 }
14658
14659 /* The default re_set method, for typical hardware or software
14660    breakpoints.  Reevaluate the breakpoint and recreate its
14661    locations.  */
14662
14663 static void
14664 breakpoint_re_set_default (struct breakpoint *b)
14665 {
14666   int found;
14667   struct symtabs_and_lines sals, sals_end;
14668   struct symtabs_and_lines expanded = {0};
14669   struct symtabs_and_lines expanded_end = {0};
14670
14671   sals = addr_string_to_sals (b, b->addr_string, &found);
14672   if (found)
14673     {
14674       make_cleanup (xfree, sals.sals);
14675       expanded = sals;
14676     }
14677
14678   if (b->addr_string_range_end)
14679     {
14680       sals_end = addr_string_to_sals (b, b->addr_string_range_end, &found);
14681       if (found)
14682         {
14683           make_cleanup (xfree, sals_end.sals);
14684           expanded_end = sals_end;
14685         }
14686     }
14687
14688   update_breakpoint_locations (b, expanded, expanded_end);
14689 }
14690
14691 /* Default method for creating SALs from an address string.  It basically
14692    calls parse_breakpoint_sals.  Return 1 for success, zero for failure.  */
14693
14694 static void
14695 create_sals_from_address_default (char **arg,
14696                                   struct linespec_result *canonical,
14697                                   enum bptype type_wanted,
14698                                   char *addr_start, char **copy_arg)
14699 {
14700   parse_breakpoint_sals (arg, canonical);
14701 }
14702
14703 /* Call create_breakpoints_sal for the given arguments.  This is the default
14704    function for the `create_breakpoints_sal' method of
14705    breakpoint_ops.  */
14706
14707 static void
14708 create_breakpoints_sal_default (struct gdbarch *gdbarch,
14709                                 struct linespec_result *canonical,
14710                                 char *cond_string,
14711                                 char *extra_string,
14712                                 enum bptype type_wanted,
14713                                 enum bpdisp disposition,
14714                                 int thread,
14715                                 int task, int ignore_count,
14716                                 const struct breakpoint_ops *ops,
14717                                 int from_tty, int enabled,
14718                                 int internal, unsigned flags)
14719 {
14720   create_breakpoints_sal (gdbarch, canonical, cond_string,
14721                           extra_string,
14722                           type_wanted, disposition,
14723                           thread, task, ignore_count, ops, from_tty,
14724                           enabled, internal, flags);
14725 }
14726
14727 /* Decode the line represented by S by calling decode_line_full.  This is the
14728    default function for the `decode_linespec' method of breakpoint_ops.  */
14729
14730 static void
14731 decode_linespec_default (struct breakpoint *b, char **s,
14732                          struct symtabs_and_lines *sals)
14733 {
14734   struct linespec_result canonical;
14735
14736   init_linespec_result (&canonical);
14737   decode_line_full (s, DECODE_LINE_FUNFIRSTLINE,
14738                     (struct symtab *) NULL, 0,
14739                     &canonical, multiple_symbols_all,
14740                     b->filter);
14741
14742   /* We should get 0 or 1 resulting SALs.  */
14743   gdb_assert (VEC_length (linespec_sals, canonical.sals) < 2);
14744
14745   if (VEC_length (linespec_sals, canonical.sals) > 0)
14746     {
14747       struct linespec_sals *lsal;
14748
14749       lsal = VEC_index (linespec_sals, canonical.sals, 0);
14750       *sals = lsal->sals;
14751       /* Arrange it so the destructor does not free the
14752          contents.  */
14753       lsal->sals.sals = NULL;
14754     }
14755
14756   destroy_linespec_result (&canonical);
14757 }
14758
14759 /* Prepare the global context for a re-set of breakpoint B.  */
14760
14761 static struct cleanup *
14762 prepare_re_set_context (struct breakpoint *b)
14763 {
14764   struct cleanup *cleanups;
14765
14766   input_radix = b->input_radix;
14767   cleanups = save_current_space_and_thread ();
14768   if (b->pspace != NULL)
14769     switch_to_program_space_and_thread (b->pspace);
14770   set_language (b->language);
14771
14772   return cleanups;
14773 }
14774
14775 /* Reset a breakpoint given it's struct breakpoint * BINT.
14776    The value we return ends up being the return value from catch_errors.
14777    Unused in this case.  */
14778
14779 static int
14780 breakpoint_re_set_one (void *bint)
14781 {
14782   /* Get past catch_errs.  */
14783   struct breakpoint *b = (struct breakpoint *) bint;
14784   struct cleanup *cleanups;
14785
14786   cleanups = prepare_re_set_context (b);
14787   b->ops->re_set (b);
14788   do_cleanups (cleanups);
14789   return 0;
14790 }
14791
14792 /* Re-set all breakpoints after symbols have been re-loaded.  */
14793 void
14794 breakpoint_re_set (void)
14795 {
14796   struct breakpoint *b, *b_tmp;
14797   enum language save_language;
14798   int save_input_radix;
14799   struct cleanup *old_chain;
14800
14801   save_language = current_language->la_language;
14802   save_input_radix = input_radix;
14803   old_chain = save_current_program_space ();
14804
14805   ALL_BREAKPOINTS_SAFE (b, b_tmp)
14806   {
14807     /* Format possible error msg.  */
14808     char *message = xstrprintf ("Error in re-setting breakpoint %d: ",
14809                                 b->number);
14810     struct cleanup *cleanups = make_cleanup (xfree, message);
14811     catch_errors (breakpoint_re_set_one, b, message, RETURN_MASK_ALL);
14812     do_cleanups (cleanups);
14813   }
14814   set_language (save_language);
14815   input_radix = save_input_radix;
14816
14817   jit_breakpoint_re_set ();
14818
14819   do_cleanups (old_chain);
14820
14821   create_overlay_event_breakpoint ();
14822   create_longjmp_master_breakpoint ();
14823   create_std_terminate_master_breakpoint ();
14824   create_exception_master_breakpoint ();
14825 }
14826 \f
14827 /* Reset the thread number of this breakpoint:
14828
14829    - If the breakpoint is for all threads, leave it as-is.
14830    - Else, reset it to the current thread for inferior_ptid.  */
14831 void
14832 breakpoint_re_set_thread (struct breakpoint *b)
14833 {
14834   if (b->thread != -1)
14835     {
14836       if (in_thread_list (inferior_ptid))
14837         b->thread = pid_to_thread_id (inferior_ptid);
14838
14839       /* We're being called after following a fork.  The new fork is
14840          selected as current, and unless this was a vfork will have a
14841          different program space from the original thread.  Reset that
14842          as well.  */
14843       b->loc->pspace = current_program_space;
14844     }
14845 }
14846
14847 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
14848    If from_tty is nonzero, it prints a message to that effect,
14849    which ends with a period (no newline).  */
14850
14851 void
14852 set_ignore_count (int bptnum, int count, int from_tty)
14853 {
14854   struct breakpoint *b;
14855
14856   if (count < 0)
14857     count = 0;
14858
14859   ALL_BREAKPOINTS (b)
14860     if (b->number == bptnum)
14861     {
14862       if (is_tracepoint (b))
14863         {
14864           if (from_tty && count != 0)
14865             printf_filtered (_("Ignore count ignored for tracepoint %d."),
14866                              bptnum);
14867           return;
14868         }
14869       
14870       b->ignore_count = count;
14871       if (from_tty)
14872         {
14873           if (count == 0)
14874             printf_filtered (_("Will stop next time "
14875                                "breakpoint %d is reached."),
14876                              bptnum);
14877           else if (count == 1)
14878             printf_filtered (_("Will ignore next crossing of breakpoint %d."),
14879                              bptnum);
14880           else
14881             printf_filtered (_("Will ignore next %d "
14882                                "crossings of breakpoint %d."),
14883                              count, bptnum);
14884         }
14885       observer_notify_breakpoint_modified (b);
14886       return;
14887     }
14888
14889   error (_("No breakpoint number %d."), bptnum);
14890 }
14891
14892 /* Command to set ignore-count of breakpoint N to COUNT.  */
14893
14894 static void
14895 ignore_command (char *args, int from_tty)
14896 {
14897   char *p = args;
14898   int num;
14899
14900   if (p == 0)
14901     error_no_arg (_("a breakpoint number"));
14902
14903   num = get_number (&p);
14904   if (num == 0)
14905     error (_("bad breakpoint number: '%s'"), args);
14906   if (*p == 0)
14907     error (_("Second argument (specified ignore-count) is missing."));
14908
14909   set_ignore_count (num,
14910                     longest_to_int (value_as_long (parse_and_eval (p))),
14911                     from_tty);
14912   if (from_tty)
14913     printf_filtered ("\n");
14914 }
14915 \f
14916 /* Call FUNCTION on each of the breakpoints
14917    whose numbers are given in ARGS.  */
14918
14919 static void
14920 map_breakpoint_numbers (char *args, void (*function) (struct breakpoint *,
14921                                                       void *),
14922                         void *data)
14923 {
14924   int num;
14925   struct breakpoint *b, *tmp;
14926   int match;
14927   struct get_number_or_range_state state;
14928
14929   if (args == 0 || *args == '\0')
14930     error_no_arg (_("one or more breakpoint numbers"));
14931
14932   init_number_or_range (&state, args);
14933
14934   while (!state.finished)
14935     {
14936       const char *p = state.string;
14937
14938       match = 0;
14939
14940       num = get_number_or_range (&state);
14941       if (num == 0)
14942         {
14943           warning (_("bad breakpoint number at or near '%s'"), p);
14944         }
14945       else
14946         {
14947           ALL_BREAKPOINTS_SAFE (b, tmp)
14948             if (b->number == num)
14949               {
14950                 match = 1;
14951                 function (b, data);
14952                 break;
14953               }
14954           if (match == 0)
14955             printf_unfiltered (_("No breakpoint number %d.\n"), num);
14956         }
14957     }
14958 }
14959
14960 static struct bp_location *
14961 find_location_by_number (char *number)
14962 {
14963   char *dot = strchr (number, '.');
14964   char *p1;
14965   int bp_num;
14966   int loc_num;
14967   struct breakpoint *b;
14968   struct bp_location *loc;  
14969
14970   *dot = '\0';
14971
14972   p1 = number;
14973   bp_num = get_number (&p1);
14974   if (bp_num == 0)
14975     error (_("Bad breakpoint number '%s'"), number);
14976
14977   ALL_BREAKPOINTS (b)
14978     if (b->number == bp_num)
14979       {
14980         break;
14981       }
14982
14983   if (!b || b->number != bp_num)
14984     error (_("Bad breakpoint number '%s'"), number);
14985   
14986   p1 = dot+1;
14987   loc_num = get_number (&p1);
14988   if (loc_num == 0)
14989     error (_("Bad breakpoint location number '%s'"), number);
14990
14991   --loc_num;
14992   loc = b->loc;
14993   for (;loc_num && loc; --loc_num, loc = loc->next)
14994     ;
14995   if (!loc)
14996     error (_("Bad breakpoint location number '%s'"), dot+1);
14997     
14998   return loc;  
14999 }
15000
15001
15002 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
15003    If from_tty is nonzero, it prints a message to that effect,
15004    which ends with a period (no newline).  */
15005
15006 void
15007 disable_breakpoint (struct breakpoint *bpt)
15008 {
15009   /* Never disable a watchpoint scope breakpoint; we want to
15010      hit them when we leave scope so we can delete both the
15011      watchpoint and its scope breakpoint at that time.  */
15012   if (bpt->type == bp_watchpoint_scope)
15013     return;
15014
15015   bpt->enable_state = bp_disabled;
15016
15017   /* Mark breakpoint locations modified.  */
15018   mark_breakpoint_modified (bpt);
15019
15020   if (target_supports_enable_disable_tracepoint ()
15021       && current_trace_status ()->running && is_tracepoint (bpt))
15022     {
15023       struct bp_location *location;
15024      
15025       for (location = bpt->loc; location; location = location->next)
15026         target_disable_tracepoint (location);
15027     }
15028
15029   update_global_location_list (UGLL_DONT_INSERT);
15030
15031   observer_notify_breakpoint_modified (bpt);
15032 }
15033
15034 /* A callback for iterate_over_related_breakpoints.  */
15035
15036 static void
15037 do_disable_breakpoint (struct breakpoint *b, void *ignore)
15038 {
15039   disable_breakpoint (b);
15040 }
15041
15042 /* A callback for map_breakpoint_numbers that calls
15043    disable_breakpoint.  */
15044
15045 static void
15046 do_map_disable_breakpoint (struct breakpoint *b, void *ignore)
15047 {
15048   iterate_over_related_breakpoints (b, do_disable_breakpoint, NULL);
15049 }
15050
15051 static void
15052 disable_command (char *args, int from_tty)
15053 {
15054   if (args == 0)
15055     {
15056       struct breakpoint *bpt;
15057
15058       ALL_BREAKPOINTS (bpt)
15059         if (user_breakpoint_p (bpt))
15060           disable_breakpoint (bpt);
15061     }
15062   else
15063     {
15064       char *num = extract_arg (&args);
15065
15066       while (num)
15067         {
15068           if (strchr (num, '.'))
15069             {
15070               struct bp_location *loc = find_location_by_number (num);
15071
15072               if (loc)
15073                 {
15074                   if (loc->enabled)
15075                     {
15076                       loc->enabled = 0;
15077                       mark_breakpoint_location_modified (loc);
15078                     }
15079                   if (target_supports_enable_disable_tracepoint ()
15080                       && current_trace_status ()->running && loc->owner
15081                       && is_tracepoint (loc->owner))
15082                     target_disable_tracepoint (loc);
15083                 }
15084               update_global_location_list (UGLL_DONT_INSERT);
15085             }
15086           else
15087             map_breakpoint_numbers (num, do_map_disable_breakpoint, NULL);
15088           num = extract_arg (&args);
15089         }
15090     }
15091 }
15092
15093 static void
15094 enable_breakpoint_disp (struct breakpoint *bpt, enum bpdisp disposition,
15095                         int count)
15096 {
15097   int target_resources_ok;
15098
15099   if (bpt->type == bp_hardware_breakpoint)
15100     {
15101       int i;
15102       i = hw_breakpoint_used_count ();
15103       target_resources_ok = 
15104         target_can_use_hardware_watchpoint (bp_hardware_breakpoint, 
15105                                             i + 1, 0);
15106       if (target_resources_ok == 0)
15107         error (_("No hardware breakpoint support in the target."));
15108       else if (target_resources_ok < 0)
15109         error (_("Hardware breakpoints used exceeds limit."));
15110     }
15111
15112   if (is_watchpoint (bpt))
15113     {
15114       /* Initialize it just to avoid a GCC false warning.  */
15115       enum enable_state orig_enable_state = 0;
15116
15117       TRY
15118         {
15119           struct watchpoint *w = (struct watchpoint *) bpt;
15120
15121           orig_enable_state = bpt->enable_state;
15122           bpt->enable_state = bp_enabled;
15123           update_watchpoint (w, 1 /* reparse */);
15124         }
15125       CATCH (e, RETURN_MASK_ALL)
15126         {
15127           bpt->enable_state = orig_enable_state;
15128           exception_fprintf (gdb_stderr, e, _("Cannot enable watchpoint %d: "),
15129                              bpt->number);
15130           return;
15131         }
15132       END_CATCH
15133     }
15134
15135   bpt->enable_state = bp_enabled;
15136
15137   /* Mark breakpoint locations modified.  */
15138   mark_breakpoint_modified (bpt);
15139
15140   if (target_supports_enable_disable_tracepoint ()
15141       && current_trace_status ()->running && is_tracepoint (bpt))
15142     {
15143       struct bp_location *location;
15144
15145       for (location = bpt->loc; location; location = location->next)
15146         target_enable_tracepoint (location);
15147     }
15148
15149   bpt->disposition = disposition;
15150   bpt->enable_count = count;
15151   update_global_location_list (UGLL_MAY_INSERT);
15152
15153   observer_notify_breakpoint_modified (bpt);
15154 }
15155
15156
15157 void
15158 enable_breakpoint (struct breakpoint *bpt)
15159 {
15160   enable_breakpoint_disp (bpt, bpt->disposition, 0);
15161 }
15162
15163 static void
15164 do_enable_breakpoint (struct breakpoint *bpt, void *arg)
15165 {
15166   enable_breakpoint (bpt);
15167 }
15168
15169 /* A callback for map_breakpoint_numbers that calls
15170    enable_breakpoint.  */
15171
15172 static void
15173 do_map_enable_breakpoint (struct breakpoint *b, void *ignore)
15174 {
15175   iterate_over_related_breakpoints (b, do_enable_breakpoint, NULL);
15176 }
15177
15178 /* The enable command enables the specified breakpoints (or all defined
15179    breakpoints) so they once again become (or continue to be) effective
15180    in stopping the inferior.  */
15181
15182 static void
15183 enable_command (char *args, int from_tty)
15184 {
15185   if (args == 0)
15186     {
15187       struct breakpoint *bpt;
15188
15189       ALL_BREAKPOINTS (bpt)
15190         if (user_breakpoint_p (bpt))
15191           enable_breakpoint (bpt);
15192     }
15193   else
15194     {
15195       char *num = extract_arg (&args);
15196
15197       while (num)
15198         {
15199           if (strchr (num, '.'))
15200             {
15201               struct bp_location *loc = find_location_by_number (num);
15202
15203               if (loc)
15204                 {
15205                   if (!loc->enabled)
15206                     {
15207                       loc->enabled = 1;
15208                       mark_breakpoint_location_modified (loc);
15209                     }
15210                   if (target_supports_enable_disable_tracepoint ()
15211                       && current_trace_status ()->running && loc->owner
15212                       && is_tracepoint (loc->owner))
15213                     target_enable_tracepoint (loc);
15214                 }
15215               update_global_location_list (UGLL_MAY_INSERT);
15216             }
15217           else
15218             map_breakpoint_numbers (num, do_map_enable_breakpoint, NULL);
15219           num = extract_arg (&args);
15220         }
15221     }
15222 }
15223
15224 /* This struct packages up disposition data for application to multiple
15225    breakpoints.  */
15226
15227 struct disp_data
15228 {
15229   enum bpdisp disp;
15230   int count;
15231 };
15232
15233 static void
15234 do_enable_breakpoint_disp (struct breakpoint *bpt, void *arg)
15235 {
15236   struct disp_data disp_data = *(struct disp_data *) arg;
15237
15238   enable_breakpoint_disp (bpt, disp_data.disp, disp_data.count);
15239 }
15240
15241 static void
15242 do_map_enable_once_breakpoint (struct breakpoint *bpt, void *ignore)
15243 {
15244   struct disp_data disp = { disp_disable, 1 };
15245
15246   iterate_over_related_breakpoints (bpt, do_enable_breakpoint_disp, &disp);
15247 }
15248
15249 static void
15250 enable_once_command (char *args, int from_tty)
15251 {
15252   map_breakpoint_numbers (args, do_map_enable_once_breakpoint, NULL);
15253 }
15254
15255 static void
15256 do_map_enable_count_breakpoint (struct breakpoint *bpt, void *countptr)
15257 {
15258   struct disp_data disp = { disp_disable, *(int *) countptr };
15259
15260   iterate_over_related_breakpoints (bpt, do_enable_breakpoint_disp, &disp);
15261 }
15262
15263 static void
15264 enable_count_command (char *args, int from_tty)
15265 {
15266   int count;
15267
15268   if (args == NULL)
15269     error_no_arg (_("hit count"));
15270
15271   count = get_number (&args);
15272
15273   map_breakpoint_numbers (args, do_map_enable_count_breakpoint, &count);
15274 }
15275
15276 static void
15277 do_map_enable_delete_breakpoint (struct breakpoint *bpt, void *ignore)
15278 {
15279   struct disp_data disp = { disp_del, 1 };
15280
15281   iterate_over_related_breakpoints (bpt, do_enable_breakpoint_disp, &disp);
15282 }
15283
15284 static void
15285 enable_delete_command (char *args, int from_tty)
15286 {
15287   map_breakpoint_numbers (args, do_map_enable_delete_breakpoint, NULL);
15288 }
15289 \f
15290 static void
15291 set_breakpoint_cmd (char *args, int from_tty)
15292 {
15293 }
15294
15295 static void
15296 show_breakpoint_cmd (char *args, int from_tty)
15297 {
15298 }
15299
15300 /* Invalidate last known value of any hardware watchpoint if
15301    the memory which that value represents has been written to by
15302    GDB itself.  */
15303
15304 static void
15305 invalidate_bp_value_on_memory_change (struct inferior *inferior,
15306                                       CORE_ADDR addr, ssize_t len,
15307                                       const bfd_byte *data)
15308 {
15309   struct breakpoint *bp;
15310
15311   ALL_BREAKPOINTS (bp)
15312     if (bp->enable_state == bp_enabled
15313         && bp->type == bp_hardware_watchpoint)
15314       {
15315         struct watchpoint *wp = (struct watchpoint *) bp;
15316
15317         if (wp->val_valid && wp->val)
15318           {
15319             struct bp_location *loc;
15320
15321             for (loc = bp->loc; loc != NULL; loc = loc->next)
15322               if (loc->loc_type == bp_loc_hardware_watchpoint
15323                   && loc->address + loc->length > addr
15324                   && addr + len > loc->address)
15325                 {
15326                   value_free (wp->val);
15327                   wp->val = NULL;
15328                   wp->val_valid = 0;
15329                 }
15330           }
15331       }
15332 }
15333
15334 /* Create and insert a breakpoint for software single step.  */
15335
15336 void
15337 insert_single_step_breakpoint (struct gdbarch *gdbarch,
15338                                struct address_space *aspace, 
15339                                CORE_ADDR next_pc)
15340 {
15341   struct thread_info *tp = inferior_thread ();
15342   struct symtab_and_line sal;
15343   CORE_ADDR pc = next_pc;
15344
15345   if (tp->control.single_step_breakpoints == NULL)
15346     {
15347       tp->control.single_step_breakpoints
15348         = new_single_step_breakpoint (tp->num, gdbarch);
15349     }
15350
15351   sal = find_pc_line (pc, 0);
15352   sal.pc = pc;
15353   sal.section = find_pc_overlay (pc);
15354   sal.explicit_pc = 1;
15355   add_location_to_breakpoint (tp->control.single_step_breakpoints, &sal);
15356
15357   update_global_location_list (UGLL_INSERT);
15358 }
15359
15360 /* See breakpoint.h.  */
15361
15362 int
15363 breakpoint_has_location_inserted_here (struct breakpoint *bp,
15364                                        struct address_space *aspace,
15365                                        CORE_ADDR pc)
15366 {
15367   struct bp_location *loc;
15368
15369   for (loc = bp->loc; loc != NULL; loc = loc->next)
15370     if (loc->inserted
15371         && breakpoint_location_address_match (loc, aspace, pc))
15372       return 1;
15373
15374   return 0;
15375 }
15376
15377 /* Check whether a software single-step breakpoint is inserted at
15378    PC.  */
15379
15380 int
15381 single_step_breakpoint_inserted_here_p (struct address_space *aspace,
15382                                         CORE_ADDR pc)
15383 {
15384   struct breakpoint *bpt;
15385
15386   ALL_BREAKPOINTS (bpt)
15387     {
15388       if (bpt->type == bp_single_step
15389           && breakpoint_has_location_inserted_here (bpt, aspace, pc))
15390         return 1;
15391     }
15392   return 0;
15393 }
15394
15395 /* Returns 0 if 'bp' is NOT a syscall catchpoint,
15396    non-zero otherwise.  */
15397 static int
15398 is_syscall_catchpoint_enabled (struct breakpoint *bp)
15399 {
15400   if (syscall_catchpoint_p (bp)
15401       && bp->enable_state != bp_disabled
15402       && bp->enable_state != bp_call_disabled)
15403     return 1;
15404   else
15405     return 0;
15406 }
15407
15408 int
15409 catch_syscall_enabled (void)
15410 {
15411   struct catch_syscall_inferior_data *inf_data
15412     = get_catch_syscall_inferior_data (current_inferior ());
15413
15414   return inf_data->total_syscalls_count != 0;
15415 }
15416
15417 int
15418 catching_syscall_number (int syscall_number)
15419 {
15420   struct breakpoint *bp;
15421
15422   ALL_BREAKPOINTS (bp)
15423     if (is_syscall_catchpoint_enabled (bp))
15424       {
15425         struct syscall_catchpoint *c = (struct syscall_catchpoint *) bp;
15426
15427         if (c->syscalls_to_be_caught)
15428           {
15429             int i, iter;
15430             for (i = 0;
15431                  VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
15432                  i++)
15433               if (syscall_number == iter)
15434                 return 1;
15435           }
15436         else
15437           return 1;
15438       }
15439
15440   return 0;
15441 }
15442
15443 /* Complete syscall names.  Used by "catch syscall".  */
15444 static VEC (char_ptr) *
15445 catch_syscall_completer (struct cmd_list_element *cmd,
15446                          const char *text, const char *word)
15447 {
15448   const char **list = get_syscall_names (get_current_arch ());
15449   VEC (char_ptr) *retlist
15450     = (list == NULL) ? NULL : complete_on_enum (list, word, word);
15451
15452   xfree (list);
15453   return retlist;
15454 }
15455
15456 /* Tracepoint-specific operations.  */
15457
15458 /* Set tracepoint count to NUM.  */
15459 static void
15460 set_tracepoint_count (int num)
15461 {
15462   tracepoint_count = num;
15463   set_internalvar_integer (lookup_internalvar ("tpnum"), num);
15464 }
15465
15466 static void
15467 trace_command (char *arg, int from_tty)
15468 {
15469   struct breakpoint_ops *ops;
15470   const char *arg_cp = arg;
15471
15472   if (arg && probe_linespec_to_ops (&arg_cp))
15473     ops = &tracepoint_probe_breakpoint_ops;
15474   else
15475     ops = &tracepoint_breakpoint_ops;
15476
15477   create_breakpoint (get_current_arch (),
15478                      arg,
15479                      NULL, 0, NULL, 1 /* parse arg */,
15480                      0 /* tempflag */,
15481                      bp_tracepoint /* type_wanted */,
15482                      0 /* Ignore count */,
15483                      pending_break_support,
15484                      ops,
15485                      from_tty,
15486                      1 /* enabled */,
15487                      0 /* internal */, 0);
15488 }
15489
15490 static void
15491 ftrace_command (char *arg, int from_tty)
15492 {
15493   create_breakpoint (get_current_arch (),
15494                      arg,
15495                      NULL, 0, NULL, 1 /* parse arg */,
15496                      0 /* tempflag */,
15497                      bp_fast_tracepoint /* type_wanted */,
15498                      0 /* Ignore count */,
15499                      pending_break_support,
15500                      &tracepoint_breakpoint_ops,
15501                      from_tty,
15502                      1 /* enabled */,
15503                      0 /* internal */, 0);
15504 }
15505
15506 /* strace command implementation.  Creates a static tracepoint.  */
15507
15508 static void
15509 strace_command (char *arg, int from_tty)
15510 {
15511   struct breakpoint_ops *ops;
15512
15513   /* Decide if we are dealing with a static tracepoint marker (`-m'),
15514      or with a normal static tracepoint.  */
15515   if (arg && startswith (arg, "-m") && isspace (arg[2]))
15516     ops = &strace_marker_breakpoint_ops;
15517   else
15518     ops = &tracepoint_breakpoint_ops;
15519
15520   create_breakpoint (get_current_arch (),
15521                      arg,
15522                      NULL, 0, NULL, 1 /* parse arg */,
15523                      0 /* tempflag */,
15524                      bp_static_tracepoint /* type_wanted */,
15525                      0 /* Ignore count */,
15526                      pending_break_support,
15527                      ops,
15528                      from_tty,
15529                      1 /* enabled */,
15530                      0 /* internal */, 0);
15531 }
15532
15533 /* Set up a fake reader function that gets command lines from a linked
15534    list that was acquired during tracepoint uploading.  */
15535
15536 static struct uploaded_tp *this_utp;
15537 static int next_cmd;
15538
15539 static char *
15540 read_uploaded_action (void)
15541 {
15542   char *rslt;
15543
15544   VEC_iterate (char_ptr, this_utp->cmd_strings, next_cmd, rslt);
15545
15546   next_cmd++;
15547
15548   return rslt;
15549 }
15550
15551 /* Given information about a tracepoint as recorded on a target (which
15552    can be either a live system or a trace file), attempt to create an
15553    equivalent GDB tracepoint.  This is not a reliable process, since
15554    the target does not necessarily have all the information used when
15555    the tracepoint was originally defined.  */
15556   
15557 struct tracepoint *
15558 create_tracepoint_from_upload (struct uploaded_tp *utp)
15559 {
15560   char *addr_str, small_buf[100];
15561   struct tracepoint *tp;
15562
15563   if (utp->at_string)
15564     addr_str = utp->at_string;
15565   else
15566     {
15567       /* In the absence of a source location, fall back to raw
15568          address.  Since there is no way to confirm that the address
15569          means the same thing as when the trace was started, warn the
15570          user.  */
15571       warning (_("Uploaded tracepoint %d has no "
15572                  "source location, using raw address"),
15573                utp->number);
15574       xsnprintf (small_buf, sizeof (small_buf), "*%s", hex_string (utp->addr));
15575       addr_str = small_buf;
15576     }
15577
15578   /* There's not much we can do with a sequence of bytecodes.  */
15579   if (utp->cond && !utp->cond_string)
15580     warning (_("Uploaded tracepoint %d condition "
15581                "has no source form, ignoring it"),
15582              utp->number);
15583
15584   if (!create_breakpoint (get_current_arch (),
15585                           addr_str,
15586                           utp->cond_string, -1, NULL,
15587                           0 /* parse cond/thread */,
15588                           0 /* tempflag */,
15589                           utp->type /* type_wanted */,
15590                           0 /* Ignore count */,
15591                           pending_break_support,
15592                           &tracepoint_breakpoint_ops,
15593                           0 /* from_tty */,
15594                           utp->enabled /* enabled */,
15595                           0 /* internal */,
15596                           CREATE_BREAKPOINT_FLAGS_INSERTED))
15597     return NULL;
15598
15599   /* Get the tracepoint we just created.  */
15600   tp = get_tracepoint (tracepoint_count);
15601   gdb_assert (tp != NULL);
15602
15603   if (utp->pass > 0)
15604     {
15605       xsnprintf (small_buf, sizeof (small_buf), "%d %d", utp->pass,
15606                  tp->base.number);
15607
15608       trace_pass_command (small_buf, 0);
15609     }
15610
15611   /* If we have uploaded versions of the original commands, set up a
15612      special-purpose "reader" function and call the usual command line
15613      reader, then pass the result to the breakpoint command-setting
15614      function.  */
15615   if (!VEC_empty (char_ptr, utp->cmd_strings))
15616     {
15617       struct command_line *cmd_list;
15618
15619       this_utp = utp;
15620       next_cmd = 0;
15621
15622       cmd_list = read_command_lines_1 (read_uploaded_action, 1, NULL, NULL);
15623
15624       breakpoint_set_commands (&tp->base, cmd_list);
15625     }
15626   else if (!VEC_empty (char_ptr, utp->actions)
15627            || !VEC_empty (char_ptr, utp->step_actions))
15628     warning (_("Uploaded tracepoint %d actions "
15629                "have no source form, ignoring them"),
15630              utp->number);
15631
15632   /* Copy any status information that might be available.  */
15633   tp->base.hit_count = utp->hit_count;
15634   tp->traceframe_usage = utp->traceframe_usage;
15635
15636   return tp;
15637 }
15638   
15639 /* Print information on tracepoint number TPNUM_EXP, or all if
15640    omitted.  */
15641
15642 static void
15643 tracepoints_info (char *args, int from_tty)
15644 {
15645   struct ui_out *uiout = current_uiout;
15646   int num_printed;
15647
15648   num_printed = breakpoint_1 (args, 0, is_tracepoint);
15649
15650   if (num_printed == 0)
15651     {
15652       if (args == NULL || *args == '\0')
15653         ui_out_message (uiout, 0, "No tracepoints.\n");
15654       else
15655         ui_out_message (uiout, 0, "No tracepoint matching '%s'.\n", args);
15656     }
15657
15658   default_collect_info ();
15659 }
15660
15661 /* The 'enable trace' command enables tracepoints.
15662    Not supported by all targets.  */
15663 static void
15664 enable_trace_command (char *args, int from_tty)
15665 {
15666   enable_command (args, from_tty);
15667 }
15668
15669 /* The 'disable trace' command disables tracepoints.
15670    Not supported by all targets.  */
15671 static void
15672 disable_trace_command (char *args, int from_tty)
15673 {
15674   disable_command (args, from_tty);
15675 }
15676
15677 /* Remove a tracepoint (or all if no argument).  */
15678 static void
15679 delete_trace_command (char *arg, int from_tty)
15680 {
15681   struct breakpoint *b, *b_tmp;
15682
15683   dont_repeat ();
15684
15685   if (arg == 0)
15686     {
15687       int breaks_to_delete = 0;
15688
15689       /* Delete all breakpoints if no argument.
15690          Do not delete internal or call-dummy breakpoints, these
15691          have to be deleted with an explicit breakpoint number 
15692          argument.  */
15693       ALL_TRACEPOINTS (b)
15694         if (is_tracepoint (b) && user_breakpoint_p (b))
15695           {
15696             breaks_to_delete = 1;
15697             break;
15698           }
15699
15700       /* Ask user only if there are some breakpoints to delete.  */
15701       if (!from_tty
15702           || (breaks_to_delete && query (_("Delete all tracepoints? "))))
15703         {
15704           ALL_BREAKPOINTS_SAFE (b, b_tmp)
15705             if (is_tracepoint (b) && user_breakpoint_p (b))
15706               delete_breakpoint (b);
15707         }
15708     }
15709   else
15710     map_breakpoint_numbers (arg, do_map_delete_breakpoint, NULL);
15711 }
15712
15713 /* Helper function for trace_pass_command.  */
15714
15715 static void
15716 trace_pass_set_count (struct tracepoint *tp, int count, int from_tty)
15717 {
15718   tp->pass_count = count;
15719   observer_notify_breakpoint_modified (&tp->base);
15720   if (from_tty)
15721     printf_filtered (_("Setting tracepoint %d's passcount to %d\n"),
15722                      tp->base.number, count);
15723 }
15724
15725 /* Set passcount for tracepoint.
15726
15727    First command argument is passcount, second is tracepoint number.
15728    If tracepoint number omitted, apply to most recently defined.
15729    Also accepts special argument "all".  */
15730
15731 static void
15732 trace_pass_command (char *args, int from_tty)
15733 {
15734   struct tracepoint *t1;
15735   unsigned int count;
15736
15737   if (args == 0 || *args == 0)
15738     error (_("passcount command requires an "
15739              "argument (count + optional TP num)"));
15740
15741   count = strtoul (args, &args, 10);    /* Count comes first, then TP num.  */
15742
15743   args = skip_spaces (args);
15744   if (*args && strncasecmp (args, "all", 3) == 0)
15745     {
15746       struct breakpoint *b;
15747
15748       args += 3;                        /* Skip special argument "all".  */
15749       if (*args)
15750         error (_("Junk at end of arguments."));
15751
15752       ALL_TRACEPOINTS (b)
15753       {
15754         t1 = (struct tracepoint *) b;
15755         trace_pass_set_count (t1, count, from_tty);
15756       }
15757     }
15758   else if (*args == '\0')
15759     {
15760       t1 = get_tracepoint_by_number (&args, NULL);
15761       if (t1)
15762         trace_pass_set_count (t1, count, from_tty);
15763     }
15764   else
15765     {
15766       struct get_number_or_range_state state;
15767
15768       init_number_or_range (&state, args);
15769       while (!state.finished)
15770         {
15771           t1 = get_tracepoint_by_number (&args, &state);
15772           if (t1)
15773             trace_pass_set_count (t1, count, from_tty);
15774         }
15775     }
15776 }
15777
15778 struct tracepoint *
15779 get_tracepoint (int num)
15780 {
15781   struct breakpoint *t;
15782
15783   ALL_TRACEPOINTS (t)
15784     if (t->number == num)
15785       return (struct tracepoint *) t;
15786
15787   return NULL;
15788 }
15789
15790 /* Find the tracepoint with the given target-side number (which may be
15791    different from the tracepoint number after disconnecting and
15792    reconnecting).  */
15793
15794 struct tracepoint *
15795 get_tracepoint_by_number_on_target (int num)
15796 {
15797   struct breakpoint *b;
15798
15799   ALL_TRACEPOINTS (b)
15800     {
15801       struct tracepoint *t = (struct tracepoint *) b;
15802
15803       if (t->number_on_target == num)
15804         return t;
15805     }
15806
15807   return NULL;
15808 }
15809
15810 /* Utility: parse a tracepoint number and look it up in the list.
15811    If STATE is not NULL, use, get_number_or_range_state and ignore ARG.
15812    If the argument is missing, the most recent tracepoint
15813    (tracepoint_count) is returned.  */
15814
15815 struct tracepoint *
15816 get_tracepoint_by_number (char **arg,
15817                           struct get_number_or_range_state *state)
15818 {
15819   struct breakpoint *t;
15820   int tpnum;
15821   char *instring = arg == NULL ? NULL : *arg;
15822
15823   if (state)
15824     {
15825       gdb_assert (!state->finished);
15826       tpnum = get_number_or_range (state);
15827     }
15828   else if (arg == NULL || *arg == NULL || ! **arg)
15829     tpnum = tracepoint_count;
15830   else
15831     tpnum = get_number (arg);
15832
15833   if (tpnum <= 0)
15834     {
15835       if (instring && *instring)
15836         printf_filtered (_("bad tracepoint number at or near '%s'\n"), 
15837                          instring);
15838       else
15839         printf_filtered (_("No previous tracepoint\n"));
15840       return NULL;
15841     }
15842
15843   ALL_TRACEPOINTS (t)
15844     if (t->number == tpnum)
15845     {
15846       return (struct tracepoint *) t;
15847     }
15848
15849   printf_unfiltered ("No tracepoint number %d.\n", tpnum);
15850   return NULL;
15851 }
15852
15853 void
15854 print_recreate_thread (struct breakpoint *b, struct ui_file *fp)
15855 {
15856   if (b->thread != -1)
15857     fprintf_unfiltered (fp, " thread %d", b->thread);
15858
15859   if (b->task != 0)
15860     fprintf_unfiltered (fp, " task %d", b->task);
15861
15862   fprintf_unfiltered (fp, "\n");
15863 }
15864
15865 /* Save information on user settable breakpoints (watchpoints, etc) to
15866    a new script file named FILENAME.  If FILTER is non-NULL, call it
15867    on each breakpoint and only include the ones for which it returns
15868    non-zero.  */
15869
15870 static void
15871 save_breakpoints (char *filename, int from_tty,
15872                   int (*filter) (const struct breakpoint *))
15873 {
15874   struct breakpoint *tp;
15875   int any = 0;
15876   struct cleanup *cleanup;
15877   struct ui_file *fp;
15878   int extra_trace_bits = 0;
15879
15880   if (filename == 0 || *filename == 0)
15881     error (_("Argument required (file name in which to save)"));
15882
15883   /* See if we have anything to save.  */
15884   ALL_BREAKPOINTS (tp)
15885   {
15886     /* Skip internal and momentary breakpoints.  */
15887     if (!user_breakpoint_p (tp))
15888       continue;
15889
15890     /* If we have a filter, only save the breakpoints it accepts.  */
15891     if (filter && !filter (tp))
15892       continue;
15893
15894     any = 1;
15895
15896     if (is_tracepoint (tp))
15897       {
15898         extra_trace_bits = 1;
15899
15900         /* We can stop searching.  */
15901         break;
15902       }
15903   }
15904
15905   if (!any)
15906     {
15907       warning (_("Nothing to save."));
15908       return;
15909     }
15910
15911   filename = tilde_expand (filename);
15912   cleanup = make_cleanup (xfree, filename);
15913   fp = gdb_fopen (filename, "w");
15914   if (!fp)
15915     error (_("Unable to open file '%s' for saving (%s)"),
15916            filename, safe_strerror (errno));
15917   make_cleanup_ui_file_delete (fp);
15918
15919   if (extra_trace_bits)
15920     save_trace_state_variables (fp);
15921
15922   ALL_BREAKPOINTS (tp)
15923   {
15924     /* Skip internal and momentary breakpoints.  */
15925     if (!user_breakpoint_p (tp))
15926       continue;
15927
15928     /* If we have a filter, only save the breakpoints it accepts.  */
15929     if (filter && !filter (tp))
15930       continue;
15931
15932     tp->ops->print_recreate (tp, fp);
15933
15934     /* Note, we can't rely on tp->number for anything, as we can't
15935        assume the recreated breakpoint numbers will match.  Use $bpnum
15936        instead.  */
15937
15938     if (tp->cond_string)
15939       fprintf_unfiltered (fp, "  condition $bpnum %s\n", tp->cond_string);
15940
15941     if (tp->ignore_count)
15942       fprintf_unfiltered (fp, "  ignore $bpnum %d\n", tp->ignore_count);
15943
15944     if (tp->type != bp_dprintf && tp->commands)
15945       {
15946         struct gdb_exception exception;
15947
15948         fprintf_unfiltered (fp, "  commands\n");
15949         
15950         ui_out_redirect (current_uiout, fp);
15951         TRY
15952           {
15953             print_command_lines (current_uiout, tp->commands->commands, 2);
15954           }
15955         CATCH (ex, RETURN_MASK_ALL)
15956           {
15957             ui_out_redirect (current_uiout, NULL);
15958             throw_exception (ex);
15959           }
15960         END_CATCH
15961
15962         ui_out_redirect (current_uiout, NULL);
15963         fprintf_unfiltered (fp, "  end\n");
15964       }
15965
15966     if (tp->enable_state == bp_disabled)
15967       fprintf_unfiltered (fp, "disable $bpnum\n");
15968
15969     /* If this is a multi-location breakpoint, check if the locations
15970        should be individually disabled.  Watchpoint locations are
15971        special, and not user visible.  */
15972     if (!is_watchpoint (tp) && tp->loc && tp->loc->next)
15973       {
15974         struct bp_location *loc;
15975         int n = 1;
15976
15977         for (loc = tp->loc; loc != NULL; loc = loc->next, n++)
15978           if (!loc->enabled)
15979             fprintf_unfiltered (fp, "disable $bpnum.%d\n", n);
15980       }
15981   }
15982
15983   if (extra_trace_bits && *default_collect)
15984     fprintf_unfiltered (fp, "set default-collect %s\n", default_collect);
15985
15986   if (from_tty)
15987     printf_filtered (_("Saved to file '%s'.\n"), filename);
15988   do_cleanups (cleanup);
15989 }
15990
15991 /* The `save breakpoints' command.  */
15992
15993 static void
15994 save_breakpoints_command (char *args, int from_tty)
15995 {
15996   save_breakpoints (args, from_tty, NULL);
15997 }
15998
15999 /* The `save tracepoints' command.  */
16000
16001 static void
16002 save_tracepoints_command (char *args, int from_tty)
16003 {
16004   save_breakpoints (args, from_tty, is_tracepoint);
16005 }
16006
16007 /* Create a vector of all tracepoints.  */
16008
16009 VEC(breakpoint_p) *
16010 all_tracepoints (void)
16011 {
16012   VEC(breakpoint_p) *tp_vec = 0;
16013   struct breakpoint *tp;
16014
16015   ALL_TRACEPOINTS (tp)
16016   {
16017     VEC_safe_push (breakpoint_p, tp_vec, tp);
16018   }
16019
16020   return tp_vec;
16021 }
16022
16023 \f
16024 /* This help string is used for the break, hbreak, tbreak and thbreak
16025    commands.  It is defined as a macro to prevent duplication.
16026    COMMAND should be a string constant containing the name of the
16027    command.  */
16028 #define BREAK_ARGS_HELP(command) \
16029 command" [PROBE_MODIFIER] [LOCATION] [thread THREADNUM] [if CONDITION]\n\
16030 PROBE_MODIFIER shall be present if the command is to be placed in a\n\
16031 probe point.  Accepted values are `-probe' (for a generic, automatically\n\
16032 guessed probe type), `-probe-stap' (for a SystemTap probe) or \n\
16033 `-probe-dtrace' (for a DTrace probe).\n\
16034 LOCATION may be a line number, function name, or \"*\" and an address.\n\
16035 If a line number is specified, break at start of code for that line.\n\
16036 If a function is specified, break at start of code for that function.\n\
16037 If an address is specified, break at that exact address.\n\
16038 With no LOCATION, uses current execution address of the selected\n\
16039 stack frame.  This is useful for breaking on return to a stack frame.\n\
16040 \n\
16041 THREADNUM is the number from \"info threads\".\n\
16042 CONDITION is a boolean expression.\n\
16043 \n\
16044 Multiple breakpoints at one place are permitted, and useful if their\n\
16045 conditions are different.\n\
16046 \n\
16047 Do \"help breakpoints\" for info on other commands dealing with breakpoints."
16048
16049 /* List of subcommands for "catch".  */
16050 static struct cmd_list_element *catch_cmdlist;
16051
16052 /* List of subcommands for "tcatch".  */
16053 static struct cmd_list_element *tcatch_cmdlist;
16054
16055 void
16056 add_catch_command (char *name, char *docstring,
16057                    cmd_sfunc_ftype *sfunc,
16058                    completer_ftype *completer,
16059                    void *user_data_catch,
16060                    void *user_data_tcatch)
16061 {
16062   struct cmd_list_element *command;
16063
16064   command = add_cmd (name, class_breakpoint, NULL, docstring,
16065                      &catch_cmdlist);
16066   set_cmd_sfunc (command, sfunc);
16067   set_cmd_context (command, user_data_catch);
16068   set_cmd_completer (command, completer);
16069
16070   command = add_cmd (name, class_breakpoint, NULL, docstring,
16071                      &tcatch_cmdlist);
16072   set_cmd_sfunc (command, sfunc);
16073   set_cmd_context (command, user_data_tcatch);
16074   set_cmd_completer (command, completer);
16075 }
16076
16077 static void
16078 clear_syscall_counts (struct inferior *inf)
16079 {
16080   struct catch_syscall_inferior_data *inf_data
16081     = get_catch_syscall_inferior_data (inf);
16082
16083   inf_data->total_syscalls_count = 0;
16084   inf_data->any_syscall_count = 0;
16085   VEC_free (int, inf_data->syscalls_counts);
16086 }
16087
16088 static void
16089 save_command (char *arg, int from_tty)
16090 {
16091   printf_unfiltered (_("\"save\" must be followed by "
16092                        "the name of a save subcommand.\n"));
16093   help_list (save_cmdlist, "save ", all_commands, gdb_stdout);
16094 }
16095
16096 struct breakpoint *
16097 iterate_over_breakpoints (int (*callback) (struct breakpoint *, void *),
16098                           void *data)
16099 {
16100   struct breakpoint *b, *b_tmp;
16101
16102   ALL_BREAKPOINTS_SAFE (b, b_tmp)
16103     {
16104       if ((*callback) (b, data))
16105         return b;
16106     }
16107
16108   return NULL;
16109 }
16110
16111 /* Zero if any of the breakpoint's locations could be a location where
16112    functions have been inlined, nonzero otherwise.  */
16113
16114 static int
16115 is_non_inline_function (struct breakpoint *b)
16116 {
16117   /* The shared library event breakpoint is set on the address of a
16118      non-inline function.  */
16119   if (b->type == bp_shlib_event)
16120     return 1;
16121
16122   return 0;
16123 }
16124
16125 /* Nonzero if the specified PC cannot be a location where functions
16126    have been inlined.  */
16127
16128 int
16129 pc_at_non_inline_function (struct address_space *aspace, CORE_ADDR pc,
16130                            const struct target_waitstatus *ws)
16131 {
16132   struct breakpoint *b;
16133   struct bp_location *bl;
16134
16135   ALL_BREAKPOINTS (b)
16136     {
16137       if (!is_non_inline_function (b))
16138         continue;
16139
16140       for (bl = b->loc; bl != NULL; bl = bl->next)
16141         {
16142           if (!bl->shlib_disabled
16143               && bpstat_check_location (bl, aspace, pc, ws))
16144             return 1;
16145         }
16146     }
16147
16148   return 0;
16149 }
16150
16151 /* Remove any references to OBJFILE which is going to be freed.  */
16152
16153 void
16154 breakpoint_free_objfile (struct objfile *objfile)
16155 {
16156   struct bp_location **locp, *loc;
16157
16158   ALL_BP_LOCATIONS (loc, locp)
16159     if (loc->symtab != NULL && SYMTAB_OBJFILE (loc->symtab) == objfile)
16160       loc->symtab = NULL;
16161 }
16162
16163 void
16164 initialize_breakpoint_ops (void)
16165 {
16166   static int initialized = 0;
16167
16168   struct breakpoint_ops *ops;
16169
16170   if (initialized)
16171     return;
16172   initialized = 1;
16173
16174   /* The breakpoint_ops structure to be inherit by all kinds of
16175      breakpoints (real breakpoints, i.e., user "break" breakpoints,
16176      internal and momentary breakpoints, etc.).  */
16177   ops = &bkpt_base_breakpoint_ops;
16178   *ops = base_breakpoint_ops;
16179   ops->re_set = bkpt_re_set;
16180   ops->insert_location = bkpt_insert_location;
16181   ops->remove_location = bkpt_remove_location;
16182   ops->breakpoint_hit = bkpt_breakpoint_hit;
16183   ops->create_sals_from_address = bkpt_create_sals_from_address;
16184   ops->create_breakpoints_sal = bkpt_create_breakpoints_sal;
16185   ops->decode_linespec = bkpt_decode_linespec;
16186
16187   /* The breakpoint_ops structure to be used in regular breakpoints.  */
16188   ops = &bkpt_breakpoint_ops;
16189   *ops = bkpt_base_breakpoint_ops;
16190   ops->re_set = bkpt_re_set;
16191   ops->resources_needed = bkpt_resources_needed;
16192   ops->print_it = bkpt_print_it;
16193   ops->print_mention = bkpt_print_mention;
16194   ops->print_recreate = bkpt_print_recreate;
16195
16196   /* Ranged breakpoints.  */
16197   ops = &ranged_breakpoint_ops;
16198   *ops = bkpt_breakpoint_ops;
16199   ops->breakpoint_hit = breakpoint_hit_ranged_breakpoint;
16200   ops->resources_needed = resources_needed_ranged_breakpoint;
16201   ops->print_it = print_it_ranged_breakpoint;
16202   ops->print_one = print_one_ranged_breakpoint;
16203   ops->print_one_detail = print_one_detail_ranged_breakpoint;
16204   ops->print_mention = print_mention_ranged_breakpoint;
16205   ops->print_recreate = print_recreate_ranged_breakpoint;
16206
16207   /* Internal breakpoints.  */
16208   ops = &internal_breakpoint_ops;
16209   *ops = bkpt_base_breakpoint_ops;
16210   ops->re_set = internal_bkpt_re_set;
16211   ops->check_status = internal_bkpt_check_status;
16212   ops->print_it = internal_bkpt_print_it;
16213   ops->print_mention = internal_bkpt_print_mention;
16214
16215   /* Momentary breakpoints.  */
16216   ops = &momentary_breakpoint_ops;
16217   *ops = bkpt_base_breakpoint_ops;
16218   ops->re_set = momentary_bkpt_re_set;
16219   ops->check_status = momentary_bkpt_check_status;
16220   ops->print_it = momentary_bkpt_print_it;
16221   ops->print_mention = momentary_bkpt_print_mention;
16222
16223   /* Momentary breakpoints for bp_longjmp and bp_exception.  */
16224   ops = &longjmp_breakpoint_ops;
16225   *ops = momentary_breakpoint_ops;
16226   ops->dtor = longjmp_bkpt_dtor;
16227
16228   /* Probe breakpoints.  */
16229   ops = &bkpt_probe_breakpoint_ops;
16230   *ops = bkpt_breakpoint_ops;
16231   ops->insert_location = bkpt_probe_insert_location;
16232   ops->remove_location = bkpt_probe_remove_location;
16233   ops->create_sals_from_address = bkpt_probe_create_sals_from_address;
16234   ops->decode_linespec = bkpt_probe_decode_linespec;
16235
16236   /* Watchpoints.  */
16237   ops = &watchpoint_breakpoint_ops;
16238   *ops = base_breakpoint_ops;
16239   ops->dtor = dtor_watchpoint;
16240   ops->re_set = re_set_watchpoint;
16241   ops->insert_location = insert_watchpoint;
16242   ops->remove_location = remove_watchpoint;
16243   ops->breakpoint_hit = breakpoint_hit_watchpoint;
16244   ops->check_status = check_status_watchpoint;
16245   ops->resources_needed = resources_needed_watchpoint;
16246   ops->works_in_software_mode = works_in_software_mode_watchpoint;
16247   ops->print_it = print_it_watchpoint;
16248   ops->print_mention = print_mention_watchpoint;
16249   ops->print_recreate = print_recreate_watchpoint;
16250   ops->explains_signal = explains_signal_watchpoint;
16251
16252   /* Masked watchpoints.  */
16253   ops = &masked_watchpoint_breakpoint_ops;
16254   *ops = watchpoint_breakpoint_ops;
16255   ops->insert_location = insert_masked_watchpoint;
16256   ops->remove_location = remove_masked_watchpoint;
16257   ops->resources_needed = resources_needed_masked_watchpoint;
16258   ops->works_in_software_mode = works_in_software_mode_masked_watchpoint;
16259   ops->print_it = print_it_masked_watchpoint;
16260   ops->print_one_detail = print_one_detail_masked_watchpoint;
16261   ops->print_mention = print_mention_masked_watchpoint;
16262   ops->print_recreate = print_recreate_masked_watchpoint;
16263
16264   /* Tracepoints.  */
16265   ops = &tracepoint_breakpoint_ops;
16266   *ops = base_breakpoint_ops;
16267   ops->re_set = tracepoint_re_set;
16268   ops->breakpoint_hit = tracepoint_breakpoint_hit;
16269   ops->print_one_detail = tracepoint_print_one_detail;
16270   ops->print_mention = tracepoint_print_mention;
16271   ops->print_recreate = tracepoint_print_recreate;
16272   ops->create_sals_from_address = tracepoint_create_sals_from_address;
16273   ops->create_breakpoints_sal = tracepoint_create_breakpoints_sal;
16274   ops->decode_linespec = tracepoint_decode_linespec;
16275
16276   /* Probe tracepoints.  */
16277   ops = &tracepoint_probe_breakpoint_ops;
16278   *ops = tracepoint_breakpoint_ops;
16279   ops->create_sals_from_address = tracepoint_probe_create_sals_from_address;
16280   ops->decode_linespec = tracepoint_probe_decode_linespec;
16281
16282   /* Static tracepoints with marker (`-m').  */
16283   ops = &strace_marker_breakpoint_ops;
16284   *ops = tracepoint_breakpoint_ops;
16285   ops->create_sals_from_address = strace_marker_create_sals_from_address;
16286   ops->create_breakpoints_sal = strace_marker_create_breakpoints_sal;
16287   ops->decode_linespec = strace_marker_decode_linespec;
16288
16289   /* Fork catchpoints.  */
16290   ops = &catch_fork_breakpoint_ops;
16291   *ops = base_breakpoint_ops;
16292   ops->insert_location = insert_catch_fork;
16293   ops->remove_location = remove_catch_fork;
16294   ops->breakpoint_hit = breakpoint_hit_catch_fork;
16295   ops->print_it = print_it_catch_fork;
16296   ops->print_one = print_one_catch_fork;
16297   ops->print_mention = print_mention_catch_fork;
16298   ops->print_recreate = print_recreate_catch_fork;
16299
16300   /* Vfork catchpoints.  */
16301   ops = &catch_vfork_breakpoint_ops;
16302   *ops = base_breakpoint_ops;
16303   ops->insert_location = insert_catch_vfork;
16304   ops->remove_location = remove_catch_vfork;
16305   ops->breakpoint_hit = breakpoint_hit_catch_vfork;
16306   ops->print_it = print_it_catch_vfork;
16307   ops->print_one = print_one_catch_vfork;
16308   ops->print_mention = print_mention_catch_vfork;
16309   ops->print_recreate = print_recreate_catch_vfork;
16310
16311   /* Exec catchpoints.  */
16312   ops = &catch_exec_breakpoint_ops;
16313   *ops = base_breakpoint_ops;
16314   ops->dtor = dtor_catch_exec;
16315   ops->insert_location = insert_catch_exec;
16316   ops->remove_location = remove_catch_exec;
16317   ops->breakpoint_hit = breakpoint_hit_catch_exec;
16318   ops->print_it = print_it_catch_exec;
16319   ops->print_one = print_one_catch_exec;
16320   ops->print_mention = print_mention_catch_exec;
16321   ops->print_recreate = print_recreate_catch_exec;
16322
16323   /* Syscall catchpoints.  */
16324   ops = &catch_syscall_breakpoint_ops;
16325   *ops = base_breakpoint_ops;
16326   ops->dtor = dtor_catch_syscall;
16327   ops->insert_location = insert_catch_syscall;
16328   ops->remove_location = remove_catch_syscall;
16329   ops->breakpoint_hit = breakpoint_hit_catch_syscall;
16330   ops->print_it = print_it_catch_syscall;
16331   ops->print_one = print_one_catch_syscall;
16332   ops->print_mention = print_mention_catch_syscall;
16333   ops->print_recreate = print_recreate_catch_syscall;
16334
16335   /* Solib-related catchpoints.  */
16336   ops = &catch_solib_breakpoint_ops;
16337   *ops = base_breakpoint_ops;
16338   ops->dtor = dtor_catch_solib;
16339   ops->insert_location = insert_catch_solib;
16340   ops->remove_location = remove_catch_solib;
16341   ops->breakpoint_hit = breakpoint_hit_catch_solib;
16342   ops->check_status = check_status_catch_solib;
16343   ops->print_it = print_it_catch_solib;
16344   ops->print_one = print_one_catch_solib;
16345   ops->print_mention = print_mention_catch_solib;
16346   ops->print_recreate = print_recreate_catch_solib;
16347
16348   ops = &dprintf_breakpoint_ops;
16349   *ops = bkpt_base_breakpoint_ops;
16350   ops->re_set = dprintf_re_set;
16351   ops->resources_needed = bkpt_resources_needed;
16352   ops->print_it = bkpt_print_it;
16353   ops->print_mention = bkpt_print_mention;
16354   ops->print_recreate = dprintf_print_recreate;
16355   ops->after_condition_true = dprintf_after_condition_true;
16356   ops->breakpoint_hit = dprintf_breakpoint_hit;
16357 }
16358
16359 /* Chain containing all defined "enable breakpoint" subcommands.  */
16360
16361 static struct cmd_list_element *enablebreaklist = NULL;
16362
16363 void
16364 _initialize_breakpoint (void)
16365 {
16366   struct cmd_list_element *c;
16367
16368   initialize_breakpoint_ops ();
16369
16370   observer_attach_solib_unloaded (disable_breakpoints_in_unloaded_shlib);
16371   observer_attach_free_objfile (disable_breakpoints_in_freed_objfile);
16372   observer_attach_inferior_exit (clear_syscall_counts);
16373   observer_attach_memory_changed (invalidate_bp_value_on_memory_change);
16374
16375   breakpoint_objfile_key
16376     = register_objfile_data_with_cleanup (NULL, free_breakpoint_probes);
16377
16378   catch_syscall_inferior_data
16379     = register_inferior_data_with_cleanup (NULL,
16380                                            catch_syscall_inferior_data_cleanup);
16381
16382   breakpoint_chain = 0;
16383   /* Don't bother to call set_breakpoint_count.  $bpnum isn't useful
16384      before a breakpoint is set.  */
16385   breakpoint_count = 0;
16386
16387   tracepoint_count = 0;
16388
16389   add_com ("ignore", class_breakpoint, ignore_command, _("\
16390 Set ignore-count of breakpoint number N to COUNT.\n\
16391 Usage is `ignore N COUNT'."));
16392   if (xdb_commands)
16393     add_com_alias ("bc", "ignore", class_breakpoint, 1);
16394
16395   add_com ("commands", class_breakpoint, commands_command, _("\
16396 Set commands to be executed when a breakpoint is hit.\n\
16397 Give breakpoint number as argument after \"commands\".\n\
16398 With no argument, the targeted breakpoint is the last one set.\n\
16399 The commands themselves follow starting on the next line.\n\
16400 Type a line containing \"end\" to indicate the end of them.\n\
16401 Give \"silent\" as the first line to make the breakpoint silent;\n\
16402 then no output is printed when it is hit, except what the commands print."));
16403
16404   c = add_com ("condition", class_breakpoint, condition_command, _("\
16405 Specify breakpoint number N to break only if COND is true.\n\
16406 Usage is `condition N COND', where N is an integer and COND is an\n\
16407 expression to be evaluated whenever breakpoint N is reached."));
16408   set_cmd_completer (c, condition_completer);
16409
16410   c = add_com ("tbreak", class_breakpoint, tbreak_command, _("\
16411 Set a temporary breakpoint.\n\
16412 Like \"break\" except the breakpoint is only temporary,\n\
16413 so it will be deleted when hit.  Equivalent to \"break\" followed\n\
16414 by using \"enable delete\" on the breakpoint number.\n\
16415 \n"
16416 BREAK_ARGS_HELP ("tbreak")));
16417   set_cmd_completer (c, location_completer);
16418
16419   c = add_com ("hbreak", class_breakpoint, hbreak_command, _("\
16420 Set a hardware assisted breakpoint.\n\
16421 Like \"break\" except the breakpoint requires hardware support,\n\
16422 some target hardware may not have this support.\n\
16423 \n"
16424 BREAK_ARGS_HELP ("hbreak")));
16425   set_cmd_completer (c, location_completer);
16426
16427   c = add_com ("thbreak", class_breakpoint, thbreak_command, _("\
16428 Set a temporary hardware assisted breakpoint.\n\
16429 Like \"hbreak\" except the breakpoint is only temporary,\n\
16430 so it will be deleted when hit.\n\
16431 \n"
16432 BREAK_ARGS_HELP ("thbreak")));
16433   set_cmd_completer (c, location_completer);
16434
16435   add_prefix_cmd ("enable", class_breakpoint, enable_command, _("\
16436 Enable some breakpoints.\n\
16437 Give breakpoint numbers (separated by spaces) as arguments.\n\
16438 With no subcommand, breakpoints are enabled until you command otherwise.\n\
16439 This is used to cancel the effect of the \"disable\" command.\n\
16440 With a subcommand you can enable temporarily."),
16441                   &enablelist, "enable ", 1, &cmdlist);
16442   if (xdb_commands)
16443     add_com ("ab", class_breakpoint, enable_command, _("\
16444 Enable some breakpoints.\n\
16445 Give breakpoint numbers (separated by spaces) as arguments.\n\
16446 With no subcommand, breakpoints are enabled until you command otherwise.\n\
16447 This is used to cancel the effect of the \"disable\" command.\n\
16448 With a subcommand you can enable temporarily."));
16449
16450   add_com_alias ("en", "enable", class_breakpoint, 1);
16451
16452   add_prefix_cmd ("breakpoints", class_breakpoint, enable_command, _("\
16453 Enable some breakpoints.\n\
16454 Give breakpoint numbers (separated by spaces) as arguments.\n\
16455 This is used to cancel the effect of the \"disable\" command.\n\
16456 May be abbreviated to simply \"enable\".\n"),
16457                    &enablebreaklist, "enable breakpoints ", 1, &enablelist);
16458
16459   add_cmd ("once", no_class, enable_once_command, _("\
16460 Enable breakpoints for one hit.  Give breakpoint numbers.\n\
16461 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
16462            &enablebreaklist);
16463
16464   add_cmd ("delete", no_class, enable_delete_command, _("\
16465 Enable breakpoints and delete when hit.  Give breakpoint numbers.\n\
16466 If a breakpoint is hit while enabled in this fashion, it is deleted."),
16467            &enablebreaklist);
16468
16469   add_cmd ("count", no_class, enable_count_command, _("\
16470 Enable breakpoints for COUNT hits.  Give count and then breakpoint numbers.\n\
16471 If a breakpoint is hit while enabled in this fashion,\n\
16472 the count is decremented; when it reaches zero, the breakpoint is disabled."),
16473            &enablebreaklist);
16474
16475   add_cmd ("delete", no_class, enable_delete_command, _("\
16476 Enable breakpoints and delete when hit.  Give breakpoint numbers.\n\
16477 If a breakpoint is hit while enabled in this fashion, it is deleted."),
16478            &enablelist);
16479
16480   add_cmd ("once", no_class, enable_once_command, _("\
16481 Enable breakpoints for one hit.  Give breakpoint numbers.\n\
16482 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
16483            &enablelist);
16484
16485   add_cmd ("count", no_class, enable_count_command, _("\
16486 Enable breakpoints for COUNT hits.  Give count and then breakpoint numbers.\n\
16487 If a breakpoint is hit while enabled in this fashion,\n\
16488 the count is decremented; when it reaches zero, the breakpoint is disabled."),
16489            &enablelist);
16490
16491   add_prefix_cmd ("disable", class_breakpoint, disable_command, _("\
16492 Disable some breakpoints.\n\
16493 Arguments are breakpoint numbers with spaces in between.\n\
16494 To disable all breakpoints, give no argument.\n\
16495 A disabled breakpoint is not forgotten, but has no effect until re-enabled."),
16496                   &disablelist, "disable ", 1, &cmdlist);
16497   add_com_alias ("dis", "disable", class_breakpoint, 1);
16498   add_com_alias ("disa", "disable", class_breakpoint, 1);
16499   if (xdb_commands)
16500     add_com ("sb", class_breakpoint, disable_command, _("\
16501 Disable some breakpoints.\n\
16502 Arguments are breakpoint numbers with spaces in between.\n\
16503 To disable all breakpoints, give no argument.\n\
16504 A disabled breakpoint is not forgotten, but has no effect until re-enabled."));
16505
16506   add_cmd ("breakpoints", class_alias, disable_command, _("\
16507 Disable some breakpoints.\n\
16508 Arguments are breakpoint numbers with spaces in between.\n\
16509 To disable all breakpoints, give no argument.\n\
16510 A disabled breakpoint is not forgotten, but has no effect until re-enabled.\n\
16511 This command may be abbreviated \"disable\"."),
16512            &disablelist);
16513
16514   add_prefix_cmd ("delete", class_breakpoint, delete_command, _("\
16515 Delete some breakpoints or auto-display expressions.\n\
16516 Arguments are breakpoint numbers with spaces in between.\n\
16517 To delete all breakpoints, give no argument.\n\
16518 \n\
16519 Also a prefix command for deletion of other GDB objects.\n\
16520 The \"unset\" command is also an alias for \"delete\"."),
16521                   &deletelist, "delete ", 1, &cmdlist);
16522   add_com_alias ("d", "delete", class_breakpoint, 1);
16523   add_com_alias ("del", "delete", class_breakpoint, 1);
16524   if (xdb_commands)
16525     add_com ("db", class_breakpoint, delete_command, _("\
16526 Delete some breakpoints.\n\
16527 Arguments are breakpoint numbers with spaces in between.\n\
16528 To delete all breakpoints, give no argument.\n"));
16529
16530   add_cmd ("breakpoints", class_alias, delete_command, _("\
16531 Delete some breakpoints or auto-display expressions.\n\
16532 Arguments are breakpoint numbers with spaces in between.\n\
16533 To delete all breakpoints, give no argument.\n\
16534 This command may be abbreviated \"delete\"."),
16535            &deletelist);
16536
16537   add_com ("clear", class_breakpoint, clear_command, _("\
16538 Clear breakpoint at specified line or function.\n\
16539 Argument may be line number, function name, or \"*\" and an address.\n\
16540 If line number is specified, all breakpoints in that line are cleared.\n\
16541 If function is specified, breakpoints at beginning of function are cleared.\n\
16542 If an address is specified, breakpoints at that address are cleared.\n\
16543 \n\
16544 With no argument, clears all breakpoints in the line that the selected frame\n\
16545 is executing in.\n\
16546 \n\
16547 See also the \"delete\" command which clears breakpoints by number."));
16548   add_com_alias ("cl", "clear", class_breakpoint, 1);
16549
16550   c = add_com ("break", class_breakpoint, break_command, _("\
16551 Set breakpoint at specified line or function.\n"
16552 BREAK_ARGS_HELP ("break")));
16553   set_cmd_completer (c, location_completer);
16554
16555   add_com_alias ("b", "break", class_run, 1);
16556   add_com_alias ("br", "break", class_run, 1);
16557   add_com_alias ("bre", "break", class_run, 1);
16558   add_com_alias ("brea", "break", class_run, 1);
16559
16560   if (xdb_commands)
16561    add_com_alias ("ba", "break", class_breakpoint, 1);
16562
16563   if (dbx_commands)
16564     {
16565       add_abbrev_prefix_cmd ("stop", class_breakpoint, stop_command, _("\
16566 Break in function/address or break at a line in the current file."),
16567                              &stoplist, "stop ", 1, &cmdlist);
16568       add_cmd ("in", class_breakpoint, stopin_command,
16569                _("Break in function or address."), &stoplist);
16570       add_cmd ("at", class_breakpoint, stopat_command,
16571                _("Break at a line in the current file."), &stoplist);
16572       add_com ("status", class_info, breakpoints_info, _("\
16573 Status of user-settable breakpoints, or breakpoint number NUMBER.\n\
16574 The \"Type\" column indicates one of:\n\
16575 \tbreakpoint     - normal breakpoint\n\
16576 \twatchpoint     - watchpoint\n\
16577 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
16578 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
16579 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
16580 address and file/line number respectively.\n\
16581 \n\
16582 Convenience variable \"$_\" and default examine address for \"x\"\n\
16583 are set to the address of the last breakpoint listed unless the command\n\
16584 is prefixed with \"server \".\n\n\
16585 Convenience variable \"$bpnum\" contains the number of the last\n\
16586 breakpoint set."));
16587     }
16588
16589   add_info ("breakpoints", breakpoints_info, _("\
16590 Status of specified breakpoints (all user-settable breakpoints if no argument).\n\
16591 The \"Type\" column indicates one of:\n\
16592 \tbreakpoint     - normal breakpoint\n\
16593 \twatchpoint     - watchpoint\n\
16594 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
16595 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
16596 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
16597 address and file/line number respectively.\n\
16598 \n\
16599 Convenience variable \"$_\" and default examine address for \"x\"\n\
16600 are set to the address of the last breakpoint listed unless the command\n\
16601 is prefixed with \"server \".\n\n\
16602 Convenience variable \"$bpnum\" contains the number of the last\n\
16603 breakpoint set."));
16604
16605   add_info_alias ("b", "breakpoints", 1);
16606
16607   if (xdb_commands)
16608     add_com ("lb", class_breakpoint, breakpoints_info, _("\
16609 Status of user-settable breakpoints, or breakpoint number NUMBER.\n\
16610 The \"Type\" column indicates one of:\n\
16611 \tbreakpoint     - normal breakpoint\n\
16612 \twatchpoint     - watchpoint\n\
16613 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
16614 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
16615 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
16616 address and file/line number respectively.\n\
16617 \n\
16618 Convenience variable \"$_\" and default examine address for \"x\"\n\
16619 are set to the address of the last breakpoint listed unless the command\n\
16620 is prefixed with \"server \".\n\n\
16621 Convenience variable \"$bpnum\" contains the number of the last\n\
16622 breakpoint set."));
16623
16624   add_cmd ("breakpoints", class_maintenance, maintenance_info_breakpoints, _("\
16625 Status of all breakpoints, or breakpoint number NUMBER.\n\
16626 The \"Type\" column indicates one of:\n\
16627 \tbreakpoint     - normal breakpoint\n\
16628 \twatchpoint     - watchpoint\n\
16629 \tlongjmp        - internal breakpoint used to step through longjmp()\n\
16630 \tlongjmp resume - internal breakpoint at the target of longjmp()\n\
16631 \tuntil          - internal breakpoint used by the \"until\" command\n\
16632 \tfinish         - internal breakpoint used by the \"finish\" command\n\
16633 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
16634 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
16635 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
16636 address and file/line number respectively.\n\
16637 \n\
16638 Convenience variable \"$_\" and default examine address for \"x\"\n\
16639 are set to the address of the last breakpoint listed unless the command\n\
16640 is prefixed with \"server \".\n\n\
16641 Convenience variable \"$bpnum\" contains the number of the last\n\
16642 breakpoint set."),
16643            &maintenanceinfolist);
16644
16645   add_prefix_cmd ("catch", class_breakpoint, catch_command, _("\
16646 Set catchpoints to catch events."),
16647                   &catch_cmdlist, "catch ",
16648                   0/*allow-unknown*/, &cmdlist);
16649
16650   add_prefix_cmd ("tcatch", class_breakpoint, tcatch_command, _("\
16651 Set temporary catchpoints to catch events."),
16652                   &tcatch_cmdlist, "tcatch ",
16653                   0/*allow-unknown*/, &cmdlist);
16654
16655   add_catch_command ("fork", _("Catch calls to fork."),
16656                      catch_fork_command_1,
16657                      NULL,
16658                      (void *) (uintptr_t) catch_fork_permanent,
16659                      (void *) (uintptr_t) catch_fork_temporary);
16660   add_catch_command ("vfork", _("Catch calls to vfork."),
16661                      catch_fork_command_1,
16662                      NULL,
16663                      (void *) (uintptr_t) catch_vfork_permanent,
16664                      (void *) (uintptr_t) catch_vfork_temporary);
16665   add_catch_command ("exec", _("Catch calls to exec."),
16666                      catch_exec_command_1,
16667                      NULL,
16668                      CATCH_PERMANENT,
16669                      CATCH_TEMPORARY);
16670   add_catch_command ("load", _("Catch loads of shared libraries.\n\
16671 Usage: catch load [REGEX]\n\
16672 If REGEX is given, only stop for libraries matching the regular expression."),
16673                      catch_load_command_1,
16674                      NULL,
16675                      CATCH_PERMANENT,
16676                      CATCH_TEMPORARY);
16677   add_catch_command ("unload", _("Catch unloads of shared libraries.\n\
16678 Usage: catch unload [REGEX]\n\
16679 If REGEX is given, only stop for libraries matching the regular expression."),
16680                      catch_unload_command_1,
16681                      NULL,
16682                      CATCH_PERMANENT,
16683                      CATCH_TEMPORARY);
16684   add_catch_command ("syscall", _("\
16685 Catch system calls by their names and/or numbers.\n\
16686 Arguments say which system calls to catch.  If no arguments\n\
16687 are given, every system call will be caught.\n\
16688 Arguments, if given, should be one or more system call names\n\
16689 (if your system supports that), or system call numbers."),
16690                      catch_syscall_command_1,
16691                      catch_syscall_completer,
16692                      CATCH_PERMANENT,
16693                      CATCH_TEMPORARY);
16694
16695   c = add_com ("watch", class_breakpoint, watch_command, _("\
16696 Set a watchpoint for an expression.\n\
16697 Usage: watch [-l|-location] EXPRESSION\n\
16698 A watchpoint stops execution of your program whenever the value of\n\
16699 an expression changes.\n\
16700 If -l or -location is given, this evaluates EXPRESSION and watches\n\
16701 the memory to which it refers."));
16702   set_cmd_completer (c, expression_completer);
16703
16704   c = add_com ("rwatch", class_breakpoint, rwatch_command, _("\
16705 Set a read watchpoint for an expression.\n\
16706 Usage: rwatch [-l|-location] EXPRESSION\n\
16707 A watchpoint stops execution of your program whenever the value of\n\
16708 an expression is read.\n\
16709 If -l or -location is given, this evaluates EXPRESSION and watches\n\
16710 the memory to which it refers."));
16711   set_cmd_completer (c, expression_completer);
16712
16713   c = add_com ("awatch", class_breakpoint, awatch_command, _("\
16714 Set a watchpoint for an expression.\n\
16715 Usage: awatch [-l|-location] EXPRESSION\n\
16716 A watchpoint stops execution of your program whenever the value of\n\
16717 an expression is either read or written.\n\
16718 If -l or -location is given, this evaluates EXPRESSION and watches\n\
16719 the memory to which it refers."));
16720   set_cmd_completer (c, expression_completer);
16721
16722   add_info ("watchpoints", watchpoints_info, _("\
16723 Status of specified watchpoints (all watchpoints if no argument)."));
16724
16725   /* XXX: cagney/2005-02-23: This should be a boolean, and should
16726      respond to changes - contrary to the description.  */
16727   add_setshow_zinteger_cmd ("can-use-hw-watchpoints", class_support,
16728                             &can_use_hw_watchpoints, _("\
16729 Set debugger's willingness to use watchpoint hardware."), _("\
16730 Show debugger's willingness to use watchpoint hardware."), _("\
16731 If zero, gdb will not use hardware for new watchpoints, even if\n\
16732 such is available.  (However, any hardware watchpoints that were\n\
16733 created before setting this to nonzero, will continue to use watchpoint\n\
16734 hardware.)"),
16735                             NULL,
16736                             show_can_use_hw_watchpoints,
16737                             &setlist, &showlist);
16738
16739   can_use_hw_watchpoints = 1;
16740
16741   /* Tracepoint manipulation commands.  */
16742
16743   c = add_com ("trace", class_breakpoint, trace_command, _("\
16744 Set a tracepoint at specified line or function.\n\
16745 \n"
16746 BREAK_ARGS_HELP ("trace") "\n\
16747 Do \"help tracepoints\" for info on other tracepoint commands."));
16748   set_cmd_completer (c, location_completer);
16749
16750   add_com_alias ("tp", "trace", class_alias, 0);
16751   add_com_alias ("tr", "trace", class_alias, 1);
16752   add_com_alias ("tra", "trace", class_alias, 1);
16753   add_com_alias ("trac", "trace", class_alias, 1);
16754
16755   c = add_com ("ftrace", class_breakpoint, ftrace_command, _("\
16756 Set a fast tracepoint at specified line or function.\n\
16757 \n"
16758 BREAK_ARGS_HELP ("ftrace") "\n\
16759 Do \"help tracepoints\" for info on other tracepoint commands."));
16760   set_cmd_completer (c, location_completer);
16761
16762   c = add_com ("strace", class_breakpoint, strace_command, _("\
16763 Set a static tracepoint at specified line, function or marker.\n\
16764 \n\
16765 strace [LOCATION] [if CONDITION]\n\
16766 LOCATION may be a line number, function name, \"*\" and an address,\n\
16767 or -m MARKER_ID.\n\
16768 If a line number is specified, probe the marker at start of code\n\
16769 for that line.  If a function is specified, probe the marker at start\n\
16770 of code for that function.  If an address is specified, probe the marker\n\
16771 at that exact address.  If a marker id is specified, probe the marker\n\
16772 with that name.  With no LOCATION, uses current execution address of\n\
16773 the selected stack frame.\n\
16774 Static tracepoints accept an extra collect action -- ``collect $_sdata''.\n\
16775 This collects arbitrary user data passed in the probe point call to the\n\
16776 tracing library.  You can inspect it when analyzing the trace buffer,\n\
16777 by printing the $_sdata variable like any other convenience variable.\n\
16778 \n\
16779 CONDITION is a boolean expression.\n\
16780 \n\
16781 Multiple tracepoints at one place are permitted, and useful if their\n\
16782 conditions are different.\n\
16783 \n\
16784 Do \"help breakpoints\" for info on other commands dealing with breakpoints.\n\
16785 Do \"help tracepoints\" for info on other tracepoint commands."));
16786   set_cmd_completer (c, location_completer);
16787
16788   add_info ("tracepoints", tracepoints_info, _("\
16789 Status of specified tracepoints (all tracepoints if no argument).\n\
16790 Convenience variable \"$tpnum\" contains the number of the\n\
16791 last tracepoint set."));
16792
16793   add_info_alias ("tp", "tracepoints", 1);
16794
16795   add_cmd ("tracepoints", class_trace, delete_trace_command, _("\
16796 Delete specified tracepoints.\n\
16797 Arguments are tracepoint numbers, separated by spaces.\n\
16798 No argument means delete all tracepoints."),
16799            &deletelist);
16800   add_alias_cmd ("tr", "tracepoints", class_trace, 1, &deletelist);
16801
16802   c = add_cmd ("tracepoints", class_trace, disable_trace_command, _("\
16803 Disable specified tracepoints.\n\
16804 Arguments are tracepoint numbers, separated by spaces.\n\
16805 No argument means disable all tracepoints."),
16806            &disablelist);
16807   deprecate_cmd (c, "disable");
16808
16809   c = add_cmd ("tracepoints", class_trace, enable_trace_command, _("\
16810 Enable specified tracepoints.\n\
16811 Arguments are tracepoint numbers, separated by spaces.\n\
16812 No argument means enable all tracepoints."),
16813            &enablelist);
16814   deprecate_cmd (c, "enable");
16815
16816   add_com ("passcount", class_trace, trace_pass_command, _("\
16817 Set the passcount for a tracepoint.\n\
16818 The trace will end when the tracepoint has been passed 'count' times.\n\
16819 Usage: passcount COUNT TPNUM, where TPNUM may also be \"all\";\n\
16820 if TPNUM is omitted, passcount refers to the last tracepoint defined."));
16821
16822   add_prefix_cmd ("save", class_breakpoint, save_command,
16823                   _("Save breakpoint definitions as a script."),
16824                   &save_cmdlist, "save ",
16825                   0/*allow-unknown*/, &cmdlist);
16826
16827   c = add_cmd ("breakpoints", class_breakpoint, save_breakpoints_command, _("\
16828 Save current breakpoint definitions as a script.\n\
16829 This includes all types of breakpoints (breakpoints, watchpoints,\n\
16830 catchpoints, tracepoints).  Use the 'source' command in another debug\n\
16831 session to restore them."),
16832                &save_cmdlist);
16833   set_cmd_completer (c, filename_completer);
16834
16835   c = add_cmd ("tracepoints", class_trace, save_tracepoints_command, _("\
16836 Save current tracepoint definitions as a script.\n\
16837 Use the 'source' command in another debug session to restore them."),
16838                &save_cmdlist);
16839   set_cmd_completer (c, filename_completer);
16840
16841   c = add_com_alias ("save-tracepoints", "save tracepoints", class_trace, 0);
16842   deprecate_cmd (c, "save tracepoints");
16843
16844   add_prefix_cmd ("breakpoint", class_maintenance, set_breakpoint_cmd, _("\
16845 Breakpoint specific settings\n\
16846 Configure various breakpoint-specific variables such as\n\
16847 pending breakpoint behavior"),
16848                   &breakpoint_set_cmdlist, "set breakpoint ",
16849                   0/*allow-unknown*/, &setlist);
16850   add_prefix_cmd ("breakpoint", class_maintenance, show_breakpoint_cmd, _("\
16851 Breakpoint specific settings\n\
16852 Configure various breakpoint-specific variables such as\n\
16853 pending breakpoint behavior"),
16854                   &breakpoint_show_cmdlist, "show breakpoint ",
16855                   0/*allow-unknown*/, &showlist);
16856
16857   add_setshow_auto_boolean_cmd ("pending", no_class,
16858                                 &pending_break_support, _("\
16859 Set debugger's behavior regarding pending breakpoints."), _("\
16860 Show debugger's behavior regarding pending breakpoints."), _("\
16861 If on, an unrecognized breakpoint location will cause gdb to create a\n\
16862 pending breakpoint.  If off, an unrecognized breakpoint location results in\n\
16863 an error.  If auto, an unrecognized breakpoint location results in a\n\
16864 user-query to see if a pending breakpoint should be created."),
16865                                 NULL,
16866                                 show_pending_break_support,
16867                                 &breakpoint_set_cmdlist,
16868                                 &breakpoint_show_cmdlist);
16869
16870   pending_break_support = AUTO_BOOLEAN_AUTO;
16871
16872   add_setshow_boolean_cmd ("auto-hw", no_class,
16873                            &automatic_hardware_breakpoints, _("\
16874 Set automatic usage of hardware breakpoints."), _("\
16875 Show automatic usage of hardware breakpoints."), _("\
16876 If set, the debugger will automatically use hardware breakpoints for\n\
16877 breakpoints set with \"break\" but falling in read-only memory.  If not set,\n\
16878 a warning will be emitted for such breakpoints."),
16879                            NULL,
16880                            show_automatic_hardware_breakpoints,
16881                            &breakpoint_set_cmdlist,
16882                            &breakpoint_show_cmdlist);
16883
16884   add_setshow_boolean_cmd ("always-inserted", class_support,
16885                            &always_inserted_mode, _("\
16886 Set mode for inserting breakpoints."), _("\
16887 Show mode for inserting breakpoints."), _("\
16888 When this mode is on, breakpoints are inserted immediately as soon as\n\
16889 they're created, kept inserted even when execution stops, and removed\n\
16890 only when the user deletes them.  When this mode is off (the default),\n\
16891 breakpoints are inserted only when execution continues, and removed\n\
16892 when execution stops."),
16893                                 NULL,
16894                                 &show_always_inserted_mode,
16895                                 &breakpoint_set_cmdlist,
16896                                 &breakpoint_show_cmdlist);
16897
16898   add_setshow_enum_cmd ("condition-evaluation", class_breakpoint,
16899                         condition_evaluation_enums,
16900                         &condition_evaluation_mode_1, _("\
16901 Set mode of breakpoint condition evaluation."), _("\
16902 Show mode of breakpoint condition evaluation."), _("\
16903 When this is set to \"host\", breakpoint conditions will be\n\
16904 evaluated on the host's side by GDB.  When it is set to \"target\",\n\
16905 breakpoint conditions will be downloaded to the target (if the target\n\
16906 supports such feature) and conditions will be evaluated on the target's side.\n\
16907 If this is set to \"auto\" (default), this will be automatically set to\n\
16908 \"target\" if it supports condition evaluation, otherwise it will\n\
16909 be set to \"gdb\""),
16910                            &set_condition_evaluation_mode,
16911                            &show_condition_evaluation_mode,
16912                            &breakpoint_set_cmdlist,
16913                            &breakpoint_show_cmdlist);
16914
16915   add_com ("break-range", class_breakpoint, break_range_command, _("\
16916 Set a breakpoint for an address range.\n\
16917 break-range START-LOCATION, END-LOCATION\n\
16918 where START-LOCATION and END-LOCATION can be one of the following:\n\
16919   LINENUM, for that line in the current file,\n\
16920   FILE:LINENUM, for that line in that file,\n\
16921   +OFFSET, for that number of lines after the current line\n\
16922            or the start of the range\n\
16923   FUNCTION, for the first line in that function,\n\
16924   FILE:FUNCTION, to distinguish among like-named static functions.\n\
16925   *ADDRESS, for the instruction at that address.\n\
16926 \n\
16927 The breakpoint will stop execution of the inferior whenever it executes\n\
16928 an instruction at any address within the [START-LOCATION, END-LOCATION]\n\
16929 range (including START-LOCATION and END-LOCATION)."));
16930
16931   c = add_com ("dprintf", class_breakpoint, dprintf_command, _("\
16932 Set a dynamic printf at specified line or function.\n\
16933 dprintf location,format string,arg1,arg2,...\n\
16934 location may be a line number, function name, or \"*\" and an address.\n\
16935 If a line number is specified, break at start of code for that line.\n\
16936 If a function is specified, break at start of code for that function."));
16937   set_cmd_completer (c, location_completer);
16938
16939   add_setshow_enum_cmd ("dprintf-style", class_support,
16940                         dprintf_style_enums, &dprintf_style, _("\
16941 Set the style of usage for dynamic printf."), _("\
16942 Show the style of usage for dynamic printf."), _("\
16943 This setting chooses how GDB will do a dynamic printf.\n\
16944 If the value is \"gdb\", then the printing is done by GDB to its own\n\
16945 console, as with the \"printf\" command.\n\
16946 If the value is \"call\", the print is done by calling a function in your\n\
16947 program; by default printf(), but you can choose a different function or\n\
16948 output stream by setting dprintf-function and dprintf-channel."),
16949                         update_dprintf_commands, NULL,
16950                         &setlist, &showlist);
16951
16952   dprintf_function = xstrdup ("printf");
16953   add_setshow_string_cmd ("dprintf-function", class_support,
16954                           &dprintf_function, _("\
16955 Set the function to use for dynamic printf"), _("\
16956 Show the function to use for dynamic printf"), NULL,
16957                           update_dprintf_commands, NULL,
16958                           &setlist, &showlist);
16959
16960   dprintf_channel = xstrdup ("");
16961   add_setshow_string_cmd ("dprintf-channel", class_support,
16962                           &dprintf_channel, _("\
16963 Set the channel to use for dynamic printf"), _("\
16964 Show the channel to use for dynamic printf"), NULL,
16965                           update_dprintf_commands, NULL,
16966                           &setlist, &showlist);
16967
16968   add_setshow_boolean_cmd ("disconnected-dprintf", no_class,
16969                            &disconnected_dprintf, _("\
16970 Set whether dprintf continues after GDB disconnects."), _("\
16971 Show whether dprintf continues after GDB disconnects."), _("\
16972 Use this to let dprintf commands continue to hit and produce output\n\
16973 even if GDB disconnects or detaches from the target."),
16974                            NULL,
16975                            NULL,
16976                            &setlist, &showlist);
16977
16978   add_com ("agent-printf", class_vars, agent_printf_command, _("\
16979 agent-printf \"printf format string\", arg1, arg2, arg3, ..., argn\n\
16980 (target agent only) This is useful for formatted output in user-defined commands."));
16981
16982   automatic_hardware_breakpoints = 1;
16983
16984   observer_attach_about_to_proceed (breakpoint_about_to_proceed);
16985   observer_attach_thread_exit (remove_threaded_breakpoints);
16986 }