]> Git Repo - binutils.git/blob - gdb/breakpoint.c
PR gdb/17472: With annotations, input while executing in the foreground crashes readl...
[binutils.git] / gdb / breakpoint.c
1 /* Everything about breakpoints, for GDB.
2
3    Copyright (C) 1986-2014 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
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 abstract base class all breakpoint_ops structures inherit
301    from.  */
302 struct breakpoint_ops base_breakpoint_ops;
303
304 /* The breakpoint_ops structure to be inherited by all breakpoint_ops
305    that are implemented on top of software or hardware breakpoints
306    (user breakpoints, internal and momentary breakpoints, etc.).  */
307 static struct breakpoint_ops bkpt_base_breakpoint_ops;
308
309 /* Internal breakpoints class type.  */
310 static struct breakpoint_ops internal_breakpoint_ops;
311
312 /* Momentary breakpoints class type.  */
313 static struct breakpoint_ops momentary_breakpoint_ops;
314
315 /* Momentary breakpoints for bp_longjmp and bp_exception class type.  */
316 static struct breakpoint_ops longjmp_breakpoint_ops;
317
318 /* The breakpoint_ops structure to be used in regular user created
319    breakpoints.  */
320 struct breakpoint_ops bkpt_breakpoint_ops;
321
322 /* Breakpoints set on probes.  */
323 static struct breakpoint_ops bkpt_probe_breakpoint_ops;
324
325 /* Dynamic printf class type.  */
326 struct breakpoint_ops dprintf_breakpoint_ops;
327
328 /* The style in which to perform a dynamic printf.  This is a user
329    option because different output options have different tradeoffs;
330    if GDB does the printing, there is better error handling if there
331    is a problem with any of the arguments, but using an inferior
332    function lets you have special-purpose printers and sending of
333    output to the same place as compiled-in print functions.  */
334
335 static const char dprintf_style_gdb[] = "gdb";
336 static const char dprintf_style_call[] = "call";
337 static const char dprintf_style_agent[] = "agent";
338 static const char *const dprintf_style_enums[] = {
339   dprintf_style_gdb,
340   dprintf_style_call,
341   dprintf_style_agent,
342   NULL
343 };
344 static const char *dprintf_style = dprintf_style_gdb;
345
346 /* The function to use for dynamic printf if the preferred style is to
347    call into the inferior.  The value is simply a string that is
348    copied into the command, so it can be anything that GDB can
349    evaluate to a callable address, not necessarily a function name.  */
350
351 static char *dprintf_function = "";
352
353 /* The channel to use for dynamic printf if the preferred style is to
354    call into the inferior; if a nonempty string, it will be passed to
355    the call as the first argument, with the format string as the
356    second.  As with the dprintf function, this can be anything that
357    GDB knows how to evaluate, so in addition to common choices like
358    "stderr", this could be an app-specific expression like
359    "mystreams[curlogger]".  */
360
361 static char *dprintf_channel = "";
362
363 /* True if dprintf commands should continue to operate even if GDB
364    has disconnected.  */
365 static int disconnected_dprintf = 1;
366
367 /* A reference-counted struct command_line.  This lets multiple
368    breakpoints share a single command list.  */
369 struct counted_command_line
370 {
371   /* The reference count.  */
372   int refc;
373
374   /* The command list.  */
375   struct command_line *commands;
376 };
377
378 struct command_line *
379 breakpoint_commands (struct breakpoint *b)
380 {
381   return b->commands ? b->commands->commands : NULL;
382 }
383
384 /* Flag indicating that a command has proceeded the inferior past the
385    current breakpoint.  */
386
387 static int breakpoint_proceeded;
388
389 const char *
390 bpdisp_text (enum bpdisp disp)
391 {
392   /* NOTE: the following values are a part of MI protocol and
393      represent values of 'disp' field returned when inferior stops at
394      a breakpoint.  */
395   static const char * const bpdisps[] = {"del", "dstp", "dis", "keep"};
396
397   return bpdisps[(int) disp];
398 }
399
400 /* Prototypes for exported functions.  */
401 /* If FALSE, gdb will not use hardware support for watchpoints, even
402    if such is available.  */
403 static int can_use_hw_watchpoints;
404
405 static void
406 show_can_use_hw_watchpoints (struct ui_file *file, int from_tty,
407                              struct cmd_list_element *c,
408                              const char *value)
409 {
410   fprintf_filtered (file,
411                     _("Debugger's willingness to use "
412                       "watchpoint hardware is %s.\n"),
413                     value);
414 }
415
416 /* If AUTO_BOOLEAN_FALSE, gdb will not attempt to create pending breakpoints.
417    If AUTO_BOOLEAN_TRUE, gdb will automatically create pending breakpoints
418    for unrecognized breakpoint locations.
419    If AUTO_BOOLEAN_AUTO, gdb will query when breakpoints are unrecognized.  */
420 static enum auto_boolean pending_break_support;
421 static void
422 show_pending_break_support (struct ui_file *file, int from_tty,
423                             struct cmd_list_element *c,
424                             const char *value)
425 {
426   fprintf_filtered (file,
427                     _("Debugger's behavior regarding "
428                       "pending breakpoints is %s.\n"),
429                     value);
430 }
431
432 /* If 1, gdb will automatically use hardware breakpoints for breakpoints
433    set with "break" but falling in read-only memory.
434    If 0, gdb will warn about such breakpoints, but won't automatically
435    use hardware breakpoints.  */
436 static int automatic_hardware_breakpoints;
437 static void
438 show_automatic_hardware_breakpoints (struct ui_file *file, int from_tty,
439                                      struct cmd_list_element *c,
440                                      const char *value)
441 {
442   fprintf_filtered (file,
443                     _("Automatic usage of hardware breakpoints is %s.\n"),
444                     value);
445 }
446
447 /* If on, GDB keeps breakpoints inserted even if the inferior is
448    stopped, and immediately inserts any new breakpoints as soon as
449    they're created.  If off (default), GDB keeps breakpoints off of
450    the target as long as possible.  That is, it delays inserting
451    breakpoints until the next resume, and removes them again when the
452    target fully stops.  This is a bit safer in case GDB crashes while
453    processing user input.  */
454 static int always_inserted_mode = 0;
455
456 static void
457 show_always_inserted_mode (struct ui_file *file, int from_tty,
458                      struct cmd_list_element *c, const char *value)
459 {
460   fprintf_filtered (file, _("Always inserted breakpoint mode is %s.\n"),
461                     value);
462 }
463
464 /* See breakpoint.h.  */
465
466 int
467 breakpoints_should_be_inserted_now (void)
468 {
469   if (gdbarch_has_global_breakpoints (target_gdbarch ()))
470     {
471       /* If breakpoints are global, they should be inserted even if no
472          thread under gdb's control is running, or even if there are
473          no threads under GDB's control yet.  */
474       return 1;
475     }
476   else if (target_has_execution)
477     {
478       if (always_inserted_mode)
479         {
480           /* The user wants breakpoints inserted even if all threads
481              are stopped.  */
482           return 1;
483         }
484
485       if (threads_are_executing ())
486         return 1;
487     }
488   return 0;
489 }
490
491 static const char condition_evaluation_both[] = "host or target";
492
493 /* Modes for breakpoint condition evaluation.  */
494 static const char condition_evaluation_auto[] = "auto";
495 static const char condition_evaluation_host[] = "host";
496 static const char condition_evaluation_target[] = "target";
497 static const char *const condition_evaluation_enums[] = {
498   condition_evaluation_auto,
499   condition_evaluation_host,
500   condition_evaluation_target,
501   NULL
502 };
503
504 /* Global that holds the current mode for breakpoint condition evaluation.  */
505 static const char *condition_evaluation_mode_1 = condition_evaluation_auto;
506
507 /* Global that we use to display information to the user (gets its value from
508    condition_evaluation_mode_1.  */
509 static const char *condition_evaluation_mode = condition_evaluation_auto;
510
511 /* Translate a condition evaluation mode MODE into either "host"
512    or "target".  This is used mostly to translate from "auto" to the
513    real setting that is being used.  It returns the translated
514    evaluation mode.  */
515
516 static const char *
517 translate_condition_evaluation_mode (const char *mode)
518 {
519   if (mode == condition_evaluation_auto)
520     {
521       if (target_supports_evaluation_of_breakpoint_conditions ())
522         return condition_evaluation_target;
523       else
524         return condition_evaluation_host;
525     }
526   else
527     return mode;
528 }
529
530 /* Discovers what condition_evaluation_auto translates to.  */
531
532 static const char *
533 breakpoint_condition_evaluation_mode (void)
534 {
535   return translate_condition_evaluation_mode (condition_evaluation_mode);
536 }
537
538 /* Return true if GDB should evaluate breakpoint conditions or false
539    otherwise.  */
540
541 static int
542 gdb_evaluates_breakpoint_condition_p (void)
543 {
544   const char *mode = breakpoint_condition_evaluation_mode ();
545
546   return (mode == condition_evaluation_host);
547 }
548
549 void _initialize_breakpoint (void);
550
551 /* Are we executing breakpoint commands?  */
552 static int executing_breakpoint_commands;
553
554 /* Are overlay event breakpoints enabled? */
555 static int overlay_events_enabled;
556
557 /* See description in breakpoint.h. */
558 int target_exact_watchpoints = 0;
559
560 /* Walk the following statement or block through all breakpoints.
561    ALL_BREAKPOINTS_SAFE does so even if the statement deletes the
562    current breakpoint.  */
563
564 #define ALL_BREAKPOINTS(B)  for (B = breakpoint_chain; B; B = B->next)
565
566 #define ALL_BREAKPOINTS_SAFE(B,TMP)     \
567         for (B = breakpoint_chain;      \
568              B ? (TMP=B->next, 1): 0;   \
569              B = TMP)
570
571 /* Similar iterator for the low-level breakpoints.  SAFE variant is
572    not provided so update_global_location_list must not be called
573    while executing the block of ALL_BP_LOCATIONS.  */
574
575 #define ALL_BP_LOCATIONS(B,BP_TMP)                                      \
576         for (BP_TMP = bp_location;                                      \
577              BP_TMP < bp_location + bp_location_count && (B = *BP_TMP); \
578              BP_TMP++)
579
580 /* Iterates through locations with address ADDRESS for the currently selected
581    program space.  BP_LOCP_TMP points to each object.  BP_LOCP_START points
582    to where the loop should start from.
583    If BP_LOCP_START is a NULL pointer, the macro automatically seeks the
584    appropriate location to start with.  */
585
586 #define ALL_BP_LOCATIONS_AT_ADDR(BP_LOCP_TMP, BP_LOCP_START, ADDRESS)   \
587         for (BP_LOCP_START = BP_LOCP_START == NULL ? get_first_locp_gte_addr (ADDRESS) : BP_LOCP_START, \
588              BP_LOCP_TMP = BP_LOCP_START;                               \
589              BP_LOCP_START                                              \
590              && (BP_LOCP_TMP < bp_location + bp_location_count          \
591              && (*BP_LOCP_TMP)->address == ADDRESS);                    \
592              BP_LOCP_TMP++)
593
594 /* Iterator for tracepoints only.  */
595
596 #define ALL_TRACEPOINTS(B)  \
597   for (B = breakpoint_chain; B; B = B->next)  \
598     if (is_tracepoint (B))
599
600 /* Chains of all breakpoints defined.  */
601
602 struct breakpoint *breakpoint_chain;
603
604 /* Array is sorted by bp_location_compare - primarily by the ADDRESS.  */
605
606 static struct bp_location **bp_location;
607
608 /* Number of elements of BP_LOCATION.  */
609
610 static unsigned bp_location_count;
611
612 /* Maximum alignment offset between bp_target_info.PLACED_ADDRESS and
613    ADDRESS for the current elements of BP_LOCATION which get a valid
614    result from bp_location_has_shadow.  You can use it for roughly
615    limiting the subrange of BP_LOCATION to scan for shadow bytes for
616    an address you need to read.  */
617
618 static CORE_ADDR bp_location_placed_address_before_address_max;
619
620 /* Maximum offset plus alignment between bp_target_info.PLACED_ADDRESS
621    + bp_target_info.SHADOW_LEN and ADDRESS for the current elements of
622    BP_LOCATION which get a valid result from bp_location_has_shadow.
623    You can use it for roughly limiting the subrange of BP_LOCATION to
624    scan for shadow bytes for an address you need to read.  */
625
626 static CORE_ADDR bp_location_shadow_len_after_address_max;
627
628 /* The locations that no longer correspond to any breakpoint, unlinked
629    from bp_location array, but for which a hit may still be reported
630    by a target.  */
631 VEC(bp_location_p) *moribund_locations = NULL;
632
633 /* Number of last breakpoint made.  */
634
635 static int breakpoint_count;
636
637 /* The value of `breakpoint_count' before the last command that
638    created breakpoints.  If the last (break-like) command created more
639    than one breakpoint, then the difference between BREAKPOINT_COUNT
640    and PREV_BREAKPOINT_COUNT is more than one.  */
641 static int prev_breakpoint_count;
642
643 /* Number of last tracepoint made.  */
644
645 static int tracepoint_count;
646
647 static struct cmd_list_element *breakpoint_set_cmdlist;
648 static struct cmd_list_element *breakpoint_show_cmdlist;
649 struct cmd_list_element *save_cmdlist;
650
651 /* Return whether a breakpoint is an active enabled breakpoint.  */
652 static int
653 breakpoint_enabled (struct breakpoint *b)
654 {
655   return (b->enable_state == bp_enabled);
656 }
657
658 /* Set breakpoint count to NUM.  */
659
660 static void
661 set_breakpoint_count (int num)
662 {
663   prev_breakpoint_count = breakpoint_count;
664   breakpoint_count = num;
665   set_internalvar_integer (lookup_internalvar ("bpnum"), num);
666 }
667
668 /* Used by `start_rbreak_breakpoints' below, to record the current
669    breakpoint count before "rbreak" creates any breakpoint.  */
670 static int rbreak_start_breakpoint_count;
671
672 /* Called at the start an "rbreak" command to record the first
673    breakpoint made.  */
674
675 void
676 start_rbreak_breakpoints (void)
677 {
678   rbreak_start_breakpoint_count = breakpoint_count;
679 }
680
681 /* Called at the end of an "rbreak" command to record the last
682    breakpoint made.  */
683
684 void
685 end_rbreak_breakpoints (void)
686 {
687   prev_breakpoint_count = rbreak_start_breakpoint_count;
688 }
689
690 /* Used in run_command to zero the hit count when a new run starts.  */
691
692 void
693 clear_breakpoint_hit_counts (void)
694 {
695   struct breakpoint *b;
696
697   ALL_BREAKPOINTS (b)
698     b->hit_count = 0;
699 }
700
701 /* Allocate a new counted_command_line with reference count of 1.
702    The new structure owns COMMANDS.  */
703
704 static struct counted_command_line *
705 alloc_counted_command_line (struct command_line *commands)
706 {
707   struct counted_command_line *result
708     = xmalloc (sizeof (struct counted_command_line));
709
710   result->refc = 1;
711   result->commands = commands;
712   return result;
713 }
714
715 /* Increment reference count.  This does nothing if CMD is NULL.  */
716
717 static void
718 incref_counted_command_line (struct counted_command_line *cmd)
719 {
720   if (cmd)
721     ++cmd->refc;
722 }
723
724 /* Decrement reference count.  If the reference count reaches 0,
725    destroy the counted_command_line.  Sets *CMDP to NULL.  This does
726    nothing if *CMDP is NULL.  */
727
728 static void
729 decref_counted_command_line (struct counted_command_line **cmdp)
730 {
731   if (*cmdp)
732     {
733       if (--(*cmdp)->refc == 0)
734         {
735           free_command_lines (&(*cmdp)->commands);
736           xfree (*cmdp);
737         }
738       *cmdp = NULL;
739     }
740 }
741
742 /* A cleanup function that calls decref_counted_command_line.  */
743
744 static void
745 do_cleanup_counted_command_line (void *arg)
746 {
747   decref_counted_command_line (arg);
748 }
749
750 /* Create a cleanup that calls decref_counted_command_line on the
751    argument.  */
752
753 static struct cleanup *
754 make_cleanup_decref_counted_command_line (struct counted_command_line **cmdp)
755 {
756   return make_cleanup (do_cleanup_counted_command_line, cmdp);
757 }
758
759 \f
760 /* Return the breakpoint with the specified number, or NULL
761    if the number does not refer to an existing breakpoint.  */
762
763 struct breakpoint *
764 get_breakpoint (int num)
765 {
766   struct breakpoint *b;
767
768   ALL_BREAKPOINTS (b)
769     if (b->number == num)
770       return b;
771   
772   return NULL;
773 }
774
775 \f
776
777 /* Mark locations as "conditions have changed" in case the target supports
778    evaluating conditions on its side.  */
779
780 static void
781 mark_breakpoint_modified (struct breakpoint *b)
782 {
783   struct bp_location *loc;
784
785   /* This is only meaningful if the target is
786      evaluating conditions and if the user has
787      opted for condition evaluation on the target's
788      side.  */
789   if (gdb_evaluates_breakpoint_condition_p ()
790       || !target_supports_evaluation_of_breakpoint_conditions ())
791     return;
792
793   if (!is_breakpoint (b))
794     return;
795
796   for (loc = b->loc; loc; loc = loc->next)
797     loc->condition_changed = condition_modified;
798 }
799
800 /* Mark location as "conditions have changed" in case the target supports
801    evaluating conditions on its side.  */
802
803 static void
804 mark_breakpoint_location_modified (struct bp_location *loc)
805 {
806   /* This is only meaningful if the target is
807      evaluating conditions and if the user has
808      opted for condition evaluation on the target's
809      side.  */
810   if (gdb_evaluates_breakpoint_condition_p ()
811       || !target_supports_evaluation_of_breakpoint_conditions ())
812
813     return;
814
815   if (!is_breakpoint (loc->owner))
816     return;
817
818   loc->condition_changed = condition_modified;
819 }
820
821 /* Sets the condition-evaluation mode using the static global
822    condition_evaluation_mode.  */
823
824 static void
825 set_condition_evaluation_mode (char *args, int from_tty,
826                                struct cmd_list_element *c)
827 {
828   const char *old_mode, *new_mode;
829
830   if ((condition_evaluation_mode_1 == condition_evaluation_target)
831       && !target_supports_evaluation_of_breakpoint_conditions ())
832     {
833       condition_evaluation_mode_1 = condition_evaluation_mode;
834       warning (_("Target does not support breakpoint condition evaluation.\n"
835                  "Using host evaluation mode instead."));
836       return;
837     }
838
839   new_mode = translate_condition_evaluation_mode (condition_evaluation_mode_1);
840   old_mode = translate_condition_evaluation_mode (condition_evaluation_mode);
841
842   /* Flip the switch.  Flip it even if OLD_MODE == NEW_MODE as one of the
843      settings was "auto".  */
844   condition_evaluation_mode = condition_evaluation_mode_1;
845
846   /* Only update the mode if the user picked a different one.  */
847   if (new_mode != old_mode)
848     {
849       struct bp_location *loc, **loc_tmp;
850       /* If the user switched to a different evaluation mode, we
851          need to synch the changes with the target as follows:
852
853          "host" -> "target": Send all (valid) conditions to the target.
854          "target" -> "host": Remove all the conditions from the target.
855       */
856
857       if (new_mode == condition_evaluation_target)
858         {
859           /* Mark everything modified and synch conditions with the
860              target.  */
861           ALL_BP_LOCATIONS (loc, loc_tmp)
862             mark_breakpoint_location_modified (loc);
863         }
864       else
865         {
866           /* Manually mark non-duplicate locations to synch conditions
867              with the target.  We do this to remove all the conditions the
868              target knows about.  */
869           ALL_BP_LOCATIONS (loc, loc_tmp)
870             if (is_breakpoint (loc->owner) && loc->inserted)
871               loc->needs_update = 1;
872         }
873
874       /* Do the update.  */
875       update_global_location_list (UGLL_MAY_INSERT);
876     }
877
878   return;
879 }
880
881 /* Shows the current mode of breakpoint condition evaluation.  Explicitly shows
882    what "auto" is translating to.  */
883
884 static void
885 show_condition_evaluation_mode (struct ui_file *file, int from_tty,
886                                 struct cmd_list_element *c, const char *value)
887 {
888   if (condition_evaluation_mode == condition_evaluation_auto)
889     fprintf_filtered (file,
890                       _("Breakpoint condition evaluation "
891                         "mode is %s (currently %s).\n"),
892                       value,
893                       breakpoint_condition_evaluation_mode ());
894   else
895     fprintf_filtered (file, _("Breakpoint condition evaluation mode is %s.\n"),
896                       value);
897 }
898
899 /* A comparison function for bp_location AP and BP that is used by
900    bsearch.  This comparison function only cares about addresses, unlike
901    the more general bp_location_compare function.  */
902
903 static int
904 bp_location_compare_addrs (const void *ap, const void *bp)
905 {
906   struct bp_location *a = *(void **) ap;
907   struct bp_location *b = *(void **) bp;
908
909   if (a->address == b->address)
910     return 0;
911   else
912     return ((a->address > b->address) - (a->address < b->address));
913 }
914
915 /* Helper function to skip all bp_locations with addresses
916    less than ADDRESS.  It returns the first bp_location that
917    is greater than or equal to ADDRESS.  If none is found, just
918    return NULL.  */
919
920 static struct bp_location **
921 get_first_locp_gte_addr (CORE_ADDR address)
922 {
923   struct bp_location dummy_loc;
924   struct bp_location *dummy_locp = &dummy_loc;
925   struct bp_location **locp_found = NULL;
926
927   /* Initialize the dummy location's address field.  */
928   memset (&dummy_loc, 0, sizeof (struct bp_location));
929   dummy_loc.address = address;
930
931   /* Find a close match to the first location at ADDRESS.  */
932   locp_found = bsearch (&dummy_locp, bp_location, bp_location_count,
933                         sizeof (struct bp_location **),
934                         bp_location_compare_addrs);
935
936   /* Nothing was found, nothing left to do.  */
937   if (locp_found == NULL)
938     return NULL;
939
940   /* We may have found a location that is at ADDRESS but is not the first in the
941      location's list.  Go backwards (if possible) and locate the first one.  */
942   while ((locp_found - 1) >= bp_location
943          && (*(locp_found - 1))->address == address)
944     locp_found--;
945
946   return locp_found;
947 }
948
949 void
950 set_breakpoint_condition (struct breakpoint *b, char *exp,
951                           int from_tty)
952 {
953   xfree (b->cond_string);
954   b->cond_string = NULL;
955
956   if (is_watchpoint (b))
957     {
958       struct watchpoint *w = (struct watchpoint *) b;
959
960       xfree (w->cond_exp);
961       w->cond_exp = NULL;
962     }
963   else
964     {
965       struct bp_location *loc;
966
967       for (loc = b->loc; loc; loc = loc->next)
968         {
969           xfree (loc->cond);
970           loc->cond = NULL;
971
972           /* No need to free the condition agent expression
973              bytecode (if we have one).  We will handle this
974              when we go through update_global_location_list.  */
975         }
976     }
977
978   if (*exp == 0)
979     {
980       if (from_tty)
981         printf_filtered (_("Breakpoint %d now unconditional.\n"), b->number);
982     }
983   else
984     {
985       const char *arg = exp;
986
987       /* I don't know if it matters whether this is the string the user
988          typed in or the decompiled expression.  */
989       b->cond_string = xstrdup (arg);
990       b->condition_not_parsed = 0;
991
992       if (is_watchpoint (b))
993         {
994           struct watchpoint *w = (struct watchpoint *) b;
995
996           innermost_block = NULL;
997           arg = exp;
998           w->cond_exp = parse_exp_1 (&arg, 0, 0, 0);
999           if (*arg)
1000             error (_("Junk at end of expression"));
1001           w->cond_exp_valid_block = innermost_block;
1002         }
1003       else
1004         {
1005           struct bp_location *loc;
1006
1007           for (loc = b->loc; loc; loc = loc->next)
1008             {
1009               arg = exp;
1010               loc->cond =
1011                 parse_exp_1 (&arg, loc->address,
1012                              block_for_pc (loc->address), 0);
1013               if (*arg)
1014                 error (_("Junk at end of expression"));
1015             }
1016         }
1017     }
1018   mark_breakpoint_modified (b);
1019
1020   observer_notify_breakpoint_modified (b);
1021 }
1022
1023 /* Completion for the "condition" command.  */
1024
1025 static VEC (char_ptr) *
1026 condition_completer (struct cmd_list_element *cmd,
1027                      const char *text, const char *word)
1028 {
1029   const char *space;
1030
1031   text = skip_spaces_const (text);
1032   space = skip_to_space_const (text);
1033   if (*space == '\0')
1034     {
1035       int len;
1036       struct breakpoint *b;
1037       VEC (char_ptr) *result = NULL;
1038
1039       if (text[0] == '$')
1040         {
1041           /* We don't support completion of history indices.  */
1042           if (isdigit (text[1]))
1043             return NULL;
1044           return complete_internalvar (&text[1]);
1045         }
1046
1047       /* We're completing the breakpoint number.  */
1048       len = strlen (text);
1049
1050       ALL_BREAKPOINTS (b)
1051         {
1052           char number[50];
1053
1054           xsnprintf (number, sizeof (number), "%d", b->number);
1055
1056           if (strncmp (number, text, len) == 0)
1057             VEC_safe_push (char_ptr, result, xstrdup (number));
1058         }
1059
1060       return result;
1061     }
1062
1063   /* We're completing the expression part.  */
1064   text = skip_spaces_const (space);
1065   return expression_completer (cmd, text, word);
1066 }
1067
1068 /* condition N EXP -- set break condition of breakpoint N to EXP.  */
1069
1070 static void
1071 condition_command (char *arg, int from_tty)
1072 {
1073   struct breakpoint *b;
1074   char *p;
1075   int bnum;
1076
1077   if (arg == 0)
1078     error_no_arg (_("breakpoint number"));
1079
1080   p = arg;
1081   bnum = get_number (&p);
1082   if (bnum == 0)
1083     error (_("Bad breakpoint argument: '%s'"), arg);
1084
1085   ALL_BREAKPOINTS (b)
1086     if (b->number == bnum)
1087       {
1088         /* Check if this breakpoint has a "stop" method implemented in an
1089            extension language.  This method and conditions entered into GDB
1090            from the CLI are mutually exclusive.  */
1091         const struct extension_language_defn *extlang
1092           = get_breakpoint_cond_ext_lang (b, EXT_LANG_NONE);
1093
1094         if (extlang != NULL)
1095           {
1096             error (_("Only one stop condition allowed.  There is currently"
1097                      " a %s stop condition defined for this breakpoint."),
1098                    ext_lang_capitalized_name (extlang));
1099           }
1100         set_breakpoint_condition (b, p, from_tty);
1101
1102         if (is_breakpoint (b))
1103           update_global_location_list (UGLL_MAY_INSERT);
1104
1105         return;
1106       }
1107
1108   error (_("No breakpoint number %d."), bnum);
1109 }
1110
1111 /* Check that COMMAND do not contain commands that are suitable
1112    only for tracepoints and not suitable for ordinary breakpoints.
1113    Throw if any such commands is found.  */
1114
1115 static void
1116 check_no_tracepoint_commands (struct command_line *commands)
1117 {
1118   struct command_line *c;
1119
1120   for (c = commands; c; c = c->next)
1121     {
1122       int i;
1123
1124       if (c->control_type == while_stepping_control)
1125         error (_("The 'while-stepping' command can "
1126                  "only be used for tracepoints"));
1127
1128       for (i = 0; i < c->body_count; ++i)
1129         check_no_tracepoint_commands ((c->body_list)[i]);
1130
1131       /* Not that command parsing removes leading whitespace and comment
1132          lines and also empty lines.  So, we only need to check for
1133          command directly.  */
1134       if (strstr (c->line, "collect ") == c->line)
1135         error (_("The 'collect' command can only be used for tracepoints"));
1136
1137       if (strstr (c->line, "teval ") == c->line)
1138         error (_("The 'teval' command can only be used for tracepoints"));
1139     }
1140 }
1141
1142 /* Encapsulate tests for different types of tracepoints.  */
1143
1144 static int
1145 is_tracepoint_type (enum bptype type)
1146 {
1147   return (type == bp_tracepoint
1148           || type == bp_fast_tracepoint
1149           || type == bp_static_tracepoint);
1150 }
1151
1152 int
1153 is_tracepoint (const struct breakpoint *b)
1154 {
1155   return is_tracepoint_type (b->type);
1156 }
1157
1158 /* A helper function that validates that COMMANDS are valid for a
1159    breakpoint.  This function will throw an exception if a problem is
1160    found.  */
1161
1162 static void
1163 validate_commands_for_breakpoint (struct breakpoint *b,
1164                                   struct command_line *commands)
1165 {
1166   if (is_tracepoint (b))
1167     {
1168       struct tracepoint *t = (struct tracepoint *) b;
1169       struct command_line *c;
1170       struct command_line *while_stepping = 0;
1171
1172       /* Reset the while-stepping step count.  The previous commands
1173          might have included a while-stepping action, while the new
1174          ones might not.  */
1175       t->step_count = 0;
1176
1177       /* We need to verify that each top-level element of commands is
1178          valid for tracepoints, that there's at most one
1179          while-stepping element, and that the while-stepping's body
1180          has valid tracing commands excluding nested while-stepping.
1181          We also need to validate the tracepoint action line in the
1182          context of the tracepoint --- validate_actionline actually
1183          has side effects, like setting the tracepoint's
1184          while-stepping STEP_COUNT, in addition to checking if the
1185          collect/teval actions parse and make sense in the
1186          tracepoint's context.  */
1187       for (c = commands; c; c = c->next)
1188         {
1189           if (c->control_type == while_stepping_control)
1190             {
1191               if (b->type == bp_fast_tracepoint)
1192                 error (_("The 'while-stepping' command "
1193                          "cannot be used for fast tracepoint"));
1194               else if (b->type == bp_static_tracepoint)
1195                 error (_("The 'while-stepping' command "
1196                          "cannot be used for static tracepoint"));
1197
1198               if (while_stepping)
1199                 error (_("The 'while-stepping' command "
1200                          "can be used only once"));
1201               else
1202                 while_stepping = c;
1203             }
1204
1205           validate_actionline (c->line, b);
1206         }
1207       if (while_stepping)
1208         {
1209           struct command_line *c2;
1210
1211           gdb_assert (while_stepping->body_count == 1);
1212           c2 = while_stepping->body_list[0];
1213           for (; c2; c2 = c2->next)
1214             {
1215               if (c2->control_type == while_stepping_control)
1216                 error (_("The 'while-stepping' command cannot be nested"));
1217             }
1218         }
1219     }
1220   else
1221     {
1222       check_no_tracepoint_commands (commands);
1223     }
1224 }
1225
1226 /* Return a vector of all the static tracepoints set at ADDR.  The
1227    caller is responsible for releasing the vector.  */
1228
1229 VEC(breakpoint_p) *
1230 static_tracepoints_here (CORE_ADDR addr)
1231 {
1232   struct breakpoint *b;
1233   VEC(breakpoint_p) *found = 0;
1234   struct bp_location *loc;
1235
1236   ALL_BREAKPOINTS (b)
1237     if (b->type == bp_static_tracepoint)
1238       {
1239         for (loc = b->loc; loc; loc = loc->next)
1240           if (loc->address == addr)
1241             VEC_safe_push(breakpoint_p, found, b);
1242       }
1243
1244   return found;
1245 }
1246
1247 /* Set the command list of B to COMMANDS.  If breakpoint is tracepoint,
1248    validate that only allowed commands are included.  */
1249
1250 void
1251 breakpoint_set_commands (struct breakpoint *b, 
1252                          struct command_line *commands)
1253 {
1254   validate_commands_for_breakpoint (b, commands);
1255
1256   decref_counted_command_line (&b->commands);
1257   b->commands = alloc_counted_command_line (commands);
1258   observer_notify_breakpoint_modified (b);
1259 }
1260
1261 /* Set the internal `silent' flag on the breakpoint.  Note that this
1262    is not the same as the "silent" that may appear in the breakpoint's
1263    commands.  */
1264
1265 void
1266 breakpoint_set_silent (struct breakpoint *b, int silent)
1267 {
1268   int old_silent = b->silent;
1269
1270   b->silent = silent;
1271   if (old_silent != silent)
1272     observer_notify_breakpoint_modified (b);
1273 }
1274
1275 /* Set the thread for this breakpoint.  If THREAD is -1, make the
1276    breakpoint work for any thread.  */
1277
1278 void
1279 breakpoint_set_thread (struct breakpoint *b, int thread)
1280 {
1281   int old_thread = b->thread;
1282
1283   b->thread = thread;
1284   if (old_thread != thread)
1285     observer_notify_breakpoint_modified (b);
1286 }
1287
1288 /* Set the task for this breakpoint.  If TASK is 0, make the
1289    breakpoint work for any task.  */
1290
1291 void
1292 breakpoint_set_task (struct breakpoint *b, int task)
1293 {
1294   int old_task = b->task;
1295
1296   b->task = task;
1297   if (old_task != task)
1298     observer_notify_breakpoint_modified (b);
1299 }
1300
1301 void
1302 check_tracepoint_command (char *line, void *closure)
1303 {
1304   struct breakpoint *b = closure;
1305
1306   validate_actionline (line, b);
1307 }
1308
1309 /* A structure used to pass information through
1310    map_breakpoint_numbers.  */
1311
1312 struct commands_info
1313 {
1314   /* True if the command was typed at a tty.  */
1315   int from_tty;
1316
1317   /* The breakpoint range spec.  */
1318   char *arg;
1319
1320   /* Non-NULL if the body of the commands are being read from this
1321      already-parsed command.  */
1322   struct command_line *control;
1323
1324   /* The command lines read from the user, or NULL if they have not
1325      yet been read.  */
1326   struct counted_command_line *cmd;
1327 };
1328
1329 /* A callback for map_breakpoint_numbers that sets the commands for
1330    commands_command.  */
1331
1332 static void
1333 do_map_commands_command (struct breakpoint *b, void *data)
1334 {
1335   struct commands_info *info = data;
1336
1337   if (info->cmd == NULL)
1338     {
1339       struct command_line *l;
1340
1341       if (info->control != NULL)
1342         l = copy_command_lines (info->control->body_list[0]);
1343       else
1344         {
1345           struct cleanup *old_chain;
1346           char *str;
1347
1348           str = xstrprintf (_("Type commands for breakpoint(s) "
1349                               "%s, one per line."),
1350                             info->arg);
1351
1352           old_chain = make_cleanup (xfree, str);
1353
1354           l = read_command_lines (str,
1355                                   info->from_tty, 1,
1356                                   (is_tracepoint (b)
1357                                    ? check_tracepoint_command : 0),
1358                                   b);
1359
1360           do_cleanups (old_chain);
1361         }
1362
1363       info->cmd = alloc_counted_command_line (l);
1364     }
1365
1366   /* If a breakpoint was on the list more than once, we don't need to
1367      do anything.  */
1368   if (b->commands != info->cmd)
1369     {
1370       validate_commands_for_breakpoint (b, info->cmd->commands);
1371       incref_counted_command_line (info->cmd);
1372       decref_counted_command_line (&b->commands);
1373       b->commands = info->cmd;
1374       observer_notify_breakpoint_modified (b);
1375     }
1376 }
1377
1378 static void
1379 commands_command_1 (char *arg, int from_tty, 
1380                     struct command_line *control)
1381 {
1382   struct cleanup *cleanups;
1383   struct commands_info info;
1384
1385   info.from_tty = from_tty;
1386   info.control = control;
1387   info.cmd = NULL;
1388   /* If we read command lines from the user, then `info' will hold an
1389      extra reference to the commands that we must clean up.  */
1390   cleanups = make_cleanup_decref_counted_command_line (&info.cmd);
1391
1392   if (arg == NULL || !*arg)
1393     {
1394       if (breakpoint_count - prev_breakpoint_count > 1)
1395         arg = xstrprintf ("%d-%d", prev_breakpoint_count + 1, 
1396                           breakpoint_count);
1397       else if (breakpoint_count > 0)
1398         arg = xstrprintf ("%d", breakpoint_count);
1399       else
1400         {
1401           /* So that we don't try to free the incoming non-NULL
1402              argument in the cleanup below.  Mapping breakpoint
1403              numbers will fail in this case.  */
1404           arg = NULL;
1405         }
1406     }
1407   else
1408     /* The command loop has some static state, so we need to preserve
1409        our argument.  */
1410     arg = xstrdup (arg);
1411
1412   if (arg != NULL)
1413     make_cleanup (xfree, arg);
1414
1415   info.arg = arg;
1416
1417   map_breakpoint_numbers (arg, do_map_commands_command, &info);
1418
1419   if (info.cmd == NULL)
1420     error (_("No breakpoints specified."));
1421
1422   do_cleanups (cleanups);
1423 }
1424
1425 static void
1426 commands_command (char *arg, int from_tty)
1427 {
1428   commands_command_1 (arg, from_tty, NULL);
1429 }
1430
1431 /* Like commands_command, but instead of reading the commands from
1432    input stream, takes them from an already parsed command structure.
1433
1434    This is used by cli-script.c to DTRT with breakpoint commands
1435    that are part of if and while bodies.  */
1436 enum command_control_type
1437 commands_from_control_command (char *arg, struct command_line *cmd)
1438 {
1439   commands_command_1 (arg, 0, cmd);
1440   return simple_control;
1441 }
1442
1443 /* Return non-zero if BL->TARGET_INFO contains valid information.  */
1444
1445 static int
1446 bp_location_has_shadow (struct bp_location *bl)
1447 {
1448   if (bl->loc_type != bp_loc_software_breakpoint)
1449     return 0;
1450   if (!bl->inserted)
1451     return 0;
1452   if (bl->target_info.shadow_len == 0)
1453     /* BL isn't valid, or doesn't shadow memory.  */
1454     return 0;
1455   return 1;
1456 }
1457
1458 /* Update BUF, which is LEN bytes read from the target address
1459    MEMADDR, by replacing a memory breakpoint with its shadowed
1460    contents.
1461
1462    If READBUF is not NULL, this buffer must not overlap with the of
1463    the breakpoint location's shadow_contents buffer.  Otherwise, a
1464    failed assertion internal error will be raised.  */
1465
1466 static void
1467 one_breakpoint_xfer_memory (gdb_byte *readbuf, gdb_byte *writebuf,
1468                             const gdb_byte *writebuf_org,
1469                             ULONGEST memaddr, LONGEST len,
1470                             struct bp_target_info *target_info,
1471                             struct gdbarch *gdbarch)
1472 {
1473   /* Now do full processing of the found relevant range of elements.  */
1474   CORE_ADDR bp_addr = 0;
1475   int bp_size = 0;
1476   int bptoffset = 0;
1477
1478   if (!breakpoint_address_match (target_info->placed_address_space, 0,
1479                                  current_program_space->aspace, 0))
1480     {
1481       /* The breakpoint is inserted in a different address space.  */
1482       return;
1483     }
1484
1485   /* Addresses and length of the part of the breakpoint that
1486      we need to copy.  */
1487   bp_addr = target_info->placed_address;
1488   bp_size = target_info->shadow_len;
1489
1490   if (bp_addr + bp_size <= memaddr)
1491     {
1492       /* The breakpoint is entirely before the chunk of memory we are
1493          reading.  */
1494       return;
1495     }
1496
1497   if (bp_addr >= memaddr + len)
1498     {
1499       /* The breakpoint is entirely after the chunk of memory we are
1500          reading.  */
1501       return;
1502     }
1503
1504   /* Offset within shadow_contents.  */
1505   if (bp_addr < memaddr)
1506     {
1507       /* Only copy the second part of the breakpoint.  */
1508       bp_size -= memaddr - bp_addr;
1509       bptoffset = memaddr - bp_addr;
1510       bp_addr = memaddr;
1511     }
1512
1513   if (bp_addr + bp_size > memaddr + len)
1514     {
1515       /* Only copy the first part of the breakpoint.  */
1516       bp_size -= (bp_addr + bp_size) - (memaddr + len);
1517     }
1518
1519   if (readbuf != NULL)
1520     {
1521       /* Verify that the readbuf buffer does not overlap with the
1522          shadow_contents buffer.  */
1523       gdb_assert (target_info->shadow_contents >= readbuf + len
1524                   || readbuf >= (target_info->shadow_contents
1525                                  + target_info->shadow_len));
1526
1527       /* Update the read buffer with this inserted breakpoint's
1528          shadow.  */
1529       memcpy (readbuf + bp_addr - memaddr,
1530               target_info->shadow_contents + bptoffset, bp_size);
1531     }
1532   else
1533     {
1534       const unsigned char *bp;
1535       CORE_ADDR addr = target_info->reqstd_address;
1536       int placed_size;
1537
1538       /* Update the shadow with what we want to write to memory.  */
1539       memcpy (target_info->shadow_contents + bptoffset,
1540               writebuf_org + bp_addr - memaddr, bp_size);
1541
1542       /* Determine appropriate breakpoint contents and size for this
1543          address.  */
1544       bp = gdbarch_breakpoint_from_pc (gdbarch, &addr, &placed_size);
1545
1546       /* Update the final write buffer with this inserted
1547          breakpoint's INSN.  */
1548       memcpy (writebuf + bp_addr - memaddr, bp + bptoffset, bp_size);
1549     }
1550 }
1551
1552 /* Update BUF, which is LEN bytes read from the target address MEMADDR,
1553    by replacing any memory breakpoints with their shadowed contents.
1554
1555    If READBUF is not NULL, this buffer must not overlap with any of
1556    the breakpoint location's shadow_contents buffers.  Otherwise,
1557    a failed assertion internal error will be raised.
1558
1559    The range of shadowed area by each bp_location is:
1560      bl->address - bp_location_placed_address_before_address_max
1561      up to bl->address + bp_location_shadow_len_after_address_max
1562    The range we were requested to resolve shadows for is:
1563      memaddr ... memaddr + len
1564    Thus the safe cutoff boundaries for performance optimization are
1565      memaddr + len <= (bl->address
1566                        - bp_location_placed_address_before_address_max)
1567    and:
1568      bl->address + bp_location_shadow_len_after_address_max <= memaddr  */
1569
1570 void
1571 breakpoint_xfer_memory (gdb_byte *readbuf, gdb_byte *writebuf,
1572                         const gdb_byte *writebuf_org,
1573                         ULONGEST memaddr, LONGEST len)
1574 {
1575   /* Left boundary, right boundary and median element of our binary
1576      search.  */
1577   unsigned bc_l, bc_r, bc;
1578   size_t i;
1579
1580   /* Find BC_L which is a leftmost element which may affect BUF
1581      content.  It is safe to report lower value but a failure to
1582      report higher one.  */
1583
1584   bc_l = 0;
1585   bc_r = bp_location_count;
1586   while (bc_l + 1 < bc_r)
1587     {
1588       struct bp_location *bl;
1589
1590       bc = (bc_l + bc_r) / 2;
1591       bl = bp_location[bc];
1592
1593       /* Check first BL->ADDRESS will not overflow due to the added
1594          constant.  Then advance the left boundary only if we are sure
1595          the BC element can in no way affect the BUF content (MEMADDR
1596          to MEMADDR + LEN range).
1597
1598          Use the BP_LOCATION_SHADOW_LEN_AFTER_ADDRESS_MAX safety
1599          offset so that we cannot miss a breakpoint with its shadow
1600          range tail still reaching MEMADDR.  */
1601
1602       if ((bl->address + bp_location_shadow_len_after_address_max
1603            >= bl->address)
1604           && (bl->address + bp_location_shadow_len_after_address_max
1605               <= memaddr))
1606         bc_l = bc;
1607       else
1608         bc_r = bc;
1609     }
1610
1611   /* Due to the binary search above, we need to make sure we pick the
1612      first location that's at BC_L's address.  E.g., if there are
1613      multiple locations at the same address, BC_L may end up pointing
1614      at a duplicate location, and miss the "master"/"inserted"
1615      location.  Say, given locations L1, L2 and L3 at addresses A and
1616      B:
1617
1618       L1@A, L2@A, L3@B, ...
1619
1620      BC_L could end up pointing at location L2, while the "master"
1621      location could be L1.  Since the `loc->inserted' flag is only set
1622      on "master" locations, we'd forget to restore the shadow of L1
1623      and L2.  */
1624   while (bc_l > 0
1625          && bp_location[bc_l]->address == bp_location[bc_l - 1]->address)
1626     bc_l--;
1627
1628   /* Now do full processing of the found relevant range of elements.  */
1629
1630   for (bc = bc_l; bc < bp_location_count; bc++)
1631   {
1632     struct bp_location *bl = bp_location[bc];
1633     CORE_ADDR bp_addr = 0;
1634     int bp_size = 0;
1635     int bptoffset = 0;
1636
1637     /* bp_location array has BL->OWNER always non-NULL.  */
1638     if (bl->owner->type == bp_none)
1639       warning (_("reading through apparently deleted breakpoint #%d?"),
1640                bl->owner->number);
1641
1642     /* Performance optimization: any further element can no longer affect BUF
1643        content.  */
1644
1645     if (bl->address >= bp_location_placed_address_before_address_max
1646         && memaddr + len <= (bl->address
1647                              - bp_location_placed_address_before_address_max))
1648       break;
1649
1650     if (!bp_location_has_shadow (bl))
1651       continue;
1652
1653     one_breakpoint_xfer_memory (readbuf, writebuf, writebuf_org,
1654                                 memaddr, len, &bl->target_info, bl->gdbarch);
1655   }
1656 }
1657
1658 \f
1659
1660 /* Return true if BPT is either a software breakpoint or a hardware
1661    breakpoint.  */
1662
1663 int
1664 is_breakpoint (const struct breakpoint *bpt)
1665 {
1666   return (bpt->type == bp_breakpoint
1667           || bpt->type == bp_hardware_breakpoint
1668           || bpt->type == bp_dprintf);
1669 }
1670
1671 /* Return true if BPT is of any hardware watchpoint kind.  */
1672
1673 static int
1674 is_hardware_watchpoint (const struct breakpoint *bpt)
1675 {
1676   return (bpt->type == bp_hardware_watchpoint
1677           || bpt->type == bp_read_watchpoint
1678           || bpt->type == bp_access_watchpoint);
1679 }
1680
1681 /* Return true if BPT is of any watchpoint kind, hardware or
1682    software.  */
1683
1684 int
1685 is_watchpoint (const struct breakpoint *bpt)
1686 {
1687   return (is_hardware_watchpoint (bpt)
1688           || bpt->type == bp_watchpoint);
1689 }
1690
1691 /* Returns true if the current thread and its running state are safe
1692    to evaluate or update watchpoint B.  Watchpoints on local
1693    expressions need to be evaluated in the context of the thread that
1694    was current when the watchpoint was created, and, that thread needs
1695    to be stopped to be able to select the correct frame context.
1696    Watchpoints on global expressions can be evaluated on any thread,
1697    and in any state.  It is presently left to the target allowing
1698    memory accesses when threads are running.  */
1699
1700 static int
1701 watchpoint_in_thread_scope (struct watchpoint *b)
1702 {
1703   return (b->base.pspace == current_program_space
1704           && (ptid_equal (b->watchpoint_thread, null_ptid)
1705               || (ptid_equal (inferior_ptid, b->watchpoint_thread)
1706                   && !is_executing (inferior_ptid))));
1707 }
1708
1709 /* Set watchpoint B to disp_del_at_next_stop, even including its possible
1710    associated bp_watchpoint_scope breakpoint.  */
1711
1712 static void
1713 watchpoint_del_at_next_stop (struct watchpoint *w)
1714 {
1715   struct breakpoint *b = &w->base;
1716
1717   if (b->related_breakpoint != b)
1718     {
1719       gdb_assert (b->related_breakpoint->type == bp_watchpoint_scope);
1720       gdb_assert (b->related_breakpoint->related_breakpoint == b);
1721       b->related_breakpoint->disposition = disp_del_at_next_stop;
1722       b->related_breakpoint->related_breakpoint = b->related_breakpoint;
1723       b->related_breakpoint = b;
1724     }
1725   b->disposition = disp_del_at_next_stop;
1726 }
1727
1728 /* Extract a bitfield value from value VAL using the bit parameters contained in
1729    watchpoint W.  */
1730
1731 static struct value *
1732 extract_bitfield_from_watchpoint_value (struct watchpoint *w, struct value *val)
1733 {
1734   struct value *bit_val;
1735
1736   if (val == NULL)
1737     return NULL;
1738
1739   bit_val = allocate_value (value_type (val));
1740
1741   unpack_value_bitfield (bit_val,
1742                          w->val_bitpos,
1743                          w->val_bitsize,
1744                          value_contents_for_printing (val),
1745                          value_offset (val),
1746                          val);
1747
1748   return bit_val;
1749 }
1750
1751 /* Assuming that B is a watchpoint:
1752    - Reparse watchpoint expression, if REPARSE is non-zero
1753    - Evaluate expression and store the result in B->val
1754    - Evaluate the condition if there is one, and store the result
1755      in b->loc->cond.
1756    - Update the list of values that must be watched in B->loc.
1757
1758    If the watchpoint disposition is disp_del_at_next_stop, then do
1759    nothing.  If this is local watchpoint that is out of scope, delete
1760    it.
1761
1762    Even with `set breakpoint always-inserted on' the watchpoints are
1763    removed + inserted on each stop here.  Normal breakpoints must
1764    never be removed because they might be missed by a running thread
1765    when debugging in non-stop mode.  On the other hand, hardware
1766    watchpoints (is_hardware_watchpoint; processed here) are specific
1767    to each LWP since they are stored in each LWP's hardware debug
1768    registers.  Therefore, such LWP must be stopped first in order to
1769    be able to modify its hardware watchpoints.
1770
1771    Hardware watchpoints must be reset exactly once after being
1772    presented to the user.  It cannot be done sooner, because it would
1773    reset the data used to present the watchpoint hit to the user.  And
1774    it must not be done later because it could display the same single
1775    watchpoint hit during multiple GDB stops.  Note that the latter is
1776    relevant only to the hardware watchpoint types bp_read_watchpoint
1777    and bp_access_watchpoint.  False hit by bp_hardware_watchpoint is
1778    not user-visible - its hit is suppressed if the memory content has
1779    not changed.
1780
1781    The following constraints influence the location where we can reset
1782    hardware watchpoints:
1783
1784    * target_stopped_by_watchpoint and target_stopped_data_address are
1785      called several times when GDB stops.
1786
1787    [linux] 
1788    * Multiple hardware watchpoints can be hit at the same time,
1789      causing GDB to stop.  GDB only presents one hardware watchpoint
1790      hit at a time as the reason for stopping, and all the other hits
1791      are presented later, one after the other, each time the user
1792      requests the execution to be resumed.  Execution is not resumed
1793      for the threads still having pending hit event stored in
1794      LWP_INFO->STATUS.  While the watchpoint is already removed from
1795      the inferior on the first stop the thread hit event is kept being
1796      reported from its cached value by linux_nat_stopped_data_address
1797      until the real thread resume happens after the watchpoint gets
1798      presented and thus its LWP_INFO->STATUS gets reset.
1799
1800    Therefore the hardware watchpoint hit can get safely reset on the
1801    watchpoint removal from inferior.  */
1802
1803 static void
1804 update_watchpoint (struct watchpoint *b, int reparse)
1805 {
1806   int within_current_scope;
1807   struct frame_id saved_frame_id;
1808   int frame_saved;
1809
1810   /* If this is a local watchpoint, we only want to check if the
1811      watchpoint frame is in scope if the current thread is the thread
1812      that was used to create the watchpoint.  */
1813   if (!watchpoint_in_thread_scope (b))
1814     return;
1815
1816   if (b->base.disposition == disp_del_at_next_stop)
1817     return;
1818  
1819   frame_saved = 0;
1820
1821   /* Determine if the watchpoint is within scope.  */
1822   if (b->exp_valid_block == NULL)
1823     within_current_scope = 1;
1824   else
1825     {
1826       struct frame_info *fi = get_current_frame ();
1827       struct gdbarch *frame_arch = get_frame_arch (fi);
1828       CORE_ADDR frame_pc = get_frame_pc (fi);
1829
1830       /* If we're in a function epilogue, unwinding may not work
1831          properly, so do not attempt to recreate locations at this
1832          point.  See similar comments in watchpoint_check.  */
1833       if (gdbarch_in_function_epilogue_p (frame_arch, frame_pc))
1834         return;
1835
1836       /* Save the current frame's ID so we can restore it after
1837          evaluating the watchpoint expression on its own frame.  */
1838       /* FIXME drow/2003-09-09: It would be nice if evaluate_expression
1839          took a frame parameter, so that we didn't have to change the
1840          selected frame.  */
1841       frame_saved = 1;
1842       saved_frame_id = get_frame_id (get_selected_frame (NULL));
1843
1844       fi = frame_find_by_id (b->watchpoint_frame);
1845       within_current_scope = (fi != NULL);
1846       if (within_current_scope)
1847         select_frame (fi);
1848     }
1849
1850   /* We don't free locations.  They are stored in the bp_location array
1851      and update_global_location_list will eventually delete them and
1852      remove breakpoints if needed.  */
1853   b->base.loc = NULL;
1854
1855   if (within_current_scope && reparse)
1856     {
1857       const char *s;
1858
1859       if (b->exp)
1860         {
1861           xfree (b->exp);
1862           b->exp = NULL;
1863         }
1864       s = b->exp_string_reparse ? b->exp_string_reparse : b->exp_string;
1865       b->exp = parse_exp_1 (&s, 0, b->exp_valid_block, 0);
1866       /* If the meaning of expression itself changed, the old value is
1867          no longer relevant.  We don't want to report a watchpoint hit
1868          to the user when the old value and the new value may actually
1869          be completely different objects.  */
1870       value_free (b->val);
1871       b->val = NULL;
1872       b->val_valid = 0;
1873
1874       /* Note that unlike with breakpoints, the watchpoint's condition
1875          expression is stored in the breakpoint object, not in the
1876          locations (re)created below.  */
1877       if (b->base.cond_string != NULL)
1878         {
1879           if (b->cond_exp != NULL)
1880             {
1881               xfree (b->cond_exp);
1882               b->cond_exp = NULL;
1883             }
1884
1885           s = b->base.cond_string;
1886           b->cond_exp = parse_exp_1 (&s, 0, b->cond_exp_valid_block, 0);
1887         }
1888     }
1889
1890   /* If we failed to parse the expression, for example because
1891      it refers to a global variable in a not-yet-loaded shared library,
1892      don't try to insert watchpoint.  We don't automatically delete
1893      such watchpoint, though, since failure to parse expression
1894      is different from out-of-scope watchpoint.  */
1895   if (!target_has_execution)
1896     {
1897       /* Without execution, memory can't change.  No use to try and
1898          set watchpoint locations.  The watchpoint will be reset when
1899          the target gains execution, through breakpoint_re_set.  */
1900       if (!can_use_hw_watchpoints)
1901         {
1902           if (b->base.ops->works_in_software_mode (&b->base))
1903             b->base.type = bp_watchpoint;
1904           else
1905             error (_("Can't set read/access watchpoint when "
1906                      "hardware watchpoints are disabled."));
1907         }
1908     }
1909   else if (within_current_scope && b->exp)
1910     {
1911       int pc = 0;
1912       struct value *val_chain, *v, *result, *next;
1913       struct program_space *frame_pspace;
1914
1915       fetch_subexp_value (b->exp, &pc, &v, &result, &val_chain, 0);
1916
1917       /* Avoid setting b->val if it's already set.  The meaning of
1918          b->val is 'the last value' user saw, and we should update
1919          it only if we reported that last value to user.  As it
1920          happens, the code that reports it updates b->val directly.
1921          We don't keep track of the memory value for masked
1922          watchpoints.  */
1923       if (!b->val_valid && !is_masked_watchpoint (&b->base))
1924         {
1925           if (b->val_bitsize != 0)
1926             {
1927               v = extract_bitfield_from_watchpoint_value (b, v);
1928               if (v != NULL)
1929                 release_value (v);
1930             }
1931           b->val = v;
1932           b->val_valid = 1;
1933         }
1934
1935       frame_pspace = get_frame_program_space (get_selected_frame (NULL));
1936
1937       /* Look at each value on the value chain.  */
1938       for (v = val_chain; v; v = value_next (v))
1939         {
1940           /* If it's a memory location, and GDB actually needed
1941              its contents to evaluate the expression, then we
1942              must watch it.  If the first value returned is
1943              still lazy, that means an error occurred reading it;
1944              watch it anyway in case it becomes readable.  */
1945           if (VALUE_LVAL (v) == lval_memory
1946               && (v == val_chain || ! value_lazy (v)))
1947             {
1948               struct type *vtype = check_typedef (value_type (v));
1949
1950               /* We only watch structs and arrays if user asked
1951                  for it explicitly, never if they just happen to
1952                  appear in the middle of some value chain.  */
1953               if (v == result
1954                   || (TYPE_CODE (vtype) != TYPE_CODE_STRUCT
1955                       && TYPE_CODE (vtype) != TYPE_CODE_ARRAY))
1956                 {
1957                   CORE_ADDR addr;
1958                   int type;
1959                   struct bp_location *loc, **tmp;
1960                   int bitpos = 0, bitsize = 0;
1961
1962                   if (value_bitsize (v) != 0)
1963                     {
1964                       /* Extract the bit parameters out from the bitfield
1965                          sub-expression.  */
1966                       bitpos = value_bitpos (v);
1967                       bitsize = value_bitsize (v);
1968                     }
1969                   else if (v == result && b->val_bitsize != 0)
1970                     {
1971                      /* If VAL_BITSIZE != 0 then RESULT is actually a bitfield
1972                         lvalue whose bit parameters are saved in the fields
1973                         VAL_BITPOS and VAL_BITSIZE.  */
1974                       bitpos = b->val_bitpos;
1975                       bitsize = b->val_bitsize;
1976                     }
1977
1978                   addr = value_address (v);
1979                   if (bitsize != 0)
1980                     {
1981                       /* Skip the bytes that don't contain the bitfield.  */
1982                       addr += bitpos / 8;
1983                     }
1984
1985                   type = hw_write;
1986                   if (b->base.type == bp_read_watchpoint)
1987                     type = hw_read;
1988                   else if (b->base.type == bp_access_watchpoint)
1989                     type = hw_access;
1990
1991                   loc = allocate_bp_location (&b->base);
1992                   for (tmp = &(b->base.loc); *tmp != NULL; tmp = &((*tmp)->next))
1993                     ;
1994                   *tmp = loc;
1995                   loc->gdbarch = get_type_arch (value_type (v));
1996
1997                   loc->pspace = frame_pspace;
1998                   loc->address = addr;
1999
2000                   if (bitsize != 0)
2001                     {
2002                       /* Just cover the bytes that make up the bitfield.  */
2003                       loc->length = ((bitpos % 8) + bitsize + 7) / 8;
2004                     }
2005                   else
2006                     loc->length = TYPE_LENGTH (value_type (v));
2007
2008                   loc->watchpoint_type = type;
2009                 }
2010             }
2011         }
2012
2013       /* Change the type of breakpoint between hardware assisted or
2014          an ordinary watchpoint depending on the hardware support
2015          and free hardware slots.  REPARSE is set when the inferior
2016          is started.  */
2017       if (reparse)
2018         {
2019           int reg_cnt;
2020           enum bp_loc_type loc_type;
2021           struct bp_location *bl;
2022
2023           reg_cnt = can_use_hardware_watchpoint (val_chain);
2024
2025           if (reg_cnt)
2026             {
2027               int i, target_resources_ok, other_type_used;
2028               enum bptype type;
2029
2030               /* Use an exact watchpoint when there's only one memory region to be
2031                  watched, and only one debug register is needed to watch it.  */
2032               b->exact = target_exact_watchpoints && reg_cnt == 1;
2033
2034               /* We need to determine how many resources are already
2035                  used for all other hardware watchpoints plus this one
2036                  to see if we still have enough resources to also fit
2037                  this watchpoint in as well.  */
2038
2039               /* If this is a software watchpoint, we try to turn it
2040                  to a hardware one -- count resources as if B was of
2041                  hardware watchpoint type.  */
2042               type = b->base.type;
2043               if (type == bp_watchpoint)
2044                 type = bp_hardware_watchpoint;
2045
2046               /* This watchpoint may or may not have been placed on
2047                  the list yet at this point (it won't be in the list
2048                  if we're trying to create it for the first time,
2049                  through watch_command), so always account for it
2050                  manually.  */
2051
2052               /* Count resources used by all watchpoints except B.  */
2053               i = hw_watchpoint_used_count_others (&b->base, type, &other_type_used);
2054
2055               /* Add in the resources needed for B.  */
2056               i += hw_watchpoint_use_count (&b->base);
2057
2058               target_resources_ok
2059                 = target_can_use_hardware_watchpoint (type, i, other_type_used);
2060               if (target_resources_ok <= 0)
2061                 {
2062                   int sw_mode = b->base.ops->works_in_software_mode (&b->base);
2063
2064                   if (target_resources_ok == 0 && !sw_mode)
2065                     error (_("Target does not support this type of "
2066                              "hardware watchpoint."));
2067                   else if (target_resources_ok < 0 && !sw_mode)
2068                     error (_("There are not enough available hardware "
2069                              "resources for this watchpoint."));
2070
2071                   /* Downgrade to software watchpoint.  */
2072                   b->base.type = bp_watchpoint;
2073                 }
2074               else
2075                 {
2076                   /* If this was a software watchpoint, we've just
2077                      found we have enough resources to turn it to a
2078                      hardware watchpoint.  Otherwise, this is a
2079                      nop.  */
2080                   b->base.type = type;
2081                 }
2082             }
2083           else if (!b->base.ops->works_in_software_mode (&b->base))
2084             {
2085               if (!can_use_hw_watchpoints)
2086                 error (_("Can't set read/access watchpoint when "
2087                          "hardware watchpoints are disabled."));
2088               else
2089                 error (_("Expression cannot be implemented with "
2090                          "read/access watchpoint."));
2091             }
2092           else
2093             b->base.type = bp_watchpoint;
2094
2095           loc_type = (b->base.type == bp_watchpoint? bp_loc_other
2096                       : bp_loc_hardware_watchpoint);
2097           for (bl = b->base.loc; bl; bl = bl->next)
2098             bl->loc_type = loc_type;
2099         }
2100
2101       for (v = val_chain; v; v = next)
2102         {
2103           next = value_next (v);
2104           if (v != b->val)
2105             value_free (v);
2106         }
2107
2108       /* If a software watchpoint is not watching any memory, then the
2109          above left it without any location set up.  But,
2110          bpstat_stop_status requires a location to be able to report
2111          stops, so make sure there's at least a dummy one.  */
2112       if (b->base.type == bp_watchpoint && b->base.loc == NULL)
2113         {
2114           struct breakpoint *base = &b->base;
2115           base->loc = allocate_bp_location (base);
2116           base->loc->pspace = frame_pspace;
2117           base->loc->address = -1;
2118           base->loc->length = -1;
2119           base->loc->watchpoint_type = -1;
2120         }
2121     }
2122   else if (!within_current_scope)
2123     {
2124       printf_filtered (_("\
2125 Watchpoint %d deleted because the program has left the block\n\
2126 in which its expression is valid.\n"),
2127                        b->base.number);
2128       watchpoint_del_at_next_stop (b);
2129     }
2130
2131   /* Restore the selected frame.  */
2132   if (frame_saved)
2133     select_frame (frame_find_by_id (saved_frame_id));
2134 }
2135
2136
2137 /* Returns 1 iff breakpoint location should be
2138    inserted in the inferior.  We don't differentiate the type of BL's owner
2139    (breakpoint vs. tracepoint), although insert_location in tracepoint's
2140    breakpoint_ops is not defined, because in insert_bp_location,
2141    tracepoint's insert_location will not be called.  */
2142 static int
2143 should_be_inserted (struct bp_location *bl)
2144 {
2145   if (bl->owner == NULL || !breakpoint_enabled (bl->owner))
2146     return 0;
2147
2148   if (bl->owner->disposition == disp_del_at_next_stop)
2149     return 0;
2150
2151   if (!bl->enabled || bl->shlib_disabled || bl->duplicate)
2152     return 0;
2153
2154   if (user_breakpoint_p (bl->owner) && bl->pspace->executing_startup)
2155     return 0;
2156
2157   /* This is set for example, when we're attached to the parent of a
2158      vfork, and have detached from the child.  The child is running
2159      free, and we expect it to do an exec or exit, at which point the
2160      OS makes the parent schedulable again (and the target reports
2161      that the vfork is done).  Until the child is done with the shared
2162      memory region, do not insert breakpoints in the parent, otherwise
2163      the child could still trip on the parent's breakpoints.  Since
2164      the parent is blocked anyway, it won't miss any breakpoint.  */
2165   if (bl->pspace->breakpoints_not_allowed)
2166     return 0;
2167
2168   /* Don't insert a breakpoint if we're trying to step past its
2169      location.  */
2170   if ((bl->loc_type == bp_loc_software_breakpoint
2171        || bl->loc_type == bp_loc_hardware_breakpoint)
2172       && stepping_past_instruction_at (bl->pspace->aspace,
2173                                        bl->address))
2174     {
2175       if (debug_infrun)
2176         {
2177           fprintf_unfiltered (gdb_stdlog,
2178                               "infrun: skipping breakpoint: "
2179                               "stepping past insn at: %s\n",
2180                               paddress (bl->gdbarch, bl->address));
2181         }
2182       return 0;
2183     }
2184
2185   /* Don't insert watchpoints if we're trying to step past the
2186      instruction that triggered one.  */
2187   if ((bl->loc_type == bp_loc_hardware_watchpoint)
2188       && stepping_past_nonsteppable_watchpoint ())
2189     {
2190       if (debug_infrun)
2191         {
2192           fprintf_unfiltered (gdb_stdlog,
2193                               "infrun: stepping past non-steppable watchpoint. "
2194                               "skipping watchpoint at %s:%d\n",
2195                               paddress (bl->gdbarch, bl->address),
2196                               bl->length);
2197         }
2198       return 0;
2199     }
2200
2201   return 1;
2202 }
2203
2204 /* Same as should_be_inserted but does the check assuming
2205    that the location is not duplicated.  */
2206
2207 static int
2208 unduplicated_should_be_inserted (struct bp_location *bl)
2209 {
2210   int result;
2211   const int save_duplicate = bl->duplicate;
2212
2213   bl->duplicate = 0;
2214   result = should_be_inserted (bl);
2215   bl->duplicate = save_duplicate;
2216   return result;
2217 }
2218
2219 /* Parses a conditional described by an expression COND into an
2220    agent expression bytecode suitable for evaluation
2221    by the bytecode interpreter.  Return NULL if there was
2222    any error during parsing.  */
2223
2224 static struct agent_expr *
2225 parse_cond_to_aexpr (CORE_ADDR scope, struct expression *cond)
2226 {
2227   struct agent_expr *aexpr = NULL;
2228   volatile struct gdb_exception ex;
2229
2230   if (!cond)
2231     return NULL;
2232
2233   /* We don't want to stop processing, so catch any errors
2234      that may show up.  */
2235   TRY_CATCH (ex, RETURN_MASK_ERROR)
2236     {
2237       aexpr = gen_eval_for_expr (scope, cond);
2238     }
2239
2240   if (ex.reason < 0)
2241     {
2242       /* If we got here, it means the condition could not be parsed to a valid
2243          bytecode expression and thus can't be evaluated on the target's side.
2244          It's no use iterating through the conditions.  */
2245       return NULL;
2246     }
2247
2248   /* We have a valid agent expression.  */
2249   return aexpr;
2250 }
2251
2252 /* Based on location BL, create a list of breakpoint conditions to be
2253    passed on to the target.  If we have duplicated locations with different
2254    conditions, we will add such conditions to the list.  The idea is that the
2255    target will evaluate the list of conditions and will only notify GDB when
2256    one of them is true.  */
2257
2258 static void
2259 build_target_condition_list (struct bp_location *bl)
2260 {
2261   struct bp_location **locp = NULL, **loc2p;
2262   int null_condition_or_parse_error = 0;
2263   int modified = bl->needs_update;
2264   struct bp_location *loc;
2265
2266   /* Release conditions left over from a previous insert.  */
2267   VEC_free (agent_expr_p, bl->target_info.conditions);
2268
2269   /* This is only meaningful if the target is
2270      evaluating conditions and if the user has
2271      opted for condition evaluation on the target's
2272      side.  */
2273   if (gdb_evaluates_breakpoint_condition_p ()
2274       || !target_supports_evaluation_of_breakpoint_conditions ())
2275     return;
2276
2277   /* Do a first pass to check for locations with no assigned
2278      conditions or conditions that fail to parse to a valid agent expression
2279      bytecode.  If any of these happen, then it's no use to send conditions
2280      to the target since this location will always trigger and generate a
2281      response back to GDB.  */
2282   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2283     {
2284       loc = (*loc2p);
2285       if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2286         {
2287           if (modified)
2288             {
2289               struct agent_expr *aexpr;
2290
2291               /* Re-parse the conditions since something changed.  In that
2292                  case we already freed the condition bytecodes (see
2293                  force_breakpoint_reinsertion).  We just
2294                  need to parse the condition to bytecodes again.  */
2295               aexpr = parse_cond_to_aexpr (bl->address, loc->cond);
2296               loc->cond_bytecode = aexpr;
2297
2298               /* Check if we managed to parse the conditional expression
2299                  correctly.  If not, we will not send this condition
2300                  to the target.  */
2301               if (aexpr)
2302                 continue;
2303             }
2304
2305           /* If we have a NULL bytecode expression, it means something
2306              went wrong or we have a null condition expression.  */
2307           if (!loc->cond_bytecode)
2308             {
2309               null_condition_or_parse_error = 1;
2310               break;
2311             }
2312         }
2313     }
2314
2315   /* If any of these happened, it means we will have to evaluate the conditions
2316      for the location's address on gdb's side.  It is no use keeping bytecodes
2317      for all the other duplicate locations, thus we free all of them here.
2318
2319      This is so we have a finer control over which locations' conditions are
2320      being evaluated by GDB or the remote stub.  */
2321   if (null_condition_or_parse_error)
2322     {
2323       ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2324         {
2325           loc = (*loc2p);
2326           if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2327             {
2328               /* Only go as far as the first NULL bytecode is
2329                  located.  */
2330               if (!loc->cond_bytecode)
2331                 return;
2332
2333               free_agent_expr (loc->cond_bytecode);
2334               loc->cond_bytecode = NULL;
2335             }
2336         }
2337     }
2338
2339   /* No NULL conditions or failed bytecode generation.  Build a condition list
2340      for this location's address.  */
2341   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2342     {
2343       loc = (*loc2p);
2344       if (loc->cond
2345           && is_breakpoint (loc->owner)
2346           && loc->pspace->num == bl->pspace->num
2347           && loc->owner->enable_state == bp_enabled
2348           && loc->enabled)
2349         /* Add the condition to the vector.  This will be used later to send the
2350            conditions to the target.  */
2351         VEC_safe_push (agent_expr_p, bl->target_info.conditions,
2352                        loc->cond_bytecode);
2353     }
2354
2355   return;
2356 }
2357
2358 /* Parses a command described by string CMD into an agent expression
2359    bytecode suitable for evaluation by the bytecode interpreter.
2360    Return NULL if there was any error during parsing.  */
2361
2362 static struct agent_expr *
2363 parse_cmd_to_aexpr (CORE_ADDR scope, char *cmd)
2364 {
2365   struct cleanup *old_cleanups = 0;
2366   struct expression *expr, **argvec;
2367   struct agent_expr *aexpr = NULL;
2368   volatile struct gdb_exception ex;
2369   const char *cmdrest;
2370   const char *format_start, *format_end;
2371   struct format_piece *fpieces;
2372   int nargs;
2373   struct gdbarch *gdbarch = get_current_arch ();
2374
2375   if (!cmd)
2376     return NULL;
2377
2378   cmdrest = cmd;
2379
2380   if (*cmdrest == ',')
2381     ++cmdrest;
2382   cmdrest = skip_spaces_const (cmdrest);
2383
2384   if (*cmdrest++ != '"')
2385     error (_("No format string following the location"));
2386
2387   format_start = cmdrest;
2388
2389   fpieces = parse_format_string (&cmdrest);
2390
2391   old_cleanups = make_cleanup (free_format_pieces_cleanup, &fpieces);
2392
2393   format_end = cmdrest;
2394
2395   if (*cmdrest++ != '"')
2396     error (_("Bad format string, non-terminated '\"'."));
2397   
2398   cmdrest = skip_spaces_const (cmdrest);
2399
2400   if (!(*cmdrest == ',' || *cmdrest == '\0'))
2401     error (_("Invalid argument syntax"));
2402
2403   if (*cmdrest == ',')
2404     cmdrest++;
2405   cmdrest = skip_spaces_const (cmdrest);
2406
2407   /* For each argument, make an expression.  */
2408
2409   argvec = (struct expression **) alloca (strlen (cmd)
2410                                          * sizeof (struct expression *));
2411
2412   nargs = 0;
2413   while (*cmdrest != '\0')
2414     {
2415       const char *cmd1;
2416
2417       cmd1 = cmdrest;
2418       expr = parse_exp_1 (&cmd1, scope, block_for_pc (scope), 1);
2419       argvec[nargs++] = expr;
2420       cmdrest = cmd1;
2421       if (*cmdrest == ',')
2422         ++cmdrest;
2423     }
2424
2425   /* We don't want to stop processing, so catch any errors
2426      that may show up.  */
2427   TRY_CATCH (ex, RETURN_MASK_ERROR)
2428     {
2429       aexpr = gen_printf (scope, gdbarch, 0, 0,
2430                           format_start, format_end - format_start,
2431                           fpieces, nargs, argvec);
2432     }
2433
2434   do_cleanups (old_cleanups);
2435
2436   if (ex.reason < 0)
2437     {
2438       /* If we got here, it means the command could not be parsed to a valid
2439          bytecode expression and thus can't be evaluated on the target's side.
2440          It's no use iterating through the other commands.  */
2441       return NULL;
2442     }
2443
2444   /* We have a valid agent expression, return it.  */
2445   return aexpr;
2446 }
2447
2448 /* Based on location BL, create a list of breakpoint commands to be
2449    passed on to the target.  If we have duplicated locations with
2450    different commands, we will add any such to the list.  */
2451
2452 static void
2453 build_target_command_list (struct bp_location *bl)
2454 {
2455   struct bp_location **locp = NULL, **loc2p;
2456   int null_command_or_parse_error = 0;
2457   int modified = bl->needs_update;
2458   struct bp_location *loc;
2459
2460   /* Release commands left over from a previous insert.  */
2461   VEC_free (agent_expr_p, bl->target_info.tcommands);
2462
2463   if (!target_can_run_breakpoint_commands ())
2464     return;
2465
2466   /* For now, limit to agent-style dprintf breakpoints.  */
2467   if (dprintf_style != dprintf_style_agent)
2468     return;
2469
2470   /* For now, if we have any duplicate location that isn't a dprintf,
2471      don't install the target-side commands, as that would make the
2472      breakpoint not be reported to the core, and we'd lose
2473      control.  */
2474   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2475     {
2476       loc = (*loc2p);
2477       if (is_breakpoint (loc->owner)
2478           && loc->pspace->num == bl->pspace->num
2479           && loc->owner->type != bp_dprintf)
2480         return;
2481     }
2482
2483   /* Do a first pass to check for locations with no assigned
2484      conditions or conditions that fail to parse to a valid agent expression
2485      bytecode.  If any of these happen, then it's no use to send conditions
2486      to the target since this location will always trigger and generate a
2487      response back to GDB.  */
2488   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2489     {
2490       loc = (*loc2p);
2491       if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2492         {
2493           if (modified)
2494             {
2495               struct agent_expr *aexpr;
2496
2497               /* Re-parse the commands since something changed.  In that
2498                  case we already freed the command bytecodes (see
2499                  force_breakpoint_reinsertion).  We just
2500                  need to parse the command to bytecodes again.  */
2501               aexpr = parse_cmd_to_aexpr (bl->address,
2502                                           loc->owner->extra_string);
2503               loc->cmd_bytecode = aexpr;
2504
2505               if (!aexpr)
2506                 continue;
2507             }
2508
2509           /* If we have a NULL bytecode expression, it means something
2510              went wrong or we have a null command expression.  */
2511           if (!loc->cmd_bytecode)
2512             {
2513               null_command_or_parse_error = 1;
2514               break;
2515             }
2516         }
2517     }
2518
2519   /* If anything failed, then we're not doing target-side commands,
2520      and so clean up.  */
2521   if (null_command_or_parse_error)
2522     {
2523       ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2524         {
2525           loc = (*loc2p);
2526           if (is_breakpoint (loc->owner)
2527               && loc->pspace->num == bl->pspace->num)
2528             {
2529               /* Only go as far as the first NULL bytecode is
2530                  located.  */
2531               if (loc->cmd_bytecode == NULL)
2532                 return;
2533
2534               free_agent_expr (loc->cmd_bytecode);
2535               loc->cmd_bytecode = NULL;
2536             }
2537         }
2538     }
2539
2540   /* No NULL commands or failed bytecode generation.  Build a command list
2541      for this location's address.  */
2542   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2543     {
2544       loc = (*loc2p);
2545       if (loc->owner->extra_string
2546           && is_breakpoint (loc->owner)
2547           && loc->pspace->num == bl->pspace->num
2548           && loc->owner->enable_state == bp_enabled
2549           && loc->enabled)
2550         /* Add the command to the vector.  This will be used later
2551            to send the commands to the target.  */
2552         VEC_safe_push (agent_expr_p, bl->target_info.tcommands,
2553                        loc->cmd_bytecode);
2554     }
2555
2556   bl->target_info.persist = 0;
2557   /* Maybe flag this location as persistent.  */
2558   if (bl->owner->type == bp_dprintf && disconnected_dprintf)
2559     bl->target_info.persist = 1;
2560 }
2561
2562 /* Insert a low-level "breakpoint" of some type.  BL is the breakpoint
2563    location.  Any error messages are printed to TMP_ERROR_STREAM; and
2564    DISABLED_BREAKS, and HW_BREAKPOINT_ERROR are used to report problems.
2565    Returns 0 for success, 1 if the bp_location type is not supported or
2566    -1 for failure.
2567
2568    NOTE drow/2003-09-09: This routine could be broken down to an
2569    object-style method for each breakpoint or catchpoint type.  */
2570 static int
2571 insert_bp_location (struct bp_location *bl,
2572                     struct ui_file *tmp_error_stream,
2573                     int *disabled_breaks,
2574                     int *hw_breakpoint_error,
2575                     int *hw_bp_error_explained_already)
2576 {
2577   enum errors bp_err = GDB_NO_ERROR;
2578   const char *bp_err_message = NULL;
2579   volatile struct gdb_exception e;
2580
2581   if (!should_be_inserted (bl) || (bl->inserted && !bl->needs_update))
2582     return 0;
2583
2584   /* Note we don't initialize bl->target_info, as that wipes out
2585      the breakpoint location's shadow_contents if the breakpoint
2586      is still inserted at that location.  This in turn breaks
2587      target_read_memory which depends on these buffers when
2588      a memory read is requested at the breakpoint location:
2589      Once the target_info has been wiped, we fail to see that
2590      we have a breakpoint inserted at that address and thus
2591      read the breakpoint instead of returning the data saved in
2592      the breakpoint location's shadow contents.  */
2593   bl->target_info.reqstd_address = bl->address;
2594   bl->target_info.placed_address_space = bl->pspace->aspace;
2595   bl->target_info.length = bl->length;
2596
2597   /* When working with target-side conditions, we must pass all the conditions
2598      for the same breakpoint address down to the target since GDB will not
2599      insert those locations.  With a list of breakpoint conditions, the target
2600      can decide when to stop and notify GDB.  */
2601
2602   if (is_breakpoint (bl->owner))
2603     {
2604       build_target_condition_list (bl);
2605       build_target_command_list (bl);
2606       /* Reset the modification marker.  */
2607       bl->needs_update = 0;
2608     }
2609
2610   if (bl->loc_type == bp_loc_software_breakpoint
2611       || bl->loc_type == bp_loc_hardware_breakpoint)
2612     {
2613       if (bl->owner->type != bp_hardware_breakpoint)
2614         {
2615           /* If the explicitly specified breakpoint type
2616              is not hardware breakpoint, check the memory map to see
2617              if the breakpoint address is in read only memory or not.
2618
2619              Two important cases are:
2620              - location type is not hardware breakpoint, memory
2621              is readonly.  We change the type of the location to
2622              hardware breakpoint.
2623              - location type is hardware breakpoint, memory is
2624              read-write.  This means we've previously made the
2625              location hardware one, but then the memory map changed,
2626              so we undo.
2627              
2628              When breakpoints are removed, remove_breakpoints will use
2629              location types we've just set here, the only possible
2630              problem is that memory map has changed during running
2631              program, but it's not going to work anyway with current
2632              gdb.  */
2633           struct mem_region *mr 
2634             = lookup_mem_region (bl->target_info.reqstd_address);
2635           
2636           if (mr)
2637             {
2638               if (automatic_hardware_breakpoints)
2639                 {
2640                   enum bp_loc_type new_type;
2641                   
2642                   if (mr->attrib.mode != MEM_RW)
2643                     new_type = bp_loc_hardware_breakpoint;
2644                   else 
2645                     new_type = bp_loc_software_breakpoint;
2646                   
2647                   if (new_type != bl->loc_type)
2648                     {
2649                       static int said = 0;
2650
2651                       bl->loc_type = new_type;
2652                       if (!said)
2653                         {
2654                           fprintf_filtered (gdb_stdout,
2655                                             _("Note: automatically using "
2656                                               "hardware breakpoints for "
2657                                               "read-only addresses.\n"));
2658                           said = 1;
2659                         }
2660                     }
2661                 }
2662               else if (bl->loc_type == bp_loc_software_breakpoint
2663                        && mr->attrib.mode != MEM_RW)
2664                 {
2665                   fprintf_unfiltered (tmp_error_stream,
2666                                       _("Cannot insert breakpoint %d.\n"
2667                                         "Cannot set software breakpoint "
2668                                         "at read-only address %s\n"),
2669                                       bl->owner->number,
2670                                       paddress (bl->gdbarch, bl->address));
2671                   return 1;
2672                 }
2673             }
2674         }
2675         
2676       /* First check to see if we have to handle an overlay.  */
2677       if (overlay_debugging == ovly_off
2678           || bl->section == NULL
2679           || !(section_is_overlay (bl->section)))
2680         {
2681           /* No overlay handling: just set the breakpoint.  */
2682           TRY_CATCH (e, RETURN_MASK_ALL)
2683             {
2684               int val;
2685
2686               val = bl->owner->ops->insert_location (bl);
2687               if (val)
2688                 bp_err = GENERIC_ERROR;
2689             }
2690           if (e.reason < 0)
2691             {
2692               bp_err = e.error;
2693               bp_err_message = e.message;
2694             }
2695         }
2696       else
2697         {
2698           /* This breakpoint is in an overlay section.
2699              Shall we set a breakpoint at the LMA?  */
2700           if (!overlay_events_enabled)
2701             {
2702               /* Yes -- overlay event support is not active, 
2703                  so we must try to set a breakpoint at the LMA.
2704                  This will not work for a hardware breakpoint.  */
2705               if (bl->loc_type == bp_loc_hardware_breakpoint)
2706                 warning (_("hardware breakpoint %d not supported in overlay!"),
2707                          bl->owner->number);
2708               else
2709                 {
2710                   CORE_ADDR addr = overlay_unmapped_address (bl->address,
2711                                                              bl->section);
2712                   /* Set a software (trap) breakpoint at the LMA.  */
2713                   bl->overlay_target_info = bl->target_info;
2714                   bl->overlay_target_info.reqstd_address = addr;
2715
2716                   /* No overlay handling: just set the breakpoint.  */
2717                   TRY_CATCH (e, RETURN_MASK_ALL)
2718                     {
2719                       int val;
2720
2721                       val = target_insert_breakpoint (bl->gdbarch,
2722                                                       &bl->overlay_target_info);
2723                       if (val)
2724                         bp_err = GENERIC_ERROR;
2725                     }
2726                   if (e.reason < 0)
2727                     {
2728                       bp_err = e.error;
2729                       bp_err_message = e.message;
2730                     }
2731
2732                   if (bp_err != GDB_NO_ERROR)
2733                     fprintf_unfiltered (tmp_error_stream,
2734                                         "Overlay breakpoint %d "
2735                                         "failed: in ROM?\n",
2736                                         bl->owner->number);
2737                 }
2738             }
2739           /* Shall we set a breakpoint at the VMA? */
2740           if (section_is_mapped (bl->section))
2741             {
2742               /* Yes.  This overlay section is mapped into memory.  */
2743               TRY_CATCH (e, RETURN_MASK_ALL)
2744                 {
2745                   int val;
2746
2747                   val = bl->owner->ops->insert_location (bl);
2748                   if (val)
2749                     bp_err = GENERIC_ERROR;
2750                 }
2751               if (e.reason < 0)
2752                 {
2753                   bp_err = e.error;
2754                   bp_err_message = e.message;
2755                 }
2756             }
2757           else
2758             {
2759               /* No.  This breakpoint will not be inserted.  
2760                  No error, but do not mark the bp as 'inserted'.  */
2761               return 0;
2762             }
2763         }
2764
2765       if (bp_err != GDB_NO_ERROR)
2766         {
2767           /* Can't set the breakpoint.  */
2768
2769           /* In some cases, we might not be able to insert a
2770              breakpoint in a shared library that has already been
2771              removed, but we have not yet processed the shlib unload
2772              event.  Unfortunately, some targets that implement
2773              breakpoint insertion themselves can't tell why the
2774              breakpoint insertion failed (e.g., the remote target
2775              doesn't define error codes), so we must treat generic
2776              errors as memory errors.  */
2777           if ((bp_err == GENERIC_ERROR || bp_err == MEMORY_ERROR)
2778               && bl->loc_type == bp_loc_software_breakpoint
2779               && (solib_name_from_address (bl->pspace, bl->address)
2780                   || shared_objfile_contains_address_p (bl->pspace,
2781                                                         bl->address)))
2782             {
2783               /* See also: disable_breakpoints_in_shlibs.  */
2784               bl->shlib_disabled = 1;
2785               observer_notify_breakpoint_modified (bl->owner);
2786               if (!*disabled_breaks)
2787                 {
2788                   fprintf_unfiltered (tmp_error_stream, 
2789                                       "Cannot insert breakpoint %d.\n", 
2790                                       bl->owner->number);
2791                   fprintf_unfiltered (tmp_error_stream, 
2792                                       "Temporarily disabling shared "
2793                                       "library breakpoints:\n");
2794                 }
2795               *disabled_breaks = 1;
2796               fprintf_unfiltered (tmp_error_stream,
2797                                   "breakpoint #%d\n", bl->owner->number);
2798               return 0;
2799             }
2800           else
2801             {
2802               if (bl->loc_type == bp_loc_hardware_breakpoint)
2803                 {
2804                   *hw_breakpoint_error = 1;
2805                   *hw_bp_error_explained_already = bp_err_message != NULL;
2806                   fprintf_unfiltered (tmp_error_stream,
2807                                       "Cannot insert hardware breakpoint %d%s",
2808                                       bl->owner->number, bp_err_message ? ":" : ".\n");
2809                   if (bp_err_message != NULL)
2810                     fprintf_unfiltered (tmp_error_stream, "%s.\n", bp_err_message);
2811                 }
2812               else
2813                 {
2814                   if (bp_err_message == NULL)
2815                     {
2816                       char *message
2817                         = memory_error_message (TARGET_XFER_E_IO,
2818                                                 bl->gdbarch, bl->address);
2819                       struct cleanup *old_chain = make_cleanup (xfree, message);
2820
2821                       fprintf_unfiltered (tmp_error_stream,
2822                                           "Cannot insert breakpoint %d.\n"
2823                                           "%s\n",
2824                                           bl->owner->number, message);
2825                       do_cleanups (old_chain);
2826                     }
2827                   else
2828                     {
2829                       fprintf_unfiltered (tmp_error_stream,
2830                                           "Cannot insert breakpoint %d: %s\n",
2831                                           bl->owner->number,
2832                                           bp_err_message);
2833                     }
2834                 }
2835               return 1;
2836
2837             }
2838         }
2839       else
2840         bl->inserted = 1;
2841
2842       return 0;
2843     }
2844
2845   else if (bl->loc_type == bp_loc_hardware_watchpoint
2846            /* NOTE drow/2003-09-08: This state only exists for removing
2847               watchpoints.  It's not clear that it's necessary...  */
2848            && bl->owner->disposition != disp_del_at_next_stop)
2849     {
2850       int val;
2851
2852       gdb_assert (bl->owner->ops != NULL
2853                   && bl->owner->ops->insert_location != NULL);
2854
2855       val = bl->owner->ops->insert_location (bl);
2856
2857       /* If trying to set a read-watchpoint, and it turns out it's not
2858          supported, try emulating one with an access watchpoint.  */
2859       if (val == 1 && bl->watchpoint_type == hw_read)
2860         {
2861           struct bp_location *loc, **loc_temp;
2862
2863           /* But don't try to insert it, if there's already another
2864              hw_access location that would be considered a duplicate
2865              of this one.  */
2866           ALL_BP_LOCATIONS (loc, loc_temp)
2867             if (loc != bl
2868                 && loc->watchpoint_type == hw_access
2869                 && watchpoint_locations_match (bl, loc))
2870               {
2871                 bl->duplicate = 1;
2872                 bl->inserted = 1;
2873                 bl->target_info = loc->target_info;
2874                 bl->watchpoint_type = hw_access;
2875                 val = 0;
2876                 break;
2877               }
2878
2879           if (val == 1)
2880             {
2881               bl->watchpoint_type = hw_access;
2882               val = bl->owner->ops->insert_location (bl);
2883
2884               if (val)
2885                 /* Back to the original value.  */
2886                 bl->watchpoint_type = hw_read;
2887             }
2888         }
2889
2890       bl->inserted = (val == 0);
2891     }
2892
2893   else if (bl->owner->type == bp_catchpoint)
2894     {
2895       int val;
2896
2897       gdb_assert (bl->owner->ops != NULL
2898                   && bl->owner->ops->insert_location != NULL);
2899
2900       val = bl->owner->ops->insert_location (bl);
2901       if (val)
2902         {
2903           bl->owner->enable_state = bp_disabled;
2904
2905           if (val == 1)
2906             warning (_("\
2907 Error inserting catchpoint %d: Your system does not support this type\n\
2908 of catchpoint."), bl->owner->number);
2909           else
2910             warning (_("Error inserting catchpoint %d."), bl->owner->number);
2911         }
2912
2913       bl->inserted = (val == 0);
2914
2915       /* We've already printed an error message if there was a problem
2916          inserting this catchpoint, and we've disabled the catchpoint,
2917          so just return success.  */
2918       return 0;
2919     }
2920
2921   return 0;
2922 }
2923
2924 /* This function is called when program space PSPACE is about to be
2925    deleted.  It takes care of updating breakpoints to not reference
2926    PSPACE anymore.  */
2927
2928 void
2929 breakpoint_program_space_exit (struct program_space *pspace)
2930 {
2931   struct breakpoint *b, *b_temp;
2932   struct bp_location *loc, **loc_temp;
2933
2934   /* Remove any breakpoint that was set through this program space.  */
2935   ALL_BREAKPOINTS_SAFE (b, b_temp)
2936     {
2937       if (b->pspace == pspace)
2938         delete_breakpoint (b);
2939     }
2940
2941   /* Breakpoints set through other program spaces could have locations
2942      bound to PSPACE as well.  Remove those.  */
2943   ALL_BP_LOCATIONS (loc, loc_temp)
2944     {
2945       struct bp_location *tmp;
2946
2947       if (loc->pspace == pspace)
2948         {
2949           /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
2950           if (loc->owner->loc == loc)
2951             loc->owner->loc = loc->next;
2952           else
2953             for (tmp = loc->owner->loc; tmp->next != NULL; tmp = tmp->next)
2954               if (tmp->next == loc)
2955                 {
2956                   tmp->next = loc->next;
2957                   break;
2958                 }
2959         }
2960     }
2961
2962   /* Now update the global location list to permanently delete the
2963      removed locations above.  */
2964   update_global_location_list (UGLL_DONT_INSERT);
2965 }
2966
2967 /* Make sure all breakpoints are inserted in inferior.
2968    Throws exception on any error.
2969    A breakpoint that is already inserted won't be inserted
2970    again, so calling this function twice is safe.  */
2971 void
2972 insert_breakpoints (void)
2973 {
2974   struct breakpoint *bpt;
2975
2976   ALL_BREAKPOINTS (bpt)
2977     if (is_hardware_watchpoint (bpt))
2978       {
2979         struct watchpoint *w = (struct watchpoint *) bpt;
2980
2981         update_watchpoint (w, 0 /* don't reparse.  */);
2982       }
2983
2984   /* Updating watchpoints creates new locations, so update the global
2985      location list.  Explicitly tell ugll to insert locations and
2986      ignore breakpoints_always_inserted_mode.  */
2987   update_global_location_list (UGLL_INSERT);
2988 }
2989
2990 /* Invoke CALLBACK for each of bp_location.  */
2991
2992 void
2993 iterate_over_bp_locations (walk_bp_location_callback callback)
2994 {
2995   struct bp_location *loc, **loc_tmp;
2996
2997   ALL_BP_LOCATIONS (loc, loc_tmp)
2998     {
2999       callback (loc, NULL);
3000     }
3001 }
3002
3003 /* This is used when we need to synch breakpoint conditions between GDB and the
3004    target.  It is the case with deleting and disabling of breakpoints when using
3005    always-inserted mode.  */
3006
3007 static void
3008 update_inserted_breakpoint_locations (void)
3009 {
3010   struct bp_location *bl, **blp_tmp;
3011   int error_flag = 0;
3012   int val = 0;
3013   int disabled_breaks = 0;
3014   int hw_breakpoint_error = 0;
3015   int hw_bp_details_reported = 0;
3016
3017   struct ui_file *tmp_error_stream = mem_fileopen ();
3018   struct cleanup *cleanups = make_cleanup_ui_file_delete (tmp_error_stream);
3019
3020   /* Explicitly mark the warning -- this will only be printed if
3021      there was an error.  */
3022   fprintf_unfiltered (tmp_error_stream, "Warning:\n");
3023
3024   save_current_space_and_thread ();
3025
3026   ALL_BP_LOCATIONS (bl, blp_tmp)
3027     {
3028       /* We only want to update software breakpoints and hardware
3029          breakpoints.  */
3030       if (!is_breakpoint (bl->owner))
3031         continue;
3032
3033       /* We only want to update locations that are already inserted
3034          and need updating.  This is to avoid unwanted insertion during
3035          deletion of breakpoints.  */
3036       if (!bl->inserted || (bl->inserted && !bl->needs_update))
3037         continue;
3038
3039       switch_to_program_space_and_thread (bl->pspace);
3040
3041       /* For targets that support global breakpoints, there's no need
3042          to select an inferior to insert breakpoint to.  In fact, even
3043          if we aren't attached to any process yet, we should still
3044          insert breakpoints.  */
3045       if (!gdbarch_has_global_breakpoints (target_gdbarch ())
3046           && ptid_equal (inferior_ptid, null_ptid))
3047         continue;
3048
3049       val = insert_bp_location (bl, tmp_error_stream, &disabled_breaks,
3050                                     &hw_breakpoint_error, &hw_bp_details_reported);
3051       if (val)
3052         error_flag = val;
3053     }
3054
3055   if (error_flag)
3056     {
3057       target_terminal_ours_for_output ();
3058       error_stream (tmp_error_stream);
3059     }
3060
3061   do_cleanups (cleanups);
3062 }
3063
3064 /* Used when starting or continuing the program.  */
3065
3066 static void
3067 insert_breakpoint_locations (void)
3068 {
3069   struct breakpoint *bpt;
3070   struct bp_location *bl, **blp_tmp;
3071   int error_flag = 0;
3072   int val = 0;
3073   int disabled_breaks = 0;
3074   int hw_breakpoint_error = 0;
3075   int hw_bp_error_explained_already = 0;
3076
3077   struct ui_file *tmp_error_stream = mem_fileopen ();
3078   struct cleanup *cleanups = make_cleanup_ui_file_delete (tmp_error_stream);
3079   
3080   /* Explicitly mark the warning -- this will only be printed if
3081      there was an error.  */
3082   fprintf_unfiltered (tmp_error_stream, "Warning:\n");
3083
3084   save_current_space_and_thread ();
3085
3086   ALL_BP_LOCATIONS (bl, blp_tmp)
3087     {
3088       if (!should_be_inserted (bl) || (bl->inserted && !bl->needs_update))
3089         continue;
3090
3091       /* There is no point inserting thread-specific breakpoints if
3092          the thread no longer exists.  ALL_BP_LOCATIONS bp_location
3093          has BL->OWNER always non-NULL.  */
3094       if (bl->owner->thread != -1
3095           && !valid_thread_id (bl->owner->thread))
3096         continue;
3097
3098       switch_to_program_space_and_thread (bl->pspace);
3099
3100       /* For targets that support global breakpoints, there's no need
3101          to select an inferior to insert breakpoint to.  In fact, even
3102          if we aren't attached to any process yet, we should still
3103          insert breakpoints.  */
3104       if (!gdbarch_has_global_breakpoints (target_gdbarch ())
3105           && ptid_equal (inferior_ptid, null_ptid))
3106         continue;
3107
3108       val = insert_bp_location (bl, tmp_error_stream, &disabled_breaks,
3109                                     &hw_breakpoint_error, &hw_bp_error_explained_already);
3110       if (val)
3111         error_flag = val;
3112     }
3113
3114   /* If we failed to insert all locations of a watchpoint, remove
3115      them, as half-inserted watchpoint is of limited use.  */
3116   ALL_BREAKPOINTS (bpt)  
3117     {
3118       int some_failed = 0;
3119       struct bp_location *loc;
3120
3121       if (!is_hardware_watchpoint (bpt))
3122         continue;
3123
3124       if (!breakpoint_enabled (bpt))
3125         continue;
3126
3127       if (bpt->disposition == disp_del_at_next_stop)
3128         continue;
3129       
3130       for (loc = bpt->loc; loc; loc = loc->next)
3131         if (!loc->inserted && should_be_inserted (loc))
3132           {
3133             some_failed = 1;
3134             break;
3135           }
3136       if (some_failed)
3137         {
3138           for (loc = bpt->loc; loc; loc = loc->next)
3139             if (loc->inserted)
3140               remove_breakpoint (loc, mark_uninserted);
3141
3142           hw_breakpoint_error = 1;
3143           fprintf_unfiltered (tmp_error_stream,
3144                               "Could not insert hardware watchpoint %d.\n", 
3145                               bpt->number);
3146           error_flag = -1;
3147         }
3148     }
3149
3150   if (error_flag)
3151     {
3152       /* If a hardware breakpoint or watchpoint was inserted, add a
3153          message about possibly exhausted resources.  */
3154       if (hw_breakpoint_error && !hw_bp_error_explained_already)
3155         {
3156           fprintf_unfiltered (tmp_error_stream, 
3157                               "Could not insert hardware breakpoints:\n\
3158 You may have requested too many hardware breakpoints/watchpoints.\n");
3159         }
3160       target_terminal_ours_for_output ();
3161       error_stream (tmp_error_stream);
3162     }
3163
3164   do_cleanups (cleanups);
3165 }
3166
3167 /* Used when the program stops.
3168    Returns zero if successful, or non-zero if there was a problem
3169    removing a breakpoint location.  */
3170
3171 int
3172 remove_breakpoints (void)
3173 {
3174   struct bp_location *bl, **blp_tmp;
3175   int val = 0;
3176
3177   ALL_BP_LOCATIONS (bl, blp_tmp)
3178   {
3179     if (bl->inserted && !is_tracepoint (bl->owner))
3180       val |= remove_breakpoint (bl, mark_uninserted);
3181   }
3182   return val;
3183 }
3184
3185 /* When a thread exits, remove breakpoints that are related to
3186    that thread.  */
3187
3188 static void
3189 remove_threaded_breakpoints (struct thread_info *tp, int silent)
3190 {
3191   struct breakpoint *b, *b_tmp;
3192
3193   ALL_BREAKPOINTS_SAFE (b, b_tmp)
3194     {
3195       if (b->thread == tp->num && user_breakpoint_p (b))
3196         {
3197           b->disposition = disp_del_at_next_stop;
3198
3199           printf_filtered (_("\
3200 Thread-specific breakpoint %d deleted - thread %d no longer in the thread list.\n"),
3201                           b->number, tp->num);
3202
3203           /* Hide it from the user.  */
3204           b->number = 0;
3205        }
3206     }
3207 }
3208
3209 /* Remove breakpoints of process PID.  */
3210
3211 int
3212 remove_breakpoints_pid (int pid)
3213 {
3214   struct bp_location *bl, **blp_tmp;
3215   int val;
3216   struct inferior *inf = find_inferior_pid (pid);
3217
3218   ALL_BP_LOCATIONS (bl, blp_tmp)
3219   {
3220     if (bl->pspace != inf->pspace)
3221       continue;
3222
3223     if (bl->owner->type == bp_dprintf)
3224       continue;
3225
3226     if (bl->inserted)
3227       {
3228         val = remove_breakpoint (bl, mark_uninserted);
3229         if (val != 0)
3230           return val;
3231       }
3232   }
3233   return 0;
3234 }
3235
3236 int
3237 reattach_breakpoints (int pid)
3238 {
3239   struct cleanup *old_chain;
3240   struct bp_location *bl, **blp_tmp;
3241   int val;
3242   struct ui_file *tmp_error_stream;
3243   int dummy1 = 0, dummy2 = 0, dummy3 = 0;
3244   struct inferior *inf;
3245   struct thread_info *tp;
3246
3247   tp = any_live_thread_of_process (pid);
3248   if (tp == NULL)
3249     return 1;
3250
3251   inf = find_inferior_pid (pid);
3252   old_chain = save_inferior_ptid ();
3253
3254   inferior_ptid = tp->ptid;
3255
3256   tmp_error_stream = mem_fileopen ();
3257   make_cleanup_ui_file_delete (tmp_error_stream);
3258
3259   ALL_BP_LOCATIONS (bl, blp_tmp)
3260   {
3261     if (bl->pspace != inf->pspace)
3262       continue;
3263
3264     if (bl->inserted)
3265       {
3266         bl->inserted = 0;
3267         val = insert_bp_location (bl, tmp_error_stream, &dummy1, &dummy2, &dummy3);
3268         if (val != 0)
3269           {
3270             do_cleanups (old_chain);
3271             return val;
3272           }
3273       }
3274   }
3275   do_cleanups (old_chain);
3276   return 0;
3277 }
3278
3279 static int internal_breakpoint_number = -1;
3280
3281 /* Set the breakpoint number of B, depending on the value of INTERNAL.
3282    If INTERNAL is non-zero, the breakpoint number will be populated
3283    from internal_breakpoint_number and that variable decremented.
3284    Otherwise the breakpoint number will be populated from
3285    breakpoint_count and that value incremented.  Internal breakpoints
3286    do not set the internal var bpnum.  */
3287 static void
3288 set_breakpoint_number (int internal, struct breakpoint *b)
3289 {
3290   if (internal)
3291     b->number = internal_breakpoint_number--;
3292   else
3293     {
3294       set_breakpoint_count (breakpoint_count + 1);
3295       b->number = breakpoint_count;
3296     }
3297 }
3298
3299 static struct breakpoint *
3300 create_internal_breakpoint (struct gdbarch *gdbarch,
3301                             CORE_ADDR address, enum bptype type,
3302                             const struct breakpoint_ops *ops)
3303 {
3304   struct symtab_and_line sal;
3305   struct breakpoint *b;
3306
3307   init_sal (&sal);              /* Initialize to zeroes.  */
3308
3309   sal.pc = address;
3310   sal.section = find_pc_overlay (sal.pc);
3311   sal.pspace = current_program_space;
3312
3313   b = set_raw_breakpoint (gdbarch, sal, type, ops);
3314   b->number = internal_breakpoint_number--;
3315   b->disposition = disp_donttouch;
3316
3317   return b;
3318 }
3319
3320 static const char *const longjmp_names[] =
3321   {
3322     "longjmp", "_longjmp", "siglongjmp", "_siglongjmp"
3323   };
3324 #define NUM_LONGJMP_NAMES ARRAY_SIZE(longjmp_names)
3325
3326 /* Per-objfile data private to breakpoint.c.  */
3327 struct breakpoint_objfile_data
3328 {
3329   /* Minimal symbol for "_ovly_debug_event" (if any).  */
3330   struct bound_minimal_symbol overlay_msym;
3331
3332   /* Minimal symbol(s) for "longjmp", "siglongjmp", etc. (if any).  */
3333   struct bound_minimal_symbol longjmp_msym[NUM_LONGJMP_NAMES];
3334
3335   /* True if we have looked for longjmp probes.  */
3336   int longjmp_searched;
3337
3338   /* SystemTap probe points for longjmp (if any).  */
3339   VEC (probe_p) *longjmp_probes;
3340
3341   /* Minimal symbol for "std::terminate()" (if any).  */
3342   struct bound_minimal_symbol terminate_msym;
3343
3344   /* Minimal symbol for "_Unwind_DebugHook" (if any).  */
3345   struct bound_minimal_symbol exception_msym;
3346
3347   /* True if we have looked for exception probes.  */
3348   int exception_searched;
3349
3350   /* SystemTap probe points for unwinding (if any).  */
3351   VEC (probe_p) *exception_probes;
3352 };
3353
3354 static const struct objfile_data *breakpoint_objfile_key;
3355
3356 /* Minimal symbol not found sentinel.  */
3357 static struct minimal_symbol msym_not_found;
3358
3359 /* Returns TRUE if MSYM point to the "not found" sentinel.  */
3360
3361 static int
3362 msym_not_found_p (const struct minimal_symbol *msym)
3363 {
3364   return msym == &msym_not_found;
3365 }
3366
3367 /* Return per-objfile data needed by breakpoint.c.
3368    Allocate the data if necessary.  */
3369
3370 static struct breakpoint_objfile_data *
3371 get_breakpoint_objfile_data (struct objfile *objfile)
3372 {
3373   struct breakpoint_objfile_data *bp_objfile_data;
3374
3375   bp_objfile_data = objfile_data (objfile, breakpoint_objfile_key);
3376   if (bp_objfile_data == NULL)
3377     {
3378       bp_objfile_data = obstack_alloc (&objfile->objfile_obstack,
3379                                        sizeof (*bp_objfile_data));
3380
3381       memset (bp_objfile_data, 0, sizeof (*bp_objfile_data));
3382       set_objfile_data (objfile, breakpoint_objfile_key, bp_objfile_data);
3383     }
3384   return bp_objfile_data;
3385 }
3386
3387 static void
3388 free_breakpoint_probes (struct objfile *obj, void *data)
3389 {
3390   struct breakpoint_objfile_data *bp_objfile_data = data;
3391
3392   VEC_free (probe_p, bp_objfile_data->longjmp_probes);
3393   VEC_free (probe_p, bp_objfile_data->exception_probes);
3394 }
3395
3396 static void
3397 create_overlay_event_breakpoint (void)
3398 {
3399   struct objfile *objfile;
3400   const char *const func_name = "_ovly_debug_event";
3401
3402   ALL_OBJFILES (objfile)
3403     {
3404       struct breakpoint *b;
3405       struct breakpoint_objfile_data *bp_objfile_data;
3406       CORE_ADDR addr;
3407
3408       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3409
3410       if (msym_not_found_p (bp_objfile_data->overlay_msym.minsym))
3411         continue;
3412
3413       if (bp_objfile_data->overlay_msym.minsym == NULL)
3414         {
3415           struct bound_minimal_symbol m;
3416
3417           m = lookup_minimal_symbol_text (func_name, objfile);
3418           if (m.minsym == NULL)
3419             {
3420               /* Avoid future lookups in this objfile.  */
3421               bp_objfile_data->overlay_msym.minsym = &msym_not_found;
3422               continue;
3423             }
3424           bp_objfile_data->overlay_msym = m;
3425         }
3426
3427       addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->overlay_msym);
3428       b = create_internal_breakpoint (get_objfile_arch (objfile), addr,
3429                                       bp_overlay_event,
3430                                       &internal_breakpoint_ops);
3431       b->addr_string = xstrdup (func_name);
3432
3433       if (overlay_debugging == ovly_auto)
3434         {
3435           b->enable_state = bp_enabled;
3436           overlay_events_enabled = 1;
3437         }
3438       else
3439        {
3440          b->enable_state = bp_disabled;
3441          overlay_events_enabled = 0;
3442        }
3443     }
3444   update_global_location_list (UGLL_MAY_INSERT);
3445 }
3446
3447 static void
3448 create_longjmp_master_breakpoint (void)
3449 {
3450   struct program_space *pspace;
3451   struct cleanup *old_chain;
3452
3453   old_chain = save_current_program_space ();
3454
3455   ALL_PSPACES (pspace)
3456   {
3457     struct objfile *objfile;
3458
3459     set_current_program_space (pspace);
3460
3461     ALL_OBJFILES (objfile)
3462     {
3463       int i;
3464       struct gdbarch *gdbarch;
3465       struct breakpoint_objfile_data *bp_objfile_data;
3466
3467       gdbarch = get_objfile_arch (objfile);
3468
3469       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3470
3471       if (!bp_objfile_data->longjmp_searched)
3472         {
3473           VEC (probe_p) *ret;
3474
3475           ret = find_probes_in_objfile (objfile, "libc", "longjmp");
3476           if (ret != NULL)
3477             {
3478               /* We are only interested in checking one element.  */
3479               struct probe *p = VEC_index (probe_p, ret, 0);
3480
3481               if (!can_evaluate_probe_arguments (p))
3482                 {
3483                   /* We cannot use the probe interface here, because it does
3484                      not know how to evaluate arguments.  */
3485                   VEC_free (probe_p, ret);
3486                   ret = NULL;
3487                 }
3488             }
3489           bp_objfile_data->longjmp_probes = ret;
3490           bp_objfile_data->longjmp_searched = 1;
3491         }
3492
3493       if (bp_objfile_data->longjmp_probes != NULL)
3494         {
3495           int i;
3496           struct probe *probe;
3497           struct gdbarch *gdbarch = get_objfile_arch (objfile);
3498
3499           for (i = 0;
3500                VEC_iterate (probe_p,
3501                             bp_objfile_data->longjmp_probes,
3502                             i, probe);
3503                ++i)
3504             {
3505               struct breakpoint *b;
3506
3507               b = create_internal_breakpoint (gdbarch,
3508                                               get_probe_address (probe,
3509                                                                  objfile),
3510                                               bp_longjmp_master,
3511                                               &internal_breakpoint_ops);
3512               b->addr_string = xstrdup ("-probe-stap libc:longjmp");
3513               b->enable_state = bp_disabled;
3514             }
3515
3516           continue;
3517         }
3518
3519       if (!gdbarch_get_longjmp_target_p (gdbarch))
3520         continue;
3521
3522       for (i = 0; i < NUM_LONGJMP_NAMES; i++)
3523         {
3524           struct breakpoint *b;
3525           const char *func_name;
3526           CORE_ADDR addr;
3527
3528           if (msym_not_found_p (bp_objfile_data->longjmp_msym[i].minsym))
3529             continue;
3530
3531           func_name = longjmp_names[i];
3532           if (bp_objfile_data->longjmp_msym[i].minsym == NULL)
3533             {
3534               struct bound_minimal_symbol m;
3535
3536               m = lookup_minimal_symbol_text (func_name, objfile);
3537               if (m.minsym == NULL)
3538                 {
3539                   /* Prevent future lookups in this objfile.  */
3540                   bp_objfile_data->longjmp_msym[i].minsym = &msym_not_found;
3541                   continue;
3542                 }
3543               bp_objfile_data->longjmp_msym[i] = m;
3544             }
3545
3546           addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->longjmp_msym[i]);
3547           b = create_internal_breakpoint (gdbarch, addr, bp_longjmp_master,
3548                                           &internal_breakpoint_ops);
3549           b->addr_string = xstrdup (func_name);
3550           b->enable_state = bp_disabled;
3551         }
3552     }
3553   }
3554   update_global_location_list (UGLL_MAY_INSERT);
3555
3556   do_cleanups (old_chain);
3557 }
3558
3559 /* Create a master std::terminate breakpoint.  */
3560 static void
3561 create_std_terminate_master_breakpoint (void)
3562 {
3563   struct program_space *pspace;
3564   struct cleanup *old_chain;
3565   const char *const func_name = "std::terminate()";
3566
3567   old_chain = save_current_program_space ();
3568
3569   ALL_PSPACES (pspace)
3570   {
3571     struct objfile *objfile;
3572     CORE_ADDR addr;
3573
3574     set_current_program_space (pspace);
3575
3576     ALL_OBJFILES (objfile)
3577     {
3578       struct breakpoint *b;
3579       struct breakpoint_objfile_data *bp_objfile_data;
3580
3581       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3582
3583       if (msym_not_found_p (bp_objfile_data->terminate_msym.minsym))
3584         continue;
3585
3586       if (bp_objfile_data->terminate_msym.minsym == NULL)
3587         {
3588           struct bound_minimal_symbol m;
3589
3590           m = lookup_minimal_symbol (func_name, NULL, objfile);
3591           if (m.minsym == NULL || (MSYMBOL_TYPE (m.minsym) != mst_text
3592                                    && MSYMBOL_TYPE (m.minsym) != mst_file_text))
3593             {
3594               /* Prevent future lookups in this objfile.  */
3595               bp_objfile_data->terminate_msym.minsym = &msym_not_found;
3596               continue;
3597             }
3598           bp_objfile_data->terminate_msym = m;
3599         }
3600
3601       addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->terminate_msym);
3602       b = create_internal_breakpoint (get_objfile_arch (objfile), addr,
3603                                       bp_std_terminate_master,
3604                                       &internal_breakpoint_ops);
3605       b->addr_string = xstrdup (func_name);
3606       b->enable_state = bp_disabled;
3607     }
3608   }
3609
3610   update_global_location_list (UGLL_MAY_INSERT);
3611
3612   do_cleanups (old_chain);
3613 }
3614
3615 /* Install a master breakpoint on the unwinder's debug hook.  */
3616
3617 static void
3618 create_exception_master_breakpoint (void)
3619 {
3620   struct objfile *objfile;
3621   const char *const func_name = "_Unwind_DebugHook";
3622
3623   ALL_OBJFILES (objfile)
3624     {
3625       struct breakpoint *b;
3626       struct gdbarch *gdbarch;
3627       struct breakpoint_objfile_data *bp_objfile_data;
3628       CORE_ADDR addr;
3629
3630       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3631
3632       /* We prefer the SystemTap probe point if it exists.  */
3633       if (!bp_objfile_data->exception_searched)
3634         {
3635           VEC (probe_p) *ret;
3636
3637           ret = find_probes_in_objfile (objfile, "libgcc", "unwind");
3638
3639           if (ret != NULL)
3640             {
3641               /* We are only interested in checking one element.  */
3642               struct probe *p = VEC_index (probe_p, ret, 0);
3643
3644               if (!can_evaluate_probe_arguments (p))
3645                 {
3646                   /* We cannot use the probe interface here, because it does
3647                      not know how to evaluate arguments.  */
3648                   VEC_free (probe_p, ret);
3649                   ret = NULL;
3650                 }
3651             }
3652           bp_objfile_data->exception_probes = ret;
3653           bp_objfile_data->exception_searched = 1;
3654         }
3655
3656       if (bp_objfile_data->exception_probes != NULL)
3657         {
3658           struct gdbarch *gdbarch = get_objfile_arch (objfile);
3659           int i;
3660           struct probe *probe;
3661
3662           for (i = 0;
3663                VEC_iterate (probe_p,
3664                             bp_objfile_data->exception_probes,
3665                             i, probe);
3666                ++i)
3667             {
3668               struct breakpoint *b;
3669
3670               b = create_internal_breakpoint (gdbarch,
3671                                               get_probe_address (probe,
3672                                                                  objfile),
3673                                               bp_exception_master,
3674                                               &internal_breakpoint_ops);
3675               b->addr_string = xstrdup ("-probe-stap libgcc:unwind");
3676               b->enable_state = bp_disabled;
3677             }
3678
3679           continue;
3680         }
3681
3682       /* Otherwise, try the hook function.  */
3683
3684       if (msym_not_found_p (bp_objfile_data->exception_msym.minsym))
3685         continue;
3686
3687       gdbarch = get_objfile_arch (objfile);
3688
3689       if (bp_objfile_data->exception_msym.minsym == NULL)
3690         {
3691           struct bound_minimal_symbol debug_hook;
3692
3693           debug_hook = lookup_minimal_symbol (func_name, NULL, objfile);
3694           if (debug_hook.minsym == NULL)
3695             {
3696               bp_objfile_data->exception_msym.minsym = &msym_not_found;
3697               continue;
3698             }
3699
3700           bp_objfile_data->exception_msym = debug_hook;
3701         }
3702
3703       addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->exception_msym);
3704       addr = gdbarch_convert_from_func_ptr_addr (gdbarch, addr,
3705                                                  &current_target);
3706       b = create_internal_breakpoint (gdbarch, addr, bp_exception_master,
3707                                       &internal_breakpoint_ops);
3708       b->addr_string = xstrdup (func_name);
3709       b->enable_state = bp_disabled;
3710     }
3711
3712   update_global_location_list (UGLL_MAY_INSERT);
3713 }
3714
3715 void
3716 update_breakpoints_after_exec (void)
3717 {
3718   struct breakpoint *b, *b_tmp;
3719   struct bp_location *bploc, **bplocp_tmp;
3720
3721   /* We're about to delete breakpoints from GDB's lists.  If the
3722      INSERTED flag is true, GDB will try to lift the breakpoints by
3723      writing the breakpoints' "shadow contents" back into memory.  The
3724      "shadow contents" are NOT valid after an exec, so GDB should not
3725      do that.  Instead, the target is responsible from marking
3726      breakpoints out as soon as it detects an exec.  We don't do that
3727      here instead, because there may be other attempts to delete
3728      breakpoints after detecting an exec and before reaching here.  */
3729   ALL_BP_LOCATIONS (bploc, bplocp_tmp)
3730     if (bploc->pspace == current_program_space)
3731       gdb_assert (!bploc->inserted);
3732
3733   ALL_BREAKPOINTS_SAFE (b, b_tmp)
3734   {
3735     if (b->pspace != current_program_space)
3736       continue;
3737
3738     /* Solib breakpoints must be explicitly reset after an exec().  */
3739     if (b->type == bp_shlib_event)
3740       {
3741         delete_breakpoint (b);
3742         continue;
3743       }
3744
3745     /* JIT breakpoints must be explicitly reset after an exec().  */
3746     if (b->type == bp_jit_event)
3747       {
3748         delete_breakpoint (b);
3749         continue;
3750       }
3751
3752     /* Thread event breakpoints must be set anew after an exec(),
3753        as must overlay event and longjmp master breakpoints.  */
3754     if (b->type == bp_thread_event || b->type == bp_overlay_event
3755         || b->type == bp_longjmp_master || b->type == bp_std_terminate_master
3756         || b->type == bp_exception_master)
3757       {
3758         delete_breakpoint (b);
3759         continue;
3760       }
3761
3762     /* Step-resume breakpoints are meaningless after an exec().  */
3763     if (b->type == bp_step_resume || b->type == bp_hp_step_resume)
3764       {
3765         delete_breakpoint (b);
3766         continue;
3767       }
3768
3769     /* Just like single-step breakpoints.  */
3770     if (b->type == bp_single_step)
3771       {
3772         delete_breakpoint (b);
3773         continue;
3774       }
3775
3776     /* Longjmp and longjmp-resume breakpoints are also meaningless
3777        after an exec.  */
3778     if (b->type == bp_longjmp || b->type == bp_longjmp_resume
3779         || b->type == bp_longjmp_call_dummy
3780         || b->type == bp_exception || b->type == bp_exception_resume)
3781       {
3782         delete_breakpoint (b);
3783         continue;
3784       }
3785
3786     if (b->type == bp_catchpoint)
3787       {
3788         /* For now, none of the bp_catchpoint breakpoints need to
3789            do anything at this point.  In the future, if some of
3790            the catchpoints need to something, we will need to add
3791            a new method, and call this method from here.  */
3792         continue;
3793       }
3794
3795     /* bp_finish is a special case.  The only way we ought to be able
3796        to see one of these when an exec() has happened, is if the user
3797        caught a vfork, and then said "finish".  Ordinarily a finish just
3798        carries them to the call-site of the current callee, by setting
3799        a temporary bp there and resuming.  But in this case, the finish
3800        will carry them entirely through the vfork & exec.
3801
3802        We don't want to allow a bp_finish to remain inserted now.  But
3803        we can't safely delete it, 'cause finish_command has a handle to
3804        the bp on a bpstat, and will later want to delete it.  There's a
3805        chance (and I've seen it happen) that if we delete the bp_finish
3806        here, that its storage will get reused by the time finish_command
3807        gets 'round to deleting the "use to be a bp_finish" breakpoint.
3808        We really must allow finish_command to delete a bp_finish.
3809
3810        In the absence of a general solution for the "how do we know
3811        it's safe to delete something others may have handles to?"
3812        problem, what we'll do here is just uninsert the bp_finish, and
3813        let finish_command delete it.
3814
3815        (We know the bp_finish is "doomed" in the sense that it's
3816        momentary, and will be deleted as soon as finish_command sees
3817        the inferior stopped.  So it doesn't matter that the bp's
3818        address is probably bogus in the new a.out, unlike e.g., the
3819        solib breakpoints.)  */
3820
3821     if (b->type == bp_finish)
3822       {
3823         continue;
3824       }
3825
3826     /* Without a symbolic address, we have little hope of the
3827        pre-exec() address meaning the same thing in the post-exec()
3828        a.out.  */
3829     if (b->addr_string == NULL)
3830       {
3831         delete_breakpoint (b);
3832         continue;
3833       }
3834   }
3835 }
3836
3837 int
3838 detach_breakpoints (ptid_t ptid)
3839 {
3840   struct bp_location *bl, **blp_tmp;
3841   int val = 0;
3842   struct cleanup *old_chain = save_inferior_ptid ();
3843   struct inferior *inf = current_inferior ();
3844
3845   if (ptid_get_pid (ptid) == ptid_get_pid (inferior_ptid))
3846     error (_("Cannot detach breakpoints of inferior_ptid"));
3847
3848   /* Set inferior_ptid; remove_breakpoint_1 uses this global.  */
3849   inferior_ptid = ptid;
3850   ALL_BP_LOCATIONS (bl, blp_tmp)
3851   {
3852     if (bl->pspace != inf->pspace)
3853       continue;
3854
3855     /* This function must physically remove breakpoints locations
3856        from the specified ptid, without modifying the breakpoint
3857        package's state.  Locations of type bp_loc_other are only
3858        maintained at GDB side.  So, there is no need to remove
3859        these bp_loc_other locations.  Moreover, removing these
3860        would modify the breakpoint package's state.  */
3861     if (bl->loc_type == bp_loc_other)
3862       continue;
3863
3864     if (bl->inserted)
3865       val |= remove_breakpoint_1 (bl, mark_inserted);
3866   }
3867
3868   do_cleanups (old_chain);
3869   return val;
3870 }
3871
3872 /* Remove the breakpoint location BL from the current address space.
3873    Note that this is used to detach breakpoints from a child fork.
3874    When we get here, the child isn't in the inferior list, and neither
3875    do we have objects to represent its address space --- we should
3876    *not* look at bl->pspace->aspace here.  */
3877
3878 static int
3879 remove_breakpoint_1 (struct bp_location *bl, insertion_state_t is)
3880 {
3881   int val;
3882
3883   /* BL is never in moribund_locations by our callers.  */
3884   gdb_assert (bl->owner != NULL);
3885
3886   if (bl->owner->enable_state == bp_permanent)
3887     /* Permanent breakpoints cannot be inserted or removed.  */
3888     return 0;
3889
3890   /* The type of none suggests that owner is actually deleted.
3891      This should not ever happen.  */
3892   gdb_assert (bl->owner->type != bp_none);
3893
3894   if (bl->loc_type == bp_loc_software_breakpoint
3895       || bl->loc_type == bp_loc_hardware_breakpoint)
3896     {
3897       /* "Normal" instruction breakpoint: either the standard
3898          trap-instruction bp (bp_breakpoint), or a
3899          bp_hardware_breakpoint.  */
3900
3901       /* First check to see if we have to handle an overlay.  */
3902       if (overlay_debugging == ovly_off
3903           || bl->section == NULL
3904           || !(section_is_overlay (bl->section)))
3905         {
3906           /* No overlay handling: just remove the breakpoint.  */
3907
3908           /* If we're trying to uninsert a memory breakpoint that we
3909              know is set in a dynamic object that is marked
3910              shlib_disabled, then either the dynamic object was
3911              removed with "remove-symbol-file" or with
3912              "nosharedlibrary".  In the former case, we don't know
3913              whether another dynamic object might have loaded over the
3914              breakpoint's address -- the user might well let us know
3915              about it next with add-symbol-file (the whole point of
3916              add-symbol-file is letting the user manually maintain a
3917              list of dynamically loaded objects).  If we have the
3918              breakpoint's shadow memory, that is, this is a software
3919              breakpoint managed by GDB, check whether the breakpoint
3920              is still inserted in memory, to avoid overwriting wrong
3921              code with stale saved shadow contents.  Note that HW
3922              breakpoints don't have shadow memory, as they're
3923              implemented using a mechanism that is not dependent on
3924              being able to modify the target's memory, and as such
3925              they should always be removed.  */
3926           if (bl->shlib_disabled
3927               && bl->target_info.shadow_len != 0
3928               && !memory_validate_breakpoint (bl->gdbarch, &bl->target_info))
3929             val = 0;
3930           else
3931             val = bl->owner->ops->remove_location (bl);
3932         }
3933       else
3934         {
3935           /* This breakpoint is in an overlay section.
3936              Did we set a breakpoint at the LMA?  */
3937           if (!overlay_events_enabled)
3938               {
3939                 /* Yes -- overlay event support is not active, so we
3940                    should have set a breakpoint at the LMA.  Remove it.  
3941                 */
3942                 /* Ignore any failures: if the LMA is in ROM, we will
3943                    have already warned when we failed to insert it.  */
3944                 if (bl->loc_type == bp_loc_hardware_breakpoint)
3945                   target_remove_hw_breakpoint (bl->gdbarch,
3946                                                &bl->overlay_target_info);
3947                 else
3948                   target_remove_breakpoint (bl->gdbarch,
3949                                             &bl->overlay_target_info);
3950               }
3951           /* Did we set a breakpoint at the VMA? 
3952              If so, we will have marked the breakpoint 'inserted'.  */
3953           if (bl->inserted)
3954             {
3955               /* Yes -- remove it.  Previously we did not bother to
3956                  remove the breakpoint if the section had been
3957                  unmapped, but let's not rely on that being safe.  We
3958                  don't know what the overlay manager might do.  */
3959
3960               /* However, we should remove *software* breakpoints only
3961                  if the section is still mapped, or else we overwrite
3962                  wrong code with the saved shadow contents.  */
3963               if (bl->loc_type == bp_loc_hardware_breakpoint
3964                   || section_is_mapped (bl->section))
3965                 val = bl->owner->ops->remove_location (bl);
3966               else
3967                 val = 0;
3968             }
3969           else
3970             {
3971               /* No -- not inserted, so no need to remove.  No error.  */
3972               val = 0;
3973             }
3974         }
3975
3976       /* In some cases, we might not be able to remove a breakpoint in
3977          a shared library that has already been removed, but we have
3978          not yet processed the shlib unload event.  Similarly for an
3979          unloaded add-symbol-file object - the user might not yet have
3980          had the chance to remove-symbol-file it.  shlib_disabled will
3981          be set if the library/object has already been removed, but
3982          the breakpoint hasn't been uninserted yet, e.g., after
3983          "nosharedlibrary" or "remove-symbol-file" with breakpoints
3984          always-inserted mode.  */
3985       if (val
3986           && (bl->loc_type == bp_loc_software_breakpoint
3987               && (bl->shlib_disabled
3988                   || solib_name_from_address (bl->pspace, bl->address)
3989                   || shared_objfile_contains_address_p (bl->pspace,
3990                                                         bl->address))))
3991         val = 0;
3992
3993       if (val)
3994         return val;
3995       bl->inserted = (is == mark_inserted);
3996     }
3997   else if (bl->loc_type == bp_loc_hardware_watchpoint)
3998     {
3999       gdb_assert (bl->owner->ops != NULL
4000                   && bl->owner->ops->remove_location != NULL);
4001
4002       bl->inserted = (is == mark_inserted);
4003       bl->owner->ops->remove_location (bl);
4004
4005       /* Failure to remove any of the hardware watchpoints comes here.  */
4006       if ((is == mark_uninserted) && (bl->inserted))
4007         warning (_("Could not remove hardware watchpoint %d."),
4008                  bl->owner->number);
4009     }
4010   else if (bl->owner->type == bp_catchpoint
4011            && breakpoint_enabled (bl->owner)
4012            && !bl->duplicate)
4013     {
4014       gdb_assert (bl->owner->ops != NULL
4015                   && bl->owner->ops->remove_location != NULL);
4016
4017       val = bl->owner->ops->remove_location (bl);
4018       if (val)
4019         return val;
4020
4021       bl->inserted = (is == mark_inserted);
4022     }
4023
4024   return 0;
4025 }
4026
4027 static int
4028 remove_breakpoint (struct bp_location *bl, insertion_state_t is)
4029 {
4030   int ret;
4031   struct cleanup *old_chain;
4032
4033   /* BL is never in moribund_locations by our callers.  */
4034   gdb_assert (bl->owner != NULL);
4035
4036   if (bl->owner->enable_state == bp_permanent)
4037     /* Permanent breakpoints cannot be inserted or removed.  */
4038     return 0;
4039
4040   /* The type of none suggests that owner is actually deleted.
4041      This should not ever happen.  */
4042   gdb_assert (bl->owner->type != bp_none);
4043
4044   old_chain = save_current_space_and_thread ();
4045
4046   switch_to_program_space_and_thread (bl->pspace);
4047
4048   ret = remove_breakpoint_1 (bl, is);
4049
4050   do_cleanups (old_chain);
4051   return ret;
4052 }
4053
4054 /* Clear the "inserted" flag in all breakpoints.  */
4055
4056 void
4057 mark_breakpoints_out (void)
4058 {
4059   struct bp_location *bl, **blp_tmp;
4060
4061   ALL_BP_LOCATIONS (bl, blp_tmp)
4062     if (bl->pspace == current_program_space)
4063       bl->inserted = 0;
4064 }
4065
4066 /* Clear the "inserted" flag in all breakpoints and delete any
4067    breakpoints which should go away between runs of the program.
4068
4069    Plus other such housekeeping that has to be done for breakpoints
4070    between runs.
4071
4072    Note: this function gets called at the end of a run (by
4073    generic_mourn_inferior) and when a run begins (by
4074    init_wait_for_inferior).  */
4075
4076
4077
4078 void
4079 breakpoint_init_inferior (enum inf_context context)
4080 {
4081   struct breakpoint *b, *b_tmp;
4082   struct bp_location *bl, **blp_tmp;
4083   int ix;
4084   struct program_space *pspace = current_program_space;
4085
4086   /* If breakpoint locations are shared across processes, then there's
4087      nothing to do.  */
4088   if (gdbarch_has_global_breakpoints (target_gdbarch ()))
4089     return;
4090
4091   ALL_BP_LOCATIONS (bl, blp_tmp)
4092   {
4093     /* ALL_BP_LOCATIONS bp_location has BL->OWNER always non-NULL.  */
4094     if (bl->pspace == pspace
4095         && bl->owner->enable_state != bp_permanent)
4096       bl->inserted = 0;
4097   }
4098
4099   ALL_BREAKPOINTS_SAFE (b, b_tmp)
4100   {
4101     if (b->loc && b->loc->pspace != pspace)
4102       continue;
4103
4104     switch (b->type)
4105       {
4106       case bp_call_dummy:
4107       case bp_longjmp_call_dummy:
4108
4109         /* If the call dummy breakpoint is at the entry point it will
4110            cause problems when the inferior is rerun, so we better get
4111            rid of it.  */
4112
4113       case bp_watchpoint_scope:
4114
4115         /* Also get rid of scope breakpoints.  */
4116
4117       case bp_shlib_event:
4118
4119         /* Also remove solib event breakpoints.  Their addresses may
4120            have changed since the last time we ran the program.
4121            Actually we may now be debugging against different target;
4122            and so the solib backend that installed this breakpoint may
4123            not be used in by the target.  E.g.,
4124
4125            (gdb) file prog-linux
4126            (gdb) run               # native linux target
4127            ...
4128            (gdb) kill
4129            (gdb) file prog-win.exe
4130            (gdb) tar rem :9999     # remote Windows gdbserver.
4131         */
4132
4133       case bp_step_resume:
4134
4135         /* Also remove step-resume breakpoints.  */
4136
4137       case bp_single_step:
4138
4139         /* Also remove single-step breakpoints.  */
4140
4141         delete_breakpoint (b);
4142         break;
4143
4144       case bp_watchpoint:
4145       case bp_hardware_watchpoint:
4146       case bp_read_watchpoint:
4147       case bp_access_watchpoint:
4148         {
4149           struct watchpoint *w = (struct watchpoint *) b;
4150
4151           /* Likewise for watchpoints on local expressions.  */
4152           if (w->exp_valid_block != NULL)
4153             delete_breakpoint (b);
4154           else if (context == inf_starting)
4155             {
4156               /* Reset val field to force reread of starting value in
4157                  insert_breakpoints.  */
4158               if (w->val)
4159                 value_free (w->val);
4160               w->val = NULL;
4161               w->val_valid = 0;
4162           }
4163         }
4164         break;
4165       default:
4166         break;
4167       }
4168   }
4169
4170   /* Get rid of the moribund locations.  */
4171   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, bl); ++ix)
4172     decref_bp_location (&bl);
4173   VEC_free (bp_location_p, moribund_locations);
4174 }
4175
4176 /* These functions concern about actual breakpoints inserted in the
4177    target --- to e.g. check if we need to do decr_pc adjustment or if
4178    we need to hop over the bkpt --- so we check for address space
4179    match, not program space.  */
4180
4181 /* breakpoint_here_p (PC) returns non-zero if an enabled breakpoint
4182    exists at PC.  It returns ordinary_breakpoint_here if it's an
4183    ordinary breakpoint, or permanent_breakpoint_here if it's a
4184    permanent breakpoint.
4185    - When continuing from a location with an ordinary breakpoint, we
4186      actually single step once before calling insert_breakpoints.
4187    - When continuing from a location with a permanent breakpoint, we
4188      need to use the `SKIP_PERMANENT_BREAKPOINT' macro, provided by
4189      the target, to advance the PC past the breakpoint.  */
4190
4191 enum breakpoint_here
4192 breakpoint_here_p (struct address_space *aspace, CORE_ADDR pc)
4193 {
4194   struct bp_location *bl, **blp_tmp;
4195   int any_breakpoint_here = 0;
4196
4197   ALL_BP_LOCATIONS (bl, blp_tmp)
4198     {
4199       if (bl->loc_type != bp_loc_software_breakpoint
4200           && bl->loc_type != bp_loc_hardware_breakpoint)
4201         continue;
4202
4203       /* ALL_BP_LOCATIONS bp_location has BL->OWNER always non-NULL.  */
4204       if ((breakpoint_enabled (bl->owner)
4205            || bl->owner->enable_state == bp_permanent)
4206           && breakpoint_location_address_match (bl, aspace, pc))
4207         {
4208           if (overlay_debugging 
4209               && section_is_overlay (bl->section)
4210               && !section_is_mapped (bl->section))
4211             continue;           /* unmapped overlay -- can't be a match */
4212           else if (bl->owner->enable_state == bp_permanent)
4213             return permanent_breakpoint_here;
4214           else
4215             any_breakpoint_here = 1;
4216         }
4217     }
4218
4219   return any_breakpoint_here ? ordinary_breakpoint_here : 0;
4220 }
4221
4222 /* Return true if there's a moribund breakpoint at PC.  */
4223
4224 int
4225 moribund_breakpoint_here_p (struct address_space *aspace, CORE_ADDR pc)
4226 {
4227   struct bp_location *loc;
4228   int ix;
4229
4230   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
4231     if (breakpoint_location_address_match (loc, aspace, pc))
4232       return 1;
4233
4234   return 0;
4235 }
4236
4237 /* Returns non-zero iff there's a breakpoint inserted at PC.  */
4238
4239 int
4240 breakpoint_inserted_here_p (struct address_space *aspace, CORE_ADDR pc)
4241 {
4242   struct bp_location *bl, **blp_tmp;
4243
4244   ALL_BP_LOCATIONS (bl, blp_tmp)
4245     {
4246       if (bl->loc_type != bp_loc_software_breakpoint
4247           && bl->loc_type != bp_loc_hardware_breakpoint)
4248         continue;
4249
4250       if (bl->inserted
4251           && breakpoint_location_address_match (bl, aspace, pc))
4252         {
4253           if (overlay_debugging 
4254               && section_is_overlay (bl->section)
4255               && !section_is_mapped (bl->section))
4256             continue;           /* unmapped overlay -- can't be a match */
4257           else
4258             return 1;
4259         }
4260     }
4261   return 0;
4262 }
4263
4264 /* This function returns non-zero iff there is a software breakpoint
4265    inserted at PC.  */
4266
4267 int
4268 software_breakpoint_inserted_here_p (struct address_space *aspace,
4269                                      CORE_ADDR pc)
4270 {
4271   struct bp_location *bl, **blp_tmp;
4272
4273   ALL_BP_LOCATIONS (bl, blp_tmp)
4274     {
4275       if (bl->loc_type != bp_loc_software_breakpoint)
4276         continue;
4277
4278       if (bl->inserted
4279           && breakpoint_address_match (bl->pspace->aspace, bl->address,
4280                                        aspace, pc))
4281         {
4282           if (overlay_debugging 
4283               && section_is_overlay (bl->section)
4284               && !section_is_mapped (bl->section))
4285             continue;           /* unmapped overlay -- can't be a match */
4286           else
4287             return 1;
4288         }
4289     }
4290
4291   return 0;
4292 }
4293
4294 int
4295 hardware_watchpoint_inserted_in_range (struct address_space *aspace,
4296                                        CORE_ADDR addr, ULONGEST len)
4297 {
4298   struct breakpoint *bpt;
4299
4300   ALL_BREAKPOINTS (bpt)
4301     {
4302       struct bp_location *loc;
4303
4304       if (bpt->type != bp_hardware_watchpoint
4305           && bpt->type != bp_access_watchpoint)
4306         continue;
4307
4308       if (!breakpoint_enabled (bpt))
4309         continue;
4310
4311       for (loc = bpt->loc; loc; loc = loc->next)
4312         if (loc->pspace->aspace == aspace && loc->inserted)
4313           {
4314             CORE_ADDR l, h;
4315
4316             /* Check for intersection.  */
4317             l = max (loc->address, addr);
4318             h = min (loc->address + loc->length, addr + len);
4319             if (l < h)
4320               return 1;
4321           }
4322     }
4323   return 0;
4324 }
4325
4326 /* breakpoint_thread_match (PC, PTID) returns true if the breakpoint at
4327    PC is valid for process/thread PTID.  */
4328
4329 int
4330 breakpoint_thread_match (struct address_space *aspace, CORE_ADDR pc,
4331                          ptid_t ptid)
4332 {
4333   struct bp_location *bl, **blp_tmp;
4334   /* The thread and task IDs associated to PTID, computed lazily.  */
4335   int thread = -1;
4336   int task = 0;
4337   
4338   ALL_BP_LOCATIONS (bl, blp_tmp)
4339     {
4340       if (bl->loc_type != bp_loc_software_breakpoint
4341           && bl->loc_type != bp_loc_hardware_breakpoint)
4342         continue;
4343
4344       /* ALL_BP_LOCATIONS bp_location has bl->OWNER always non-NULL.  */
4345       if (!breakpoint_enabled (bl->owner)
4346           && bl->owner->enable_state != bp_permanent)
4347         continue;
4348
4349       if (!breakpoint_location_address_match (bl, aspace, pc))
4350         continue;
4351
4352       if (bl->owner->thread != -1)
4353         {
4354           /* This is a thread-specific breakpoint.  Check that ptid
4355              matches that thread.  If thread hasn't been computed yet,
4356              it is now time to do so.  */
4357           if (thread == -1)
4358             thread = pid_to_thread_id (ptid);
4359           if (bl->owner->thread != thread)
4360             continue;
4361         }
4362
4363       if (bl->owner->task != 0)
4364         {
4365           /* This is a task-specific breakpoint.  Check that ptid
4366              matches that task.  If task hasn't been computed yet,
4367              it is now time to do so.  */
4368           if (task == 0)
4369             task = ada_get_task_number (ptid);
4370           if (bl->owner->task != task)
4371             continue;
4372         }
4373
4374       if (overlay_debugging 
4375           && section_is_overlay (bl->section)
4376           && !section_is_mapped (bl->section))
4377         continue;           /* unmapped overlay -- can't be a match */
4378
4379       return 1;
4380     }
4381
4382   return 0;
4383 }
4384 \f
4385
4386 /* bpstat stuff.  External routines' interfaces are documented
4387    in breakpoint.h.  */
4388
4389 int
4390 is_catchpoint (struct breakpoint *ep)
4391 {
4392   return (ep->type == bp_catchpoint);
4393 }
4394
4395 /* Frees any storage that is part of a bpstat.  Does not walk the
4396    'next' chain.  */
4397
4398 static void
4399 bpstat_free (bpstat bs)
4400 {
4401   if (bs->old_val != NULL)
4402     value_free (bs->old_val);
4403   decref_counted_command_line (&bs->commands);
4404   decref_bp_location (&bs->bp_location_at);
4405   xfree (bs);
4406 }
4407
4408 /* Clear a bpstat so that it says we are not at any breakpoint.
4409    Also free any storage that is part of a bpstat.  */
4410
4411 void
4412 bpstat_clear (bpstat *bsp)
4413 {
4414   bpstat p;
4415   bpstat q;
4416
4417   if (bsp == 0)
4418     return;
4419   p = *bsp;
4420   while (p != NULL)
4421     {
4422       q = p->next;
4423       bpstat_free (p);
4424       p = q;
4425     }
4426   *bsp = NULL;
4427 }
4428
4429 /* Return a copy of a bpstat.  Like "bs1 = bs2" but all storage that
4430    is part of the bpstat is copied as well.  */
4431
4432 bpstat
4433 bpstat_copy (bpstat bs)
4434 {
4435   bpstat p = NULL;
4436   bpstat tmp;
4437   bpstat retval = NULL;
4438
4439   if (bs == NULL)
4440     return bs;
4441
4442   for (; bs != NULL; bs = bs->next)
4443     {
4444       tmp = (bpstat) xmalloc (sizeof (*tmp));
4445       memcpy (tmp, bs, sizeof (*tmp));
4446       incref_counted_command_line (tmp->commands);
4447       incref_bp_location (tmp->bp_location_at);
4448       if (bs->old_val != NULL)
4449         {
4450           tmp->old_val = value_copy (bs->old_val);
4451           release_value (tmp->old_val);
4452         }
4453
4454       if (p == NULL)
4455         /* This is the first thing in the chain.  */
4456         retval = tmp;
4457       else
4458         p->next = tmp;
4459       p = tmp;
4460     }
4461   p->next = NULL;
4462   return retval;
4463 }
4464
4465 /* Find the bpstat associated with this breakpoint.  */
4466
4467 bpstat
4468 bpstat_find_breakpoint (bpstat bsp, struct breakpoint *breakpoint)
4469 {
4470   if (bsp == NULL)
4471     return NULL;
4472
4473   for (; bsp != NULL; bsp = bsp->next)
4474     {
4475       if (bsp->breakpoint_at == breakpoint)
4476         return bsp;
4477     }
4478   return NULL;
4479 }
4480
4481 /* See breakpoint.h.  */
4482
4483 int
4484 bpstat_explains_signal (bpstat bsp, enum gdb_signal sig)
4485 {
4486   for (; bsp != NULL; bsp = bsp->next)
4487     {
4488       if (bsp->breakpoint_at == NULL)
4489         {
4490           /* A moribund location can never explain a signal other than
4491              GDB_SIGNAL_TRAP.  */
4492           if (sig == GDB_SIGNAL_TRAP)
4493             return 1;
4494         }
4495       else
4496         {
4497           if (bsp->breakpoint_at->ops->explains_signal (bsp->breakpoint_at,
4498                                                         sig))
4499             return 1;
4500         }
4501     }
4502
4503   return 0;
4504 }
4505
4506 /* Put in *NUM the breakpoint number of the first breakpoint we are
4507    stopped at.  *BSP upon return is a bpstat which points to the
4508    remaining breakpoints stopped at (but which is not guaranteed to be
4509    good for anything but further calls to bpstat_num).
4510
4511    Return 0 if passed a bpstat which does not indicate any breakpoints.
4512    Return -1 if stopped at a breakpoint that has been deleted since
4513    we set it.
4514    Return 1 otherwise.  */
4515
4516 int
4517 bpstat_num (bpstat *bsp, int *num)
4518 {
4519   struct breakpoint *b;
4520
4521   if ((*bsp) == NULL)
4522     return 0;                   /* No more breakpoint values */
4523
4524   /* We assume we'll never have several bpstats that correspond to a
4525      single breakpoint -- otherwise, this function might return the
4526      same number more than once and this will look ugly.  */
4527   b = (*bsp)->breakpoint_at;
4528   *bsp = (*bsp)->next;
4529   if (b == NULL)
4530     return -1;                  /* breakpoint that's been deleted since */
4531
4532   *num = b->number;             /* We have its number */
4533   return 1;
4534 }
4535
4536 /* See breakpoint.h.  */
4537
4538 void
4539 bpstat_clear_actions (void)
4540 {
4541   struct thread_info *tp;
4542   bpstat bs;
4543
4544   if (ptid_equal (inferior_ptid, null_ptid))
4545     return;
4546
4547   tp = find_thread_ptid (inferior_ptid);
4548   if (tp == NULL)
4549     return;
4550
4551   for (bs = tp->control.stop_bpstat; bs != NULL; bs = bs->next)
4552     {
4553       decref_counted_command_line (&bs->commands);
4554
4555       if (bs->old_val != NULL)
4556         {
4557           value_free (bs->old_val);
4558           bs->old_val = NULL;
4559         }
4560     }
4561 }
4562
4563 /* Called when a command is about to proceed the inferior.  */
4564
4565 static void
4566 breakpoint_about_to_proceed (void)
4567 {
4568   if (!ptid_equal (inferior_ptid, null_ptid))
4569     {
4570       struct thread_info *tp = inferior_thread ();
4571
4572       /* Allow inferior function calls in breakpoint commands to not
4573          interrupt the command list.  When the call finishes
4574          successfully, the inferior will be standing at the same
4575          breakpoint as if nothing happened.  */
4576       if (tp->control.in_infcall)
4577         return;
4578     }
4579
4580   breakpoint_proceeded = 1;
4581 }
4582
4583 /* Stub for cleaning up our state if we error-out of a breakpoint
4584    command.  */
4585 static void
4586 cleanup_executing_breakpoints (void *ignore)
4587 {
4588   executing_breakpoint_commands = 0;
4589 }
4590
4591 /* Return non-zero iff CMD as the first line of a command sequence is `silent'
4592    or its equivalent.  */
4593
4594 static int
4595 command_line_is_silent (struct command_line *cmd)
4596 {
4597   return cmd && (strcmp ("silent", cmd->line) == 0
4598                  || (xdb_commands && strcmp ("Q", cmd->line) == 0));
4599 }
4600
4601 /* Execute all the commands associated with all the breakpoints at
4602    this location.  Any of these commands could cause the process to
4603    proceed beyond this point, etc.  We look out for such changes by
4604    checking the global "breakpoint_proceeded" after each command.
4605
4606    Returns true if a breakpoint command resumed the inferior.  In that
4607    case, it is the caller's responsibility to recall it again with the
4608    bpstat of the current thread.  */
4609
4610 static int
4611 bpstat_do_actions_1 (bpstat *bsp)
4612 {
4613   bpstat bs;
4614   struct cleanup *old_chain;
4615   int again = 0;
4616
4617   /* Avoid endless recursion if a `source' command is contained
4618      in bs->commands.  */
4619   if (executing_breakpoint_commands)
4620     return 0;
4621
4622   executing_breakpoint_commands = 1;
4623   old_chain = make_cleanup (cleanup_executing_breakpoints, 0);
4624
4625   prevent_dont_repeat ();
4626
4627   /* This pointer will iterate over the list of bpstat's.  */
4628   bs = *bsp;
4629
4630   breakpoint_proceeded = 0;
4631   for (; bs != NULL; bs = bs->next)
4632     {
4633       struct counted_command_line *ccmd;
4634       struct command_line *cmd;
4635       struct cleanup *this_cmd_tree_chain;
4636
4637       /* Take ownership of the BSP's command tree, if it has one.
4638
4639          The command tree could legitimately contain commands like
4640          'step' and 'next', which call clear_proceed_status, which
4641          frees stop_bpstat's command tree.  To make sure this doesn't
4642          free the tree we're executing out from under us, we need to
4643          take ownership of the tree ourselves.  Since a given bpstat's
4644          commands are only executed once, we don't need to copy it; we
4645          can clear the pointer in the bpstat, and make sure we free
4646          the tree when we're done.  */
4647       ccmd = bs->commands;
4648       bs->commands = NULL;
4649       this_cmd_tree_chain = make_cleanup_decref_counted_command_line (&ccmd);
4650       cmd = ccmd ? ccmd->commands : NULL;
4651       if (command_line_is_silent (cmd))
4652         {
4653           /* The action has been already done by bpstat_stop_status.  */
4654           cmd = cmd->next;
4655         }
4656
4657       while (cmd != NULL)
4658         {
4659           execute_control_command (cmd);
4660
4661           if (breakpoint_proceeded)
4662             break;
4663           else
4664             cmd = cmd->next;
4665         }
4666
4667       /* We can free this command tree now.  */
4668       do_cleanups (this_cmd_tree_chain);
4669
4670       if (breakpoint_proceeded)
4671         {
4672           if (target_can_async_p ())
4673             /* If we are in async mode, then the target might be still
4674                running, not stopped at any breakpoint, so nothing for
4675                us to do here -- just return to the event loop.  */
4676             ;
4677           else
4678             /* In sync mode, when execute_control_command returns
4679                we're already standing on the next breakpoint.
4680                Breakpoint commands for that stop were not run, since
4681                execute_command does not run breakpoint commands --
4682                only command_line_handler does, but that one is not
4683                involved in execution of breakpoint commands.  So, we
4684                can now execute breakpoint commands.  It should be
4685                noted that making execute_command do bpstat actions is
4686                not an option -- in this case we'll have recursive
4687                invocation of bpstat for each breakpoint with a
4688                command, and can easily blow up GDB stack.  Instead, we
4689                return true, which will trigger the caller to recall us
4690                with the new stop_bpstat.  */
4691             again = 1;
4692           break;
4693         }
4694     }
4695   do_cleanups (old_chain);
4696   return again;
4697 }
4698
4699 void
4700 bpstat_do_actions (void)
4701 {
4702   struct cleanup *cleanup_if_error = make_bpstat_clear_actions_cleanup ();
4703
4704   /* Do any commands attached to breakpoint we are stopped at.  */
4705   while (!ptid_equal (inferior_ptid, null_ptid)
4706          && target_has_execution
4707          && !is_exited (inferior_ptid)
4708          && !is_executing (inferior_ptid))
4709     /* Since in sync mode, bpstat_do_actions may resume the inferior,
4710        and only return when it is stopped at the next breakpoint, we
4711        keep doing breakpoint actions until it returns false to
4712        indicate the inferior was not resumed.  */
4713     if (!bpstat_do_actions_1 (&inferior_thread ()->control.stop_bpstat))
4714       break;
4715
4716   discard_cleanups (cleanup_if_error);
4717 }
4718
4719 /* Print out the (old or new) value associated with a watchpoint.  */
4720
4721 static void
4722 watchpoint_value_print (struct value *val, struct ui_file *stream)
4723 {
4724   if (val == NULL)
4725     fprintf_unfiltered (stream, _("<unreadable>"));
4726   else
4727     {
4728       struct value_print_options opts;
4729       get_user_print_options (&opts);
4730       value_print (val, stream, &opts);
4731     }
4732 }
4733
4734 /* Generic routine for printing messages indicating why we
4735    stopped.  The behavior of this function depends on the value
4736    'print_it' in the bpstat structure.  Under some circumstances we
4737    may decide not to print anything here and delegate the task to
4738    normal_stop().  */
4739
4740 static enum print_stop_action
4741 print_bp_stop_message (bpstat bs)
4742 {
4743   switch (bs->print_it)
4744     {
4745     case print_it_noop:
4746       /* Nothing should be printed for this bpstat entry.  */
4747       return PRINT_UNKNOWN;
4748       break;
4749
4750     case print_it_done:
4751       /* We still want to print the frame, but we already printed the
4752          relevant messages.  */
4753       return PRINT_SRC_AND_LOC;
4754       break;
4755
4756     case print_it_normal:
4757       {
4758         struct breakpoint *b = bs->breakpoint_at;
4759
4760         /* bs->breakpoint_at can be NULL if it was a momentary breakpoint
4761            which has since been deleted.  */
4762         if (b == NULL)
4763           return PRINT_UNKNOWN;
4764
4765         /* Normal case.  Call the breakpoint's print_it method.  */
4766         return b->ops->print_it (bs);
4767       }
4768       break;
4769
4770     default:
4771       internal_error (__FILE__, __LINE__,
4772                       _("print_bp_stop_message: unrecognized enum value"));
4773       break;
4774     }
4775 }
4776
4777 /* A helper function that prints a shared library stopped event.  */
4778
4779 static void
4780 print_solib_event (int is_catchpoint)
4781 {
4782   int any_deleted
4783     = !VEC_empty (char_ptr, current_program_space->deleted_solibs);
4784   int any_added
4785     = !VEC_empty (so_list_ptr, current_program_space->added_solibs);
4786
4787   if (!is_catchpoint)
4788     {
4789       if (any_added || any_deleted)
4790         ui_out_text (current_uiout,
4791                      _("Stopped due to shared library event:\n"));
4792       else
4793         ui_out_text (current_uiout,
4794                      _("Stopped due to shared library event (no "
4795                        "libraries added or removed)\n"));
4796     }
4797
4798   if (ui_out_is_mi_like_p (current_uiout))
4799     ui_out_field_string (current_uiout, "reason",
4800                          async_reason_lookup (EXEC_ASYNC_SOLIB_EVENT));
4801
4802   if (any_deleted)
4803     {
4804       struct cleanup *cleanup;
4805       char *name;
4806       int ix;
4807
4808       ui_out_text (current_uiout, _("  Inferior unloaded "));
4809       cleanup = make_cleanup_ui_out_list_begin_end (current_uiout,
4810                                                     "removed");
4811       for (ix = 0;
4812            VEC_iterate (char_ptr, current_program_space->deleted_solibs,
4813                         ix, name);
4814            ++ix)
4815         {
4816           if (ix > 0)
4817             ui_out_text (current_uiout, "    ");
4818           ui_out_field_string (current_uiout, "library", name);
4819           ui_out_text (current_uiout, "\n");
4820         }
4821
4822       do_cleanups (cleanup);
4823     }
4824
4825   if (any_added)
4826     {
4827       struct so_list *iter;
4828       int ix;
4829       struct cleanup *cleanup;
4830
4831       ui_out_text (current_uiout, _("  Inferior loaded "));
4832       cleanup = make_cleanup_ui_out_list_begin_end (current_uiout,
4833                                                     "added");
4834       for (ix = 0;
4835            VEC_iterate (so_list_ptr, current_program_space->added_solibs,
4836                         ix, iter);
4837            ++ix)
4838         {
4839           if (ix > 0)
4840             ui_out_text (current_uiout, "    ");
4841           ui_out_field_string (current_uiout, "library", iter->so_name);
4842           ui_out_text (current_uiout, "\n");
4843         }
4844
4845       do_cleanups (cleanup);
4846     }
4847 }
4848
4849 /* Print a message indicating what happened.  This is called from
4850    normal_stop().  The input to this routine is the head of the bpstat
4851    list - a list of the eventpoints that caused this stop.  KIND is
4852    the target_waitkind for the stopping event.  This
4853    routine calls the generic print routine for printing a message
4854    about reasons for stopping.  This will print (for example) the
4855    "Breakpoint n," part of the output.  The return value of this
4856    routine is one of:
4857
4858    PRINT_UNKNOWN: Means we printed nothing.
4859    PRINT_SRC_AND_LOC: Means we printed something, and expect subsequent
4860    code to print the location.  An example is 
4861    "Breakpoint 1, " which should be followed by
4862    the location.
4863    PRINT_SRC_ONLY: Means we printed something, but there is no need
4864    to also print the location part of the message.
4865    An example is the catch/throw messages, which
4866    don't require a location appended to the end.
4867    PRINT_NOTHING: We have done some printing and we don't need any 
4868    further info to be printed.  */
4869
4870 enum print_stop_action
4871 bpstat_print (bpstat bs, int kind)
4872 {
4873   int val;
4874
4875   /* Maybe another breakpoint in the chain caused us to stop.
4876      (Currently all watchpoints go on the bpstat whether hit or not.
4877      That probably could (should) be changed, provided care is taken
4878      with respect to bpstat_explains_signal).  */
4879   for (; bs; bs = bs->next)
4880     {
4881       val = print_bp_stop_message (bs);
4882       if (val == PRINT_SRC_ONLY 
4883           || val == PRINT_SRC_AND_LOC 
4884           || val == PRINT_NOTHING)
4885         return val;
4886     }
4887
4888   /* If we had hit a shared library event breakpoint,
4889      print_bp_stop_message would print out this message.  If we hit an
4890      OS-level shared library event, do the same thing.  */
4891   if (kind == TARGET_WAITKIND_LOADED)
4892     {
4893       print_solib_event (0);
4894       return PRINT_NOTHING;
4895     }
4896
4897   /* We reached the end of the chain, or we got a null BS to start
4898      with and nothing was printed.  */
4899   return PRINT_UNKNOWN;
4900 }
4901
4902 /* Evaluate the expression EXP and return 1 if value is zero.
4903    This returns the inverse of the condition because it is called
4904    from catch_errors which returns 0 if an exception happened, and if an
4905    exception happens we want execution to stop.
4906    The argument is a "struct expression *" that has been cast to a
4907    "void *" to make it pass through catch_errors.  */
4908
4909 static int
4910 breakpoint_cond_eval (void *exp)
4911 {
4912   struct value *mark = value_mark ();
4913   int i = !value_true (evaluate_expression ((struct expression *) exp));
4914
4915   value_free_to_mark (mark);
4916   return i;
4917 }
4918
4919 /* Allocate a new bpstat.  Link it to the FIFO list by BS_LINK_POINTER.  */
4920
4921 static bpstat
4922 bpstat_alloc (struct bp_location *bl, bpstat **bs_link_pointer)
4923 {
4924   bpstat bs;
4925
4926   bs = (bpstat) xmalloc (sizeof (*bs));
4927   bs->next = NULL;
4928   **bs_link_pointer = bs;
4929   *bs_link_pointer = &bs->next;
4930   bs->breakpoint_at = bl->owner;
4931   bs->bp_location_at = bl;
4932   incref_bp_location (bl);
4933   /* If the condition is false, etc., don't do the commands.  */
4934   bs->commands = NULL;
4935   bs->old_val = NULL;
4936   bs->print_it = print_it_normal;
4937   return bs;
4938 }
4939 \f
4940 /* The target has stopped with waitstatus WS.  Check if any hardware
4941    watchpoints have triggered, according to the target.  */
4942
4943 int
4944 watchpoints_triggered (struct target_waitstatus *ws)
4945 {
4946   int stopped_by_watchpoint = target_stopped_by_watchpoint ();
4947   CORE_ADDR addr;
4948   struct breakpoint *b;
4949
4950   if (!stopped_by_watchpoint)
4951     {
4952       /* We were not stopped by a watchpoint.  Mark all watchpoints
4953          as not triggered.  */
4954       ALL_BREAKPOINTS (b)
4955         if (is_hardware_watchpoint (b))
4956           {
4957             struct watchpoint *w = (struct watchpoint *) b;
4958
4959             w->watchpoint_triggered = watch_triggered_no;
4960           }
4961
4962       return 0;
4963     }
4964
4965   if (!target_stopped_data_address (&current_target, &addr))
4966     {
4967       /* We were stopped by a watchpoint, but we don't know where.
4968          Mark all watchpoints as unknown.  */
4969       ALL_BREAKPOINTS (b)
4970         if (is_hardware_watchpoint (b))
4971           {
4972             struct watchpoint *w = (struct watchpoint *) b;
4973
4974             w->watchpoint_triggered = watch_triggered_unknown;
4975           }
4976
4977       return 1;
4978     }
4979
4980   /* The target could report the data address.  Mark watchpoints
4981      affected by this data address as triggered, and all others as not
4982      triggered.  */
4983
4984   ALL_BREAKPOINTS (b)
4985     if (is_hardware_watchpoint (b))
4986       {
4987         struct watchpoint *w = (struct watchpoint *) b;
4988         struct bp_location *loc;
4989
4990         w->watchpoint_triggered = watch_triggered_no;
4991         for (loc = b->loc; loc; loc = loc->next)
4992           {
4993             if (is_masked_watchpoint (b))
4994               {
4995                 CORE_ADDR newaddr = addr & w->hw_wp_mask;
4996                 CORE_ADDR start = loc->address & w->hw_wp_mask;
4997
4998                 if (newaddr == start)
4999                   {
5000                     w->watchpoint_triggered = watch_triggered_yes;
5001                     break;
5002                   }
5003               }
5004             /* Exact match not required.  Within range is sufficient.  */
5005             else if (target_watchpoint_addr_within_range (&current_target,
5006                                                          addr, loc->address,
5007                                                          loc->length))
5008               {
5009                 w->watchpoint_triggered = watch_triggered_yes;
5010                 break;
5011               }
5012           }
5013       }
5014
5015   return 1;
5016 }
5017
5018 /* Possible return values for watchpoint_check (this can't be an enum
5019    because of check_errors).  */
5020 /* The watchpoint has been deleted.  */
5021 #define WP_DELETED 1
5022 /* The value has changed.  */
5023 #define WP_VALUE_CHANGED 2
5024 /* The value has not changed.  */
5025 #define WP_VALUE_NOT_CHANGED 3
5026 /* Ignore this watchpoint, no matter if the value changed or not.  */
5027 #define WP_IGNORE 4
5028
5029 #define BP_TEMPFLAG 1
5030 #define BP_HARDWAREFLAG 2
5031
5032 /* Evaluate watchpoint condition expression and check if its value
5033    changed.
5034
5035    P should be a pointer to struct bpstat, but is defined as a void *
5036    in order for this function to be usable with catch_errors.  */
5037
5038 static int
5039 watchpoint_check (void *p)
5040 {
5041   bpstat bs = (bpstat) p;
5042   struct watchpoint *b;
5043   struct frame_info *fr;
5044   int within_current_scope;
5045
5046   /* BS is built from an existing struct breakpoint.  */
5047   gdb_assert (bs->breakpoint_at != NULL);
5048   b = (struct watchpoint *) bs->breakpoint_at;
5049
5050   /* If this is a local watchpoint, we only want to check if the
5051      watchpoint frame is in scope if the current thread is the thread
5052      that was used to create the watchpoint.  */
5053   if (!watchpoint_in_thread_scope (b))
5054     return WP_IGNORE;
5055
5056   if (b->exp_valid_block == NULL)
5057     within_current_scope = 1;
5058   else
5059     {
5060       struct frame_info *frame = get_current_frame ();
5061       struct gdbarch *frame_arch = get_frame_arch (frame);
5062       CORE_ADDR frame_pc = get_frame_pc (frame);
5063
5064       /* in_function_epilogue_p() returns a non-zero value if we're
5065          still in the function but the stack frame has already been
5066          invalidated.  Since we can't rely on the values of local
5067          variables after the stack has been destroyed, we are treating
5068          the watchpoint in that state as `not changed' without further
5069          checking.  Don't mark watchpoints as changed if the current
5070          frame is in an epilogue - even if they are in some other
5071          frame, our view of the stack is likely to be wrong and
5072          frame_find_by_id could error out.  */
5073       if (gdbarch_in_function_epilogue_p (frame_arch, frame_pc))
5074         return WP_IGNORE;
5075
5076       fr = frame_find_by_id (b->watchpoint_frame);
5077       within_current_scope = (fr != NULL);
5078
5079       /* If we've gotten confused in the unwinder, we might have
5080          returned a frame that can't describe this variable.  */
5081       if (within_current_scope)
5082         {
5083           struct symbol *function;
5084
5085           function = get_frame_function (fr);
5086           if (function == NULL
5087               || !contained_in (b->exp_valid_block,
5088                                 SYMBOL_BLOCK_VALUE (function)))
5089             within_current_scope = 0;
5090         }
5091
5092       if (within_current_scope)
5093         /* If we end up stopping, the current frame will get selected
5094            in normal_stop.  So this call to select_frame won't affect
5095            the user.  */
5096         select_frame (fr);
5097     }
5098
5099   if (within_current_scope)
5100     {
5101       /* We use value_{,free_to_}mark because it could be a *long*
5102          time before we return to the command level and call
5103          free_all_values.  We can't call free_all_values because we
5104          might be in the middle of evaluating a function call.  */
5105
5106       int pc = 0;
5107       struct value *mark;
5108       struct value *new_val;
5109
5110       if (is_masked_watchpoint (&b->base))
5111         /* Since we don't know the exact trigger address (from
5112            stopped_data_address), just tell the user we've triggered
5113            a mask watchpoint.  */
5114         return WP_VALUE_CHANGED;
5115
5116       mark = value_mark ();
5117       fetch_subexp_value (b->exp, &pc, &new_val, NULL, NULL, 0);
5118
5119       if (b->val_bitsize != 0)
5120         new_val = extract_bitfield_from_watchpoint_value (b, new_val);
5121
5122       /* We use value_equal_contents instead of value_equal because
5123          the latter coerces an array to a pointer, thus comparing just
5124          the address of the array instead of its contents.  This is
5125          not what we want.  */
5126       if ((b->val != NULL) != (new_val != NULL)
5127           || (b->val != NULL && !value_equal_contents (b->val, new_val)))
5128         {
5129           if (new_val != NULL)
5130             {
5131               release_value (new_val);
5132               value_free_to_mark (mark);
5133             }
5134           bs->old_val = b->val;
5135           b->val = new_val;
5136           b->val_valid = 1;
5137           return WP_VALUE_CHANGED;
5138         }
5139       else
5140         {
5141           /* Nothing changed.  */
5142           value_free_to_mark (mark);
5143           return WP_VALUE_NOT_CHANGED;
5144         }
5145     }
5146   else
5147     {
5148       struct ui_out *uiout = current_uiout;
5149
5150       /* This seems like the only logical thing to do because
5151          if we temporarily ignored the watchpoint, then when
5152          we reenter the block in which it is valid it contains
5153          garbage (in the case of a function, it may have two
5154          garbage values, one before and one after the prologue).
5155          So we can't even detect the first assignment to it and
5156          watch after that (since the garbage may or may not equal
5157          the first value assigned).  */
5158       /* We print all the stop information in
5159          breakpoint_ops->print_it, but in this case, by the time we
5160          call breakpoint_ops->print_it this bp will be deleted
5161          already.  So we have no choice but print the information
5162          here.  */
5163       if (ui_out_is_mi_like_p (uiout))
5164         ui_out_field_string
5165           (uiout, "reason", async_reason_lookup (EXEC_ASYNC_WATCHPOINT_SCOPE));
5166       ui_out_text (uiout, "\nWatchpoint ");
5167       ui_out_field_int (uiout, "wpnum", b->base.number);
5168       ui_out_text (uiout,
5169                    " deleted because the program has left the block in\n\
5170 which its expression is valid.\n");     
5171
5172       /* Make sure the watchpoint's commands aren't executed.  */
5173       decref_counted_command_line (&b->base.commands);
5174       watchpoint_del_at_next_stop (b);
5175
5176       return WP_DELETED;
5177     }
5178 }
5179
5180 /* Return true if it looks like target has stopped due to hitting
5181    breakpoint location BL.  This function does not check if we should
5182    stop, only if BL explains the stop.  */
5183
5184 static int
5185 bpstat_check_location (const struct bp_location *bl,
5186                        struct address_space *aspace, CORE_ADDR bp_addr,
5187                        const struct target_waitstatus *ws)
5188 {
5189   struct breakpoint *b = bl->owner;
5190
5191   /* BL is from an existing breakpoint.  */
5192   gdb_assert (b != NULL);
5193
5194   return b->ops->breakpoint_hit (bl, aspace, bp_addr, ws);
5195 }
5196
5197 /* Determine if the watched values have actually changed, and we
5198    should stop.  If not, set BS->stop to 0.  */
5199
5200 static void
5201 bpstat_check_watchpoint (bpstat bs)
5202 {
5203   const struct bp_location *bl;
5204   struct watchpoint *b;
5205
5206   /* BS is built for existing struct breakpoint.  */
5207   bl = bs->bp_location_at;
5208   gdb_assert (bl != NULL);
5209   b = (struct watchpoint *) bs->breakpoint_at;
5210   gdb_assert (b != NULL);
5211
5212     {
5213       int must_check_value = 0;
5214       
5215       if (b->base.type == bp_watchpoint)
5216         /* For a software watchpoint, we must always check the
5217            watched value.  */
5218         must_check_value = 1;
5219       else if (b->watchpoint_triggered == watch_triggered_yes)
5220         /* We have a hardware watchpoint (read, write, or access)
5221            and the target earlier reported an address watched by
5222            this watchpoint.  */
5223         must_check_value = 1;
5224       else if (b->watchpoint_triggered == watch_triggered_unknown
5225                && b->base.type == bp_hardware_watchpoint)
5226         /* We were stopped by a hardware watchpoint, but the target could
5227            not report the data address.  We must check the watchpoint's
5228            value.  Access and read watchpoints are out of luck; without
5229            a data address, we can't figure it out.  */
5230         must_check_value = 1;
5231
5232       if (must_check_value)
5233         {
5234           char *message
5235             = xstrprintf ("Error evaluating expression for watchpoint %d\n",
5236                           b->base.number);
5237           struct cleanup *cleanups = make_cleanup (xfree, message);
5238           int e = catch_errors (watchpoint_check, bs, message,
5239                                 RETURN_MASK_ALL);
5240           do_cleanups (cleanups);
5241           switch (e)
5242             {
5243             case WP_DELETED:
5244               /* We've already printed what needs to be printed.  */
5245               bs->print_it = print_it_done;
5246               /* Stop.  */
5247               break;
5248             case WP_IGNORE:
5249               bs->print_it = print_it_noop;
5250               bs->stop = 0;
5251               break;
5252             case WP_VALUE_CHANGED:
5253               if (b->base.type == bp_read_watchpoint)
5254                 {
5255                   /* There are two cases to consider here:
5256
5257                      1. We're watching the triggered memory for reads.
5258                      In that case, trust the target, and always report
5259                      the watchpoint hit to the user.  Even though
5260                      reads don't cause value changes, the value may
5261                      have changed since the last time it was read, and
5262                      since we're not trapping writes, we will not see
5263                      those, and as such we should ignore our notion of
5264                      old value.
5265
5266                      2. We're watching the triggered memory for both
5267                      reads and writes.  There are two ways this may
5268                      happen:
5269
5270                      2.1. This is a target that can't break on data
5271                      reads only, but can break on accesses (reads or
5272                      writes), such as e.g., x86.  We detect this case
5273                      at the time we try to insert read watchpoints.
5274
5275                      2.2. Otherwise, the target supports read
5276                      watchpoints, but, the user set an access or write
5277                      watchpoint watching the same memory as this read
5278                      watchpoint.
5279
5280                      If we're watching memory writes as well as reads,
5281                      ignore watchpoint hits when we find that the
5282                      value hasn't changed, as reads don't cause
5283                      changes.  This still gives false positives when
5284                      the program writes the same value to memory as
5285                      what there was already in memory (we will confuse
5286                      it for a read), but it's much better than
5287                      nothing.  */
5288
5289                   int other_write_watchpoint = 0;
5290
5291                   if (bl->watchpoint_type == hw_read)
5292                     {
5293                       struct breakpoint *other_b;
5294
5295                       ALL_BREAKPOINTS (other_b)
5296                         if (other_b->type == bp_hardware_watchpoint
5297                             || other_b->type == bp_access_watchpoint)
5298                           {
5299                             struct watchpoint *other_w =
5300                               (struct watchpoint *) other_b;
5301
5302                             if (other_w->watchpoint_triggered
5303                                 == watch_triggered_yes)
5304                               {
5305                                 other_write_watchpoint = 1;
5306                                 break;
5307                               }
5308                           }
5309                     }
5310
5311                   if (other_write_watchpoint
5312                       || bl->watchpoint_type == hw_access)
5313                     {
5314                       /* We're watching the same memory for writes,
5315                          and the value changed since the last time we
5316                          updated it, so this trap must be for a write.
5317                          Ignore it.  */
5318                       bs->print_it = print_it_noop;
5319                       bs->stop = 0;
5320                     }
5321                 }
5322               break;
5323             case WP_VALUE_NOT_CHANGED:
5324               if (b->base.type == bp_hardware_watchpoint
5325                   || b->base.type == bp_watchpoint)
5326                 {
5327                   /* Don't stop: write watchpoints shouldn't fire if
5328                      the value hasn't changed.  */
5329                   bs->print_it = print_it_noop;
5330                   bs->stop = 0;
5331                 }
5332               /* Stop.  */
5333               break;
5334             default:
5335               /* Can't happen.  */
5336             case 0:
5337               /* Error from catch_errors.  */
5338               printf_filtered (_("Watchpoint %d deleted.\n"), b->base.number);
5339               watchpoint_del_at_next_stop (b);
5340               /* We've already printed what needs to be printed.  */
5341               bs->print_it = print_it_done;
5342               break;
5343             }
5344         }
5345       else      /* must_check_value == 0 */
5346         {
5347           /* This is a case where some watchpoint(s) triggered, but
5348              not at the address of this watchpoint, or else no
5349              watchpoint triggered after all.  So don't print
5350              anything for this watchpoint.  */
5351           bs->print_it = print_it_noop;
5352           bs->stop = 0;
5353         }
5354     }
5355 }
5356
5357 /* For breakpoints that are currently marked as telling gdb to stop,
5358    check conditions (condition proper, frame, thread and ignore count)
5359    of breakpoint referred to by BS.  If we should not stop for this
5360    breakpoint, set BS->stop to 0.  */
5361
5362 static void
5363 bpstat_check_breakpoint_conditions (bpstat bs, ptid_t ptid)
5364 {
5365   const struct bp_location *bl;
5366   struct breakpoint *b;
5367   int value_is_zero = 0;
5368   struct expression *cond;
5369
5370   gdb_assert (bs->stop);
5371
5372   /* BS is built for existing struct breakpoint.  */
5373   bl = bs->bp_location_at;
5374   gdb_assert (bl != NULL);
5375   b = bs->breakpoint_at;
5376   gdb_assert (b != NULL);
5377
5378   /* Even if the target evaluated the condition on its end and notified GDB, we
5379      need to do so again since GDB does not know if we stopped due to a
5380      breakpoint or a single step breakpoint.  */
5381
5382   if (frame_id_p (b->frame_id)
5383       && !frame_id_eq (b->frame_id, get_stack_frame_id (get_current_frame ())))
5384     {
5385       bs->stop = 0;
5386       return;
5387     }
5388
5389   /* If this is a thread/task-specific breakpoint, don't waste cpu
5390      evaluating the condition if this isn't the specified
5391      thread/task.  */
5392   if ((b->thread != -1 && b->thread != pid_to_thread_id (ptid))
5393       || (b->task != 0 && b->task != ada_get_task_number (ptid)))
5394
5395     {
5396       bs->stop = 0;
5397       return;
5398     }
5399
5400   /* Evaluate extension language breakpoints that have a "stop" method
5401      implemented.  */
5402   bs->stop = breakpoint_ext_lang_cond_says_stop (b);
5403
5404   if (is_watchpoint (b))
5405     {
5406       struct watchpoint *w = (struct watchpoint *) b;
5407
5408       cond = w->cond_exp;
5409     }
5410   else
5411     cond = bl->cond;
5412
5413   if (cond && b->disposition != disp_del_at_next_stop)
5414     {
5415       int within_current_scope = 1;
5416       struct watchpoint * w;
5417
5418       /* We use value_mark and value_free_to_mark because it could
5419          be a long time before we return to the command level and
5420          call free_all_values.  We can't call free_all_values
5421          because we might be in the middle of evaluating a
5422          function call.  */
5423       struct value *mark = value_mark ();
5424
5425       if (is_watchpoint (b))
5426         w = (struct watchpoint *) b;
5427       else
5428         w = NULL;
5429
5430       /* Need to select the frame, with all that implies so that
5431          the conditions will have the right context.  Because we
5432          use the frame, we will not see an inlined function's
5433          variables when we arrive at a breakpoint at the start
5434          of the inlined function; the current frame will be the
5435          call site.  */
5436       if (w == NULL || w->cond_exp_valid_block == NULL)
5437         select_frame (get_current_frame ());
5438       else
5439         {
5440           struct frame_info *frame;
5441
5442           /* For local watchpoint expressions, which particular
5443              instance of a local is being watched matters, so we
5444              keep track of the frame to evaluate the expression
5445              in.  To evaluate the condition however, it doesn't
5446              really matter which instantiation of the function
5447              where the condition makes sense triggers the
5448              watchpoint.  This allows an expression like "watch
5449              global if q > 10" set in `func', catch writes to
5450              global on all threads that call `func', or catch
5451              writes on all recursive calls of `func' by a single
5452              thread.  We simply always evaluate the condition in
5453              the innermost frame that's executing where it makes
5454              sense to evaluate the condition.  It seems
5455              intuitive.  */
5456           frame = block_innermost_frame (w->cond_exp_valid_block);
5457           if (frame != NULL)
5458             select_frame (frame);
5459           else
5460             within_current_scope = 0;
5461         }
5462       if (within_current_scope)
5463         value_is_zero
5464           = catch_errors (breakpoint_cond_eval, cond,
5465                           "Error in testing breakpoint condition:\n",
5466                           RETURN_MASK_ALL);
5467       else
5468         {
5469           warning (_("Watchpoint condition cannot be tested "
5470                      "in the current scope"));
5471           /* If we failed to set the right context for this
5472              watchpoint, unconditionally report it.  */
5473           value_is_zero = 0;
5474         }
5475       /* FIXME-someday, should give breakpoint #.  */
5476       value_free_to_mark (mark);
5477     }
5478
5479   if (cond && value_is_zero)
5480     {
5481       bs->stop = 0;
5482     }
5483   else if (b->ignore_count > 0)
5484     {
5485       b->ignore_count--;
5486       bs->stop = 0;
5487       /* Increase the hit count even though we don't stop.  */
5488       ++(b->hit_count);
5489       observer_notify_breakpoint_modified (b);
5490     }   
5491 }
5492
5493
5494 /* Get a bpstat associated with having just stopped at address
5495    BP_ADDR in thread PTID.
5496
5497    Determine whether we stopped at a breakpoint, etc, or whether we
5498    don't understand this stop.  Result is a chain of bpstat's such
5499    that:
5500
5501    if we don't understand the stop, the result is a null pointer.
5502
5503    if we understand why we stopped, the result is not null.
5504
5505    Each element of the chain refers to a particular breakpoint or
5506    watchpoint at which we have stopped.  (We may have stopped for
5507    several reasons concurrently.)
5508
5509    Each element of the chain has valid next, breakpoint_at,
5510    commands, FIXME??? fields.  */
5511
5512 bpstat
5513 bpstat_stop_status (struct address_space *aspace,
5514                     CORE_ADDR bp_addr, ptid_t ptid,
5515                     const struct target_waitstatus *ws)
5516 {
5517   struct breakpoint *b = NULL;
5518   struct bp_location *bl;
5519   struct bp_location *loc;
5520   /* First item of allocated bpstat's.  */
5521   bpstat bs_head = NULL, *bs_link = &bs_head;
5522   /* Pointer to the last thing in the chain currently.  */
5523   bpstat bs;
5524   int ix;
5525   int need_remove_insert;
5526   int removed_any;
5527
5528   /* First, build the bpstat chain with locations that explain a
5529      target stop, while being careful to not set the target running,
5530      as that may invalidate locations (in particular watchpoint
5531      locations are recreated).  Resuming will happen here with
5532      breakpoint conditions or watchpoint expressions that include
5533      inferior function calls.  */
5534
5535   ALL_BREAKPOINTS (b)
5536     {
5537       if (!breakpoint_enabled (b) && b->enable_state != bp_permanent)
5538         continue;
5539
5540       for (bl = b->loc; bl != NULL; bl = bl->next)
5541         {
5542           /* For hardware watchpoints, we look only at the first
5543              location.  The watchpoint_check function will work on the
5544              entire expression, not the individual locations.  For
5545              read watchpoints, the watchpoints_triggered function has
5546              checked all locations already.  */
5547           if (b->type == bp_hardware_watchpoint && bl != b->loc)
5548             break;
5549
5550           if (!bl->enabled || bl->shlib_disabled)
5551             continue;
5552
5553           if (!bpstat_check_location (bl, aspace, bp_addr, ws))
5554             continue;
5555
5556           /* Come here if it's a watchpoint, or if the break address
5557              matches.  */
5558
5559           bs = bpstat_alloc (bl, &bs_link);     /* Alloc a bpstat to
5560                                                    explain stop.  */
5561
5562           /* Assume we stop.  Should we find a watchpoint that is not
5563              actually triggered, or if the condition of the breakpoint
5564              evaluates as false, we'll reset 'stop' to 0.  */
5565           bs->stop = 1;
5566           bs->print = 1;
5567
5568           /* If this is a scope breakpoint, mark the associated
5569              watchpoint as triggered so that we will handle the
5570              out-of-scope event.  We'll get to the watchpoint next
5571              iteration.  */
5572           if (b->type == bp_watchpoint_scope && b->related_breakpoint != b)
5573             {
5574               struct watchpoint *w = (struct watchpoint *) b->related_breakpoint;
5575
5576               w->watchpoint_triggered = watch_triggered_yes;
5577             }
5578         }
5579     }
5580
5581   /* Check if a moribund breakpoint explains the stop.  */
5582   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
5583     {
5584       if (breakpoint_location_address_match (loc, aspace, bp_addr))
5585         {
5586           bs = bpstat_alloc (loc, &bs_link);
5587           /* For hits of moribund locations, we should just proceed.  */
5588           bs->stop = 0;
5589           bs->print = 0;
5590           bs->print_it = print_it_noop;
5591         }
5592     }
5593
5594   /* A bit of special processing for shlib breakpoints.  We need to
5595      process solib loading here, so that the lists of loaded and
5596      unloaded libraries are correct before we handle "catch load" and
5597      "catch unload".  */
5598   for (bs = bs_head; bs != NULL; bs = bs->next)
5599     {
5600       if (bs->breakpoint_at && bs->breakpoint_at->type == bp_shlib_event)
5601         {
5602           handle_solib_event ();
5603           break;
5604         }
5605     }
5606
5607   /* Now go through the locations that caused the target to stop, and
5608      check whether we're interested in reporting this stop to higher
5609      layers, or whether we should resume the target transparently.  */
5610
5611   removed_any = 0;
5612
5613   for (bs = bs_head; bs != NULL; bs = bs->next)
5614     {
5615       if (!bs->stop)
5616         continue;
5617
5618       b = bs->breakpoint_at;
5619       b->ops->check_status (bs);
5620       if (bs->stop)
5621         {
5622           bpstat_check_breakpoint_conditions (bs, ptid);
5623
5624           if (bs->stop)
5625             {
5626               ++(b->hit_count);
5627               observer_notify_breakpoint_modified (b);
5628
5629               /* We will stop here.  */
5630               if (b->disposition == disp_disable)
5631                 {
5632                   --(b->enable_count);
5633                   if (b->enable_count <= 0
5634                       && b->enable_state != bp_permanent)
5635                     b->enable_state = bp_disabled;
5636                   removed_any = 1;
5637                 }
5638               if (b->silent)
5639                 bs->print = 0;
5640               bs->commands = b->commands;
5641               incref_counted_command_line (bs->commands);
5642               if (command_line_is_silent (bs->commands
5643                                           ? bs->commands->commands : NULL))
5644                 bs->print = 0;
5645
5646               b->ops->after_condition_true (bs);
5647             }
5648
5649         }
5650
5651       /* Print nothing for this entry if we don't stop or don't
5652          print.  */
5653       if (!bs->stop || !bs->print)
5654         bs->print_it = print_it_noop;
5655     }
5656
5657   /* If we aren't stopping, the value of some hardware watchpoint may
5658      not have changed, but the intermediate memory locations we are
5659      watching may have.  Don't bother if we're stopping; this will get
5660      done later.  */
5661   need_remove_insert = 0;
5662   if (! bpstat_causes_stop (bs_head))
5663     for (bs = bs_head; bs != NULL; bs = bs->next)
5664       if (!bs->stop
5665           && bs->breakpoint_at
5666           && is_hardware_watchpoint (bs->breakpoint_at))
5667         {
5668           struct watchpoint *w = (struct watchpoint *) bs->breakpoint_at;
5669
5670           update_watchpoint (w, 0 /* don't reparse.  */);
5671           need_remove_insert = 1;
5672         }
5673
5674   if (need_remove_insert)
5675     update_global_location_list (UGLL_MAY_INSERT);
5676   else if (removed_any)
5677     update_global_location_list (UGLL_DONT_INSERT);
5678
5679   return bs_head;
5680 }
5681
5682 static void
5683 handle_jit_event (void)
5684 {
5685   struct frame_info *frame;
5686   struct gdbarch *gdbarch;
5687
5688   /* Switch terminal for any messages produced by
5689      breakpoint_re_set.  */
5690   target_terminal_ours_for_output ();
5691
5692   frame = get_current_frame ();
5693   gdbarch = get_frame_arch (frame);
5694
5695   jit_event_handler (gdbarch);
5696
5697   target_terminal_inferior ();
5698 }
5699
5700 /* Prepare WHAT final decision for infrun.  */
5701
5702 /* Decide what infrun needs to do with this bpstat.  */
5703
5704 struct bpstat_what
5705 bpstat_what (bpstat bs_head)
5706 {
5707   struct bpstat_what retval;
5708   int jit_event = 0;
5709   bpstat bs;
5710
5711   retval.main_action = BPSTAT_WHAT_KEEP_CHECKING;
5712   retval.call_dummy = STOP_NONE;
5713   retval.is_longjmp = 0;
5714
5715   for (bs = bs_head; bs != NULL; bs = bs->next)
5716     {
5717       /* Extract this BS's action.  After processing each BS, we check
5718          if its action overrides all we've seem so far.  */
5719       enum bpstat_what_main_action this_action = BPSTAT_WHAT_KEEP_CHECKING;
5720       enum bptype bptype;
5721
5722       if (bs->breakpoint_at == NULL)
5723         {
5724           /* I suspect this can happen if it was a momentary
5725              breakpoint which has since been deleted.  */
5726           bptype = bp_none;
5727         }
5728       else
5729         bptype = bs->breakpoint_at->type;
5730
5731       switch (bptype)
5732         {
5733         case bp_none:
5734           break;
5735         case bp_breakpoint:
5736         case bp_hardware_breakpoint:
5737         case bp_single_step:
5738         case bp_until:
5739         case bp_finish:
5740         case bp_shlib_event:
5741           if (bs->stop)
5742             {
5743               if (bs->print)
5744                 this_action = BPSTAT_WHAT_STOP_NOISY;
5745               else
5746                 this_action = BPSTAT_WHAT_STOP_SILENT;
5747             }
5748           else
5749             this_action = BPSTAT_WHAT_SINGLE;
5750           break;
5751         case bp_watchpoint:
5752         case bp_hardware_watchpoint:
5753         case bp_read_watchpoint:
5754         case bp_access_watchpoint:
5755           if (bs->stop)
5756             {
5757               if (bs->print)
5758                 this_action = BPSTAT_WHAT_STOP_NOISY;
5759               else
5760                 this_action = BPSTAT_WHAT_STOP_SILENT;
5761             }
5762           else
5763             {
5764               /* There was a watchpoint, but we're not stopping.
5765                  This requires no further action.  */
5766             }
5767           break;
5768         case bp_longjmp:
5769         case bp_longjmp_call_dummy:
5770         case bp_exception:
5771           this_action = BPSTAT_WHAT_SET_LONGJMP_RESUME;
5772           retval.is_longjmp = bptype != bp_exception;
5773           break;
5774         case bp_longjmp_resume:
5775         case bp_exception_resume:
5776           this_action = BPSTAT_WHAT_CLEAR_LONGJMP_RESUME;
5777           retval.is_longjmp = bptype == bp_longjmp_resume;
5778           break;
5779         case bp_step_resume:
5780           if (bs->stop)
5781             this_action = BPSTAT_WHAT_STEP_RESUME;
5782           else
5783             {
5784               /* It is for the wrong frame.  */
5785               this_action = BPSTAT_WHAT_SINGLE;
5786             }
5787           break;
5788         case bp_hp_step_resume:
5789           if (bs->stop)
5790             this_action = BPSTAT_WHAT_HP_STEP_RESUME;
5791           else
5792             {
5793               /* It is for the wrong frame.  */
5794               this_action = BPSTAT_WHAT_SINGLE;
5795             }
5796           break;
5797         case bp_watchpoint_scope:
5798         case bp_thread_event:
5799         case bp_overlay_event:
5800         case bp_longjmp_master:
5801         case bp_std_terminate_master:
5802         case bp_exception_master:
5803           this_action = BPSTAT_WHAT_SINGLE;
5804           break;
5805         case bp_catchpoint:
5806           if (bs->stop)
5807             {
5808               if (bs->print)
5809                 this_action = BPSTAT_WHAT_STOP_NOISY;
5810               else
5811                 this_action = BPSTAT_WHAT_STOP_SILENT;
5812             }
5813           else
5814             {
5815               /* There was a catchpoint, but we're not stopping.
5816                  This requires no further action.  */
5817             }
5818           break;
5819         case bp_jit_event:
5820           jit_event = 1;
5821           this_action = BPSTAT_WHAT_SINGLE;
5822           break;
5823         case bp_call_dummy:
5824           /* Make sure the action is stop (silent or noisy),
5825              so infrun.c pops the dummy frame.  */
5826           retval.call_dummy = STOP_STACK_DUMMY;
5827           this_action = BPSTAT_WHAT_STOP_SILENT;
5828           break;
5829         case bp_std_terminate:
5830           /* Make sure the action is stop (silent or noisy),
5831              so infrun.c pops the dummy frame.  */
5832           retval.call_dummy = STOP_STD_TERMINATE;
5833           this_action = BPSTAT_WHAT_STOP_SILENT;
5834           break;
5835         case bp_tracepoint:
5836         case bp_fast_tracepoint:
5837         case bp_static_tracepoint:
5838           /* Tracepoint hits should not be reported back to GDB, and
5839              if one got through somehow, it should have been filtered
5840              out already.  */
5841           internal_error (__FILE__, __LINE__,
5842                           _("bpstat_what: tracepoint encountered"));
5843           break;
5844         case bp_gnu_ifunc_resolver:
5845           /* Step over it (and insert bp_gnu_ifunc_resolver_return).  */
5846           this_action = BPSTAT_WHAT_SINGLE;
5847           break;
5848         case bp_gnu_ifunc_resolver_return:
5849           /* The breakpoint will be removed, execution will restart from the
5850              PC of the former breakpoint.  */
5851           this_action = BPSTAT_WHAT_KEEP_CHECKING;
5852           break;
5853
5854         case bp_dprintf:
5855           if (bs->stop)
5856             this_action = BPSTAT_WHAT_STOP_SILENT;
5857           else
5858             this_action = BPSTAT_WHAT_SINGLE;
5859           break;
5860
5861         default:
5862           internal_error (__FILE__, __LINE__,
5863                           _("bpstat_what: unhandled bptype %d"), (int) bptype);
5864         }
5865
5866       retval.main_action = max (retval.main_action, this_action);
5867     }
5868
5869   /* These operations may affect the bs->breakpoint_at state so they are
5870      delayed after MAIN_ACTION is decided above.  */
5871
5872   if (jit_event)
5873     {
5874       if (debug_infrun)
5875         fprintf_unfiltered (gdb_stdlog, "bpstat_what: bp_jit_event\n");
5876
5877       handle_jit_event ();
5878     }
5879
5880   for (bs = bs_head; bs != NULL; bs = bs->next)
5881     {
5882       struct breakpoint *b = bs->breakpoint_at;
5883
5884       if (b == NULL)
5885         continue;
5886       switch (b->type)
5887         {
5888         case bp_gnu_ifunc_resolver:
5889           gnu_ifunc_resolver_stop (b);
5890           break;
5891         case bp_gnu_ifunc_resolver_return:
5892           gnu_ifunc_resolver_return_stop (b);
5893           break;
5894         }
5895     }
5896
5897   return retval;
5898 }
5899
5900 /* Nonzero if we should step constantly (e.g. watchpoints on machines
5901    without hardware support).  This isn't related to a specific bpstat,
5902    just to things like whether watchpoints are set.  */
5903
5904 int
5905 bpstat_should_step (void)
5906 {
5907   struct breakpoint *b;
5908
5909   ALL_BREAKPOINTS (b)
5910     if (breakpoint_enabled (b) && b->type == bp_watchpoint && b->loc != NULL)
5911       return 1;
5912   return 0;
5913 }
5914
5915 int
5916 bpstat_causes_stop (bpstat bs)
5917 {
5918   for (; bs != NULL; bs = bs->next)
5919     if (bs->stop)
5920       return 1;
5921
5922   return 0;
5923 }
5924
5925 \f
5926
5927 /* Compute a string of spaces suitable to indent the next line
5928    so it starts at the position corresponding to the table column
5929    named COL_NAME in the currently active table of UIOUT.  */
5930
5931 static char *
5932 wrap_indent_at_field (struct ui_out *uiout, const char *col_name)
5933 {
5934   static char wrap_indent[80];
5935   int i, total_width, width, align;
5936   char *text;
5937
5938   total_width = 0;
5939   for (i = 1; ui_out_query_field (uiout, i, &width, &align, &text); i++)
5940     {
5941       if (strcmp (text, col_name) == 0)
5942         {
5943           gdb_assert (total_width < sizeof wrap_indent);
5944           memset (wrap_indent, ' ', total_width);
5945           wrap_indent[total_width] = 0;
5946
5947           return wrap_indent;
5948         }
5949
5950       total_width += width + 1;
5951     }
5952
5953   return NULL;
5954 }
5955
5956 /* Determine if the locations of this breakpoint will have their conditions
5957    evaluated by the target, host or a mix of both.  Returns the following:
5958
5959     "host": Host evals condition.
5960     "host or target": Host or Target evals condition.
5961     "target": Target evals condition.
5962 */
5963
5964 static const char *
5965 bp_condition_evaluator (struct breakpoint *b)
5966 {
5967   struct bp_location *bl;
5968   char host_evals = 0;
5969   char target_evals = 0;
5970
5971   if (!b)
5972     return NULL;
5973
5974   if (!is_breakpoint (b))
5975     return NULL;
5976
5977   if (gdb_evaluates_breakpoint_condition_p ()
5978       || !target_supports_evaluation_of_breakpoint_conditions ())
5979     return condition_evaluation_host;
5980
5981   for (bl = b->loc; bl; bl = bl->next)
5982     {
5983       if (bl->cond_bytecode)
5984         target_evals++;
5985       else
5986         host_evals++;
5987     }
5988
5989   if (host_evals && target_evals)
5990     return condition_evaluation_both;
5991   else if (target_evals)
5992     return condition_evaluation_target;
5993   else
5994     return condition_evaluation_host;
5995 }
5996
5997 /* Determine the breakpoint location's condition evaluator.  This is
5998    similar to bp_condition_evaluator, but for locations.  */
5999
6000 static const char *
6001 bp_location_condition_evaluator (struct bp_location *bl)
6002 {
6003   if (bl && !is_breakpoint (bl->owner))
6004     return NULL;
6005
6006   if (gdb_evaluates_breakpoint_condition_p ()
6007       || !target_supports_evaluation_of_breakpoint_conditions ())
6008     return condition_evaluation_host;
6009
6010   if (bl && bl->cond_bytecode)
6011     return condition_evaluation_target;
6012   else
6013     return condition_evaluation_host;
6014 }
6015
6016 /* Print the LOC location out of the list of B->LOC locations.  */
6017
6018 static void
6019 print_breakpoint_location (struct breakpoint *b,
6020                            struct bp_location *loc)
6021 {
6022   struct ui_out *uiout = current_uiout;
6023   struct cleanup *old_chain = save_current_program_space ();
6024
6025   if (loc != NULL && loc->shlib_disabled)
6026     loc = NULL;
6027
6028   if (loc != NULL)
6029     set_current_program_space (loc->pspace);
6030
6031   if (b->display_canonical)
6032     ui_out_field_string (uiout, "what", b->addr_string);
6033   else if (loc && loc->symtab)
6034     {
6035       struct symbol *sym 
6036         = find_pc_sect_function (loc->address, loc->section);
6037       if (sym)
6038         {
6039           ui_out_text (uiout, "in ");
6040           ui_out_field_string (uiout, "func",
6041                                SYMBOL_PRINT_NAME (sym));
6042           ui_out_text (uiout, " ");
6043           ui_out_wrap_hint (uiout, wrap_indent_at_field (uiout, "what"));
6044           ui_out_text (uiout, "at ");
6045         }
6046       ui_out_field_string (uiout, "file",
6047                            symtab_to_filename_for_display (loc->symtab));
6048       ui_out_text (uiout, ":");
6049
6050       if (ui_out_is_mi_like_p (uiout))
6051         ui_out_field_string (uiout, "fullname",
6052                              symtab_to_fullname (loc->symtab));
6053       
6054       ui_out_field_int (uiout, "line", loc->line_number);
6055     }
6056   else if (loc)
6057     {
6058       struct ui_file *stb = mem_fileopen ();
6059       struct cleanup *stb_chain = make_cleanup_ui_file_delete (stb);
6060
6061       print_address_symbolic (loc->gdbarch, loc->address, stb,
6062                               demangle, "");
6063       ui_out_field_stream (uiout, "at", stb);
6064
6065       do_cleanups (stb_chain);
6066     }
6067   else
6068     ui_out_field_string (uiout, "pending", b->addr_string);
6069
6070   if (loc && is_breakpoint (b)
6071       && breakpoint_condition_evaluation_mode () == condition_evaluation_target
6072       && bp_condition_evaluator (b) == condition_evaluation_both)
6073     {
6074       ui_out_text (uiout, " (");
6075       ui_out_field_string (uiout, "evaluated-by",
6076                            bp_location_condition_evaluator (loc));
6077       ui_out_text (uiout, ")");
6078     }
6079
6080   do_cleanups (old_chain);
6081 }
6082
6083 static const char *
6084 bptype_string (enum bptype type)
6085 {
6086   struct ep_type_description
6087     {
6088       enum bptype type;
6089       char *description;
6090     };
6091   static struct ep_type_description bptypes[] =
6092   {
6093     {bp_none, "?deleted?"},
6094     {bp_breakpoint, "breakpoint"},
6095     {bp_hardware_breakpoint, "hw breakpoint"},
6096     {bp_single_step, "sw single-step"},
6097     {bp_until, "until"},
6098     {bp_finish, "finish"},
6099     {bp_watchpoint, "watchpoint"},
6100     {bp_hardware_watchpoint, "hw watchpoint"},
6101     {bp_read_watchpoint, "read watchpoint"},
6102     {bp_access_watchpoint, "acc watchpoint"},
6103     {bp_longjmp, "longjmp"},
6104     {bp_longjmp_resume, "longjmp resume"},
6105     {bp_longjmp_call_dummy, "longjmp for call dummy"},
6106     {bp_exception, "exception"},
6107     {bp_exception_resume, "exception resume"},
6108     {bp_step_resume, "step resume"},
6109     {bp_hp_step_resume, "high-priority step resume"},
6110     {bp_watchpoint_scope, "watchpoint scope"},
6111     {bp_call_dummy, "call dummy"},
6112     {bp_std_terminate, "std::terminate"},
6113     {bp_shlib_event, "shlib events"},
6114     {bp_thread_event, "thread events"},
6115     {bp_overlay_event, "overlay events"},
6116     {bp_longjmp_master, "longjmp master"},
6117     {bp_std_terminate_master, "std::terminate master"},
6118     {bp_exception_master, "exception master"},
6119     {bp_catchpoint, "catchpoint"},
6120     {bp_tracepoint, "tracepoint"},
6121     {bp_fast_tracepoint, "fast tracepoint"},
6122     {bp_static_tracepoint, "static tracepoint"},
6123     {bp_dprintf, "dprintf"},
6124     {bp_jit_event, "jit events"},
6125     {bp_gnu_ifunc_resolver, "STT_GNU_IFUNC resolver"},
6126     {bp_gnu_ifunc_resolver_return, "STT_GNU_IFUNC resolver return"},
6127   };
6128
6129   if (((int) type >= (sizeof (bptypes) / sizeof (bptypes[0])))
6130       || ((int) type != bptypes[(int) type].type))
6131     internal_error (__FILE__, __LINE__,
6132                     _("bptypes table does not describe type #%d."),
6133                     (int) type);
6134
6135   return bptypes[(int) type].description;
6136 }
6137
6138 /* For MI, output a field named 'thread-groups' with a list as the value.
6139    For CLI, prefix the list with the string 'inf'. */
6140
6141 static void
6142 output_thread_groups (struct ui_out *uiout,
6143                       const char *field_name,
6144                       VEC(int) *inf_num,
6145                       int mi_only)
6146 {
6147   struct cleanup *back_to;
6148   int is_mi = ui_out_is_mi_like_p (uiout);
6149   int inf;
6150   int i;
6151
6152   /* For backward compatibility, don't display inferiors in CLI unless
6153      there are several.  Always display them for MI. */
6154   if (!is_mi && mi_only)
6155     return;
6156
6157   back_to = make_cleanup_ui_out_list_begin_end (uiout, field_name);
6158
6159   for (i = 0; VEC_iterate (int, inf_num, i, inf); ++i)
6160     {
6161       if (is_mi)
6162         {
6163           char mi_group[10];
6164
6165           xsnprintf (mi_group, sizeof (mi_group), "i%d", inf);
6166           ui_out_field_string (uiout, NULL, mi_group);
6167         }
6168       else
6169         {
6170           if (i == 0)
6171             ui_out_text (uiout, " inf ");
6172           else
6173             ui_out_text (uiout, ", ");
6174         
6175           ui_out_text (uiout, plongest (inf));
6176         }
6177     }
6178
6179   do_cleanups (back_to);
6180 }
6181
6182 /* Print B to gdb_stdout.  */
6183
6184 static void
6185 print_one_breakpoint_location (struct breakpoint *b,
6186                                struct bp_location *loc,
6187                                int loc_number,
6188                                struct bp_location **last_loc,
6189                                int allflag)
6190 {
6191   struct command_line *l;
6192   static char bpenables[] = "nynny";
6193
6194   struct ui_out *uiout = current_uiout;
6195   int header_of_multiple = 0;
6196   int part_of_multiple = (loc != NULL);
6197   struct value_print_options opts;
6198
6199   get_user_print_options (&opts);
6200
6201   gdb_assert (!loc || loc_number != 0);
6202   /* See comment in print_one_breakpoint concerning treatment of
6203      breakpoints with single disabled location.  */
6204   if (loc == NULL 
6205       && (b->loc != NULL 
6206           && (b->loc->next != NULL || !b->loc->enabled)))
6207     header_of_multiple = 1;
6208   if (loc == NULL)
6209     loc = b->loc;
6210
6211   annotate_record ();
6212
6213   /* 1 */
6214   annotate_field (0);
6215   if (part_of_multiple)
6216     {
6217       char *formatted;
6218       formatted = xstrprintf ("%d.%d", b->number, loc_number);
6219       ui_out_field_string (uiout, "number", formatted);
6220       xfree (formatted);
6221     }
6222   else
6223     {
6224       ui_out_field_int (uiout, "number", b->number);
6225     }
6226
6227   /* 2 */
6228   annotate_field (1);
6229   if (part_of_multiple)
6230     ui_out_field_skip (uiout, "type");
6231   else
6232     ui_out_field_string (uiout, "type", bptype_string (b->type));
6233
6234   /* 3 */
6235   annotate_field (2);
6236   if (part_of_multiple)
6237     ui_out_field_skip (uiout, "disp");
6238   else
6239     ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
6240
6241
6242   /* 4 */
6243   annotate_field (3);
6244   if (part_of_multiple)
6245     ui_out_field_string (uiout, "enabled", loc->enabled ? "y" : "n");
6246   else
6247     ui_out_field_fmt (uiout, "enabled", "%c", 
6248                       bpenables[(int) b->enable_state]);
6249   ui_out_spaces (uiout, 2);
6250
6251   
6252   /* 5 and 6 */
6253   if (b->ops != NULL && b->ops->print_one != NULL)
6254     {
6255       /* Although the print_one can possibly print all locations,
6256          calling it here is not likely to get any nice result.  So,
6257          make sure there's just one location.  */
6258       gdb_assert (b->loc == NULL || b->loc->next == NULL);
6259       b->ops->print_one (b, last_loc);
6260     }
6261   else
6262     switch (b->type)
6263       {
6264       case bp_none:
6265         internal_error (__FILE__, __LINE__,
6266                         _("print_one_breakpoint: bp_none encountered\n"));
6267         break;
6268
6269       case bp_watchpoint:
6270       case bp_hardware_watchpoint:
6271       case bp_read_watchpoint:
6272       case bp_access_watchpoint:
6273         {
6274           struct watchpoint *w = (struct watchpoint *) b;
6275
6276           /* Field 4, the address, is omitted (which makes the columns
6277              not line up too nicely with the headers, but the effect
6278              is relatively readable).  */
6279           if (opts.addressprint)
6280             ui_out_field_skip (uiout, "addr");
6281           annotate_field (5);
6282           ui_out_field_string (uiout, "what", w->exp_string);
6283         }
6284         break;
6285
6286       case bp_breakpoint:
6287       case bp_hardware_breakpoint:
6288       case bp_single_step:
6289       case bp_until:
6290       case bp_finish:
6291       case bp_longjmp:
6292       case bp_longjmp_resume:
6293       case bp_longjmp_call_dummy:
6294       case bp_exception:
6295       case bp_exception_resume:
6296       case bp_step_resume:
6297       case bp_hp_step_resume:
6298       case bp_watchpoint_scope:
6299       case bp_call_dummy:
6300       case bp_std_terminate:
6301       case bp_shlib_event:
6302       case bp_thread_event:
6303       case bp_overlay_event:
6304       case bp_longjmp_master:
6305       case bp_std_terminate_master:
6306       case bp_exception_master:
6307       case bp_tracepoint:
6308       case bp_fast_tracepoint:
6309       case bp_static_tracepoint:
6310       case bp_dprintf:
6311       case bp_jit_event:
6312       case bp_gnu_ifunc_resolver:
6313       case bp_gnu_ifunc_resolver_return:
6314         if (opts.addressprint)
6315           {
6316             annotate_field (4);
6317             if (header_of_multiple)
6318               ui_out_field_string (uiout, "addr", "<MULTIPLE>");
6319             else if (b->loc == NULL || loc->shlib_disabled)
6320               ui_out_field_string (uiout, "addr", "<PENDING>");
6321             else
6322               ui_out_field_core_addr (uiout, "addr",
6323                                       loc->gdbarch, loc->address);
6324           }
6325         annotate_field (5);
6326         if (!header_of_multiple)
6327           print_breakpoint_location (b, loc);
6328         if (b->loc)
6329           *last_loc = b->loc;
6330         break;
6331       }
6332
6333
6334   if (loc != NULL && !header_of_multiple)
6335     {
6336       struct inferior *inf;
6337       VEC(int) *inf_num = NULL;
6338       int mi_only = 1;
6339
6340       ALL_INFERIORS (inf)
6341         {
6342           if (inf->pspace == loc->pspace)
6343             VEC_safe_push (int, inf_num, inf->num);
6344         }
6345
6346         /* For backward compatibility, don't display inferiors in CLI unless
6347            there are several.  Always display for MI. */
6348         if (allflag
6349             || (!gdbarch_has_global_breakpoints (target_gdbarch ())
6350                 && (number_of_program_spaces () > 1
6351                     || number_of_inferiors () > 1)
6352                 /* LOC is for existing B, it cannot be in
6353                    moribund_locations and thus having NULL OWNER.  */
6354                 && loc->owner->type != bp_catchpoint))
6355         mi_only = 0;
6356       output_thread_groups (uiout, "thread-groups", inf_num, mi_only);
6357       VEC_free (int, inf_num);
6358     }
6359
6360   if (!part_of_multiple)
6361     {
6362       if (b->thread != -1)
6363         {
6364           /* FIXME: This seems to be redundant and lost here; see the
6365              "stop only in" line a little further down.  */
6366           ui_out_text (uiout, " thread ");
6367           ui_out_field_int (uiout, "thread", b->thread);
6368         }
6369       else if (b->task != 0)
6370         {
6371           ui_out_text (uiout, " task ");
6372           ui_out_field_int (uiout, "task", b->task);
6373         }
6374     }
6375
6376   ui_out_text (uiout, "\n");
6377
6378   if (!part_of_multiple)
6379     b->ops->print_one_detail (b, uiout);
6380
6381   if (part_of_multiple && frame_id_p (b->frame_id))
6382     {
6383       annotate_field (6);
6384       ui_out_text (uiout, "\tstop only in stack frame at ");
6385       /* FIXME: cagney/2002-12-01: Shouldn't be poking around inside
6386          the frame ID.  */
6387       ui_out_field_core_addr (uiout, "frame",
6388                               b->gdbarch, b->frame_id.stack_addr);
6389       ui_out_text (uiout, "\n");
6390     }
6391   
6392   if (!part_of_multiple && b->cond_string)
6393     {
6394       annotate_field (7);
6395       if (is_tracepoint (b))
6396         ui_out_text (uiout, "\ttrace only if ");
6397       else
6398         ui_out_text (uiout, "\tstop only if ");
6399       ui_out_field_string (uiout, "cond", b->cond_string);
6400
6401       /* Print whether the target is doing the breakpoint's condition
6402          evaluation.  If GDB is doing the evaluation, don't print anything.  */
6403       if (is_breakpoint (b)
6404           && breakpoint_condition_evaluation_mode ()
6405           == condition_evaluation_target)
6406         {
6407           ui_out_text (uiout, " (");
6408           ui_out_field_string (uiout, "evaluated-by",
6409                                bp_condition_evaluator (b));
6410           ui_out_text (uiout, " evals)");
6411         }
6412       ui_out_text (uiout, "\n");
6413     }
6414
6415   if (!part_of_multiple && b->thread != -1)
6416     {
6417       /* FIXME should make an annotation for this.  */
6418       ui_out_text (uiout, "\tstop only in thread ");
6419       ui_out_field_int (uiout, "thread", b->thread);
6420       ui_out_text (uiout, "\n");
6421     }
6422   
6423   if (!part_of_multiple)
6424     {
6425       if (b->hit_count)
6426         {
6427           /* FIXME should make an annotation for this.  */
6428           if (is_catchpoint (b))
6429             ui_out_text (uiout, "\tcatchpoint");
6430           else if (is_tracepoint (b))
6431             ui_out_text (uiout, "\ttracepoint");
6432           else
6433             ui_out_text (uiout, "\tbreakpoint");
6434           ui_out_text (uiout, " already hit ");
6435           ui_out_field_int (uiout, "times", b->hit_count);
6436           if (b->hit_count == 1)
6437             ui_out_text (uiout, " time\n");
6438           else
6439             ui_out_text (uiout, " times\n");
6440         }
6441       else
6442         {
6443           /* Output the count also if it is zero, but only if this is mi.  */
6444           if (ui_out_is_mi_like_p (uiout))
6445             ui_out_field_int (uiout, "times", b->hit_count);
6446         }
6447     }
6448
6449   if (!part_of_multiple && b->ignore_count)
6450     {
6451       annotate_field (8);
6452       ui_out_text (uiout, "\tignore next ");
6453       ui_out_field_int (uiout, "ignore", b->ignore_count);
6454       ui_out_text (uiout, " hits\n");
6455     }
6456
6457   /* Note that an enable count of 1 corresponds to "enable once"
6458      behavior, which is reported by the combination of enablement and
6459      disposition, so we don't need to mention it here.  */
6460   if (!part_of_multiple && b->enable_count > 1)
6461     {
6462       annotate_field (8);
6463       ui_out_text (uiout, "\tdisable after ");
6464       /* Tweak the wording to clarify that ignore and enable counts
6465          are distinct, and have additive effect.  */
6466       if (b->ignore_count)
6467         ui_out_text (uiout, "additional ");
6468       else
6469         ui_out_text (uiout, "next ");
6470       ui_out_field_int (uiout, "enable", b->enable_count);
6471       ui_out_text (uiout, " hits\n");
6472     }
6473
6474   if (!part_of_multiple && is_tracepoint (b))
6475     {
6476       struct tracepoint *tp = (struct tracepoint *) b;
6477
6478       if (tp->traceframe_usage)
6479         {
6480           ui_out_text (uiout, "\ttrace buffer usage ");
6481           ui_out_field_int (uiout, "traceframe-usage", tp->traceframe_usage);
6482           ui_out_text (uiout, " bytes\n");
6483         }
6484     }
6485
6486   l = b->commands ? b->commands->commands : NULL;
6487   if (!part_of_multiple && l)
6488     {
6489       struct cleanup *script_chain;
6490
6491       annotate_field (9);
6492       script_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "script");
6493       print_command_lines (uiout, l, 4);
6494       do_cleanups (script_chain);
6495     }
6496
6497   if (is_tracepoint (b))
6498     {
6499       struct tracepoint *t = (struct tracepoint *) b;
6500
6501       if (!part_of_multiple && t->pass_count)
6502         {
6503           annotate_field (10);
6504           ui_out_text (uiout, "\tpass count ");
6505           ui_out_field_int (uiout, "pass", t->pass_count);
6506           ui_out_text (uiout, " \n");
6507         }
6508
6509       /* Don't display it when tracepoint or tracepoint location is
6510          pending.   */
6511       if (!header_of_multiple && loc != NULL && !loc->shlib_disabled)
6512         {
6513           annotate_field (11);
6514
6515           if (ui_out_is_mi_like_p (uiout))
6516             ui_out_field_string (uiout, "installed",
6517                                  loc->inserted ? "y" : "n");
6518           else
6519             {
6520               if (loc->inserted)
6521                 ui_out_text (uiout, "\t");
6522               else
6523                 ui_out_text (uiout, "\tnot ");
6524               ui_out_text (uiout, "installed on target\n");
6525             }
6526         }
6527     }
6528
6529   if (ui_out_is_mi_like_p (uiout) && !part_of_multiple)
6530     {
6531       if (is_watchpoint (b))
6532         {
6533           struct watchpoint *w = (struct watchpoint *) b;
6534
6535           ui_out_field_string (uiout, "original-location", w->exp_string);
6536         }
6537       else if (b->addr_string)
6538         ui_out_field_string (uiout, "original-location", b->addr_string);
6539     }
6540 }
6541
6542 static void
6543 print_one_breakpoint (struct breakpoint *b,
6544                       struct bp_location **last_loc, 
6545                       int allflag)
6546 {
6547   struct cleanup *bkpt_chain;
6548   struct ui_out *uiout = current_uiout;
6549
6550   bkpt_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "bkpt");
6551
6552   print_one_breakpoint_location (b, NULL, 0, last_loc, allflag);
6553   do_cleanups (bkpt_chain);
6554
6555   /* If this breakpoint has custom print function,
6556      it's already printed.  Otherwise, print individual
6557      locations, if any.  */
6558   if (b->ops == NULL || b->ops->print_one == NULL)
6559     {
6560       /* If breakpoint has a single location that is disabled, we
6561          print it as if it had several locations, since otherwise it's
6562          hard to represent "breakpoint enabled, location disabled"
6563          situation.
6564
6565          Note that while hardware watchpoints have several locations
6566          internally, that's not a property exposed to user.  */
6567       if (b->loc 
6568           && !is_hardware_watchpoint (b)
6569           && (b->loc->next || !b->loc->enabled))
6570         {
6571           struct bp_location *loc;
6572           int n = 1;
6573
6574           for (loc = b->loc; loc; loc = loc->next, ++n)
6575             {
6576               struct cleanup *inner2 =
6577                 make_cleanup_ui_out_tuple_begin_end (uiout, NULL);
6578               print_one_breakpoint_location (b, loc, n, last_loc, allflag);
6579               do_cleanups (inner2);
6580             }
6581         }
6582     }
6583 }
6584
6585 static int
6586 breakpoint_address_bits (struct breakpoint *b)
6587 {
6588   int print_address_bits = 0;
6589   struct bp_location *loc;
6590
6591   for (loc = b->loc; loc; loc = loc->next)
6592     {
6593       int addr_bit;
6594
6595       /* Software watchpoints that aren't watching memory don't have
6596          an address to print.  */
6597       if (b->type == bp_watchpoint && loc->watchpoint_type == -1)
6598         continue;
6599
6600       addr_bit = gdbarch_addr_bit (loc->gdbarch);
6601       if (addr_bit > print_address_bits)
6602         print_address_bits = addr_bit;
6603     }
6604
6605   return print_address_bits;
6606 }
6607
6608 struct captured_breakpoint_query_args
6609   {
6610     int bnum;
6611   };
6612
6613 static int
6614 do_captured_breakpoint_query (struct ui_out *uiout, void *data)
6615 {
6616   struct captured_breakpoint_query_args *args = data;
6617   struct breakpoint *b;
6618   struct bp_location *dummy_loc = NULL;
6619
6620   ALL_BREAKPOINTS (b)
6621     {
6622       if (args->bnum == b->number)
6623         {
6624           print_one_breakpoint (b, &dummy_loc, 0);
6625           return GDB_RC_OK;
6626         }
6627     }
6628   return GDB_RC_NONE;
6629 }
6630
6631 enum gdb_rc
6632 gdb_breakpoint_query (struct ui_out *uiout, int bnum, 
6633                       char **error_message)
6634 {
6635   struct captured_breakpoint_query_args args;
6636
6637   args.bnum = bnum;
6638   /* For the moment we don't trust print_one_breakpoint() to not throw
6639      an error.  */
6640   if (catch_exceptions_with_msg (uiout, do_captured_breakpoint_query, &args,
6641                                  error_message, RETURN_MASK_ALL) < 0)
6642     return GDB_RC_FAIL;
6643   else
6644     return GDB_RC_OK;
6645 }
6646
6647 /* Return true if this breakpoint was set by the user, false if it is
6648    internal or momentary.  */
6649
6650 int
6651 user_breakpoint_p (struct breakpoint *b)
6652 {
6653   return b->number > 0;
6654 }
6655
6656 /* Print information on user settable breakpoint (watchpoint, etc)
6657    number BNUM.  If BNUM is -1 print all user-settable breakpoints.
6658    If ALLFLAG is non-zero, include non-user-settable breakpoints.  If
6659    FILTER is non-NULL, call it on each breakpoint and only include the
6660    ones for which it returns non-zero.  Return the total number of
6661    breakpoints listed.  */
6662
6663 static int
6664 breakpoint_1 (char *args, int allflag, 
6665               int (*filter) (const struct breakpoint *))
6666 {
6667   struct breakpoint *b;
6668   struct bp_location *last_loc = NULL;
6669   int nr_printable_breakpoints;
6670   struct cleanup *bkpttbl_chain;
6671   struct value_print_options opts;
6672   int print_address_bits = 0;
6673   int print_type_col_width = 14;
6674   struct ui_out *uiout = current_uiout;
6675
6676   get_user_print_options (&opts);
6677
6678   /* Compute the number of rows in the table, as well as the size
6679      required for address fields.  */
6680   nr_printable_breakpoints = 0;
6681   ALL_BREAKPOINTS (b)
6682     {
6683       /* If we have a filter, only list the breakpoints it accepts.  */
6684       if (filter && !filter (b))
6685         continue;
6686
6687       /* If we have an "args" string, it is a list of breakpoints to 
6688          accept.  Skip the others.  */
6689       if (args != NULL && *args != '\0')
6690         {
6691           if (allflag && parse_and_eval_long (args) != b->number)
6692             continue;
6693           if (!allflag && !number_is_in_list (args, b->number))
6694             continue;
6695         }
6696
6697       if (allflag || user_breakpoint_p (b))
6698         {
6699           int addr_bit, type_len;
6700
6701           addr_bit = breakpoint_address_bits (b);
6702           if (addr_bit > print_address_bits)
6703             print_address_bits = addr_bit;
6704
6705           type_len = strlen (bptype_string (b->type));
6706           if (type_len > print_type_col_width)
6707             print_type_col_width = type_len;
6708
6709           nr_printable_breakpoints++;
6710         }
6711     }
6712
6713   if (opts.addressprint)
6714     bkpttbl_chain 
6715       = make_cleanup_ui_out_table_begin_end (uiout, 6,
6716                                              nr_printable_breakpoints,
6717                                              "BreakpointTable");
6718   else
6719     bkpttbl_chain 
6720       = make_cleanup_ui_out_table_begin_end (uiout, 5,
6721                                              nr_printable_breakpoints,
6722                                              "BreakpointTable");
6723
6724   if (nr_printable_breakpoints > 0)
6725     annotate_breakpoints_headers ();
6726   if (nr_printable_breakpoints > 0)
6727     annotate_field (0);
6728   ui_out_table_header (uiout, 7, ui_left, "number", "Num");     /* 1 */
6729   if (nr_printable_breakpoints > 0)
6730     annotate_field (1);
6731   ui_out_table_header (uiout, print_type_col_width, ui_left,
6732                        "type", "Type");                         /* 2 */
6733   if (nr_printable_breakpoints > 0)
6734     annotate_field (2);
6735   ui_out_table_header (uiout, 4, ui_left, "disp", "Disp");      /* 3 */
6736   if (nr_printable_breakpoints > 0)
6737     annotate_field (3);
6738   ui_out_table_header (uiout, 3, ui_left, "enabled", "Enb");    /* 4 */
6739   if (opts.addressprint)
6740     {
6741       if (nr_printable_breakpoints > 0)
6742         annotate_field (4);
6743       if (print_address_bits <= 32)
6744         ui_out_table_header (uiout, 10, ui_left, 
6745                              "addr", "Address");                /* 5 */
6746       else
6747         ui_out_table_header (uiout, 18, ui_left, 
6748                              "addr", "Address");                /* 5 */
6749     }
6750   if (nr_printable_breakpoints > 0)
6751     annotate_field (5);
6752   ui_out_table_header (uiout, 40, ui_noalign, "what", "What");  /* 6 */
6753   ui_out_table_body (uiout);
6754   if (nr_printable_breakpoints > 0)
6755     annotate_breakpoints_table ();
6756
6757   ALL_BREAKPOINTS (b)
6758     {
6759       QUIT;
6760       /* If we have a filter, only list the breakpoints it accepts.  */
6761       if (filter && !filter (b))
6762         continue;
6763
6764       /* If we have an "args" string, it is a list of breakpoints to 
6765          accept.  Skip the others.  */
6766
6767       if (args != NULL && *args != '\0')
6768         {
6769           if (allflag)  /* maintenance info breakpoint */
6770             {
6771               if (parse_and_eval_long (args) != b->number)
6772                 continue;
6773             }
6774           else          /* all others */
6775             {
6776               if (!number_is_in_list (args, b->number))
6777                 continue;
6778             }
6779         }
6780       /* We only print out user settable breakpoints unless the
6781          allflag is set.  */
6782       if (allflag || user_breakpoint_p (b))
6783         print_one_breakpoint (b, &last_loc, allflag);
6784     }
6785
6786   do_cleanups (bkpttbl_chain);
6787
6788   if (nr_printable_breakpoints == 0)
6789     {
6790       /* If there's a filter, let the caller decide how to report
6791          empty list.  */
6792       if (!filter)
6793         {
6794           if (args == NULL || *args == '\0')
6795             ui_out_message (uiout, 0, "No breakpoints or watchpoints.\n");
6796           else
6797             ui_out_message (uiout, 0, 
6798                             "No breakpoint or watchpoint matching '%s'.\n",
6799                             args);
6800         }
6801     }
6802   else
6803     {
6804       if (last_loc && !server_command)
6805         set_next_address (last_loc->gdbarch, last_loc->address);
6806     }
6807
6808   /* FIXME?  Should this be moved up so that it is only called when
6809      there have been breakpoints? */
6810   annotate_breakpoints_table_end ();
6811
6812   return nr_printable_breakpoints;
6813 }
6814
6815 /* Display the value of default-collect in a way that is generally
6816    compatible with the breakpoint list.  */
6817
6818 static void
6819 default_collect_info (void)
6820 {
6821   struct ui_out *uiout = current_uiout;
6822
6823   /* If it has no value (which is frequently the case), say nothing; a
6824      message like "No default-collect." gets in user's face when it's
6825      not wanted.  */
6826   if (!*default_collect)
6827     return;
6828
6829   /* The following phrase lines up nicely with per-tracepoint collect
6830      actions.  */
6831   ui_out_text (uiout, "default collect ");
6832   ui_out_field_string (uiout, "default-collect", default_collect);
6833   ui_out_text (uiout, " \n");
6834 }
6835   
6836 static void
6837 breakpoints_info (char *args, int from_tty)
6838 {
6839   breakpoint_1 (args, 0, NULL);
6840
6841   default_collect_info ();
6842 }
6843
6844 static void
6845 watchpoints_info (char *args, int from_tty)
6846 {
6847   int num_printed = breakpoint_1 (args, 0, is_watchpoint);
6848   struct ui_out *uiout = current_uiout;
6849
6850   if (num_printed == 0)
6851     {
6852       if (args == NULL || *args == '\0')
6853         ui_out_message (uiout, 0, "No watchpoints.\n");
6854       else
6855         ui_out_message (uiout, 0, "No watchpoint matching '%s'.\n", args);
6856     }
6857 }
6858
6859 static void
6860 maintenance_info_breakpoints (char *args, int from_tty)
6861 {
6862   breakpoint_1 (args, 1, NULL);
6863
6864   default_collect_info ();
6865 }
6866
6867 static int
6868 breakpoint_has_pc (struct breakpoint *b,
6869                    struct program_space *pspace,
6870                    CORE_ADDR pc, struct obj_section *section)
6871 {
6872   struct bp_location *bl = b->loc;
6873
6874   for (; bl; bl = bl->next)
6875     {
6876       if (bl->pspace == pspace
6877           && bl->address == pc
6878           && (!overlay_debugging || bl->section == section))
6879         return 1;         
6880     }
6881   return 0;
6882 }
6883
6884 /* Print a message describing any user-breakpoints set at PC.  This
6885    concerns with logical breakpoints, so we match program spaces, not
6886    address spaces.  */
6887
6888 static void
6889 describe_other_breakpoints (struct gdbarch *gdbarch,
6890                             struct program_space *pspace, CORE_ADDR pc,
6891                             struct obj_section *section, int thread)
6892 {
6893   int others = 0;
6894   struct breakpoint *b;
6895
6896   ALL_BREAKPOINTS (b)
6897     others += (user_breakpoint_p (b)
6898                && breakpoint_has_pc (b, pspace, pc, section));
6899   if (others > 0)
6900     {
6901       if (others == 1)
6902         printf_filtered (_("Note: breakpoint "));
6903       else /* if (others == ???) */
6904         printf_filtered (_("Note: breakpoints "));
6905       ALL_BREAKPOINTS (b)
6906         if (user_breakpoint_p (b) && breakpoint_has_pc (b, pspace, pc, section))
6907           {
6908             others--;
6909             printf_filtered ("%d", b->number);
6910             if (b->thread == -1 && thread != -1)
6911               printf_filtered (" (all threads)");
6912             else if (b->thread != -1)
6913               printf_filtered (" (thread %d)", b->thread);
6914             printf_filtered ("%s%s ",
6915                              ((b->enable_state == bp_disabled
6916                                || b->enable_state == bp_call_disabled)
6917                               ? " (disabled)"
6918                               : b->enable_state == bp_permanent 
6919                               ? " (permanent)"
6920                               : ""),
6921                              (others > 1) ? "," 
6922                              : ((others == 1) ? " and" : ""));
6923           }
6924       printf_filtered (_("also set at pc "));
6925       fputs_filtered (paddress (gdbarch, pc), gdb_stdout);
6926       printf_filtered (".\n");
6927     }
6928 }
6929 \f
6930
6931 /* Return true iff it is meaningful to use the address member of
6932    BPT.  For some breakpoint types, the address member is irrelevant
6933    and it makes no sense to attempt to compare it to other addresses
6934    (or use it for any other purpose either).
6935
6936    More specifically, each of the following breakpoint types will
6937    always have a zero valued address and we don't want to mark
6938    breakpoints of any of these types to be a duplicate of an actual
6939    breakpoint at address zero:
6940
6941       bp_watchpoint
6942       bp_catchpoint
6943
6944 */
6945
6946 static int
6947 breakpoint_address_is_meaningful (struct breakpoint *bpt)
6948 {
6949   enum bptype type = bpt->type;
6950
6951   return (type != bp_watchpoint && type != bp_catchpoint);
6952 }
6953
6954 /* Assuming LOC1 and LOC2's owners are hardware watchpoints, returns
6955    true if LOC1 and LOC2 represent the same watchpoint location.  */
6956
6957 static int
6958 watchpoint_locations_match (struct bp_location *loc1, 
6959                             struct bp_location *loc2)
6960 {
6961   struct watchpoint *w1 = (struct watchpoint *) loc1->owner;
6962   struct watchpoint *w2 = (struct watchpoint *) loc2->owner;
6963
6964   /* Both of them must exist.  */
6965   gdb_assert (w1 != NULL);
6966   gdb_assert (w2 != NULL);
6967
6968   /* If the target can evaluate the condition expression in hardware,
6969      then we we need to insert both watchpoints even if they are at
6970      the same place.  Otherwise the watchpoint will only trigger when
6971      the condition of whichever watchpoint was inserted evaluates to
6972      true, not giving a chance for GDB to check the condition of the
6973      other watchpoint.  */
6974   if ((w1->cond_exp
6975        && target_can_accel_watchpoint_condition (loc1->address, 
6976                                                  loc1->length,
6977                                                  loc1->watchpoint_type,
6978                                                  w1->cond_exp))
6979       || (w2->cond_exp
6980           && target_can_accel_watchpoint_condition (loc2->address, 
6981                                                     loc2->length,
6982                                                     loc2->watchpoint_type,
6983                                                     w2->cond_exp)))
6984     return 0;
6985
6986   /* Note that this checks the owner's type, not the location's.  In
6987      case the target does not support read watchpoints, but does
6988      support access watchpoints, we'll have bp_read_watchpoint
6989      watchpoints with hw_access locations.  Those should be considered
6990      duplicates of hw_read locations.  The hw_read locations will
6991      become hw_access locations later.  */
6992   return (loc1->owner->type == loc2->owner->type
6993           && loc1->pspace->aspace == loc2->pspace->aspace
6994           && loc1->address == loc2->address
6995           && loc1->length == loc2->length);
6996 }
6997
6998 /* See breakpoint.h.  */
6999
7000 int
7001 breakpoint_address_match (struct address_space *aspace1, CORE_ADDR addr1,
7002                           struct address_space *aspace2, CORE_ADDR addr2)
7003 {
7004   return ((gdbarch_has_global_breakpoints (target_gdbarch ())
7005            || aspace1 == aspace2)
7006           && addr1 == addr2);
7007 }
7008
7009 /* Returns true if {ASPACE2,ADDR2} falls within the range determined by
7010    {ASPACE1,ADDR1,LEN1}.  In most targets, this can only be true if ASPACE1
7011    matches ASPACE2.  On targets that have global breakpoints, the address
7012    space doesn't really matter.  */
7013
7014 static int
7015 breakpoint_address_match_range (struct address_space *aspace1, CORE_ADDR addr1,
7016                                 int len1, struct address_space *aspace2,
7017                                 CORE_ADDR addr2)
7018 {
7019   return ((gdbarch_has_global_breakpoints (target_gdbarch ())
7020            || aspace1 == aspace2)
7021           && addr2 >= addr1 && addr2 < addr1 + len1);
7022 }
7023
7024 /* Returns true if {ASPACE,ADDR} matches the breakpoint BL.  BL may be
7025    a ranged breakpoint.  In most targets, a match happens only if ASPACE
7026    matches the breakpoint's address space.  On targets that have global
7027    breakpoints, the address space doesn't really matter.  */
7028
7029 static int
7030 breakpoint_location_address_match (struct bp_location *bl,
7031                                    struct address_space *aspace,
7032                                    CORE_ADDR addr)
7033 {
7034   return (breakpoint_address_match (bl->pspace->aspace, bl->address,
7035                                     aspace, addr)
7036           || (bl->length
7037               && breakpoint_address_match_range (bl->pspace->aspace,
7038                                                  bl->address, bl->length,
7039                                                  aspace, addr)));
7040 }
7041
7042 /* If LOC1 and LOC2's owners are not tracepoints, returns false directly.
7043    Then, if LOC1 and LOC2 represent the same tracepoint location, returns
7044    true, otherwise returns false.  */
7045
7046 static int
7047 tracepoint_locations_match (struct bp_location *loc1,
7048                             struct bp_location *loc2)
7049 {
7050   if (is_tracepoint (loc1->owner) && is_tracepoint (loc2->owner))
7051     /* Since tracepoint locations are never duplicated with others', tracepoint
7052        locations at the same address of different tracepoints are regarded as
7053        different locations.  */
7054     return (loc1->address == loc2->address && loc1->owner == loc2->owner);
7055   else
7056     return 0;
7057 }
7058
7059 /* Assuming LOC1 and LOC2's types' have meaningful target addresses
7060    (breakpoint_address_is_meaningful), returns true if LOC1 and LOC2
7061    represent the same location.  */
7062
7063 static int
7064 breakpoint_locations_match (struct bp_location *loc1, 
7065                             struct bp_location *loc2)
7066 {
7067   int hw_point1, hw_point2;
7068
7069   /* Both of them must not be in moribund_locations.  */
7070   gdb_assert (loc1->owner != NULL);
7071   gdb_assert (loc2->owner != NULL);
7072
7073   hw_point1 = is_hardware_watchpoint (loc1->owner);
7074   hw_point2 = is_hardware_watchpoint (loc2->owner);
7075
7076   if (hw_point1 != hw_point2)
7077     return 0;
7078   else if (hw_point1)
7079     return watchpoint_locations_match (loc1, loc2);
7080   else if (is_tracepoint (loc1->owner) || is_tracepoint (loc2->owner))
7081     return tracepoint_locations_match (loc1, loc2);
7082   else
7083     /* We compare bp_location.length in order to cover ranged breakpoints.  */
7084     return (breakpoint_address_match (loc1->pspace->aspace, loc1->address,
7085                                      loc2->pspace->aspace, loc2->address)
7086             && loc1->length == loc2->length);
7087 }
7088
7089 static void
7090 breakpoint_adjustment_warning (CORE_ADDR from_addr, CORE_ADDR to_addr,
7091                                int bnum, int have_bnum)
7092 {
7093   /* The longest string possibly returned by hex_string_custom
7094      is 50 chars.  These must be at least that big for safety.  */
7095   char astr1[64];
7096   char astr2[64];
7097
7098   strcpy (astr1, hex_string_custom ((unsigned long) from_addr, 8));
7099   strcpy (astr2, hex_string_custom ((unsigned long) to_addr, 8));
7100   if (have_bnum)
7101     warning (_("Breakpoint %d address previously adjusted from %s to %s."),
7102              bnum, astr1, astr2);
7103   else
7104     warning (_("Breakpoint address adjusted from %s to %s."), astr1, astr2);
7105 }
7106
7107 /* Adjust a breakpoint's address to account for architectural
7108    constraints on breakpoint placement.  Return the adjusted address.
7109    Note: Very few targets require this kind of adjustment.  For most
7110    targets, this function is simply the identity function.  */
7111
7112 static CORE_ADDR
7113 adjust_breakpoint_address (struct gdbarch *gdbarch,
7114                            CORE_ADDR bpaddr, enum bptype bptype)
7115 {
7116   if (!gdbarch_adjust_breakpoint_address_p (gdbarch))
7117     {
7118       /* Very few targets need any kind of breakpoint adjustment.  */
7119       return bpaddr;
7120     }
7121   else if (bptype == bp_watchpoint
7122            || bptype == bp_hardware_watchpoint
7123            || bptype == bp_read_watchpoint
7124            || bptype == bp_access_watchpoint
7125            || bptype == bp_catchpoint)
7126     {
7127       /* Watchpoints and the various bp_catch_* eventpoints should not
7128          have their addresses modified.  */
7129       return bpaddr;
7130     }
7131   else if (bptype == bp_single_step)
7132     {
7133       /* Single-step breakpoints should not have their addresses
7134          modified.  If there's any architectural constrain that
7135          applies to this address, then it should have already been
7136          taken into account when the breakpoint was created in the
7137          first place.  If we didn't do this, stepping through e.g.,
7138          Thumb-2 IT blocks would break.  */
7139       return bpaddr;
7140     }
7141   else
7142     {
7143       CORE_ADDR adjusted_bpaddr;
7144
7145       /* Some targets have architectural constraints on the placement
7146          of breakpoint instructions.  Obtain the adjusted address.  */
7147       adjusted_bpaddr = gdbarch_adjust_breakpoint_address (gdbarch, bpaddr);
7148
7149       /* An adjusted breakpoint address can significantly alter
7150          a user's expectations.  Print a warning if an adjustment
7151          is required.  */
7152       if (adjusted_bpaddr != bpaddr)
7153         breakpoint_adjustment_warning (bpaddr, adjusted_bpaddr, 0, 0);
7154
7155       return adjusted_bpaddr;
7156     }
7157 }
7158
7159 void
7160 init_bp_location (struct bp_location *loc, const struct bp_location_ops *ops,
7161                   struct breakpoint *owner)
7162 {
7163   memset (loc, 0, sizeof (*loc));
7164
7165   gdb_assert (ops != NULL);
7166
7167   loc->ops = ops;
7168   loc->owner = owner;
7169   loc->cond = NULL;
7170   loc->cond_bytecode = NULL;
7171   loc->shlib_disabled = 0;
7172   loc->enabled = 1;
7173
7174   switch (owner->type)
7175     {
7176     case bp_breakpoint:
7177     case bp_single_step:
7178     case bp_until:
7179     case bp_finish:
7180     case bp_longjmp:
7181     case bp_longjmp_resume:
7182     case bp_longjmp_call_dummy:
7183     case bp_exception:
7184     case bp_exception_resume:
7185     case bp_step_resume:
7186     case bp_hp_step_resume:
7187     case bp_watchpoint_scope:
7188     case bp_call_dummy:
7189     case bp_std_terminate:
7190     case bp_shlib_event:
7191     case bp_thread_event:
7192     case bp_overlay_event:
7193     case bp_jit_event:
7194     case bp_longjmp_master:
7195     case bp_std_terminate_master:
7196     case bp_exception_master:
7197     case bp_gnu_ifunc_resolver:
7198     case bp_gnu_ifunc_resolver_return:
7199     case bp_dprintf:
7200       loc->loc_type = bp_loc_software_breakpoint;
7201       mark_breakpoint_location_modified (loc);
7202       break;
7203     case bp_hardware_breakpoint:
7204       loc->loc_type = bp_loc_hardware_breakpoint;
7205       mark_breakpoint_location_modified (loc);
7206       break;
7207     case bp_hardware_watchpoint:
7208     case bp_read_watchpoint:
7209     case bp_access_watchpoint:
7210       loc->loc_type = bp_loc_hardware_watchpoint;
7211       break;
7212     case bp_watchpoint:
7213     case bp_catchpoint:
7214     case bp_tracepoint:
7215     case bp_fast_tracepoint:
7216     case bp_static_tracepoint:
7217       loc->loc_type = bp_loc_other;
7218       break;
7219     default:
7220       internal_error (__FILE__, __LINE__, _("unknown breakpoint type"));
7221     }
7222
7223   loc->refc = 1;
7224 }
7225
7226 /* Allocate a struct bp_location.  */
7227
7228 static struct bp_location *
7229 allocate_bp_location (struct breakpoint *bpt)
7230 {
7231   return bpt->ops->allocate_location (bpt);
7232 }
7233
7234 static void
7235 free_bp_location (struct bp_location *loc)
7236 {
7237   loc->ops->dtor (loc);
7238   xfree (loc);
7239 }
7240
7241 /* Increment reference count.  */
7242
7243 static void
7244 incref_bp_location (struct bp_location *bl)
7245 {
7246   ++bl->refc;
7247 }
7248
7249 /* Decrement reference count.  If the reference count reaches 0,
7250    destroy the bp_location.  Sets *BLP to NULL.  */
7251
7252 static void
7253 decref_bp_location (struct bp_location **blp)
7254 {
7255   gdb_assert ((*blp)->refc > 0);
7256
7257   if (--(*blp)->refc == 0)
7258     free_bp_location (*blp);
7259   *blp = NULL;
7260 }
7261
7262 /* Add breakpoint B at the end of the global breakpoint chain.  */
7263
7264 static void
7265 add_to_breakpoint_chain (struct breakpoint *b)
7266 {
7267   struct breakpoint *b1;
7268
7269   /* Add this breakpoint to the end of the chain so that a list of
7270      breakpoints will come out in order of increasing numbers.  */
7271
7272   b1 = breakpoint_chain;
7273   if (b1 == 0)
7274     breakpoint_chain = b;
7275   else
7276     {
7277       while (b1->next)
7278         b1 = b1->next;
7279       b1->next = b;
7280     }
7281 }
7282
7283 /* Initializes breakpoint B with type BPTYPE and no locations yet.  */
7284
7285 static void
7286 init_raw_breakpoint_without_location (struct breakpoint *b,
7287                                       struct gdbarch *gdbarch,
7288                                       enum bptype bptype,
7289                                       const struct breakpoint_ops *ops)
7290 {
7291   memset (b, 0, sizeof (*b));
7292
7293   gdb_assert (ops != NULL);
7294
7295   b->ops = ops;
7296   b->type = bptype;
7297   b->gdbarch = gdbarch;
7298   b->language = current_language->la_language;
7299   b->input_radix = input_radix;
7300   b->thread = -1;
7301   b->enable_state = bp_enabled;
7302   b->next = 0;
7303   b->silent = 0;
7304   b->ignore_count = 0;
7305   b->commands = NULL;
7306   b->frame_id = null_frame_id;
7307   b->condition_not_parsed = 0;
7308   b->py_bp_object = NULL;
7309   b->related_breakpoint = b;
7310 }
7311
7312 /* Helper to set_raw_breakpoint below.  Creates a breakpoint
7313    that has type BPTYPE and has no locations as yet.  */
7314
7315 static struct breakpoint *
7316 set_raw_breakpoint_without_location (struct gdbarch *gdbarch,
7317                                      enum bptype bptype,
7318                                      const struct breakpoint_ops *ops)
7319 {
7320   struct breakpoint *b = XNEW (struct breakpoint);
7321
7322   init_raw_breakpoint_without_location (b, gdbarch, bptype, ops);
7323   add_to_breakpoint_chain (b);
7324   return b;
7325 }
7326
7327 /* Initialize loc->function_name.  EXPLICIT_LOC says no indirect function
7328    resolutions should be made as the user specified the location explicitly
7329    enough.  */
7330
7331 static void
7332 set_breakpoint_location_function (struct bp_location *loc, int explicit_loc)
7333 {
7334   gdb_assert (loc->owner != NULL);
7335
7336   if (loc->owner->type == bp_breakpoint
7337       || loc->owner->type == bp_hardware_breakpoint
7338       || is_tracepoint (loc->owner))
7339     {
7340       int is_gnu_ifunc;
7341       const char *function_name;
7342       CORE_ADDR func_addr;
7343
7344       find_pc_partial_function_gnu_ifunc (loc->address, &function_name,
7345                                           &func_addr, NULL, &is_gnu_ifunc);
7346
7347       if (is_gnu_ifunc && !explicit_loc)
7348         {
7349           struct breakpoint *b = loc->owner;
7350
7351           gdb_assert (loc->pspace == current_program_space);
7352           if (gnu_ifunc_resolve_name (function_name,
7353                                       &loc->requested_address))
7354             {
7355               /* Recalculate ADDRESS based on new REQUESTED_ADDRESS.  */
7356               loc->address = adjust_breakpoint_address (loc->gdbarch,
7357                                                         loc->requested_address,
7358                                                         b->type);
7359             }
7360           else if (b->type == bp_breakpoint && b->loc == loc
7361                    && loc->next == NULL && b->related_breakpoint == b)
7362             {
7363               /* Create only the whole new breakpoint of this type but do not
7364                  mess more complicated breakpoints with multiple locations.  */
7365               b->type = bp_gnu_ifunc_resolver;
7366               /* Remember the resolver's address for use by the return
7367                  breakpoint.  */
7368               loc->related_address = func_addr;
7369             }
7370         }
7371
7372       if (function_name)
7373         loc->function_name = xstrdup (function_name);
7374     }
7375 }
7376
7377 /* Attempt to determine architecture of location identified by SAL.  */
7378 struct gdbarch *
7379 get_sal_arch (struct symtab_and_line sal)
7380 {
7381   if (sal.section)
7382     return get_objfile_arch (sal.section->objfile);
7383   if (sal.symtab)
7384     return get_objfile_arch (sal.symtab->objfile);
7385
7386   return NULL;
7387 }
7388
7389 /* Low level routine for partially initializing a breakpoint of type
7390    BPTYPE.  The newly created breakpoint's address, section, source
7391    file name, and line number are provided by SAL.
7392
7393    It is expected that the caller will complete the initialization of
7394    the newly created breakpoint struct as well as output any status
7395    information regarding the creation of a new breakpoint.  */
7396
7397 static void
7398 init_raw_breakpoint (struct breakpoint *b, struct gdbarch *gdbarch,
7399                      struct symtab_and_line sal, enum bptype bptype,
7400                      const struct breakpoint_ops *ops)
7401 {
7402   init_raw_breakpoint_without_location (b, gdbarch, bptype, ops);
7403
7404   add_location_to_breakpoint (b, &sal);
7405
7406   if (bptype != bp_catchpoint)
7407     gdb_assert (sal.pspace != NULL);
7408
7409   /* Store the program space that was used to set the breakpoint,
7410      except for ordinary breakpoints, which are independent of the
7411      program space.  */
7412   if (bptype != bp_breakpoint && bptype != bp_hardware_breakpoint)
7413     b->pspace = sal.pspace;
7414 }
7415
7416 /* set_raw_breakpoint is a low level routine for allocating and
7417    partially initializing a breakpoint of type BPTYPE.  The newly
7418    created breakpoint's address, section, source file name, and line
7419    number are provided by SAL.  The newly created and partially
7420    initialized breakpoint is added to the breakpoint chain and
7421    is also returned as the value of this function.
7422
7423    It is expected that the caller will complete the initialization of
7424    the newly created breakpoint struct as well as output any status
7425    information regarding the creation of a new breakpoint.  In
7426    particular, set_raw_breakpoint does NOT set the breakpoint
7427    number!  Care should be taken to not allow an error to occur
7428    prior to completing the initialization of the breakpoint.  If this
7429    should happen, a bogus breakpoint will be left on the chain.  */
7430
7431 struct breakpoint *
7432 set_raw_breakpoint (struct gdbarch *gdbarch,
7433                     struct symtab_and_line sal, enum bptype bptype,
7434                     const struct breakpoint_ops *ops)
7435 {
7436   struct breakpoint *b = XNEW (struct breakpoint);
7437
7438   init_raw_breakpoint (b, gdbarch, sal, bptype, ops);
7439   add_to_breakpoint_chain (b);
7440   return b;
7441 }
7442
7443
7444 /* Note that the breakpoint object B describes a permanent breakpoint
7445    instruction, hard-wired into the inferior's code.  */
7446 void
7447 make_breakpoint_permanent (struct breakpoint *b)
7448 {
7449   struct bp_location *bl;
7450
7451   b->enable_state = bp_permanent;
7452
7453   /* By definition, permanent breakpoints are already present in the
7454      code.  Mark all locations as inserted.  For now,
7455      make_breakpoint_permanent is called in just one place, so it's
7456      hard to say if it's reasonable to have permanent breakpoint with
7457      multiple locations or not, but it's easy to implement.  */
7458   for (bl = b->loc; bl; bl = bl->next)
7459     bl->inserted = 1;
7460 }
7461
7462 /* Call this routine when stepping and nexting to enable a breakpoint
7463    if we do a longjmp() or 'throw' in TP.  FRAME is the frame which
7464    initiated the operation.  */
7465
7466 void
7467 set_longjmp_breakpoint (struct thread_info *tp, struct frame_id frame)
7468 {
7469   struct breakpoint *b, *b_tmp;
7470   int thread = tp->num;
7471
7472   /* To avoid having to rescan all objfile symbols at every step,
7473      we maintain a list of continually-inserted but always disabled
7474      longjmp "master" breakpoints.  Here, we simply create momentary
7475      clones of those and enable them for the requested thread.  */
7476   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7477     if (b->pspace == current_program_space
7478         && (b->type == bp_longjmp_master
7479             || b->type == bp_exception_master))
7480       {
7481         enum bptype type = b->type == bp_longjmp_master ? bp_longjmp : bp_exception;
7482         struct breakpoint *clone;
7483
7484         /* longjmp_breakpoint_ops ensures INITIATING_FRAME is cleared again
7485            after their removal.  */
7486         clone = momentary_breakpoint_from_master (b, type,
7487                                                   &longjmp_breakpoint_ops, 1);
7488         clone->thread = thread;
7489       }
7490
7491   tp->initiating_frame = frame;
7492 }
7493
7494 /* Delete all longjmp breakpoints from THREAD.  */
7495 void
7496 delete_longjmp_breakpoint (int thread)
7497 {
7498   struct breakpoint *b, *b_tmp;
7499
7500   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7501     if (b->type == bp_longjmp || b->type == bp_exception)
7502       {
7503         if (b->thread == thread)
7504           delete_breakpoint (b);
7505       }
7506 }
7507
7508 void
7509 delete_longjmp_breakpoint_at_next_stop (int thread)
7510 {
7511   struct breakpoint *b, *b_tmp;
7512
7513   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7514     if (b->type == bp_longjmp || b->type == bp_exception)
7515       {
7516         if (b->thread == thread)
7517           b->disposition = disp_del_at_next_stop;
7518       }
7519 }
7520
7521 /* Place breakpoints of type bp_longjmp_call_dummy to catch longjmp for
7522    INFERIOR_PTID thread.  Chain them all by RELATED_BREAKPOINT and return
7523    pointer to any of them.  Return NULL if this system cannot place longjmp
7524    breakpoints.  */
7525
7526 struct breakpoint *
7527 set_longjmp_breakpoint_for_call_dummy (void)
7528 {
7529   struct breakpoint *b, *retval = NULL;
7530
7531   ALL_BREAKPOINTS (b)
7532     if (b->pspace == current_program_space && b->type == bp_longjmp_master)
7533       {
7534         struct breakpoint *new_b;
7535
7536         new_b = momentary_breakpoint_from_master (b, bp_longjmp_call_dummy,
7537                                                   &momentary_breakpoint_ops,
7538                                                   1);
7539         new_b->thread = pid_to_thread_id (inferior_ptid);
7540
7541         /* Link NEW_B into the chain of RETVAL breakpoints.  */
7542
7543         gdb_assert (new_b->related_breakpoint == new_b);
7544         if (retval == NULL)
7545           retval = new_b;
7546         new_b->related_breakpoint = retval;
7547         while (retval->related_breakpoint != new_b->related_breakpoint)
7548           retval = retval->related_breakpoint;
7549         retval->related_breakpoint = new_b;
7550       }
7551
7552   return retval;
7553 }
7554
7555 /* Verify all existing dummy frames and their associated breakpoints for
7556    TP.  Remove those which can no longer be found in the current frame
7557    stack.
7558
7559    You should call this function only at places where it is safe to currently
7560    unwind the whole stack.  Failed stack unwind would discard live dummy
7561    frames.  */
7562
7563 void
7564 check_longjmp_breakpoint_for_call_dummy (struct thread_info *tp)
7565 {
7566   struct breakpoint *b, *b_tmp;
7567
7568   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7569     if (b->type == bp_longjmp_call_dummy && b->thread == tp->num)
7570       {
7571         struct breakpoint *dummy_b = b->related_breakpoint;
7572
7573         while (dummy_b != b && dummy_b->type != bp_call_dummy)
7574           dummy_b = dummy_b->related_breakpoint;
7575         if (dummy_b->type != bp_call_dummy
7576             || frame_find_by_id (dummy_b->frame_id) != NULL)
7577           continue;
7578         
7579         dummy_frame_discard (dummy_b->frame_id, tp->ptid);
7580
7581         while (b->related_breakpoint != b)
7582           {
7583             if (b_tmp == b->related_breakpoint)
7584               b_tmp = b->related_breakpoint->next;
7585             delete_breakpoint (b->related_breakpoint);
7586           }
7587         delete_breakpoint (b);
7588       }
7589 }
7590
7591 void
7592 enable_overlay_breakpoints (void)
7593 {
7594   struct breakpoint *b;
7595
7596   ALL_BREAKPOINTS (b)
7597     if (b->type == bp_overlay_event)
7598     {
7599       b->enable_state = bp_enabled;
7600       update_global_location_list (UGLL_MAY_INSERT);
7601       overlay_events_enabled = 1;
7602     }
7603 }
7604
7605 void
7606 disable_overlay_breakpoints (void)
7607 {
7608   struct breakpoint *b;
7609
7610   ALL_BREAKPOINTS (b)
7611     if (b->type == bp_overlay_event)
7612     {
7613       b->enable_state = bp_disabled;
7614       update_global_location_list (UGLL_DONT_INSERT);
7615       overlay_events_enabled = 0;
7616     }
7617 }
7618
7619 /* Set an active std::terminate breakpoint for each std::terminate
7620    master breakpoint.  */
7621 void
7622 set_std_terminate_breakpoint (void)
7623 {
7624   struct breakpoint *b, *b_tmp;
7625
7626   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7627     if (b->pspace == current_program_space
7628         && b->type == bp_std_terminate_master)
7629       {
7630         momentary_breakpoint_from_master (b, bp_std_terminate,
7631                                           &momentary_breakpoint_ops, 1);
7632       }
7633 }
7634
7635 /* Delete all the std::terminate breakpoints.  */
7636 void
7637 delete_std_terminate_breakpoint (void)
7638 {
7639   struct breakpoint *b, *b_tmp;
7640
7641   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7642     if (b->type == bp_std_terminate)
7643       delete_breakpoint (b);
7644 }
7645
7646 struct breakpoint *
7647 create_thread_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7648 {
7649   struct breakpoint *b;
7650
7651   b = create_internal_breakpoint (gdbarch, address, bp_thread_event,
7652                                   &internal_breakpoint_ops);
7653
7654   b->enable_state = bp_enabled;
7655   /* addr_string has to be used or breakpoint_re_set will delete me.  */
7656   b->addr_string
7657     = xstrprintf ("*%s", paddress (b->loc->gdbarch, b->loc->address));
7658
7659   update_global_location_list_nothrow (UGLL_MAY_INSERT);
7660
7661   return b;
7662 }
7663
7664 void
7665 remove_thread_event_breakpoints (void)
7666 {
7667   struct breakpoint *b, *b_tmp;
7668
7669   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7670     if (b->type == bp_thread_event
7671         && b->loc->pspace == current_program_space)
7672       delete_breakpoint (b);
7673 }
7674
7675 struct lang_and_radix
7676   {
7677     enum language lang;
7678     int radix;
7679   };
7680
7681 /* Create a breakpoint for JIT code registration and unregistration.  */
7682
7683 struct breakpoint *
7684 create_jit_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7685 {
7686   struct breakpoint *b;
7687
7688   b = create_internal_breakpoint (gdbarch, address, bp_jit_event,
7689                                   &internal_breakpoint_ops);
7690   update_global_location_list_nothrow (UGLL_MAY_INSERT);
7691   return b;
7692 }
7693
7694 /* Remove JIT code registration and unregistration breakpoint(s).  */
7695
7696 void
7697 remove_jit_event_breakpoints (void)
7698 {
7699   struct breakpoint *b, *b_tmp;
7700
7701   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7702     if (b->type == bp_jit_event
7703         && b->loc->pspace == current_program_space)
7704       delete_breakpoint (b);
7705 }
7706
7707 void
7708 remove_solib_event_breakpoints (void)
7709 {
7710   struct breakpoint *b, *b_tmp;
7711
7712   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7713     if (b->type == bp_shlib_event
7714         && b->loc->pspace == current_program_space)
7715       delete_breakpoint (b);
7716 }
7717
7718 /* See breakpoint.h.  */
7719
7720 void
7721 remove_solib_event_breakpoints_at_next_stop (void)
7722 {
7723   struct breakpoint *b, *b_tmp;
7724
7725   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7726     if (b->type == bp_shlib_event
7727         && b->loc->pspace == current_program_space)
7728       b->disposition = disp_del_at_next_stop;
7729 }
7730
7731 /* Helper for create_solib_event_breakpoint /
7732    create_and_insert_solib_event_breakpoint.  Allows specifying which
7733    INSERT_MODE to pass through to update_global_location_list.  */
7734
7735 static struct breakpoint *
7736 create_solib_event_breakpoint_1 (struct gdbarch *gdbarch, CORE_ADDR address,
7737                                  enum ugll_insert_mode insert_mode)
7738 {
7739   struct breakpoint *b;
7740
7741   b = create_internal_breakpoint (gdbarch, address, bp_shlib_event,
7742                                   &internal_breakpoint_ops);
7743   update_global_location_list_nothrow (insert_mode);
7744   return b;
7745 }
7746
7747 struct breakpoint *
7748 create_solib_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7749 {
7750   return create_solib_event_breakpoint_1 (gdbarch, address, UGLL_MAY_INSERT);
7751 }
7752
7753 /* See breakpoint.h.  */
7754
7755 struct breakpoint *
7756 create_and_insert_solib_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7757 {
7758   struct breakpoint *b;
7759
7760   /* Explicitly tell update_global_location_list to insert
7761      locations.  */
7762   b = create_solib_event_breakpoint_1 (gdbarch, address, UGLL_INSERT);
7763   if (!b->loc->inserted)
7764     {
7765       delete_breakpoint (b);
7766       return NULL;
7767     }
7768   return b;
7769 }
7770
7771 /* Disable any breakpoints that are on code in shared libraries.  Only
7772    apply to enabled breakpoints, disabled ones can just stay disabled.  */
7773
7774 void
7775 disable_breakpoints_in_shlibs (void)
7776 {
7777   struct bp_location *loc, **locp_tmp;
7778
7779   ALL_BP_LOCATIONS (loc, locp_tmp)
7780   {
7781     /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
7782     struct breakpoint *b = loc->owner;
7783
7784     /* We apply the check to all breakpoints, including disabled for
7785        those with loc->duplicate set.  This is so that when breakpoint
7786        becomes enabled, or the duplicate is removed, gdb will try to
7787        insert all breakpoints.  If we don't set shlib_disabled here,
7788        we'll try to insert those breakpoints and fail.  */
7789     if (((b->type == bp_breakpoint)
7790          || (b->type == bp_jit_event)
7791          || (b->type == bp_hardware_breakpoint)
7792          || (is_tracepoint (b)))
7793         && loc->pspace == current_program_space
7794         && !loc->shlib_disabled
7795         && solib_name_from_address (loc->pspace, loc->address)
7796         )
7797       {
7798         loc->shlib_disabled = 1;
7799       }
7800   }
7801 }
7802
7803 /* Disable any breakpoints and tracepoints that are in SOLIB upon
7804    notification of unloaded_shlib.  Only apply to enabled breakpoints,
7805    disabled ones can just stay disabled.  */
7806
7807 static void
7808 disable_breakpoints_in_unloaded_shlib (struct so_list *solib)
7809 {
7810   struct bp_location *loc, **locp_tmp;
7811   int disabled_shlib_breaks = 0;
7812
7813   /* SunOS a.out shared libraries are always mapped, so do not
7814      disable breakpoints; they will only be reported as unloaded
7815      through clear_solib when GDB discards its shared library
7816      list.  See clear_solib for more information.  */
7817   if (exec_bfd != NULL
7818       && bfd_get_flavour (exec_bfd) == bfd_target_aout_flavour)
7819     return;
7820
7821   ALL_BP_LOCATIONS (loc, locp_tmp)
7822   {
7823     /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
7824     struct breakpoint *b = loc->owner;
7825
7826     if (solib->pspace == loc->pspace
7827         && !loc->shlib_disabled
7828         && (((b->type == bp_breakpoint
7829               || b->type == bp_jit_event
7830               || b->type == bp_hardware_breakpoint)
7831              && (loc->loc_type == bp_loc_hardware_breakpoint
7832                  || loc->loc_type == bp_loc_software_breakpoint))
7833             || is_tracepoint (b))
7834         && solib_contains_address_p (solib, loc->address))
7835       {
7836         loc->shlib_disabled = 1;
7837         /* At this point, we cannot rely on remove_breakpoint
7838            succeeding so we must mark the breakpoint as not inserted
7839            to prevent future errors occurring in remove_breakpoints.  */
7840         loc->inserted = 0;
7841
7842         /* This may cause duplicate notifications for the same breakpoint.  */
7843         observer_notify_breakpoint_modified (b);
7844
7845         if (!disabled_shlib_breaks)
7846           {
7847             target_terminal_ours_for_output ();
7848             warning (_("Temporarily disabling breakpoints "
7849                        "for unloaded shared library \"%s\""),
7850                      solib->so_name);
7851           }
7852         disabled_shlib_breaks = 1;
7853       }
7854   }
7855 }
7856
7857 /* Disable any breakpoints and tracepoints in OBJFILE upon
7858    notification of free_objfile.  Only apply to enabled breakpoints,
7859    disabled ones can just stay disabled.  */
7860
7861 static void
7862 disable_breakpoints_in_freed_objfile (struct objfile *objfile)
7863 {
7864   struct breakpoint *b;
7865
7866   if (objfile == NULL)
7867     return;
7868
7869   /* OBJF_SHARED|OBJF_USERLOADED objfiles are dynamic modules manually
7870      managed by the user with add-symbol-file/remove-symbol-file.
7871      Similarly to how breakpoints in shared libraries are handled in
7872      response to "nosharedlibrary", mark breakpoints in such modules
7873      shlib_disabled so they end up uninserted on the next global
7874      location list update.  Shared libraries not loaded by the user
7875      aren't handled here -- they're already handled in
7876      disable_breakpoints_in_unloaded_shlib, called by solib.c's
7877      solib_unloaded observer.  We skip objfiles that are not
7878      OBJF_SHARED as those aren't considered dynamic objects (e.g. the
7879      main objfile).  */
7880   if ((objfile->flags & OBJF_SHARED) == 0
7881       || (objfile->flags & OBJF_USERLOADED) == 0)
7882     return;
7883
7884   ALL_BREAKPOINTS (b)
7885     {
7886       struct bp_location *loc;
7887       int bp_modified = 0;
7888
7889       if (!is_breakpoint (b) && !is_tracepoint (b))
7890         continue;
7891
7892       for (loc = b->loc; loc != NULL; loc = loc->next)
7893         {
7894           CORE_ADDR loc_addr = loc->address;
7895
7896           if (loc->loc_type != bp_loc_hardware_breakpoint
7897               && loc->loc_type != bp_loc_software_breakpoint)
7898             continue;
7899
7900           if (loc->shlib_disabled != 0)
7901             continue;
7902
7903           if (objfile->pspace != loc->pspace)
7904             continue;
7905
7906           if (loc->loc_type != bp_loc_hardware_breakpoint
7907               && loc->loc_type != bp_loc_software_breakpoint)
7908             continue;
7909
7910           if (is_addr_in_objfile (loc_addr, objfile))
7911             {
7912               loc->shlib_disabled = 1;
7913               /* At this point, we don't know whether the object was
7914                  unmapped from the inferior or not, so leave the
7915                  inserted flag alone.  We'll handle failure to
7916                  uninsert quietly, in case the object was indeed
7917                  unmapped.  */
7918
7919               mark_breakpoint_location_modified (loc);
7920
7921               bp_modified = 1;
7922             }
7923         }
7924
7925       if (bp_modified)
7926         observer_notify_breakpoint_modified (b);
7927     }
7928 }
7929
7930 /* FORK & VFORK catchpoints.  */
7931
7932 /* An instance of this type is used to represent a fork or vfork
7933    catchpoint.  It includes a "struct breakpoint" as a kind of base
7934    class; users downcast to "struct breakpoint *" when needed.  A
7935    breakpoint is really of this type iff its ops pointer points to
7936    CATCH_FORK_BREAKPOINT_OPS.  */
7937
7938 struct fork_catchpoint
7939 {
7940   /* The base class.  */
7941   struct breakpoint base;
7942
7943   /* Process id of a child process whose forking triggered this
7944      catchpoint.  This field is only valid immediately after this
7945      catchpoint has triggered.  */
7946   ptid_t forked_inferior_pid;
7947 };
7948
7949 /* Implement the "insert" breakpoint_ops method for fork
7950    catchpoints.  */
7951
7952 static int
7953 insert_catch_fork (struct bp_location *bl)
7954 {
7955   return target_insert_fork_catchpoint (ptid_get_pid (inferior_ptid));
7956 }
7957
7958 /* Implement the "remove" breakpoint_ops method for fork
7959    catchpoints.  */
7960
7961 static int
7962 remove_catch_fork (struct bp_location *bl)
7963 {
7964   return target_remove_fork_catchpoint (ptid_get_pid (inferior_ptid));
7965 }
7966
7967 /* Implement the "breakpoint_hit" breakpoint_ops method for fork
7968    catchpoints.  */
7969
7970 static int
7971 breakpoint_hit_catch_fork (const struct bp_location *bl,
7972                            struct address_space *aspace, CORE_ADDR bp_addr,
7973                            const struct target_waitstatus *ws)
7974 {
7975   struct fork_catchpoint *c = (struct fork_catchpoint *) bl->owner;
7976
7977   if (ws->kind != TARGET_WAITKIND_FORKED)
7978     return 0;
7979
7980   c->forked_inferior_pid = ws->value.related_pid;
7981   return 1;
7982 }
7983
7984 /* Implement the "print_it" breakpoint_ops method for fork
7985    catchpoints.  */
7986
7987 static enum print_stop_action
7988 print_it_catch_fork (bpstat bs)
7989 {
7990   struct ui_out *uiout = current_uiout;
7991   struct breakpoint *b = bs->breakpoint_at;
7992   struct fork_catchpoint *c = (struct fork_catchpoint *) bs->breakpoint_at;
7993
7994   annotate_catchpoint (b->number);
7995   if (b->disposition == disp_del)
7996     ui_out_text (uiout, "\nTemporary catchpoint ");
7997   else
7998     ui_out_text (uiout, "\nCatchpoint ");
7999   if (ui_out_is_mi_like_p (uiout))
8000     {
8001       ui_out_field_string (uiout, "reason",
8002                            async_reason_lookup (EXEC_ASYNC_FORK));
8003       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
8004     }
8005   ui_out_field_int (uiout, "bkptno", b->number);
8006   ui_out_text (uiout, " (forked process ");
8007   ui_out_field_int (uiout, "newpid", ptid_get_pid (c->forked_inferior_pid));
8008   ui_out_text (uiout, "), ");
8009   return PRINT_SRC_AND_LOC;
8010 }
8011
8012 /* Implement the "print_one" breakpoint_ops method for fork
8013    catchpoints.  */
8014
8015 static void
8016 print_one_catch_fork (struct breakpoint *b, struct bp_location **last_loc)
8017 {
8018   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
8019   struct value_print_options opts;
8020   struct ui_out *uiout = current_uiout;
8021
8022   get_user_print_options (&opts);
8023
8024   /* Field 4, the address, is omitted (which makes the columns not
8025      line up too nicely with the headers, but the effect is relatively
8026      readable).  */
8027   if (opts.addressprint)
8028     ui_out_field_skip (uiout, "addr");
8029   annotate_field (5);
8030   ui_out_text (uiout, "fork");
8031   if (!ptid_equal (c->forked_inferior_pid, null_ptid))
8032     {
8033       ui_out_text (uiout, ", process ");
8034       ui_out_field_int (uiout, "what",
8035                         ptid_get_pid (c->forked_inferior_pid));
8036       ui_out_spaces (uiout, 1);
8037     }
8038
8039   if (ui_out_is_mi_like_p (uiout))
8040     ui_out_field_string (uiout, "catch-type", "fork");
8041 }
8042
8043 /* Implement the "print_mention" breakpoint_ops method for fork
8044    catchpoints.  */
8045
8046 static void
8047 print_mention_catch_fork (struct breakpoint *b)
8048 {
8049   printf_filtered (_("Catchpoint %d (fork)"), b->number);
8050 }
8051
8052 /* Implement the "print_recreate" breakpoint_ops method for fork
8053    catchpoints.  */
8054
8055 static void
8056 print_recreate_catch_fork (struct breakpoint *b, struct ui_file *fp)
8057 {
8058   fprintf_unfiltered (fp, "catch fork");
8059   print_recreate_thread (b, fp);
8060 }
8061
8062 /* The breakpoint_ops structure to be used in fork catchpoints.  */
8063
8064 static struct breakpoint_ops catch_fork_breakpoint_ops;
8065
8066 /* Implement the "insert" breakpoint_ops method for vfork
8067    catchpoints.  */
8068
8069 static int
8070 insert_catch_vfork (struct bp_location *bl)
8071 {
8072   return target_insert_vfork_catchpoint (ptid_get_pid (inferior_ptid));
8073 }
8074
8075 /* Implement the "remove" breakpoint_ops method for vfork
8076    catchpoints.  */
8077
8078 static int
8079 remove_catch_vfork (struct bp_location *bl)
8080 {
8081   return target_remove_vfork_catchpoint (ptid_get_pid (inferior_ptid));
8082 }
8083
8084 /* Implement the "breakpoint_hit" breakpoint_ops method for vfork
8085    catchpoints.  */
8086
8087 static int
8088 breakpoint_hit_catch_vfork (const struct bp_location *bl,
8089                             struct address_space *aspace, CORE_ADDR bp_addr,
8090                             const struct target_waitstatus *ws)
8091 {
8092   struct fork_catchpoint *c = (struct fork_catchpoint *) bl->owner;
8093
8094   if (ws->kind != TARGET_WAITKIND_VFORKED)
8095     return 0;
8096
8097   c->forked_inferior_pid = ws->value.related_pid;
8098   return 1;
8099 }
8100
8101 /* Implement the "print_it" breakpoint_ops method for vfork
8102    catchpoints.  */
8103
8104 static enum print_stop_action
8105 print_it_catch_vfork (bpstat bs)
8106 {
8107   struct ui_out *uiout = current_uiout;
8108   struct breakpoint *b = bs->breakpoint_at;
8109   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
8110
8111   annotate_catchpoint (b->number);
8112   if (b->disposition == disp_del)
8113     ui_out_text (uiout, "\nTemporary catchpoint ");
8114   else
8115     ui_out_text (uiout, "\nCatchpoint ");
8116   if (ui_out_is_mi_like_p (uiout))
8117     {
8118       ui_out_field_string (uiout, "reason",
8119                            async_reason_lookup (EXEC_ASYNC_VFORK));
8120       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
8121     }
8122   ui_out_field_int (uiout, "bkptno", b->number);
8123   ui_out_text (uiout, " (vforked process ");
8124   ui_out_field_int (uiout, "newpid", ptid_get_pid (c->forked_inferior_pid));
8125   ui_out_text (uiout, "), ");
8126   return PRINT_SRC_AND_LOC;
8127 }
8128
8129 /* Implement the "print_one" breakpoint_ops method for vfork
8130    catchpoints.  */
8131
8132 static void
8133 print_one_catch_vfork (struct breakpoint *b, struct bp_location **last_loc)
8134 {
8135   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
8136   struct value_print_options opts;
8137   struct ui_out *uiout = current_uiout;
8138
8139   get_user_print_options (&opts);
8140   /* Field 4, the address, is omitted (which makes the columns not
8141      line up too nicely with the headers, but the effect is relatively
8142      readable).  */
8143   if (opts.addressprint)
8144     ui_out_field_skip (uiout, "addr");
8145   annotate_field (5);
8146   ui_out_text (uiout, "vfork");
8147   if (!ptid_equal (c->forked_inferior_pid, null_ptid))
8148     {
8149       ui_out_text (uiout, ", process ");
8150       ui_out_field_int (uiout, "what",
8151                         ptid_get_pid (c->forked_inferior_pid));
8152       ui_out_spaces (uiout, 1);
8153     }
8154
8155   if (ui_out_is_mi_like_p (uiout))
8156     ui_out_field_string (uiout, "catch-type", "vfork");
8157 }
8158
8159 /* Implement the "print_mention" breakpoint_ops method for vfork
8160    catchpoints.  */
8161
8162 static void
8163 print_mention_catch_vfork (struct breakpoint *b)
8164 {
8165   printf_filtered (_("Catchpoint %d (vfork)"), b->number);
8166 }
8167
8168 /* Implement the "print_recreate" breakpoint_ops method for vfork
8169    catchpoints.  */
8170
8171 static void
8172 print_recreate_catch_vfork (struct breakpoint *b, struct ui_file *fp)
8173 {
8174   fprintf_unfiltered (fp, "catch vfork");
8175   print_recreate_thread (b, fp);
8176 }
8177
8178 /* The breakpoint_ops structure to be used in vfork catchpoints.  */
8179
8180 static struct breakpoint_ops catch_vfork_breakpoint_ops;
8181
8182 /* An instance of this type is used to represent an solib catchpoint.
8183    It includes a "struct breakpoint" as a kind of base class; users
8184    downcast to "struct breakpoint *" when needed.  A breakpoint is
8185    really of this type iff its ops pointer points to
8186    CATCH_SOLIB_BREAKPOINT_OPS.  */
8187
8188 struct solib_catchpoint
8189 {
8190   /* The base class.  */
8191   struct breakpoint base;
8192
8193   /* True for "catch load", false for "catch unload".  */
8194   unsigned char is_load;
8195
8196   /* Regular expression to match, if any.  COMPILED is only valid when
8197      REGEX is non-NULL.  */
8198   char *regex;
8199   regex_t compiled;
8200 };
8201
8202 static void
8203 dtor_catch_solib (struct breakpoint *b)
8204 {
8205   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8206
8207   if (self->regex)
8208     regfree (&self->compiled);
8209   xfree (self->regex);
8210
8211   base_breakpoint_ops.dtor (b);
8212 }
8213
8214 static int
8215 insert_catch_solib (struct bp_location *ignore)
8216 {
8217   return 0;
8218 }
8219
8220 static int
8221 remove_catch_solib (struct bp_location *ignore)
8222 {
8223   return 0;
8224 }
8225
8226 static int
8227 breakpoint_hit_catch_solib (const struct bp_location *bl,
8228                             struct address_space *aspace,
8229                             CORE_ADDR bp_addr,
8230                             const struct target_waitstatus *ws)
8231 {
8232   struct solib_catchpoint *self = (struct solib_catchpoint *) bl->owner;
8233   struct breakpoint *other;
8234
8235   if (ws->kind == TARGET_WAITKIND_LOADED)
8236     return 1;
8237
8238   ALL_BREAKPOINTS (other)
8239   {
8240     struct bp_location *other_bl;
8241
8242     if (other == bl->owner)
8243       continue;
8244
8245     if (other->type != bp_shlib_event)
8246       continue;
8247
8248     if (self->base.pspace != NULL && other->pspace != self->base.pspace)
8249       continue;
8250
8251     for (other_bl = other->loc; other_bl != NULL; other_bl = other_bl->next)
8252       {
8253         if (other->ops->breakpoint_hit (other_bl, aspace, bp_addr, ws))
8254           return 1;
8255       }
8256   }
8257
8258   return 0;
8259 }
8260
8261 static void
8262 check_status_catch_solib (struct bpstats *bs)
8263 {
8264   struct solib_catchpoint *self
8265     = (struct solib_catchpoint *) bs->breakpoint_at;
8266   int ix;
8267
8268   if (self->is_load)
8269     {
8270       struct so_list *iter;
8271
8272       for (ix = 0;
8273            VEC_iterate (so_list_ptr, current_program_space->added_solibs,
8274                         ix, iter);
8275            ++ix)
8276         {
8277           if (!self->regex
8278               || regexec (&self->compiled, iter->so_name, 0, NULL, 0) == 0)
8279             return;
8280         }
8281     }
8282   else
8283     {
8284       char *iter;
8285
8286       for (ix = 0;
8287            VEC_iterate (char_ptr, current_program_space->deleted_solibs,
8288                         ix, iter);
8289            ++ix)
8290         {
8291           if (!self->regex
8292               || regexec (&self->compiled, iter, 0, NULL, 0) == 0)
8293             return;
8294         }
8295     }
8296
8297   bs->stop = 0;
8298   bs->print_it = print_it_noop;
8299 }
8300
8301 static enum print_stop_action
8302 print_it_catch_solib (bpstat bs)
8303 {
8304   struct breakpoint *b = bs->breakpoint_at;
8305   struct ui_out *uiout = current_uiout;
8306
8307   annotate_catchpoint (b->number);
8308   if (b->disposition == disp_del)
8309     ui_out_text (uiout, "\nTemporary catchpoint ");
8310   else
8311     ui_out_text (uiout, "\nCatchpoint ");
8312   ui_out_field_int (uiout, "bkptno", b->number);
8313   ui_out_text (uiout, "\n");
8314   if (ui_out_is_mi_like_p (uiout))
8315     ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
8316   print_solib_event (1);
8317   return PRINT_SRC_AND_LOC;
8318 }
8319
8320 static void
8321 print_one_catch_solib (struct breakpoint *b, struct bp_location **locs)
8322 {
8323   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8324   struct value_print_options opts;
8325   struct ui_out *uiout = current_uiout;
8326   char *msg;
8327
8328   get_user_print_options (&opts);
8329   /* Field 4, the address, is omitted (which makes the columns not
8330      line up too nicely with the headers, but the effect is relatively
8331      readable).  */
8332   if (opts.addressprint)
8333     {
8334       annotate_field (4);
8335       ui_out_field_skip (uiout, "addr");
8336     }
8337
8338   annotate_field (5);
8339   if (self->is_load)
8340     {
8341       if (self->regex)
8342         msg = xstrprintf (_("load of library matching %s"), self->regex);
8343       else
8344         msg = xstrdup (_("load of library"));
8345     }
8346   else
8347     {
8348       if (self->regex)
8349         msg = xstrprintf (_("unload of library matching %s"), self->regex);
8350       else
8351         msg = xstrdup (_("unload of library"));
8352     }
8353   ui_out_field_string (uiout, "what", msg);
8354   xfree (msg);
8355
8356   if (ui_out_is_mi_like_p (uiout))
8357     ui_out_field_string (uiout, "catch-type",
8358                          self->is_load ? "load" : "unload");
8359 }
8360
8361 static void
8362 print_mention_catch_solib (struct breakpoint *b)
8363 {
8364   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8365
8366   printf_filtered (_("Catchpoint %d (%s)"), b->number,
8367                    self->is_load ? "load" : "unload");
8368 }
8369
8370 static void
8371 print_recreate_catch_solib (struct breakpoint *b, struct ui_file *fp)
8372 {
8373   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8374
8375   fprintf_unfiltered (fp, "%s %s",
8376                       b->disposition == disp_del ? "tcatch" : "catch",
8377                       self->is_load ? "load" : "unload");
8378   if (self->regex)
8379     fprintf_unfiltered (fp, " %s", self->regex);
8380   fprintf_unfiltered (fp, "\n");
8381 }
8382
8383 static struct breakpoint_ops catch_solib_breakpoint_ops;
8384
8385 /* Shared helper function (MI and CLI) for creating and installing
8386    a shared object event catchpoint.  If IS_LOAD is non-zero then
8387    the events to be caught are load events, otherwise they are
8388    unload events.  If IS_TEMP is non-zero the catchpoint is a
8389    temporary one.  If ENABLED is non-zero the catchpoint is
8390    created in an enabled state.  */
8391
8392 void
8393 add_solib_catchpoint (char *arg, int is_load, int is_temp, int enabled)
8394 {
8395   struct solib_catchpoint *c;
8396   struct gdbarch *gdbarch = get_current_arch ();
8397   struct cleanup *cleanup;
8398
8399   if (!arg)
8400     arg = "";
8401   arg = skip_spaces (arg);
8402
8403   c = XCNEW (struct solib_catchpoint);
8404   cleanup = make_cleanup (xfree, c);
8405
8406   if (*arg != '\0')
8407     {
8408       int errcode;
8409
8410       errcode = regcomp (&c->compiled, arg, REG_NOSUB);
8411       if (errcode != 0)
8412         {
8413           char *err = get_regcomp_error (errcode, &c->compiled);
8414
8415           make_cleanup (xfree, err);
8416           error (_("Invalid regexp (%s): %s"), err, arg);
8417         }
8418       c->regex = xstrdup (arg);
8419     }
8420
8421   c->is_load = is_load;
8422   init_catchpoint (&c->base, gdbarch, is_temp, NULL,
8423                    &catch_solib_breakpoint_ops);
8424
8425   c->base.enable_state = enabled ? bp_enabled : bp_disabled;
8426
8427   discard_cleanups (cleanup);
8428   install_breakpoint (0, &c->base, 1);
8429 }
8430
8431 /* A helper function that does all the work for "catch load" and
8432    "catch unload".  */
8433
8434 static void
8435 catch_load_or_unload (char *arg, int from_tty, int is_load,
8436                       struct cmd_list_element *command)
8437 {
8438   int tempflag;
8439   const int enabled = 1;
8440
8441   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
8442
8443   add_solib_catchpoint (arg, is_load, tempflag, enabled);
8444 }
8445
8446 static void
8447 catch_load_command_1 (char *arg, int from_tty,
8448                       struct cmd_list_element *command)
8449 {
8450   catch_load_or_unload (arg, from_tty, 1, command);
8451 }
8452
8453 static void
8454 catch_unload_command_1 (char *arg, int from_tty,
8455                         struct cmd_list_element *command)
8456 {
8457   catch_load_or_unload (arg, from_tty, 0, command);
8458 }
8459
8460 /* An instance of this type is used to represent a syscall catchpoint.
8461    It includes a "struct breakpoint" as a kind of base class; users
8462    downcast to "struct breakpoint *" when needed.  A breakpoint is
8463    really of this type iff its ops pointer points to
8464    CATCH_SYSCALL_BREAKPOINT_OPS.  */
8465
8466 struct syscall_catchpoint
8467 {
8468   /* The base class.  */
8469   struct breakpoint base;
8470
8471   /* Syscall numbers used for the 'catch syscall' feature.  If no
8472      syscall has been specified for filtering, its value is NULL.
8473      Otherwise, it holds a list of all syscalls to be caught.  The
8474      list elements are allocated with xmalloc.  */
8475   VEC(int) *syscalls_to_be_caught;
8476 };
8477
8478 /* Implement the "dtor" breakpoint_ops method for syscall
8479    catchpoints.  */
8480
8481 static void
8482 dtor_catch_syscall (struct breakpoint *b)
8483 {
8484   struct syscall_catchpoint *c = (struct syscall_catchpoint *) b;
8485
8486   VEC_free (int, c->syscalls_to_be_caught);
8487
8488   base_breakpoint_ops.dtor (b);
8489 }
8490
8491 static const struct inferior_data *catch_syscall_inferior_data = NULL;
8492
8493 struct catch_syscall_inferior_data
8494 {
8495   /* We keep a count of the number of times the user has requested a
8496      particular syscall to be tracked, and pass this information to the
8497      target.  This lets capable targets implement filtering directly.  */
8498
8499   /* Number of times that "any" syscall is requested.  */
8500   int any_syscall_count;
8501
8502   /* Count of each system call.  */
8503   VEC(int) *syscalls_counts;
8504
8505   /* This counts all syscall catch requests, so we can readily determine
8506      if any catching is necessary.  */
8507   int total_syscalls_count;
8508 };
8509
8510 static struct catch_syscall_inferior_data*
8511 get_catch_syscall_inferior_data (struct inferior *inf)
8512 {
8513   struct catch_syscall_inferior_data *inf_data;
8514
8515   inf_data = inferior_data (inf, catch_syscall_inferior_data);
8516   if (inf_data == NULL)
8517     {
8518       inf_data = XCNEW (struct catch_syscall_inferior_data);
8519       set_inferior_data (inf, catch_syscall_inferior_data, inf_data);
8520     }
8521
8522   return inf_data;
8523 }
8524
8525 static void
8526 catch_syscall_inferior_data_cleanup (struct inferior *inf, void *arg)
8527 {
8528   xfree (arg);
8529 }
8530
8531
8532 /* Implement the "insert" breakpoint_ops method for syscall
8533    catchpoints.  */
8534
8535 static int
8536 insert_catch_syscall (struct bp_location *bl)
8537 {
8538   struct syscall_catchpoint *c = (struct syscall_catchpoint *) bl->owner;
8539   struct inferior *inf = current_inferior ();
8540   struct catch_syscall_inferior_data *inf_data
8541     = get_catch_syscall_inferior_data (inf);
8542
8543   ++inf_data->total_syscalls_count;
8544   if (!c->syscalls_to_be_caught)
8545     ++inf_data->any_syscall_count;
8546   else
8547     {
8548       int i, iter;
8549
8550       for (i = 0;
8551            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
8552            i++)
8553         {
8554           int elem;
8555
8556           if (iter >= VEC_length (int, inf_data->syscalls_counts))
8557             {
8558               int old_size = VEC_length (int, inf_data->syscalls_counts);
8559               uintptr_t vec_addr_offset
8560                 = old_size * ((uintptr_t) sizeof (int));
8561               uintptr_t vec_addr;
8562               VEC_safe_grow (int, inf_data->syscalls_counts, iter + 1);
8563               vec_addr = ((uintptr_t) VEC_address (int,
8564                                                   inf_data->syscalls_counts)
8565                           + vec_addr_offset);
8566               memset ((void *) vec_addr, 0,
8567                       (iter + 1 - old_size) * sizeof (int));
8568             }
8569           elem = VEC_index (int, inf_data->syscalls_counts, iter);
8570           VEC_replace (int, inf_data->syscalls_counts, iter, ++elem);
8571         }
8572     }
8573
8574   return target_set_syscall_catchpoint (ptid_get_pid (inferior_ptid),
8575                                         inf_data->total_syscalls_count != 0,
8576                                         inf_data->any_syscall_count,
8577                                         VEC_length (int,
8578                                                     inf_data->syscalls_counts),
8579                                         VEC_address (int,
8580                                                      inf_data->syscalls_counts));
8581 }
8582
8583 /* Implement the "remove" breakpoint_ops method for syscall
8584    catchpoints.  */
8585
8586 static int
8587 remove_catch_syscall (struct bp_location *bl)
8588 {
8589   struct syscall_catchpoint *c = (struct syscall_catchpoint *) bl->owner;
8590   struct inferior *inf = current_inferior ();
8591   struct catch_syscall_inferior_data *inf_data
8592     = get_catch_syscall_inferior_data (inf);
8593
8594   --inf_data->total_syscalls_count;
8595   if (!c->syscalls_to_be_caught)
8596     --inf_data->any_syscall_count;
8597   else
8598     {
8599       int i, iter;
8600
8601       for (i = 0;
8602            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
8603            i++)
8604         {
8605           int elem;
8606           if (iter >= VEC_length (int, inf_data->syscalls_counts))
8607             /* Shouldn't happen.  */
8608             continue;
8609           elem = VEC_index (int, inf_data->syscalls_counts, iter);
8610           VEC_replace (int, inf_data->syscalls_counts, iter, --elem);
8611         }
8612     }
8613
8614   return target_set_syscall_catchpoint (ptid_get_pid (inferior_ptid),
8615                                         inf_data->total_syscalls_count != 0,
8616                                         inf_data->any_syscall_count,
8617                                         VEC_length (int,
8618                                                     inf_data->syscalls_counts),
8619                                         VEC_address (int,
8620                                                      inf_data->syscalls_counts));
8621 }
8622
8623 /* Implement the "breakpoint_hit" breakpoint_ops method for syscall
8624    catchpoints.  */
8625
8626 static int
8627 breakpoint_hit_catch_syscall (const struct bp_location *bl,
8628                               struct address_space *aspace, CORE_ADDR bp_addr,
8629                               const struct target_waitstatus *ws)
8630 {
8631   /* We must check if we are catching specific syscalls in this
8632      breakpoint.  If we are, then we must guarantee that the called
8633      syscall is the same syscall we are catching.  */
8634   int syscall_number = 0;
8635   const struct syscall_catchpoint *c
8636     = (const struct syscall_catchpoint *) bl->owner;
8637
8638   if (ws->kind != TARGET_WAITKIND_SYSCALL_ENTRY
8639       && ws->kind != TARGET_WAITKIND_SYSCALL_RETURN)
8640     return 0;
8641
8642   syscall_number = ws->value.syscall_number;
8643
8644   /* Now, checking if the syscall is the same.  */
8645   if (c->syscalls_to_be_caught)
8646     {
8647       int i, iter;
8648
8649       for (i = 0;
8650            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
8651            i++)
8652         if (syscall_number == iter)
8653           return 1;
8654
8655       return 0;
8656     }
8657
8658   return 1;
8659 }
8660
8661 /* Implement the "print_it" breakpoint_ops method for syscall
8662    catchpoints.  */
8663
8664 static enum print_stop_action
8665 print_it_catch_syscall (bpstat bs)
8666 {
8667   struct ui_out *uiout = current_uiout;
8668   struct breakpoint *b = bs->breakpoint_at;
8669   /* These are needed because we want to know in which state a
8670      syscall is.  It can be in the TARGET_WAITKIND_SYSCALL_ENTRY
8671      or TARGET_WAITKIND_SYSCALL_RETURN, and depending on it we
8672      must print "called syscall" or "returned from syscall".  */
8673   ptid_t ptid;
8674   struct target_waitstatus last;
8675   struct syscall s;
8676
8677   get_last_target_status (&ptid, &last);
8678
8679   get_syscall_by_number (last.value.syscall_number, &s);
8680
8681   annotate_catchpoint (b->number);
8682
8683   if (b->disposition == disp_del)
8684     ui_out_text (uiout, "\nTemporary catchpoint ");
8685   else
8686     ui_out_text (uiout, "\nCatchpoint ");
8687   if (ui_out_is_mi_like_p (uiout))
8688     {
8689       ui_out_field_string (uiout, "reason",
8690                            async_reason_lookup (last.kind == TARGET_WAITKIND_SYSCALL_ENTRY
8691                                                 ? EXEC_ASYNC_SYSCALL_ENTRY
8692                                                 : EXEC_ASYNC_SYSCALL_RETURN));
8693       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
8694     }
8695   ui_out_field_int (uiout, "bkptno", b->number);
8696
8697   if (last.kind == TARGET_WAITKIND_SYSCALL_ENTRY)
8698     ui_out_text (uiout, " (call to syscall ");
8699   else
8700     ui_out_text (uiout, " (returned from syscall ");
8701
8702   if (s.name == NULL || ui_out_is_mi_like_p (uiout))
8703     ui_out_field_int (uiout, "syscall-number", last.value.syscall_number);
8704   if (s.name != NULL)
8705     ui_out_field_string (uiout, "syscall-name", s.name);
8706
8707   ui_out_text (uiout, "), ");
8708
8709   return PRINT_SRC_AND_LOC;
8710 }
8711
8712 /* Implement the "print_one" breakpoint_ops method for syscall
8713    catchpoints.  */
8714
8715 static void
8716 print_one_catch_syscall (struct breakpoint *b,
8717                          struct bp_location **last_loc)
8718 {
8719   struct syscall_catchpoint *c = (struct syscall_catchpoint *) b;
8720   struct value_print_options opts;
8721   struct ui_out *uiout = current_uiout;
8722
8723   get_user_print_options (&opts);
8724   /* Field 4, the address, is omitted (which makes the columns not
8725      line up too nicely with the headers, but the effect is relatively
8726      readable).  */
8727   if (opts.addressprint)
8728     ui_out_field_skip (uiout, "addr");
8729   annotate_field (5);
8730
8731   if (c->syscalls_to_be_caught
8732       && VEC_length (int, c->syscalls_to_be_caught) > 1)
8733     ui_out_text (uiout, "syscalls \"");
8734   else
8735     ui_out_text (uiout, "syscall \"");
8736
8737   if (c->syscalls_to_be_caught)
8738     {
8739       int i, iter;
8740       char *text = xstrprintf ("%s", "");
8741
8742       for (i = 0;
8743            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
8744            i++)
8745         {
8746           char *x = text;
8747           struct syscall s;
8748           get_syscall_by_number (iter, &s);
8749
8750           if (s.name != NULL)
8751             text = xstrprintf ("%s%s, ", text, s.name);
8752           else
8753             text = xstrprintf ("%s%d, ", text, iter);
8754
8755           /* We have to xfree the last 'text' (now stored at 'x')
8756              because xstrprintf dynamically allocates new space for it
8757              on every call.  */
8758           xfree (x);
8759         }
8760       /* Remove the last comma.  */
8761       text[strlen (text) - 2] = '\0';
8762       ui_out_field_string (uiout, "what", text);
8763     }
8764   else
8765     ui_out_field_string (uiout, "what", "<any syscall>");
8766   ui_out_text (uiout, "\" ");
8767
8768   if (ui_out_is_mi_like_p (uiout))
8769     ui_out_field_string (uiout, "catch-type", "syscall");
8770 }
8771
8772 /* Implement the "print_mention" breakpoint_ops method for syscall
8773    catchpoints.  */
8774
8775 static void
8776 print_mention_catch_syscall (struct breakpoint *b)
8777 {
8778   struct syscall_catchpoint *c = (struct syscall_catchpoint *) b;
8779
8780   if (c->syscalls_to_be_caught)
8781     {
8782       int i, iter;
8783
8784       if (VEC_length (int, c->syscalls_to_be_caught) > 1)
8785         printf_filtered (_("Catchpoint %d (syscalls"), b->number);
8786       else
8787         printf_filtered (_("Catchpoint %d (syscall"), b->number);
8788
8789       for (i = 0;
8790            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
8791            i++)
8792         {
8793           struct syscall s;
8794           get_syscall_by_number (iter, &s);
8795
8796           if (s.name)
8797             printf_filtered (" '%s' [%d]", s.name, s.number);
8798           else
8799             printf_filtered (" %d", s.number);
8800         }
8801       printf_filtered (")");
8802     }
8803   else
8804     printf_filtered (_("Catchpoint %d (any syscall)"),
8805                      b->number);
8806 }
8807
8808 /* Implement the "print_recreate" breakpoint_ops method for syscall
8809    catchpoints.  */
8810
8811 static void
8812 print_recreate_catch_syscall (struct breakpoint *b, struct ui_file *fp)
8813 {
8814   struct syscall_catchpoint *c = (struct syscall_catchpoint *) b;
8815
8816   fprintf_unfiltered (fp, "catch syscall");
8817
8818   if (c->syscalls_to_be_caught)
8819     {
8820       int i, iter;
8821
8822       for (i = 0;
8823            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
8824            i++)
8825         {
8826           struct syscall s;
8827
8828           get_syscall_by_number (iter, &s);
8829           if (s.name)
8830             fprintf_unfiltered (fp, " %s", s.name);
8831           else
8832             fprintf_unfiltered (fp, " %d", s.number);
8833         }
8834     }
8835   print_recreate_thread (b, fp);
8836 }
8837
8838 /* The breakpoint_ops structure to be used in syscall catchpoints.  */
8839
8840 static struct breakpoint_ops catch_syscall_breakpoint_ops;
8841
8842 /* Returns non-zero if 'b' is a syscall catchpoint.  */
8843
8844 static int
8845 syscall_catchpoint_p (struct breakpoint *b)
8846 {
8847   return (b->ops == &catch_syscall_breakpoint_ops);
8848 }
8849
8850 /* Initialize a new breakpoint of the bp_catchpoint kind.  If TEMPFLAG
8851    is non-zero, then make the breakpoint temporary.  If COND_STRING is
8852    not NULL, then store it in the breakpoint.  OPS, if not NULL, is
8853    the breakpoint_ops structure associated to the catchpoint.  */
8854
8855 void
8856 init_catchpoint (struct breakpoint *b,
8857                  struct gdbarch *gdbarch, int tempflag,
8858                  char *cond_string,
8859                  const struct breakpoint_ops *ops)
8860 {
8861   struct symtab_and_line sal;
8862
8863   init_sal (&sal);
8864   sal.pspace = current_program_space;
8865
8866   init_raw_breakpoint (b, gdbarch, sal, bp_catchpoint, ops);
8867
8868   b->cond_string = (cond_string == NULL) ? NULL : xstrdup (cond_string);
8869   b->disposition = tempflag ? disp_del : disp_donttouch;
8870 }
8871
8872 void
8873 install_breakpoint (int internal, struct breakpoint *b, int update_gll)
8874 {
8875   add_to_breakpoint_chain (b);
8876   set_breakpoint_number (internal, b);
8877   if (is_tracepoint (b))
8878     set_tracepoint_count (breakpoint_count);
8879   if (!internal)
8880     mention (b);
8881   observer_notify_breakpoint_created (b);
8882
8883   if (update_gll)
8884     update_global_location_list (UGLL_MAY_INSERT);
8885 }
8886
8887 static void
8888 create_fork_vfork_event_catchpoint (struct gdbarch *gdbarch,
8889                                     int tempflag, char *cond_string,
8890                                     const struct breakpoint_ops *ops)
8891 {
8892   struct fork_catchpoint *c = XNEW (struct fork_catchpoint);
8893
8894   init_catchpoint (&c->base, gdbarch, tempflag, cond_string, ops);
8895
8896   c->forked_inferior_pid = null_ptid;
8897
8898   install_breakpoint (0, &c->base, 1);
8899 }
8900
8901 /* Exec catchpoints.  */
8902
8903 /* An instance of this type is used to represent an exec catchpoint.
8904    It includes a "struct breakpoint" as a kind of base class; users
8905    downcast to "struct breakpoint *" when needed.  A breakpoint is
8906    really of this type iff its ops pointer points to
8907    CATCH_EXEC_BREAKPOINT_OPS.  */
8908
8909 struct exec_catchpoint
8910 {
8911   /* The base class.  */
8912   struct breakpoint base;
8913
8914   /* Filename of a program whose exec triggered this catchpoint.
8915      This field is only valid immediately after this catchpoint has
8916      triggered.  */
8917   char *exec_pathname;
8918 };
8919
8920 /* Implement the "dtor" breakpoint_ops method for exec
8921    catchpoints.  */
8922
8923 static void
8924 dtor_catch_exec (struct breakpoint *b)
8925 {
8926   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
8927
8928   xfree (c->exec_pathname);
8929
8930   base_breakpoint_ops.dtor (b);
8931 }
8932
8933 static int
8934 insert_catch_exec (struct bp_location *bl)
8935 {
8936   return target_insert_exec_catchpoint (ptid_get_pid (inferior_ptid));
8937 }
8938
8939 static int
8940 remove_catch_exec (struct bp_location *bl)
8941 {
8942   return target_remove_exec_catchpoint (ptid_get_pid (inferior_ptid));
8943 }
8944
8945 static int
8946 breakpoint_hit_catch_exec (const struct bp_location *bl,
8947                            struct address_space *aspace, CORE_ADDR bp_addr,
8948                            const struct target_waitstatus *ws)
8949 {
8950   struct exec_catchpoint *c = (struct exec_catchpoint *) bl->owner;
8951
8952   if (ws->kind != TARGET_WAITKIND_EXECD)
8953     return 0;
8954
8955   c->exec_pathname = xstrdup (ws->value.execd_pathname);
8956   return 1;
8957 }
8958
8959 static enum print_stop_action
8960 print_it_catch_exec (bpstat bs)
8961 {
8962   struct ui_out *uiout = current_uiout;
8963   struct breakpoint *b = bs->breakpoint_at;
8964   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
8965
8966   annotate_catchpoint (b->number);
8967   if (b->disposition == disp_del)
8968     ui_out_text (uiout, "\nTemporary catchpoint ");
8969   else
8970     ui_out_text (uiout, "\nCatchpoint ");
8971   if (ui_out_is_mi_like_p (uiout))
8972     {
8973       ui_out_field_string (uiout, "reason",
8974                            async_reason_lookup (EXEC_ASYNC_EXEC));
8975       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
8976     }
8977   ui_out_field_int (uiout, "bkptno", b->number);
8978   ui_out_text (uiout, " (exec'd ");
8979   ui_out_field_string (uiout, "new-exec", c->exec_pathname);
8980   ui_out_text (uiout, "), ");
8981
8982   return PRINT_SRC_AND_LOC;
8983 }
8984
8985 static void
8986 print_one_catch_exec (struct breakpoint *b, struct bp_location **last_loc)
8987 {
8988   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
8989   struct value_print_options opts;
8990   struct ui_out *uiout = current_uiout;
8991
8992   get_user_print_options (&opts);
8993
8994   /* Field 4, the address, is omitted (which makes the columns
8995      not line up too nicely with the headers, but the effect
8996      is relatively readable).  */
8997   if (opts.addressprint)
8998     ui_out_field_skip (uiout, "addr");
8999   annotate_field (5);
9000   ui_out_text (uiout, "exec");
9001   if (c->exec_pathname != NULL)
9002     {
9003       ui_out_text (uiout, ", program \"");
9004       ui_out_field_string (uiout, "what", c->exec_pathname);
9005       ui_out_text (uiout, "\" ");
9006     }
9007
9008   if (ui_out_is_mi_like_p (uiout))
9009     ui_out_field_string (uiout, "catch-type", "exec");
9010 }
9011
9012 static void
9013 print_mention_catch_exec (struct breakpoint *b)
9014 {
9015   printf_filtered (_("Catchpoint %d (exec)"), b->number);
9016 }
9017
9018 /* Implement the "print_recreate" breakpoint_ops method for exec
9019    catchpoints.  */
9020
9021 static void
9022 print_recreate_catch_exec (struct breakpoint *b, struct ui_file *fp)
9023 {
9024   fprintf_unfiltered (fp, "catch exec");
9025   print_recreate_thread (b, fp);
9026 }
9027
9028 static struct breakpoint_ops catch_exec_breakpoint_ops;
9029
9030 static void
9031 create_syscall_event_catchpoint (int tempflag, VEC(int) *filter,
9032                                  const struct breakpoint_ops *ops)
9033 {
9034   struct syscall_catchpoint *c;
9035   struct gdbarch *gdbarch = get_current_arch ();
9036
9037   c = XNEW (struct syscall_catchpoint);
9038   init_catchpoint (&c->base, gdbarch, tempflag, NULL, ops);
9039   c->syscalls_to_be_caught = filter;
9040
9041   install_breakpoint (0, &c->base, 1);
9042 }
9043
9044 static int
9045 hw_breakpoint_used_count (void)
9046 {
9047   int i = 0;
9048   struct breakpoint *b;
9049   struct bp_location *bl;
9050
9051   ALL_BREAKPOINTS (b)
9052   {
9053     if (b->type == bp_hardware_breakpoint && breakpoint_enabled (b))
9054       for (bl = b->loc; bl; bl = bl->next)
9055         {
9056           /* Special types of hardware breakpoints may use more than
9057              one register.  */
9058           i += b->ops->resources_needed (bl);
9059         }
9060   }
9061
9062   return i;
9063 }
9064
9065 /* Returns the resources B would use if it were a hardware
9066    watchpoint.  */
9067
9068 static int
9069 hw_watchpoint_use_count (struct breakpoint *b)
9070 {
9071   int i = 0;
9072   struct bp_location *bl;
9073
9074   if (!breakpoint_enabled (b))
9075     return 0;
9076
9077   for (bl = b->loc; bl; bl = bl->next)
9078     {
9079       /* Special types of hardware watchpoints may use more than
9080          one register.  */
9081       i += b->ops->resources_needed (bl);
9082     }
9083
9084   return i;
9085 }
9086
9087 /* Returns the sum the used resources of all hardware watchpoints of
9088    type TYPE in the breakpoints list.  Also returns in OTHER_TYPE_USED
9089    the sum of the used resources of all hardware watchpoints of other
9090    types _not_ TYPE.  */
9091
9092 static int
9093 hw_watchpoint_used_count_others (struct breakpoint *except,
9094                                  enum bptype type, int *other_type_used)
9095 {
9096   int i = 0;
9097   struct breakpoint *b;
9098
9099   *other_type_used = 0;
9100   ALL_BREAKPOINTS (b)
9101     {
9102       if (b == except)
9103         continue;
9104       if (!breakpoint_enabled (b))
9105         continue;
9106
9107       if (b->type == type)
9108         i += hw_watchpoint_use_count (b);
9109       else if (is_hardware_watchpoint (b))
9110         *other_type_used = 1;
9111     }
9112
9113   return i;
9114 }
9115
9116 void
9117 disable_watchpoints_before_interactive_call_start (void)
9118 {
9119   struct breakpoint *b;
9120
9121   ALL_BREAKPOINTS (b)
9122   {
9123     if (is_watchpoint (b) && breakpoint_enabled (b))
9124       {
9125         b->enable_state = bp_call_disabled;
9126         update_global_location_list (UGLL_DONT_INSERT);
9127       }
9128   }
9129 }
9130
9131 void
9132 enable_watchpoints_after_interactive_call_stop (void)
9133 {
9134   struct breakpoint *b;
9135
9136   ALL_BREAKPOINTS (b)
9137   {
9138     if (is_watchpoint (b) && b->enable_state == bp_call_disabled)
9139       {
9140         b->enable_state = bp_enabled;
9141         update_global_location_list (UGLL_MAY_INSERT);
9142       }
9143   }
9144 }
9145
9146 void
9147 disable_breakpoints_before_startup (void)
9148 {
9149   current_program_space->executing_startup = 1;
9150   update_global_location_list (UGLL_DONT_INSERT);
9151 }
9152
9153 void
9154 enable_breakpoints_after_startup (void)
9155 {
9156   current_program_space->executing_startup = 0;
9157   breakpoint_re_set ();
9158 }
9159
9160 /* Create a new single-step breakpoint for thread THREAD, with no
9161    locations.  */
9162
9163 static struct breakpoint *
9164 new_single_step_breakpoint (int thread, struct gdbarch *gdbarch)
9165 {
9166   struct breakpoint *b = XNEW (struct breakpoint);
9167
9168   init_raw_breakpoint_without_location (b, gdbarch, bp_single_step,
9169                                         &momentary_breakpoint_ops);
9170
9171   b->disposition = disp_donttouch;
9172   b->frame_id = null_frame_id;
9173
9174   b->thread = thread;
9175   gdb_assert (b->thread != 0);
9176
9177   add_to_breakpoint_chain (b);
9178
9179   return b;
9180 }
9181
9182 /* Set a momentary breakpoint of type TYPE at address specified by
9183    SAL.  If FRAME_ID is valid, the breakpoint is restricted to that
9184    frame.  */
9185
9186 struct breakpoint *
9187 set_momentary_breakpoint (struct gdbarch *gdbarch, struct symtab_and_line sal,
9188                           struct frame_id frame_id, enum bptype type)
9189 {
9190   struct breakpoint *b;
9191
9192   /* If FRAME_ID is valid, it should be a real frame, not an inlined or
9193      tail-called one.  */
9194   gdb_assert (!frame_id_artificial_p (frame_id));
9195
9196   b = set_raw_breakpoint (gdbarch, sal, type, &momentary_breakpoint_ops);
9197   b->enable_state = bp_enabled;
9198   b->disposition = disp_donttouch;
9199   b->frame_id = frame_id;
9200
9201   /* If we're debugging a multi-threaded program, then we want
9202      momentary breakpoints to be active in only a single thread of
9203      control.  */
9204   if (in_thread_list (inferior_ptid))
9205     b->thread = pid_to_thread_id (inferior_ptid);
9206
9207   update_global_location_list_nothrow (UGLL_MAY_INSERT);
9208
9209   return b;
9210 }
9211
9212 /* Make a momentary breakpoint based on the master breakpoint ORIG.
9213    The new breakpoint will have type TYPE, use OPS as its
9214    breakpoint_ops, and will set enabled to LOC_ENABLED.  */
9215
9216 static struct breakpoint *
9217 momentary_breakpoint_from_master (struct breakpoint *orig,
9218                                   enum bptype type,
9219                                   const struct breakpoint_ops *ops,
9220                                   int loc_enabled)
9221 {
9222   struct breakpoint *copy;
9223
9224   copy = set_raw_breakpoint_without_location (orig->gdbarch, type, ops);
9225   copy->loc = allocate_bp_location (copy);
9226   set_breakpoint_location_function (copy->loc, 1);
9227
9228   copy->loc->gdbarch = orig->loc->gdbarch;
9229   copy->loc->requested_address = orig->loc->requested_address;
9230   copy->loc->address = orig->loc->address;
9231   copy->loc->section = orig->loc->section;
9232   copy->loc->pspace = orig->loc->pspace;
9233   copy->loc->probe = orig->loc->probe;
9234   copy->loc->line_number = orig->loc->line_number;
9235   copy->loc->symtab = orig->loc->symtab;
9236   copy->loc->enabled = loc_enabled;
9237   copy->frame_id = orig->frame_id;
9238   copy->thread = orig->thread;
9239   copy->pspace = orig->pspace;
9240
9241   copy->enable_state = bp_enabled;
9242   copy->disposition = disp_donttouch;
9243   copy->number = internal_breakpoint_number--;
9244
9245   update_global_location_list_nothrow (UGLL_DONT_INSERT);
9246   return copy;
9247 }
9248
9249 /* Make a deep copy of momentary breakpoint ORIG.  Returns NULL if
9250    ORIG is NULL.  */
9251
9252 struct breakpoint *
9253 clone_momentary_breakpoint (struct breakpoint *orig)
9254 {
9255   /* If there's nothing to clone, then return nothing.  */
9256   if (orig == NULL)
9257     return NULL;
9258
9259   return momentary_breakpoint_from_master (orig, orig->type, orig->ops, 0);
9260 }
9261
9262 struct breakpoint *
9263 set_momentary_breakpoint_at_pc (struct gdbarch *gdbarch, CORE_ADDR pc,
9264                                 enum bptype type)
9265 {
9266   struct symtab_and_line sal;
9267
9268   sal = find_pc_line (pc, 0);
9269   sal.pc = pc;
9270   sal.section = find_pc_overlay (pc);
9271   sal.explicit_pc = 1;
9272
9273   return set_momentary_breakpoint (gdbarch, sal, null_frame_id, type);
9274 }
9275 \f
9276
9277 /* Tell the user we have just set a breakpoint B.  */
9278
9279 static void
9280 mention (struct breakpoint *b)
9281 {
9282   b->ops->print_mention (b);
9283   if (ui_out_is_mi_like_p (current_uiout))
9284     return;
9285   printf_filtered ("\n");
9286 }
9287 \f
9288
9289 static struct bp_location *
9290 add_location_to_breakpoint (struct breakpoint *b,
9291                             const struct symtab_and_line *sal)
9292 {
9293   struct bp_location *loc, **tmp;
9294   CORE_ADDR adjusted_address;
9295   struct gdbarch *loc_gdbarch = get_sal_arch (*sal);
9296
9297   if (loc_gdbarch == NULL)
9298     loc_gdbarch = b->gdbarch;
9299
9300   /* Adjust the breakpoint's address prior to allocating a location.
9301      Once we call allocate_bp_location(), that mostly uninitialized
9302      location will be placed on the location chain.  Adjustment of the
9303      breakpoint may cause target_read_memory() to be called and we do
9304      not want its scan of the location chain to find a breakpoint and
9305      location that's only been partially initialized.  */
9306   adjusted_address = adjust_breakpoint_address (loc_gdbarch,
9307                                                 sal->pc, b->type);
9308
9309   /* Sort the locations by their ADDRESS.  */
9310   loc = allocate_bp_location (b);
9311   for (tmp = &(b->loc); *tmp != NULL && (*tmp)->address <= adjusted_address;
9312        tmp = &((*tmp)->next))
9313     ;
9314   loc->next = *tmp;
9315   *tmp = loc;
9316
9317   loc->requested_address = sal->pc;
9318   loc->address = adjusted_address;
9319   loc->pspace = sal->pspace;
9320   loc->probe.probe = sal->probe;
9321   loc->probe.objfile = sal->objfile;
9322   gdb_assert (loc->pspace != NULL);
9323   loc->section = sal->section;
9324   loc->gdbarch = loc_gdbarch;
9325   loc->line_number = sal->line;
9326   loc->symtab = sal->symtab;
9327
9328   set_breakpoint_location_function (loc,
9329                                     sal->explicit_pc || sal->explicit_line);
9330   return loc;
9331 }
9332 \f
9333
9334 /* Return 1 if LOC is pointing to a permanent breakpoint, 
9335    return 0 otherwise.  */
9336
9337 static int
9338 bp_loc_is_permanent (struct bp_location *loc)
9339 {
9340   int len;
9341   CORE_ADDR addr;
9342   const gdb_byte *bpoint;
9343   gdb_byte *target_mem;
9344   struct cleanup *cleanup;
9345   int retval = 0;
9346
9347   gdb_assert (loc != NULL);
9348
9349   addr = loc->address;
9350   bpoint = gdbarch_breakpoint_from_pc (loc->gdbarch, &addr, &len);
9351
9352   /* Software breakpoints unsupported?  */
9353   if (bpoint == NULL)
9354     return 0;
9355
9356   target_mem = alloca (len);
9357
9358   /* Enable the automatic memory restoration from breakpoints while
9359      we read the memory.  Otherwise we could say about our temporary
9360      breakpoints they are permanent.  */
9361   cleanup = save_current_space_and_thread ();
9362
9363   switch_to_program_space_and_thread (loc->pspace);
9364   make_show_memory_breakpoints_cleanup (0);
9365
9366   if (target_read_memory (loc->address, target_mem, len) == 0
9367       && memcmp (target_mem, bpoint, len) == 0)
9368     retval = 1;
9369
9370   do_cleanups (cleanup);
9371
9372   return retval;
9373 }
9374
9375 /* Build a command list for the dprintf corresponding to the current
9376    settings of the dprintf style options.  */
9377
9378 static void
9379 update_dprintf_command_list (struct breakpoint *b)
9380 {
9381   char *dprintf_args = b->extra_string;
9382   char *printf_line = NULL;
9383
9384   if (!dprintf_args)
9385     return;
9386
9387   dprintf_args = skip_spaces (dprintf_args);
9388
9389   /* Allow a comma, as it may have terminated a location, but don't
9390      insist on it.  */
9391   if (*dprintf_args == ',')
9392     ++dprintf_args;
9393   dprintf_args = skip_spaces (dprintf_args);
9394
9395   if (*dprintf_args != '"')
9396     error (_("Bad format string, missing '\"'."));
9397
9398   if (strcmp (dprintf_style, dprintf_style_gdb) == 0)
9399     printf_line = xstrprintf ("printf %s", dprintf_args);
9400   else if (strcmp (dprintf_style, dprintf_style_call) == 0)
9401     {
9402       if (!dprintf_function)
9403         error (_("No function supplied for dprintf call"));
9404
9405       if (dprintf_channel && strlen (dprintf_channel) > 0)
9406         printf_line = xstrprintf ("call (void) %s (%s,%s)",
9407                                   dprintf_function,
9408                                   dprintf_channel,
9409                                   dprintf_args);
9410       else
9411         printf_line = xstrprintf ("call (void) %s (%s)",
9412                                   dprintf_function,
9413                                   dprintf_args);
9414     }
9415   else if (strcmp (dprintf_style, dprintf_style_agent) == 0)
9416     {
9417       if (target_can_run_breakpoint_commands ())
9418         printf_line = xstrprintf ("agent-printf %s", dprintf_args);
9419       else
9420         {
9421           warning (_("Target cannot run dprintf commands, falling back to GDB printf"));
9422           printf_line = xstrprintf ("printf %s", dprintf_args);
9423         }
9424     }
9425   else
9426     internal_error (__FILE__, __LINE__,
9427                     _("Invalid dprintf style."));
9428
9429   gdb_assert (printf_line != NULL);
9430   /* Manufacture a printf sequence.  */
9431   {
9432     struct command_line *printf_cmd_line
9433       = xmalloc (sizeof (struct command_line));
9434
9435     printf_cmd_line = xmalloc (sizeof (struct command_line));
9436     printf_cmd_line->control_type = simple_control;
9437     printf_cmd_line->body_count = 0;
9438     printf_cmd_line->body_list = NULL;
9439     printf_cmd_line->next = NULL;
9440     printf_cmd_line->line = printf_line;
9441
9442     breakpoint_set_commands (b, printf_cmd_line);
9443   }
9444 }
9445
9446 /* Update all dprintf commands, making their command lists reflect
9447    current style settings.  */
9448
9449 static void
9450 update_dprintf_commands (char *args, int from_tty,
9451                          struct cmd_list_element *c)
9452 {
9453   struct breakpoint *b;
9454
9455   ALL_BREAKPOINTS (b)
9456     {
9457       if (b->type == bp_dprintf)
9458         update_dprintf_command_list (b);
9459     }
9460 }
9461
9462 /* Create a breakpoint with SAL as location.  Use ADDR_STRING
9463    as textual description of the location, and COND_STRING
9464    as condition expression.  */
9465
9466 static void
9467 init_breakpoint_sal (struct breakpoint *b, struct gdbarch *gdbarch,
9468                      struct symtabs_and_lines sals, char *addr_string,
9469                      char *filter, char *cond_string,
9470                      char *extra_string,
9471                      enum bptype type, enum bpdisp disposition,
9472                      int thread, int task, int ignore_count,
9473                      const struct breakpoint_ops *ops, int from_tty,
9474                      int enabled, int internal, unsigned flags,
9475                      int display_canonical)
9476 {
9477   int i;
9478
9479   if (type == bp_hardware_breakpoint)
9480     {
9481       int target_resources_ok;
9482
9483       i = hw_breakpoint_used_count ();
9484       target_resources_ok =
9485         target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
9486                                             i + 1, 0);
9487       if (target_resources_ok == 0)
9488         error (_("No hardware breakpoint support in the target."));
9489       else if (target_resources_ok < 0)
9490         error (_("Hardware breakpoints used exceeds limit."));
9491     }
9492
9493   gdb_assert (sals.nelts > 0);
9494
9495   for (i = 0; i < sals.nelts; ++i)
9496     {
9497       struct symtab_and_line sal = sals.sals[i];
9498       struct bp_location *loc;
9499
9500       if (from_tty)
9501         {
9502           struct gdbarch *loc_gdbarch = get_sal_arch (sal);
9503           if (!loc_gdbarch)
9504             loc_gdbarch = gdbarch;
9505
9506           describe_other_breakpoints (loc_gdbarch,
9507                                       sal.pspace, sal.pc, sal.section, thread);
9508         }
9509
9510       if (i == 0)
9511         {
9512           init_raw_breakpoint (b, gdbarch, sal, type, ops);
9513           b->thread = thread;
9514           b->task = task;
9515
9516           b->cond_string = cond_string;
9517           b->extra_string = extra_string;
9518           b->ignore_count = ignore_count;
9519           b->enable_state = enabled ? bp_enabled : bp_disabled;
9520           b->disposition = disposition;
9521
9522           if ((flags & CREATE_BREAKPOINT_FLAGS_INSERTED) != 0)
9523             b->loc->inserted = 1;
9524
9525           if (type == bp_static_tracepoint)
9526             {
9527               struct tracepoint *t = (struct tracepoint *) b;
9528               struct static_tracepoint_marker marker;
9529
9530               if (strace_marker_p (b))
9531                 {
9532                   /* We already know the marker exists, otherwise, we
9533                      wouldn't see a sal for it.  */
9534                   char *p = &addr_string[3];
9535                   char *endp;
9536                   char *marker_str;
9537
9538                   p = skip_spaces (p);
9539
9540                   endp = skip_to_space (p);
9541
9542                   marker_str = savestring (p, endp - p);
9543                   t->static_trace_marker_id = marker_str;
9544
9545                   printf_filtered (_("Probed static tracepoint "
9546                                      "marker \"%s\"\n"),
9547                                    t->static_trace_marker_id);
9548                 }
9549               else if (target_static_tracepoint_marker_at (sal.pc, &marker))
9550                 {
9551                   t->static_trace_marker_id = xstrdup (marker.str_id);
9552                   release_static_tracepoint_marker (&marker);
9553
9554                   printf_filtered (_("Probed static tracepoint "
9555                                      "marker \"%s\"\n"),
9556                                    t->static_trace_marker_id);
9557                 }
9558               else
9559                 warning (_("Couldn't determine the static "
9560                            "tracepoint marker to probe"));
9561             }
9562
9563           loc = b->loc;
9564         }
9565       else
9566         {
9567           loc = add_location_to_breakpoint (b, &sal);
9568           if ((flags & CREATE_BREAKPOINT_FLAGS_INSERTED) != 0)
9569             loc->inserted = 1;
9570         }
9571
9572       if (bp_loc_is_permanent (loc))
9573         make_breakpoint_permanent (b);
9574
9575       if (b->cond_string)
9576         {
9577           const char *arg = b->cond_string;
9578
9579           loc->cond = parse_exp_1 (&arg, loc->address,
9580                                    block_for_pc (loc->address), 0);
9581           if (*arg)
9582               error (_("Garbage '%s' follows condition"), arg);
9583         }
9584
9585       /* Dynamic printf requires and uses additional arguments on the
9586          command line, otherwise it's an error.  */
9587       if (type == bp_dprintf)
9588         {
9589           if (b->extra_string)
9590             update_dprintf_command_list (b);
9591           else
9592             error (_("Format string required"));
9593         }
9594       else if (b->extra_string)
9595         error (_("Garbage '%s' at end of command"), b->extra_string);
9596     }
9597
9598   b->display_canonical = display_canonical;
9599   if (addr_string)
9600     b->addr_string = addr_string;
9601   else
9602     /* addr_string has to be used or breakpoint_re_set will delete
9603        me.  */
9604     b->addr_string
9605       = xstrprintf ("*%s", paddress (b->loc->gdbarch, b->loc->address));
9606   b->filter = filter;
9607 }
9608
9609 static void
9610 create_breakpoint_sal (struct gdbarch *gdbarch,
9611                        struct symtabs_and_lines sals, char *addr_string,
9612                        char *filter, char *cond_string,
9613                        char *extra_string,
9614                        enum bptype type, enum bpdisp disposition,
9615                        int thread, int task, int ignore_count,
9616                        const struct breakpoint_ops *ops, int from_tty,
9617                        int enabled, int internal, unsigned flags,
9618                        int display_canonical)
9619 {
9620   struct breakpoint *b;
9621   struct cleanup *old_chain;
9622
9623   if (is_tracepoint_type (type))
9624     {
9625       struct tracepoint *t;
9626
9627       t = XCNEW (struct tracepoint);
9628       b = &t->base;
9629     }
9630   else
9631     b = XNEW (struct breakpoint);
9632
9633   old_chain = make_cleanup (xfree, b);
9634
9635   init_breakpoint_sal (b, gdbarch,
9636                        sals, addr_string,
9637                        filter, cond_string, extra_string,
9638                        type, disposition,
9639                        thread, task, ignore_count,
9640                        ops, from_tty,
9641                        enabled, internal, flags,
9642                        display_canonical);
9643   discard_cleanups (old_chain);
9644
9645   install_breakpoint (internal, b, 0);
9646 }
9647
9648 /* Add SALS.nelts breakpoints to the breakpoint table.  For each
9649    SALS.sal[i] breakpoint, include the corresponding ADDR_STRING[i]
9650    value.  COND_STRING, if not NULL, specified the condition to be
9651    used for all breakpoints.  Essentially the only case where
9652    SALS.nelts is not 1 is when we set a breakpoint on an overloaded
9653    function.  In that case, it's still not possible to specify
9654    separate conditions for different overloaded functions, so
9655    we take just a single condition string.
9656    
9657    NOTE: If the function succeeds, the caller is expected to cleanup
9658    the arrays ADDR_STRING, COND_STRING, and SALS (but not the
9659    array contents).  If the function fails (error() is called), the
9660    caller is expected to cleanups both the ADDR_STRING, COND_STRING,
9661    COND and SALS arrays and each of those arrays contents.  */
9662
9663 static void
9664 create_breakpoints_sal (struct gdbarch *gdbarch,
9665                         struct linespec_result *canonical,
9666                         char *cond_string, char *extra_string,
9667                         enum bptype type, enum bpdisp disposition,
9668                         int thread, int task, int ignore_count,
9669                         const struct breakpoint_ops *ops, int from_tty,
9670                         int enabled, int internal, unsigned flags)
9671 {
9672   int i;
9673   struct linespec_sals *lsal;
9674
9675   if (canonical->pre_expanded)
9676     gdb_assert (VEC_length (linespec_sals, canonical->sals) == 1);
9677
9678   for (i = 0; VEC_iterate (linespec_sals, canonical->sals, i, lsal); ++i)
9679     {
9680       /* Note that 'addr_string' can be NULL in the case of a plain
9681          'break', without arguments.  */
9682       char *addr_string = (canonical->addr_string
9683                            ? xstrdup (canonical->addr_string)
9684                            : NULL);
9685       char *filter_string = lsal->canonical ? xstrdup (lsal->canonical) : NULL;
9686       struct cleanup *inner = make_cleanup (xfree, addr_string);
9687
9688       make_cleanup (xfree, filter_string);
9689       create_breakpoint_sal (gdbarch, lsal->sals,
9690                              addr_string,
9691                              filter_string,
9692                              cond_string, extra_string,
9693                              type, disposition,
9694                              thread, task, ignore_count, ops,
9695                              from_tty, enabled, internal, flags,
9696                              canonical->special_display);
9697       discard_cleanups (inner);
9698     }
9699 }
9700
9701 /* Parse ADDRESS which is assumed to be a SAL specification possibly
9702    followed by conditionals.  On return, SALS contains an array of SAL
9703    addresses found.  ADDR_STRING contains a vector of (canonical)
9704    address strings.  ADDRESS points to the end of the SAL.
9705
9706    The array and the line spec strings are allocated on the heap, it is
9707    the caller's responsibility to free them.  */
9708
9709 static void
9710 parse_breakpoint_sals (char **address,
9711                        struct linespec_result *canonical)
9712 {
9713   /* If no arg given, or if first arg is 'if ', use the default
9714      breakpoint.  */
9715   if ((*address) == NULL
9716       || (strncmp ((*address), "if", 2) == 0 && isspace ((*address)[2])))
9717     {
9718       /* The last displayed codepoint, if it's valid, is our default breakpoint
9719          address.  */
9720       if (last_displayed_sal_is_valid ())
9721         {
9722           struct linespec_sals lsal;
9723           struct symtab_and_line sal;
9724           CORE_ADDR pc;
9725
9726           init_sal (&sal);              /* Initialize to zeroes.  */
9727           lsal.sals.sals = (struct symtab_and_line *)
9728             xmalloc (sizeof (struct symtab_and_line));
9729
9730           /* Set sal's pspace, pc, symtab, and line to the values
9731              corresponding to the last call to print_frame_info.
9732              Be sure to reinitialize LINE with NOTCURRENT == 0
9733              as the breakpoint line number is inappropriate otherwise.
9734              find_pc_line would adjust PC, re-set it back.  */
9735           get_last_displayed_sal (&sal);
9736           pc = sal.pc;
9737           sal = find_pc_line (pc, 0);
9738
9739           /* "break" without arguments is equivalent to "break *PC"
9740              where PC is the last displayed codepoint's address.  So
9741              make sure to set sal.explicit_pc to prevent GDB from
9742              trying to expand the list of sals to include all other
9743              instances with the same symtab and line.  */
9744           sal.pc = pc;
9745           sal.explicit_pc = 1;
9746
9747           lsal.sals.sals[0] = sal;
9748           lsal.sals.nelts = 1;
9749           lsal.canonical = NULL;
9750
9751           VEC_safe_push (linespec_sals, canonical->sals, &lsal);
9752         }
9753       else
9754         error (_("No default breakpoint address now."));
9755     }
9756   else
9757     {
9758       struct symtab_and_line cursal = get_current_source_symtab_and_line ();
9759
9760       /* Force almost all breakpoints to be in terms of the
9761          current_source_symtab (which is decode_line_1's default).
9762          This should produce the results we want almost all of the
9763          time while leaving default_breakpoint_* alone.
9764
9765          ObjC: However, don't match an Objective-C method name which
9766          may have a '+' or '-' succeeded by a '['.  */
9767       if (last_displayed_sal_is_valid ()
9768           && (!cursal.symtab
9769               || ((strchr ("+-", (*address)[0]) != NULL)
9770                   && ((*address)[1] != '['))))
9771         decode_line_full (address, DECODE_LINE_FUNFIRSTLINE,
9772                           get_last_displayed_symtab (),
9773                           get_last_displayed_line (),
9774                           canonical, NULL, NULL);
9775       else
9776         decode_line_full (address, DECODE_LINE_FUNFIRSTLINE,
9777                           cursal.symtab, cursal.line, canonical, NULL, NULL);
9778     }
9779 }
9780
9781
9782 /* Convert each SAL into a real PC.  Verify that the PC can be
9783    inserted as a breakpoint.  If it can't throw an error.  */
9784
9785 static void
9786 breakpoint_sals_to_pc (struct symtabs_and_lines *sals)
9787 {    
9788   int i;
9789
9790   for (i = 0; i < sals->nelts; i++)
9791     resolve_sal_pc (&sals->sals[i]);
9792 }
9793
9794 /* Fast tracepoints may have restrictions on valid locations.  For
9795    instance, a fast tracepoint using a jump instead of a trap will
9796    likely have to overwrite more bytes than a trap would, and so can
9797    only be placed where the instruction is longer than the jump, or a
9798    multi-instruction sequence does not have a jump into the middle of
9799    it, etc.  */
9800
9801 static void
9802 check_fast_tracepoint_sals (struct gdbarch *gdbarch,
9803                             struct symtabs_and_lines *sals)
9804 {
9805   int i, rslt;
9806   struct symtab_and_line *sal;
9807   char *msg;
9808   struct cleanup *old_chain;
9809
9810   for (i = 0; i < sals->nelts; i++)
9811     {
9812       struct gdbarch *sarch;
9813
9814       sal = &sals->sals[i];
9815
9816       sarch = get_sal_arch (*sal);
9817       /* We fall back to GDBARCH if there is no architecture
9818          associated with SAL.  */
9819       if (sarch == NULL)
9820         sarch = gdbarch;
9821       rslt = gdbarch_fast_tracepoint_valid_at (sarch, sal->pc,
9822                                                NULL, &msg);
9823       old_chain = make_cleanup (xfree, msg);
9824
9825       if (!rslt)
9826         error (_("May not have a fast tracepoint at 0x%s%s"),
9827                paddress (sarch, sal->pc), (msg ? msg : ""));
9828
9829       do_cleanups (old_chain);
9830     }
9831 }
9832
9833 /* Issue an invalid thread ID error.  */
9834
9835 static void ATTRIBUTE_NORETURN
9836 invalid_thread_id_error (int id)
9837 {
9838   error (_("Unknown thread %d."), id);
9839 }
9840
9841 /* Given TOK, a string specification of condition and thread, as
9842    accepted by the 'break' command, extract the condition
9843    string and thread number and set *COND_STRING and *THREAD.
9844    PC identifies the context at which the condition should be parsed.
9845    If no condition is found, *COND_STRING is set to NULL.
9846    If no thread is found, *THREAD is set to -1.  */
9847
9848 static void
9849 find_condition_and_thread (const char *tok, CORE_ADDR pc,
9850                            char **cond_string, int *thread, int *task,
9851                            char **rest)
9852 {
9853   *cond_string = NULL;
9854   *thread = -1;
9855   *task = 0;
9856   *rest = NULL;
9857
9858   while (tok && *tok)
9859     {
9860       const char *end_tok;
9861       int toklen;
9862       const char *cond_start = NULL;
9863       const char *cond_end = NULL;
9864
9865       tok = skip_spaces_const (tok);
9866
9867       if ((*tok == '"' || *tok == ',') && rest)
9868         {
9869           *rest = savestring (tok, strlen (tok));
9870           return;
9871         }
9872
9873       end_tok = skip_to_space_const (tok);
9874
9875       toklen = end_tok - tok;
9876
9877       if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
9878         {
9879           struct expression *expr;
9880
9881           tok = cond_start = end_tok + 1;
9882           expr = parse_exp_1 (&tok, pc, block_for_pc (pc), 0);
9883           xfree (expr);
9884           cond_end = tok;
9885           *cond_string = savestring (cond_start, cond_end - cond_start);
9886         }
9887       else if (toklen >= 1 && strncmp (tok, "thread", toklen) == 0)
9888         {
9889           char *tmptok;
9890
9891           tok = end_tok + 1;
9892           *thread = strtol (tok, &tmptok, 0);
9893           if (tok == tmptok)
9894             error (_("Junk after thread keyword."));
9895           if (!valid_thread_id (*thread))
9896             invalid_thread_id_error (*thread);
9897           tok = tmptok;
9898         }
9899       else if (toklen >= 1 && strncmp (tok, "task", toklen) == 0)
9900         {
9901           char *tmptok;
9902
9903           tok = end_tok + 1;
9904           *task = strtol (tok, &tmptok, 0);
9905           if (tok == tmptok)
9906             error (_("Junk after task keyword."));
9907           if (!valid_task_id (*task))
9908             error (_("Unknown task %d."), *task);
9909           tok = tmptok;
9910         }
9911       else if (rest)
9912         {
9913           *rest = savestring (tok, strlen (tok));
9914           return;
9915         }
9916       else
9917         error (_("Junk at end of arguments."));
9918     }
9919 }
9920
9921 /* Decode a static tracepoint marker spec.  */
9922
9923 static struct symtabs_and_lines
9924 decode_static_tracepoint_spec (char **arg_p)
9925 {
9926   VEC(static_tracepoint_marker_p) *markers = NULL;
9927   struct symtabs_and_lines sals;
9928   struct cleanup *old_chain;
9929   char *p = &(*arg_p)[3];
9930   char *endp;
9931   char *marker_str;
9932   int i;
9933
9934   p = skip_spaces (p);
9935
9936   endp = skip_to_space (p);
9937
9938   marker_str = savestring (p, endp - p);
9939   old_chain = make_cleanup (xfree, marker_str);
9940
9941   markers = target_static_tracepoint_markers_by_strid (marker_str);
9942   if (VEC_empty(static_tracepoint_marker_p, markers))
9943     error (_("No known static tracepoint marker named %s"), marker_str);
9944
9945   sals.nelts = VEC_length(static_tracepoint_marker_p, markers);
9946   sals.sals = xmalloc (sizeof *sals.sals * sals.nelts);
9947
9948   for (i = 0; i < sals.nelts; i++)
9949     {
9950       struct static_tracepoint_marker *marker;
9951
9952       marker = VEC_index (static_tracepoint_marker_p, markers, i);
9953
9954       init_sal (&sals.sals[i]);
9955
9956       sals.sals[i] = find_pc_line (marker->address, 0);
9957       sals.sals[i].pc = marker->address;
9958
9959       release_static_tracepoint_marker (marker);
9960     }
9961
9962   do_cleanups (old_chain);
9963
9964   *arg_p = endp;
9965   return sals;
9966 }
9967
9968 /* Set a breakpoint.  This function is shared between CLI and MI
9969    functions for setting a breakpoint.  This function has two major
9970    modes of operations, selected by the PARSE_ARG parameter.  If
9971    non-zero, the function will parse ARG, extracting location,
9972    condition, thread and extra string.  Otherwise, ARG is just the
9973    breakpoint's location, with condition, thread, and extra string
9974    specified by the COND_STRING, THREAD and EXTRA_STRING parameters.
9975    If INTERNAL is non-zero, the breakpoint number will be allocated
9976    from the internal breakpoint count.  Returns true if any breakpoint
9977    was created; false otherwise.  */
9978
9979 int
9980 create_breakpoint (struct gdbarch *gdbarch,
9981                    char *arg, char *cond_string,
9982                    int thread, char *extra_string,
9983                    int parse_arg,
9984                    int tempflag, enum bptype type_wanted,
9985                    int ignore_count,
9986                    enum auto_boolean pending_break_support,
9987                    const struct breakpoint_ops *ops,
9988                    int from_tty, int enabled, int internal,
9989                    unsigned flags)
9990 {
9991   volatile struct gdb_exception e;
9992   char *copy_arg = NULL;
9993   char *addr_start = arg;
9994   struct linespec_result canonical;
9995   struct cleanup *old_chain;
9996   struct cleanup *bkpt_chain = NULL;
9997   int pending = 0;
9998   int task = 0;
9999   int prev_bkpt_count = breakpoint_count;
10000
10001   gdb_assert (ops != NULL);
10002
10003   init_linespec_result (&canonical);
10004
10005   TRY_CATCH (e, RETURN_MASK_ALL)
10006     {
10007       ops->create_sals_from_address (&arg, &canonical, type_wanted,
10008                                      addr_start, &copy_arg);
10009     }
10010
10011   /* If caller is interested in rc value from parse, set value.  */
10012   switch (e.reason)
10013     {
10014     case GDB_NO_ERROR:
10015       if (VEC_empty (linespec_sals, canonical.sals))
10016         return 0;
10017       break;
10018     case RETURN_ERROR:
10019       switch (e.error)
10020         {
10021         case NOT_FOUND_ERROR:
10022
10023           /* If pending breakpoint support is turned off, throw
10024              error.  */
10025
10026           if (pending_break_support == AUTO_BOOLEAN_FALSE)
10027             throw_exception (e);
10028
10029           exception_print (gdb_stderr, e);
10030
10031           /* If pending breakpoint support is auto query and the user
10032              selects no, then simply return the error code.  */
10033           if (pending_break_support == AUTO_BOOLEAN_AUTO
10034               && !nquery (_("Make %s pending on future shared library load? "),
10035                           bptype_string (type_wanted)))
10036             return 0;
10037
10038           /* At this point, either the user was queried about setting
10039              a pending breakpoint and selected yes, or pending
10040              breakpoint behavior is on and thus a pending breakpoint
10041              is defaulted on behalf of the user.  */
10042           {
10043             struct linespec_sals lsal;
10044
10045             copy_arg = xstrdup (addr_start);
10046             lsal.canonical = xstrdup (copy_arg);
10047             lsal.sals.nelts = 1;
10048             lsal.sals.sals = XNEW (struct symtab_and_line);
10049             init_sal (&lsal.sals.sals[0]);
10050             pending = 1;
10051             VEC_safe_push (linespec_sals, canonical.sals, &lsal);
10052           }
10053           break;
10054         default:
10055           throw_exception (e);
10056         }
10057       break;
10058     default:
10059       throw_exception (e);
10060     }
10061
10062   /* Create a chain of things that always need to be cleaned up.  */
10063   old_chain = make_cleanup_destroy_linespec_result (&canonical);
10064
10065   /* ----------------------------- SNIP -----------------------------
10066      Anything added to the cleanup chain beyond this point is assumed
10067      to be part of a breakpoint.  If the breakpoint create succeeds
10068      then the memory is not reclaimed.  */
10069   bkpt_chain = make_cleanup (null_cleanup, 0);
10070
10071   /* Resolve all line numbers to PC's and verify that the addresses
10072      are ok for the target.  */
10073   if (!pending)
10074     {
10075       int ix;
10076       struct linespec_sals *iter;
10077
10078       for (ix = 0; VEC_iterate (linespec_sals, canonical.sals, ix, iter); ++ix)
10079         breakpoint_sals_to_pc (&iter->sals);
10080     }
10081
10082   /* Fast tracepoints may have additional restrictions on location.  */
10083   if (!pending && type_wanted == bp_fast_tracepoint)
10084     {
10085       int ix;
10086       struct linespec_sals *iter;
10087
10088       for (ix = 0; VEC_iterate (linespec_sals, canonical.sals, ix, iter); ++ix)
10089         check_fast_tracepoint_sals (gdbarch, &iter->sals);
10090     }
10091
10092   /* Verify that condition can be parsed, before setting any
10093      breakpoints.  Allocate a separate condition expression for each
10094      breakpoint.  */
10095   if (!pending)
10096     {
10097       if (parse_arg)
10098         {
10099           char *rest;
10100           struct linespec_sals *lsal;
10101
10102           lsal = VEC_index (linespec_sals, canonical.sals, 0);
10103
10104           /* Here we only parse 'arg' to separate condition
10105              from thread number, so parsing in context of first
10106              sal is OK.  When setting the breakpoint we'll
10107              re-parse it in context of each sal.  */
10108
10109           find_condition_and_thread (arg, lsal->sals.sals[0].pc, &cond_string,
10110                                      &thread, &task, &rest);
10111           if (cond_string)
10112             make_cleanup (xfree, cond_string);
10113           if (rest)
10114             make_cleanup (xfree, rest);
10115           if (rest)
10116             extra_string = rest;
10117         }
10118       else
10119         {
10120           if (*arg != '\0')
10121             error (_("Garbage '%s' at end of location"), arg);
10122
10123           /* Create a private copy of condition string.  */
10124           if (cond_string)
10125             {
10126               cond_string = xstrdup (cond_string);
10127               make_cleanup (xfree, cond_string);
10128             }
10129           /* Create a private copy of any extra string.  */
10130           if (extra_string)
10131             {
10132               extra_string = xstrdup (extra_string);
10133               make_cleanup (xfree, extra_string);
10134             }
10135         }
10136
10137       ops->create_breakpoints_sal (gdbarch, &canonical,
10138                                    cond_string, extra_string, type_wanted,
10139                                    tempflag ? disp_del : disp_donttouch,
10140                                    thread, task, ignore_count, ops,
10141                                    from_tty, enabled, internal, flags);
10142     }
10143   else
10144     {
10145       struct breakpoint *b;
10146
10147       make_cleanup (xfree, copy_arg);
10148
10149       if (is_tracepoint_type (type_wanted))
10150         {
10151           struct tracepoint *t;
10152
10153           t = XCNEW (struct tracepoint);
10154           b = &t->base;
10155         }
10156       else
10157         b = XNEW (struct breakpoint);
10158
10159       init_raw_breakpoint_without_location (b, gdbarch, type_wanted, ops);
10160
10161       b->addr_string = copy_arg;
10162       if (parse_arg)
10163         b->cond_string = NULL;
10164       else
10165         {
10166           /* Create a private copy of condition string.  */
10167           if (cond_string)
10168             {
10169               cond_string = xstrdup (cond_string);
10170               make_cleanup (xfree, cond_string);
10171             }
10172           b->cond_string = cond_string;
10173         }
10174       b->extra_string = NULL;
10175       b->ignore_count = ignore_count;
10176       b->disposition = tempflag ? disp_del : disp_donttouch;
10177       b->condition_not_parsed = 1;
10178       b->enable_state = enabled ? bp_enabled : bp_disabled;
10179       if ((type_wanted != bp_breakpoint
10180            && type_wanted != bp_hardware_breakpoint) || thread != -1)
10181         b->pspace = current_program_space;
10182
10183       install_breakpoint (internal, b, 0);
10184     }
10185   
10186   if (VEC_length (linespec_sals, canonical.sals) > 1)
10187     {
10188       warning (_("Multiple breakpoints were set.\nUse the "
10189                  "\"delete\" command to delete unwanted breakpoints."));
10190       prev_breakpoint_count = prev_bkpt_count;
10191     }
10192
10193   /* That's it.  Discard the cleanups for data inserted into the
10194      breakpoint.  */
10195   discard_cleanups (bkpt_chain);
10196   /* But cleanup everything else.  */
10197   do_cleanups (old_chain);
10198
10199   /* error call may happen here - have BKPT_CHAIN already discarded.  */
10200   update_global_location_list (UGLL_MAY_INSERT);
10201
10202   return 1;
10203 }
10204
10205 /* Set a breakpoint.
10206    ARG is a string describing breakpoint address,
10207    condition, and thread.
10208    FLAG specifies if a breakpoint is hardware on,
10209    and if breakpoint is temporary, using BP_HARDWARE_FLAG
10210    and BP_TEMPFLAG.  */
10211
10212 static void
10213 break_command_1 (char *arg, int flag, int from_tty)
10214 {
10215   int tempflag = flag & BP_TEMPFLAG;
10216   enum bptype type_wanted = (flag & BP_HARDWAREFLAG
10217                              ? bp_hardware_breakpoint
10218                              : bp_breakpoint);
10219   struct breakpoint_ops *ops;
10220   const char *arg_cp = arg;
10221
10222   /* Matching breakpoints on probes.  */
10223   if (arg && probe_linespec_to_ops (&arg_cp) != NULL)
10224     ops = &bkpt_probe_breakpoint_ops;
10225   else
10226     ops = &bkpt_breakpoint_ops;
10227
10228   create_breakpoint (get_current_arch (),
10229                      arg,
10230                      NULL, 0, NULL, 1 /* parse arg */,
10231                      tempflag, type_wanted,
10232                      0 /* Ignore count */,
10233                      pending_break_support,
10234                      ops,
10235                      from_tty,
10236                      1 /* enabled */,
10237                      0 /* internal */,
10238                      0);
10239 }
10240
10241 /* Helper function for break_command_1 and disassemble_command.  */
10242
10243 void
10244 resolve_sal_pc (struct symtab_and_line *sal)
10245 {
10246   CORE_ADDR pc;
10247
10248   if (sal->pc == 0 && sal->symtab != NULL)
10249     {
10250       if (!find_line_pc (sal->symtab, sal->line, &pc))
10251         error (_("No line %d in file \"%s\"."),
10252                sal->line, symtab_to_filename_for_display (sal->symtab));
10253       sal->pc = pc;
10254
10255       /* If this SAL corresponds to a breakpoint inserted using a line
10256          number, then skip the function prologue if necessary.  */
10257       if (sal->explicit_line)
10258         skip_prologue_sal (sal);
10259     }
10260
10261   if (sal->section == 0 && sal->symtab != NULL)
10262     {
10263       const struct blockvector *bv;
10264       const struct block *b;
10265       struct symbol *sym;
10266
10267       bv = blockvector_for_pc_sect (sal->pc, 0, &b, sal->symtab);
10268       if (bv != NULL)
10269         {
10270           sym = block_linkage_function (b);
10271           if (sym != NULL)
10272             {
10273               fixup_symbol_section (sym, sal->symtab->objfile);
10274               sal->section = SYMBOL_OBJ_SECTION (sal->symtab->objfile, sym);
10275             }
10276           else
10277             {
10278               /* It really is worthwhile to have the section, so we'll
10279                  just have to look harder. This case can be executed
10280                  if we have line numbers but no functions (as can
10281                  happen in assembly source).  */
10282
10283               struct bound_minimal_symbol msym;
10284               struct cleanup *old_chain = save_current_space_and_thread ();
10285
10286               switch_to_program_space_and_thread (sal->pspace);
10287
10288               msym = lookup_minimal_symbol_by_pc (sal->pc);
10289               if (msym.minsym)
10290                 sal->section = MSYMBOL_OBJ_SECTION (msym.objfile, msym.minsym);
10291
10292               do_cleanups (old_chain);
10293             }
10294         }
10295     }
10296 }
10297
10298 void
10299 break_command (char *arg, int from_tty)
10300 {
10301   break_command_1 (arg, 0, from_tty);
10302 }
10303
10304 void
10305 tbreak_command (char *arg, int from_tty)
10306 {
10307   break_command_1 (arg, BP_TEMPFLAG, from_tty);
10308 }
10309
10310 static void
10311 hbreak_command (char *arg, int from_tty)
10312 {
10313   break_command_1 (arg, BP_HARDWAREFLAG, from_tty);
10314 }
10315
10316 static void
10317 thbreak_command (char *arg, int from_tty)
10318 {
10319   break_command_1 (arg, (BP_TEMPFLAG | BP_HARDWAREFLAG), from_tty);
10320 }
10321
10322 static void
10323 stop_command (char *arg, int from_tty)
10324 {
10325   printf_filtered (_("Specify the type of breakpoint to set.\n\
10326 Usage: stop in <function | address>\n\
10327        stop at <line>\n"));
10328 }
10329
10330 static void
10331 stopin_command (char *arg, int from_tty)
10332 {
10333   int badInput = 0;
10334
10335   if (arg == (char *) NULL)
10336     badInput = 1;
10337   else if (*arg != '*')
10338     {
10339       char *argptr = arg;
10340       int hasColon = 0;
10341
10342       /* Look for a ':'.  If this is a line number specification, then
10343          say it is bad, otherwise, it should be an address or
10344          function/method name.  */
10345       while (*argptr && !hasColon)
10346         {
10347           hasColon = (*argptr == ':');
10348           argptr++;
10349         }
10350
10351       if (hasColon)
10352         badInput = (*argptr != ':');    /* Not a class::method */
10353       else
10354         badInput = isdigit (*arg);      /* a simple line number */
10355     }
10356
10357   if (badInput)
10358     printf_filtered (_("Usage: stop in <function | address>\n"));
10359   else
10360     break_command_1 (arg, 0, from_tty);
10361 }
10362
10363 static void
10364 stopat_command (char *arg, int from_tty)
10365 {
10366   int badInput = 0;
10367
10368   if (arg == (char *) NULL || *arg == '*')      /* no line number */
10369     badInput = 1;
10370   else
10371     {
10372       char *argptr = arg;
10373       int hasColon = 0;
10374
10375       /* Look for a ':'.  If there is a '::' then get out, otherwise
10376          it is probably a line number.  */
10377       while (*argptr && !hasColon)
10378         {
10379           hasColon = (*argptr == ':');
10380           argptr++;
10381         }
10382
10383       if (hasColon)
10384         badInput = (*argptr == ':');    /* we have class::method */
10385       else
10386         badInput = !isdigit (*arg);     /* not a line number */
10387     }
10388
10389   if (badInput)
10390     printf_filtered (_("Usage: stop at <line>\n"));
10391   else
10392     break_command_1 (arg, 0, from_tty);
10393 }
10394
10395 /* The dynamic printf command is mostly like a regular breakpoint, but
10396    with a prewired command list consisting of a single output command,
10397    built from extra arguments supplied on the dprintf command
10398    line.  */
10399
10400 static void
10401 dprintf_command (char *arg, int from_tty)
10402 {
10403   create_breakpoint (get_current_arch (),
10404                      arg,
10405                      NULL, 0, NULL, 1 /* parse arg */,
10406                      0, bp_dprintf,
10407                      0 /* Ignore count */,
10408                      pending_break_support,
10409                      &dprintf_breakpoint_ops,
10410                      from_tty,
10411                      1 /* enabled */,
10412                      0 /* internal */,
10413                      0);
10414 }
10415
10416 static void
10417 agent_printf_command (char *arg, int from_tty)
10418 {
10419   error (_("May only run agent-printf on the target"));
10420 }
10421
10422 /* Implement the "breakpoint_hit" breakpoint_ops method for
10423    ranged breakpoints.  */
10424
10425 static int
10426 breakpoint_hit_ranged_breakpoint (const struct bp_location *bl,
10427                                   struct address_space *aspace,
10428                                   CORE_ADDR bp_addr,
10429                                   const struct target_waitstatus *ws)
10430 {
10431   if (ws->kind != TARGET_WAITKIND_STOPPED
10432       || ws->value.sig != GDB_SIGNAL_TRAP)
10433     return 0;
10434
10435   return breakpoint_address_match_range (bl->pspace->aspace, bl->address,
10436                                          bl->length, aspace, bp_addr);
10437 }
10438
10439 /* Implement the "resources_needed" breakpoint_ops method for
10440    ranged breakpoints.  */
10441
10442 static int
10443 resources_needed_ranged_breakpoint (const struct bp_location *bl)
10444 {
10445   return target_ranged_break_num_registers ();
10446 }
10447
10448 /* Implement the "print_it" breakpoint_ops method for
10449    ranged breakpoints.  */
10450
10451 static enum print_stop_action
10452 print_it_ranged_breakpoint (bpstat bs)
10453 {
10454   struct breakpoint *b = bs->breakpoint_at;
10455   struct bp_location *bl = b->loc;
10456   struct ui_out *uiout = current_uiout;
10457
10458   gdb_assert (b->type == bp_hardware_breakpoint);
10459
10460   /* Ranged breakpoints have only one location.  */
10461   gdb_assert (bl && bl->next == NULL);
10462
10463   annotate_breakpoint (b->number);
10464   if (b->disposition == disp_del)
10465     ui_out_text (uiout, "\nTemporary ranged breakpoint ");
10466   else
10467     ui_out_text (uiout, "\nRanged breakpoint ");
10468   if (ui_out_is_mi_like_p (uiout))
10469     {
10470       ui_out_field_string (uiout, "reason",
10471                       async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
10472       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
10473     }
10474   ui_out_field_int (uiout, "bkptno", b->number);
10475   ui_out_text (uiout, ", ");
10476
10477   return PRINT_SRC_AND_LOC;
10478 }
10479
10480 /* Implement the "print_one" breakpoint_ops method for
10481    ranged breakpoints.  */
10482
10483 static void
10484 print_one_ranged_breakpoint (struct breakpoint *b,
10485                              struct bp_location **last_loc)
10486 {
10487   struct bp_location *bl = b->loc;
10488   struct value_print_options opts;
10489   struct ui_out *uiout = current_uiout;
10490
10491   /* Ranged breakpoints have only one location.  */
10492   gdb_assert (bl && bl->next == NULL);
10493
10494   get_user_print_options (&opts);
10495
10496   if (opts.addressprint)
10497     /* We don't print the address range here, it will be printed later
10498        by print_one_detail_ranged_breakpoint.  */
10499     ui_out_field_skip (uiout, "addr");
10500   annotate_field (5);
10501   print_breakpoint_location (b, bl);
10502   *last_loc = bl;
10503 }
10504
10505 /* Implement the "print_one_detail" breakpoint_ops method for
10506    ranged breakpoints.  */
10507
10508 static void
10509 print_one_detail_ranged_breakpoint (const struct breakpoint *b,
10510                                     struct ui_out *uiout)
10511 {
10512   CORE_ADDR address_start, address_end;
10513   struct bp_location *bl = b->loc;
10514   struct ui_file *stb = mem_fileopen ();
10515   struct cleanup *cleanup = make_cleanup_ui_file_delete (stb);
10516
10517   gdb_assert (bl);
10518
10519   address_start = bl->address;
10520   address_end = address_start + bl->length - 1;
10521
10522   ui_out_text (uiout, "\taddress range: ");
10523   fprintf_unfiltered (stb, "[%s, %s]",
10524                       print_core_address (bl->gdbarch, address_start),
10525                       print_core_address (bl->gdbarch, address_end));
10526   ui_out_field_stream (uiout, "addr", stb);
10527   ui_out_text (uiout, "\n");
10528
10529   do_cleanups (cleanup);
10530 }
10531
10532 /* Implement the "print_mention" breakpoint_ops method for
10533    ranged breakpoints.  */
10534
10535 static void
10536 print_mention_ranged_breakpoint (struct breakpoint *b)
10537 {
10538   struct bp_location *bl = b->loc;
10539   struct ui_out *uiout = current_uiout;
10540
10541   gdb_assert (bl);
10542   gdb_assert (b->type == bp_hardware_breakpoint);
10543
10544   if (ui_out_is_mi_like_p (uiout))
10545     return;
10546
10547   printf_filtered (_("Hardware assisted ranged breakpoint %d from %s to %s."),
10548                    b->number, paddress (bl->gdbarch, bl->address),
10549                    paddress (bl->gdbarch, bl->address + bl->length - 1));
10550 }
10551
10552 /* Implement the "print_recreate" breakpoint_ops method for
10553    ranged breakpoints.  */
10554
10555 static void
10556 print_recreate_ranged_breakpoint (struct breakpoint *b, struct ui_file *fp)
10557 {
10558   fprintf_unfiltered (fp, "break-range %s, %s", b->addr_string,
10559                       b->addr_string_range_end);
10560   print_recreate_thread (b, fp);
10561 }
10562
10563 /* The breakpoint_ops structure to be used in ranged breakpoints.  */
10564
10565 static struct breakpoint_ops ranged_breakpoint_ops;
10566
10567 /* Find the address where the end of the breakpoint range should be
10568    placed, given the SAL of the end of the range.  This is so that if
10569    the user provides a line number, the end of the range is set to the
10570    last instruction of the given line.  */
10571
10572 static CORE_ADDR
10573 find_breakpoint_range_end (struct symtab_and_line sal)
10574 {
10575   CORE_ADDR end;
10576
10577   /* If the user provided a PC value, use it.  Otherwise,
10578      find the address of the end of the given location.  */
10579   if (sal.explicit_pc)
10580     end = sal.pc;
10581   else
10582     {
10583       int ret;
10584       CORE_ADDR start;
10585
10586       ret = find_line_pc_range (sal, &start, &end);
10587       if (!ret)
10588         error (_("Could not find location of the end of the range."));
10589
10590       /* find_line_pc_range returns the start of the next line.  */
10591       end--;
10592     }
10593
10594   return end;
10595 }
10596
10597 /* Implement the "break-range" CLI command.  */
10598
10599 static void
10600 break_range_command (char *arg, int from_tty)
10601 {
10602   char *arg_start, *addr_string_start, *addr_string_end;
10603   struct linespec_result canonical_start, canonical_end;
10604   int bp_count, can_use_bp, length;
10605   CORE_ADDR end;
10606   struct breakpoint *b;
10607   struct symtab_and_line sal_start, sal_end;
10608   struct cleanup *cleanup_bkpt;
10609   struct linespec_sals *lsal_start, *lsal_end;
10610
10611   /* We don't support software ranged breakpoints.  */
10612   if (target_ranged_break_num_registers () < 0)
10613     error (_("This target does not support hardware ranged breakpoints."));
10614
10615   bp_count = hw_breakpoint_used_count ();
10616   bp_count += target_ranged_break_num_registers ();
10617   can_use_bp = target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
10618                                                    bp_count, 0);
10619   if (can_use_bp < 0)
10620     error (_("Hardware breakpoints used exceeds limit."));
10621
10622   arg = skip_spaces (arg);
10623   if (arg == NULL || arg[0] == '\0')
10624     error(_("No address range specified."));
10625
10626   init_linespec_result (&canonical_start);
10627
10628   arg_start = arg;
10629   parse_breakpoint_sals (&arg, &canonical_start);
10630
10631   cleanup_bkpt = make_cleanup_destroy_linespec_result (&canonical_start);
10632
10633   if (arg[0] != ',')
10634     error (_("Too few arguments."));
10635   else if (VEC_empty (linespec_sals, canonical_start.sals))
10636     error (_("Could not find location of the beginning of the range."));
10637
10638   lsal_start = VEC_index (linespec_sals, canonical_start.sals, 0);
10639
10640   if (VEC_length (linespec_sals, canonical_start.sals) > 1
10641       || lsal_start->sals.nelts != 1)
10642     error (_("Cannot create a ranged breakpoint with multiple locations."));
10643
10644   sal_start = lsal_start->sals.sals[0];
10645   addr_string_start = savestring (arg_start, arg - arg_start);
10646   make_cleanup (xfree, addr_string_start);
10647
10648   arg++;        /* Skip the comma.  */
10649   arg = skip_spaces (arg);
10650
10651   /* Parse the end location.  */
10652
10653   init_linespec_result (&canonical_end);
10654   arg_start = arg;
10655
10656   /* We call decode_line_full directly here instead of using
10657      parse_breakpoint_sals because we need to specify the start location's
10658      symtab and line as the default symtab and line for the end of the
10659      range.  This makes it possible to have ranges like "foo.c:27, +14",
10660      where +14 means 14 lines from the start location.  */
10661   decode_line_full (&arg, DECODE_LINE_FUNFIRSTLINE,
10662                     sal_start.symtab, sal_start.line,
10663                     &canonical_end, NULL, NULL);
10664
10665   make_cleanup_destroy_linespec_result (&canonical_end);
10666
10667   if (VEC_empty (linespec_sals, canonical_end.sals))
10668     error (_("Could not find location of the end of the range."));
10669
10670   lsal_end = VEC_index (linespec_sals, canonical_end.sals, 0);
10671   if (VEC_length (linespec_sals, canonical_end.sals) > 1
10672       || lsal_end->sals.nelts != 1)
10673     error (_("Cannot create a ranged breakpoint with multiple locations."));
10674
10675   sal_end = lsal_end->sals.sals[0];
10676   addr_string_end = savestring (arg_start, arg - arg_start);
10677   make_cleanup (xfree, addr_string_end);
10678
10679   end = find_breakpoint_range_end (sal_end);
10680   if (sal_start.pc > end)
10681     error (_("Invalid address range, end precedes start."));
10682
10683   length = end - sal_start.pc + 1;
10684   if (length < 0)
10685     /* Length overflowed.  */
10686     error (_("Address range too large."));
10687   else if (length == 1)
10688     {
10689       /* This range is simple enough to be handled by
10690          the `hbreak' command.  */
10691       hbreak_command (addr_string_start, 1);
10692
10693       do_cleanups (cleanup_bkpt);
10694
10695       return;
10696     }
10697
10698   /* Now set up the breakpoint.  */
10699   b = set_raw_breakpoint (get_current_arch (), sal_start,
10700                           bp_hardware_breakpoint, &ranged_breakpoint_ops);
10701   set_breakpoint_count (breakpoint_count + 1);
10702   b->number = breakpoint_count;
10703   b->disposition = disp_donttouch;
10704   b->addr_string = xstrdup (addr_string_start);
10705   b->addr_string_range_end = xstrdup (addr_string_end);
10706   b->loc->length = length;
10707
10708   do_cleanups (cleanup_bkpt);
10709
10710   mention (b);
10711   observer_notify_breakpoint_created (b);
10712   update_global_location_list (UGLL_MAY_INSERT);
10713 }
10714
10715 /*  Return non-zero if EXP is verified as constant.  Returned zero
10716     means EXP is variable.  Also the constant detection may fail for
10717     some constant expressions and in such case still falsely return
10718     zero.  */
10719
10720 static int
10721 watchpoint_exp_is_const (const struct expression *exp)
10722 {
10723   int i = exp->nelts;
10724
10725   while (i > 0)
10726     {
10727       int oplenp, argsp;
10728
10729       /* We are only interested in the descriptor of each element.  */
10730       operator_length (exp, i, &oplenp, &argsp);
10731       i -= oplenp;
10732
10733       switch (exp->elts[i].opcode)
10734         {
10735         case BINOP_ADD:
10736         case BINOP_SUB:
10737         case BINOP_MUL:
10738         case BINOP_DIV:
10739         case BINOP_REM:
10740         case BINOP_MOD:
10741         case BINOP_LSH:
10742         case BINOP_RSH:
10743         case BINOP_LOGICAL_AND:
10744         case BINOP_LOGICAL_OR:
10745         case BINOP_BITWISE_AND:
10746         case BINOP_BITWISE_IOR:
10747         case BINOP_BITWISE_XOR:
10748         case BINOP_EQUAL:
10749         case BINOP_NOTEQUAL:
10750         case BINOP_LESS:
10751         case BINOP_GTR:
10752         case BINOP_LEQ:
10753         case BINOP_GEQ:
10754         case BINOP_REPEAT:
10755         case BINOP_COMMA:
10756         case BINOP_EXP:
10757         case BINOP_MIN:
10758         case BINOP_MAX:
10759         case BINOP_INTDIV:
10760         case BINOP_CONCAT:
10761         case TERNOP_COND:
10762         case TERNOP_SLICE:
10763
10764         case OP_LONG:
10765         case OP_DOUBLE:
10766         case OP_DECFLOAT:
10767         case OP_LAST:
10768         case OP_COMPLEX:
10769         case OP_STRING:
10770         case OP_ARRAY:
10771         case OP_TYPE:
10772         case OP_TYPEOF:
10773         case OP_DECLTYPE:
10774         case OP_TYPEID:
10775         case OP_NAME:
10776         case OP_OBJC_NSSTRING:
10777
10778         case UNOP_NEG:
10779         case UNOP_LOGICAL_NOT:
10780         case UNOP_COMPLEMENT:
10781         case UNOP_ADDR:
10782         case UNOP_HIGH:
10783         case UNOP_CAST:
10784
10785         case UNOP_CAST_TYPE:
10786         case UNOP_REINTERPRET_CAST:
10787         case UNOP_DYNAMIC_CAST:
10788           /* Unary, binary and ternary operators: We have to check
10789              their operands.  If they are constant, then so is the
10790              result of that operation.  For instance, if A and B are
10791              determined to be constants, then so is "A + B".
10792
10793              UNOP_IND is one exception to the rule above, because the
10794              value of *ADDR is not necessarily a constant, even when
10795              ADDR is.  */
10796           break;
10797
10798         case OP_VAR_VALUE:
10799           /* Check whether the associated symbol is a constant.
10800
10801              We use SYMBOL_CLASS rather than TYPE_CONST because it's
10802              possible that a buggy compiler could mark a variable as
10803              constant even when it is not, and TYPE_CONST would return
10804              true in this case, while SYMBOL_CLASS wouldn't.
10805
10806              We also have to check for function symbols because they
10807              are always constant.  */
10808           {
10809             struct symbol *s = exp->elts[i + 2].symbol;
10810
10811             if (SYMBOL_CLASS (s) != LOC_BLOCK
10812                 && SYMBOL_CLASS (s) != LOC_CONST
10813                 && SYMBOL_CLASS (s) != LOC_CONST_BYTES)
10814               return 0;
10815             break;
10816           }
10817
10818         /* The default action is to return 0 because we are using
10819            the optimistic approach here: If we don't know something,
10820            then it is not a constant.  */
10821         default:
10822           return 0;
10823         }
10824     }
10825
10826   return 1;
10827 }
10828
10829 /* Implement the "dtor" breakpoint_ops method for watchpoints.  */
10830
10831 static void
10832 dtor_watchpoint (struct breakpoint *self)
10833 {
10834   struct watchpoint *w = (struct watchpoint *) self;
10835
10836   xfree (w->cond_exp);
10837   xfree (w->exp);
10838   xfree (w->exp_string);
10839   xfree (w->exp_string_reparse);
10840   value_free (w->val);
10841
10842   base_breakpoint_ops.dtor (self);
10843 }
10844
10845 /* Implement the "re_set" breakpoint_ops method for watchpoints.  */
10846
10847 static void
10848 re_set_watchpoint (struct breakpoint *b)
10849 {
10850   struct watchpoint *w = (struct watchpoint *) b;
10851
10852   /* Watchpoint can be either on expression using entirely global
10853      variables, or it can be on local variables.
10854
10855      Watchpoints of the first kind are never auto-deleted, and even
10856      persist across program restarts.  Since they can use variables
10857      from shared libraries, we need to reparse expression as libraries
10858      are loaded and unloaded.
10859
10860      Watchpoints on local variables can also change meaning as result
10861      of solib event.  For example, if a watchpoint uses both a local
10862      and a global variables in expression, it's a local watchpoint,
10863      but unloading of a shared library will make the expression
10864      invalid.  This is not a very common use case, but we still
10865      re-evaluate expression, to avoid surprises to the user.
10866
10867      Note that for local watchpoints, we re-evaluate it only if
10868      watchpoints frame id is still valid.  If it's not, it means the
10869      watchpoint is out of scope and will be deleted soon.  In fact,
10870      I'm not sure we'll ever be called in this case.
10871
10872      If a local watchpoint's frame id is still valid, then
10873      w->exp_valid_block is likewise valid, and we can safely use it.
10874
10875      Don't do anything about disabled watchpoints, since they will be
10876      reevaluated again when enabled.  */
10877   update_watchpoint (w, 1 /* reparse */);
10878 }
10879
10880 /* Implement the "insert" breakpoint_ops method for hardware watchpoints.  */
10881
10882 static int
10883 insert_watchpoint (struct bp_location *bl)
10884 {
10885   struct watchpoint *w = (struct watchpoint *) bl->owner;
10886   int length = w->exact ? 1 : bl->length;
10887
10888   return target_insert_watchpoint (bl->address, length, bl->watchpoint_type,
10889                                    w->cond_exp);
10890 }
10891
10892 /* Implement the "remove" breakpoint_ops method for hardware watchpoints.  */
10893
10894 static int
10895 remove_watchpoint (struct bp_location *bl)
10896 {
10897   struct watchpoint *w = (struct watchpoint *) bl->owner;
10898   int length = w->exact ? 1 : bl->length;
10899
10900   return target_remove_watchpoint (bl->address, length, bl->watchpoint_type,
10901                                    w->cond_exp);
10902 }
10903
10904 static int
10905 breakpoint_hit_watchpoint (const struct bp_location *bl,
10906                            struct address_space *aspace, CORE_ADDR bp_addr,
10907                            const struct target_waitstatus *ws)
10908 {
10909   struct breakpoint *b = bl->owner;
10910   struct watchpoint *w = (struct watchpoint *) b;
10911
10912   /* Continuable hardware watchpoints are treated as non-existent if the
10913      reason we stopped wasn't a hardware watchpoint (we didn't stop on
10914      some data address).  Otherwise gdb won't stop on a break instruction
10915      in the code (not from a breakpoint) when a hardware watchpoint has
10916      been defined.  Also skip watchpoints which we know did not trigger
10917      (did not match the data address).  */
10918   if (is_hardware_watchpoint (b)
10919       && w->watchpoint_triggered == watch_triggered_no)
10920     return 0;
10921
10922   return 1;
10923 }
10924
10925 static void
10926 check_status_watchpoint (bpstat bs)
10927 {
10928   gdb_assert (is_watchpoint (bs->breakpoint_at));
10929
10930   bpstat_check_watchpoint (bs);
10931 }
10932
10933 /* Implement the "resources_needed" breakpoint_ops method for
10934    hardware watchpoints.  */
10935
10936 static int
10937 resources_needed_watchpoint (const struct bp_location *bl)
10938 {
10939   struct watchpoint *w = (struct watchpoint *) bl->owner;
10940   int length = w->exact? 1 : bl->length;
10941
10942   return target_region_ok_for_hw_watchpoint (bl->address, length);
10943 }
10944
10945 /* Implement the "works_in_software_mode" breakpoint_ops method for
10946    hardware watchpoints.  */
10947
10948 static int
10949 works_in_software_mode_watchpoint (const struct breakpoint *b)
10950 {
10951   /* Read and access watchpoints only work with hardware support.  */
10952   return b->type == bp_watchpoint || b->type == bp_hardware_watchpoint;
10953 }
10954
10955 static enum print_stop_action
10956 print_it_watchpoint (bpstat bs)
10957 {
10958   struct cleanup *old_chain;
10959   struct breakpoint *b;
10960   struct ui_file *stb;
10961   enum print_stop_action result;
10962   struct watchpoint *w;
10963   struct ui_out *uiout = current_uiout;
10964
10965   gdb_assert (bs->bp_location_at != NULL);
10966
10967   b = bs->breakpoint_at;
10968   w = (struct watchpoint *) b;
10969
10970   stb = mem_fileopen ();
10971   old_chain = make_cleanup_ui_file_delete (stb);
10972
10973   switch (b->type)
10974     {
10975     case bp_watchpoint:
10976     case bp_hardware_watchpoint:
10977       annotate_watchpoint (b->number);
10978       if (ui_out_is_mi_like_p (uiout))
10979         ui_out_field_string
10980           (uiout, "reason",
10981            async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
10982       mention (b);
10983       make_cleanup_ui_out_tuple_begin_end (uiout, "value");
10984       ui_out_text (uiout, "\nOld value = ");
10985       watchpoint_value_print (bs->old_val, stb);
10986       ui_out_field_stream (uiout, "old", stb);
10987       ui_out_text (uiout, "\nNew value = ");
10988       watchpoint_value_print (w->val, stb);
10989       ui_out_field_stream (uiout, "new", stb);
10990       ui_out_text (uiout, "\n");
10991       /* More than one watchpoint may have been triggered.  */
10992       result = PRINT_UNKNOWN;
10993       break;
10994
10995     case bp_read_watchpoint:
10996       if (ui_out_is_mi_like_p (uiout))
10997         ui_out_field_string
10998           (uiout, "reason",
10999            async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
11000       mention (b);
11001       make_cleanup_ui_out_tuple_begin_end (uiout, "value");
11002       ui_out_text (uiout, "\nValue = ");
11003       watchpoint_value_print (w->val, stb);
11004       ui_out_field_stream (uiout, "value", stb);
11005       ui_out_text (uiout, "\n");
11006       result = PRINT_UNKNOWN;
11007       break;
11008
11009     case bp_access_watchpoint:
11010       if (bs->old_val != NULL)
11011         {
11012           annotate_watchpoint (b->number);
11013           if (ui_out_is_mi_like_p (uiout))
11014             ui_out_field_string
11015               (uiout, "reason",
11016                async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
11017           mention (b);
11018           make_cleanup_ui_out_tuple_begin_end (uiout, "value");
11019           ui_out_text (uiout, "\nOld value = ");
11020           watchpoint_value_print (bs->old_val, stb);
11021           ui_out_field_stream (uiout, "old", stb);
11022           ui_out_text (uiout, "\nNew value = ");
11023         }
11024       else
11025         {
11026           mention (b);
11027           if (ui_out_is_mi_like_p (uiout))
11028             ui_out_field_string
11029               (uiout, "reason",
11030                async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
11031           make_cleanup_ui_out_tuple_begin_end (uiout, "value");
11032           ui_out_text (uiout, "\nValue = ");
11033         }
11034       watchpoint_value_print (w->val, stb);
11035       ui_out_field_stream (uiout, "new", stb);
11036       ui_out_text (uiout, "\n");
11037       result = PRINT_UNKNOWN;
11038       break;
11039     default:
11040       result = PRINT_UNKNOWN;
11041     }
11042
11043   do_cleanups (old_chain);
11044   return result;
11045 }
11046
11047 /* Implement the "print_mention" breakpoint_ops method for hardware
11048    watchpoints.  */
11049
11050 static void
11051 print_mention_watchpoint (struct breakpoint *b)
11052 {
11053   struct cleanup *ui_out_chain;
11054   struct watchpoint *w = (struct watchpoint *) b;
11055   struct ui_out *uiout = current_uiout;
11056
11057   switch (b->type)
11058     {
11059     case bp_watchpoint:
11060       ui_out_text (uiout, "Watchpoint ");
11061       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "wpt");
11062       break;
11063     case bp_hardware_watchpoint:
11064       ui_out_text (uiout, "Hardware watchpoint ");
11065       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "wpt");
11066       break;
11067     case bp_read_watchpoint:
11068       ui_out_text (uiout, "Hardware read watchpoint ");
11069       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-rwpt");
11070       break;
11071     case bp_access_watchpoint:
11072       ui_out_text (uiout, "Hardware access (read/write) watchpoint ");
11073       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-awpt");
11074       break;
11075     default:
11076       internal_error (__FILE__, __LINE__,
11077                       _("Invalid hardware watchpoint type."));
11078     }
11079
11080   ui_out_field_int (uiout, "number", b->number);
11081   ui_out_text (uiout, ": ");
11082   ui_out_field_string (uiout, "exp", w->exp_string);
11083   do_cleanups (ui_out_chain);
11084 }
11085
11086 /* Implement the "print_recreate" breakpoint_ops method for
11087    watchpoints.  */
11088
11089 static void
11090 print_recreate_watchpoint (struct breakpoint *b, struct ui_file *fp)
11091 {
11092   struct watchpoint *w = (struct watchpoint *) b;
11093
11094   switch (b->type)
11095     {
11096     case bp_watchpoint:
11097     case bp_hardware_watchpoint:
11098       fprintf_unfiltered (fp, "watch");
11099       break;
11100     case bp_read_watchpoint:
11101       fprintf_unfiltered (fp, "rwatch");
11102       break;
11103     case bp_access_watchpoint:
11104       fprintf_unfiltered (fp, "awatch");
11105       break;
11106     default:
11107       internal_error (__FILE__, __LINE__,
11108                       _("Invalid watchpoint type."));
11109     }
11110
11111   fprintf_unfiltered (fp, " %s", w->exp_string);
11112   print_recreate_thread (b, fp);
11113 }
11114
11115 /* Implement the "explains_signal" breakpoint_ops method for
11116    watchpoints.  */
11117
11118 static int
11119 explains_signal_watchpoint (struct breakpoint *b, enum gdb_signal sig)
11120 {
11121   /* A software watchpoint cannot cause a signal other than
11122      GDB_SIGNAL_TRAP.  */
11123   if (b->type == bp_watchpoint && sig != GDB_SIGNAL_TRAP)
11124     return 0;
11125
11126   return 1;
11127 }
11128
11129 /* The breakpoint_ops structure to be used in hardware watchpoints.  */
11130
11131 static struct breakpoint_ops watchpoint_breakpoint_ops;
11132
11133 /* Implement the "insert" breakpoint_ops method for
11134    masked hardware watchpoints.  */
11135
11136 static int
11137 insert_masked_watchpoint (struct bp_location *bl)
11138 {
11139   struct watchpoint *w = (struct watchpoint *) bl->owner;
11140
11141   return target_insert_mask_watchpoint (bl->address, w->hw_wp_mask,
11142                                         bl->watchpoint_type);
11143 }
11144
11145 /* Implement the "remove" breakpoint_ops method for
11146    masked hardware watchpoints.  */
11147
11148 static int
11149 remove_masked_watchpoint (struct bp_location *bl)
11150 {
11151   struct watchpoint *w = (struct watchpoint *) bl->owner;
11152
11153   return target_remove_mask_watchpoint (bl->address, w->hw_wp_mask,
11154                                         bl->watchpoint_type);
11155 }
11156
11157 /* Implement the "resources_needed" breakpoint_ops method for
11158    masked hardware watchpoints.  */
11159
11160 static int
11161 resources_needed_masked_watchpoint (const struct bp_location *bl)
11162 {
11163   struct watchpoint *w = (struct watchpoint *) bl->owner;
11164
11165   return target_masked_watch_num_registers (bl->address, w->hw_wp_mask);
11166 }
11167
11168 /* Implement the "works_in_software_mode" breakpoint_ops method for
11169    masked hardware watchpoints.  */
11170
11171 static int
11172 works_in_software_mode_masked_watchpoint (const struct breakpoint *b)
11173 {
11174   return 0;
11175 }
11176
11177 /* Implement the "print_it" breakpoint_ops method for
11178    masked hardware watchpoints.  */
11179
11180 static enum print_stop_action
11181 print_it_masked_watchpoint (bpstat bs)
11182 {
11183   struct breakpoint *b = bs->breakpoint_at;
11184   struct ui_out *uiout = current_uiout;
11185
11186   /* Masked watchpoints have only one location.  */
11187   gdb_assert (b->loc && b->loc->next == NULL);
11188
11189   switch (b->type)
11190     {
11191     case bp_hardware_watchpoint:
11192       annotate_watchpoint (b->number);
11193       if (ui_out_is_mi_like_p (uiout))
11194         ui_out_field_string
11195           (uiout, "reason",
11196            async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
11197       break;
11198
11199     case bp_read_watchpoint:
11200       if (ui_out_is_mi_like_p (uiout))
11201         ui_out_field_string
11202           (uiout, "reason",
11203            async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
11204       break;
11205
11206     case bp_access_watchpoint:
11207       if (ui_out_is_mi_like_p (uiout))
11208         ui_out_field_string
11209           (uiout, "reason",
11210            async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
11211       break;
11212     default:
11213       internal_error (__FILE__, __LINE__,
11214                       _("Invalid hardware watchpoint type."));
11215     }
11216
11217   mention (b);
11218   ui_out_text (uiout, _("\n\
11219 Check the underlying instruction at PC for the memory\n\
11220 address and value which triggered this watchpoint.\n"));
11221   ui_out_text (uiout, "\n");
11222
11223   /* More than one watchpoint may have been triggered.  */
11224   return PRINT_UNKNOWN;
11225 }
11226
11227 /* Implement the "print_one_detail" breakpoint_ops method for
11228    masked hardware watchpoints.  */
11229
11230 static void
11231 print_one_detail_masked_watchpoint (const struct breakpoint *b,
11232                                     struct ui_out *uiout)
11233 {
11234   struct watchpoint *w = (struct watchpoint *) b;
11235
11236   /* Masked watchpoints have only one location.  */
11237   gdb_assert (b->loc && b->loc->next == NULL);
11238
11239   ui_out_text (uiout, "\tmask ");
11240   ui_out_field_core_addr (uiout, "mask", b->loc->gdbarch, w->hw_wp_mask);
11241   ui_out_text (uiout, "\n");
11242 }
11243
11244 /* Implement the "print_mention" breakpoint_ops method for
11245    masked hardware watchpoints.  */
11246
11247 static void
11248 print_mention_masked_watchpoint (struct breakpoint *b)
11249 {
11250   struct watchpoint *w = (struct watchpoint *) b;
11251   struct ui_out *uiout = current_uiout;
11252   struct cleanup *ui_out_chain;
11253
11254   switch (b->type)
11255     {
11256     case bp_hardware_watchpoint:
11257       ui_out_text (uiout, "Masked hardware watchpoint ");
11258       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "wpt");
11259       break;
11260     case bp_read_watchpoint:
11261       ui_out_text (uiout, "Masked hardware read watchpoint ");
11262       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-rwpt");
11263       break;
11264     case bp_access_watchpoint:
11265       ui_out_text (uiout, "Masked hardware access (read/write) watchpoint ");
11266       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-awpt");
11267       break;
11268     default:
11269       internal_error (__FILE__, __LINE__,
11270                       _("Invalid hardware watchpoint type."));
11271     }
11272
11273   ui_out_field_int (uiout, "number", b->number);
11274   ui_out_text (uiout, ": ");
11275   ui_out_field_string (uiout, "exp", w->exp_string);
11276   do_cleanups (ui_out_chain);
11277 }
11278
11279 /* Implement the "print_recreate" breakpoint_ops method for
11280    masked hardware watchpoints.  */
11281
11282 static void
11283 print_recreate_masked_watchpoint (struct breakpoint *b, struct ui_file *fp)
11284 {
11285   struct watchpoint *w = (struct watchpoint *) b;
11286   char tmp[40];
11287
11288   switch (b->type)
11289     {
11290     case bp_hardware_watchpoint:
11291       fprintf_unfiltered (fp, "watch");
11292       break;
11293     case bp_read_watchpoint:
11294       fprintf_unfiltered (fp, "rwatch");
11295       break;
11296     case bp_access_watchpoint:
11297       fprintf_unfiltered (fp, "awatch");
11298       break;
11299     default:
11300       internal_error (__FILE__, __LINE__,
11301                       _("Invalid hardware watchpoint type."));
11302     }
11303
11304   sprintf_vma (tmp, w->hw_wp_mask);
11305   fprintf_unfiltered (fp, " %s mask 0x%s", w->exp_string, tmp);
11306   print_recreate_thread (b, fp);
11307 }
11308
11309 /* The breakpoint_ops structure to be used in masked hardware watchpoints.  */
11310
11311 static struct breakpoint_ops masked_watchpoint_breakpoint_ops;
11312
11313 /* Tell whether the given watchpoint is a masked hardware watchpoint.  */
11314
11315 static int
11316 is_masked_watchpoint (const struct breakpoint *b)
11317 {
11318   return b->ops == &masked_watchpoint_breakpoint_ops;
11319 }
11320
11321 /* accessflag:  hw_write:  watch write, 
11322                 hw_read:   watch read, 
11323                 hw_access: watch access (read or write) */
11324 static void
11325 watch_command_1 (const char *arg, int accessflag, int from_tty,
11326                  int just_location, int internal)
11327 {
11328   volatile struct gdb_exception e;
11329   struct breakpoint *b, *scope_breakpoint = NULL;
11330   struct expression *exp;
11331   const struct block *exp_valid_block = NULL, *cond_exp_valid_block = NULL;
11332   struct value *val, *mark, *result;
11333   int saved_bitpos = 0, saved_bitsize = 0;
11334   struct frame_info *frame;
11335   const char *exp_start = NULL;
11336   const char *exp_end = NULL;
11337   const char *tok, *end_tok;
11338   int toklen = -1;
11339   const char *cond_start = NULL;
11340   const char *cond_end = NULL;
11341   enum bptype bp_type;
11342   int thread = -1;
11343   int pc = 0;
11344   /* Flag to indicate whether we are going to use masks for
11345      the hardware watchpoint.  */
11346   int use_mask = 0;
11347   CORE_ADDR mask = 0;
11348   struct watchpoint *w;
11349   char *expression;
11350   struct cleanup *back_to;
11351
11352   /* Make sure that we actually have parameters to parse.  */
11353   if (arg != NULL && arg[0] != '\0')
11354     {
11355       const char *value_start;
11356
11357       exp_end = arg + strlen (arg);
11358
11359       /* Look for "parameter value" pairs at the end
11360          of the arguments string.  */
11361       for (tok = exp_end - 1; tok > arg; tok--)
11362         {
11363           /* Skip whitespace at the end of the argument list.  */
11364           while (tok > arg && (*tok == ' ' || *tok == '\t'))
11365             tok--;
11366
11367           /* Find the beginning of the last token.
11368              This is the value of the parameter.  */
11369           while (tok > arg && (*tok != ' ' && *tok != '\t'))
11370             tok--;
11371           value_start = tok + 1;
11372
11373           /* Skip whitespace.  */
11374           while (tok > arg && (*tok == ' ' || *tok == '\t'))
11375             tok--;
11376
11377           end_tok = tok;
11378
11379           /* Find the beginning of the second to last token.
11380              This is the parameter itself.  */
11381           while (tok > arg && (*tok != ' ' && *tok != '\t'))
11382             tok--;
11383           tok++;
11384           toklen = end_tok - tok + 1;
11385
11386           if (toklen == 6 && !strncmp (tok, "thread", 6))
11387             {
11388               /* At this point we've found a "thread" token, which means
11389                  the user is trying to set a watchpoint that triggers
11390                  only in a specific thread.  */
11391               char *endp;
11392
11393               if (thread != -1)
11394                 error(_("You can specify only one thread."));
11395
11396               /* Extract the thread ID from the next token.  */
11397               thread = strtol (value_start, &endp, 0);
11398
11399               /* Check if the user provided a valid numeric value for the
11400                  thread ID.  */
11401               if (*endp != ' ' && *endp != '\t' && *endp != '\0')
11402                 error (_("Invalid thread ID specification %s."), value_start);
11403
11404               /* Check if the thread actually exists.  */
11405               if (!valid_thread_id (thread))
11406                 invalid_thread_id_error (thread);
11407             }
11408           else if (toklen == 4 && !strncmp (tok, "mask", 4))
11409             {
11410               /* We've found a "mask" token, which means the user wants to
11411                  create a hardware watchpoint that is going to have the mask
11412                  facility.  */
11413               struct value *mask_value, *mark;
11414
11415               if (use_mask)
11416                 error(_("You can specify only one mask."));
11417
11418               use_mask = just_location = 1;
11419
11420               mark = value_mark ();
11421               mask_value = parse_to_comma_and_eval (&value_start);
11422               mask = value_as_address (mask_value);
11423               value_free_to_mark (mark);
11424             }
11425           else
11426             /* We didn't recognize what we found.  We should stop here.  */
11427             break;
11428
11429           /* Truncate the string and get rid of the "parameter value" pair before
11430              the arguments string is parsed by the parse_exp_1 function.  */
11431           exp_end = tok;
11432         }
11433     }
11434   else
11435     exp_end = arg;
11436
11437   /* Parse the rest of the arguments.  From here on out, everything
11438      is in terms of a newly allocated string instead of the original
11439      ARG.  */
11440   innermost_block = NULL;
11441   expression = savestring (arg, exp_end - arg);
11442   back_to = make_cleanup (xfree, expression);
11443   exp_start = arg = expression;
11444   exp = parse_exp_1 (&arg, 0, 0, 0);
11445   exp_end = arg;
11446   /* Remove trailing whitespace from the expression before saving it.
11447      This makes the eventual display of the expression string a bit
11448      prettier.  */
11449   while (exp_end > exp_start && (exp_end[-1] == ' ' || exp_end[-1] == '\t'))
11450     --exp_end;
11451
11452   /* Checking if the expression is not constant.  */
11453   if (watchpoint_exp_is_const (exp))
11454     {
11455       int len;
11456
11457       len = exp_end - exp_start;
11458       while (len > 0 && isspace (exp_start[len - 1]))
11459         len--;
11460       error (_("Cannot watch constant value `%.*s'."), len, exp_start);
11461     }
11462
11463   exp_valid_block = innermost_block;
11464   mark = value_mark ();
11465   fetch_subexp_value (exp, &pc, &val, &result, NULL, just_location);
11466
11467   if (val != NULL && just_location)
11468     {
11469       saved_bitpos = value_bitpos (val);
11470       saved_bitsize = value_bitsize (val);
11471     }
11472
11473   if (just_location)
11474     {
11475       int ret;
11476
11477       exp_valid_block = NULL;
11478       val = value_addr (result);
11479       release_value (val);
11480       value_free_to_mark (mark);
11481
11482       if (use_mask)
11483         {
11484           ret = target_masked_watch_num_registers (value_as_address (val),
11485                                                    mask);
11486           if (ret == -1)
11487             error (_("This target does not support masked watchpoints."));
11488           else if (ret == -2)
11489             error (_("Invalid mask or memory region."));
11490         }
11491     }
11492   else if (val != NULL)
11493     release_value (val);
11494
11495   tok = skip_spaces_const (arg);
11496   end_tok = skip_to_space_const (tok);
11497
11498   toklen = end_tok - tok;
11499   if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
11500     {
11501       struct expression *cond;
11502
11503       innermost_block = NULL;
11504       tok = cond_start = end_tok + 1;
11505       cond = parse_exp_1 (&tok, 0, 0, 0);
11506
11507       /* The watchpoint expression may not be local, but the condition
11508          may still be.  E.g.: `watch global if local > 0'.  */
11509       cond_exp_valid_block = innermost_block;
11510
11511       xfree (cond);
11512       cond_end = tok;
11513     }
11514   if (*tok)
11515     error (_("Junk at end of command."));
11516
11517   frame = block_innermost_frame (exp_valid_block);
11518
11519   /* If the expression is "local", then set up a "watchpoint scope"
11520      breakpoint at the point where we've left the scope of the watchpoint
11521      expression.  Create the scope breakpoint before the watchpoint, so
11522      that we will encounter it first in bpstat_stop_status.  */
11523   if (exp_valid_block && frame)
11524     {
11525       if (frame_id_p (frame_unwind_caller_id (frame)))
11526         {
11527           scope_breakpoint
11528             = create_internal_breakpoint (frame_unwind_caller_arch (frame),
11529                                           frame_unwind_caller_pc (frame),
11530                                           bp_watchpoint_scope,
11531                                           &momentary_breakpoint_ops);
11532
11533           scope_breakpoint->enable_state = bp_enabled;
11534
11535           /* Automatically delete the breakpoint when it hits.  */
11536           scope_breakpoint->disposition = disp_del;
11537
11538           /* Only break in the proper frame (help with recursion).  */
11539           scope_breakpoint->frame_id = frame_unwind_caller_id (frame);
11540
11541           /* Set the address at which we will stop.  */
11542           scope_breakpoint->loc->gdbarch
11543             = frame_unwind_caller_arch (frame);
11544           scope_breakpoint->loc->requested_address
11545             = frame_unwind_caller_pc (frame);
11546           scope_breakpoint->loc->address
11547             = adjust_breakpoint_address (scope_breakpoint->loc->gdbarch,
11548                                          scope_breakpoint->loc->requested_address,
11549                                          scope_breakpoint->type);
11550         }
11551     }
11552
11553   /* Now set up the breakpoint.  We create all watchpoints as hardware
11554      watchpoints here even if hardware watchpoints are turned off, a call
11555      to update_watchpoint later in this function will cause the type to
11556      drop back to bp_watchpoint (software watchpoint) if required.  */
11557
11558   if (accessflag == hw_read)
11559     bp_type = bp_read_watchpoint;
11560   else if (accessflag == hw_access)
11561     bp_type = bp_access_watchpoint;
11562   else
11563     bp_type = bp_hardware_watchpoint;
11564
11565   w = XCNEW (struct watchpoint);
11566   b = &w->base;
11567   if (use_mask)
11568     init_raw_breakpoint_without_location (b, NULL, bp_type,
11569                                           &masked_watchpoint_breakpoint_ops);
11570   else
11571     init_raw_breakpoint_without_location (b, NULL, bp_type,
11572                                           &watchpoint_breakpoint_ops);
11573   b->thread = thread;
11574   b->disposition = disp_donttouch;
11575   b->pspace = current_program_space;
11576   w->exp = exp;
11577   w->exp_valid_block = exp_valid_block;
11578   w->cond_exp_valid_block = cond_exp_valid_block;
11579   if (just_location)
11580     {
11581       struct type *t = value_type (val);
11582       CORE_ADDR addr = value_as_address (val);
11583       char *name;
11584
11585       t = check_typedef (TYPE_TARGET_TYPE (check_typedef (t)));
11586       name = type_to_string (t);
11587
11588       w->exp_string_reparse = xstrprintf ("* (%s *) %s", name,
11589                                           core_addr_to_string (addr));
11590       xfree (name);
11591
11592       w->exp_string = xstrprintf ("-location %.*s",
11593                                   (int) (exp_end - exp_start), exp_start);
11594
11595       /* The above expression is in C.  */
11596       b->language = language_c;
11597     }
11598   else
11599     w->exp_string = savestring (exp_start, exp_end - exp_start);
11600
11601   if (use_mask)
11602     {
11603       w->hw_wp_mask = mask;
11604     }
11605   else
11606     {
11607       w->val = val;
11608       w->val_bitpos = saved_bitpos;
11609       w->val_bitsize = saved_bitsize;
11610       w->val_valid = 1;
11611     }
11612
11613   if (cond_start)
11614     b->cond_string = savestring (cond_start, cond_end - cond_start);
11615   else
11616     b->cond_string = 0;
11617
11618   if (frame)
11619     {
11620       w->watchpoint_frame = get_frame_id (frame);
11621       w->watchpoint_thread = inferior_ptid;
11622     }
11623   else
11624     {
11625       w->watchpoint_frame = null_frame_id;
11626       w->watchpoint_thread = null_ptid;
11627     }
11628
11629   if (scope_breakpoint != NULL)
11630     {
11631       /* The scope breakpoint is related to the watchpoint.  We will
11632          need to act on them together.  */
11633       b->related_breakpoint = scope_breakpoint;
11634       scope_breakpoint->related_breakpoint = b;
11635     }
11636
11637   if (!just_location)
11638     value_free_to_mark (mark);
11639
11640   TRY_CATCH (e, RETURN_MASK_ALL)
11641     {
11642       /* Finally update the new watchpoint.  This creates the locations
11643          that should be inserted.  */
11644       update_watchpoint (w, 1);
11645     }
11646   if (e.reason < 0)
11647     {
11648       delete_breakpoint (b);
11649       throw_exception (e);
11650     }
11651
11652   install_breakpoint (internal, b, 1);
11653   do_cleanups (back_to);
11654 }
11655
11656 /* Return count of debug registers needed to watch the given expression.
11657    If the watchpoint cannot be handled in hardware return zero.  */
11658
11659 static int
11660 can_use_hardware_watchpoint (struct value *v)
11661 {
11662   int found_memory_cnt = 0;
11663   struct value *head = v;
11664
11665   /* Did the user specifically forbid us to use hardware watchpoints? */
11666   if (!can_use_hw_watchpoints)
11667     return 0;
11668
11669   /* Make sure that the value of the expression depends only upon
11670      memory contents, and values computed from them within GDB.  If we
11671      find any register references or function calls, we can't use a
11672      hardware watchpoint.
11673
11674      The idea here is that evaluating an expression generates a series
11675      of values, one holding the value of every subexpression.  (The
11676      expression a*b+c has five subexpressions: a, b, a*b, c, and
11677      a*b+c.)  GDB's values hold almost enough information to establish
11678      the criteria given above --- they identify memory lvalues,
11679      register lvalues, computed values, etcetera.  So we can evaluate
11680      the expression, and then scan the chain of values that leaves
11681      behind to decide whether we can detect any possible change to the
11682      expression's final value using only hardware watchpoints.
11683
11684      However, I don't think that the values returned by inferior
11685      function calls are special in any way.  So this function may not
11686      notice that an expression involving an inferior function call
11687      can't be watched with hardware watchpoints.  FIXME.  */
11688   for (; v; v = value_next (v))
11689     {
11690       if (VALUE_LVAL (v) == lval_memory)
11691         {
11692           if (v != head && value_lazy (v))
11693             /* A lazy memory lvalue in the chain is one that GDB never
11694                needed to fetch; we either just used its address (e.g.,
11695                `a' in `a.b') or we never needed it at all (e.g., `a'
11696                in `a,b').  This doesn't apply to HEAD; if that is
11697                lazy then it was not readable, but watch it anyway.  */
11698             ;
11699           else
11700             {
11701               /* Ahh, memory we actually used!  Check if we can cover
11702                  it with hardware watchpoints.  */
11703               struct type *vtype = check_typedef (value_type (v));
11704
11705               /* We only watch structs and arrays if user asked for it
11706                  explicitly, never if they just happen to appear in a
11707                  middle of some value chain.  */
11708               if (v == head
11709                   || (TYPE_CODE (vtype) != TYPE_CODE_STRUCT
11710                       && TYPE_CODE (vtype) != TYPE_CODE_ARRAY))
11711                 {
11712                   CORE_ADDR vaddr = value_address (v);
11713                   int len;
11714                   int num_regs;
11715
11716                   len = (target_exact_watchpoints
11717                          && is_scalar_type_recursive (vtype))?
11718                     1 : TYPE_LENGTH (value_type (v));
11719
11720                   num_regs = target_region_ok_for_hw_watchpoint (vaddr, len);
11721                   if (!num_regs)
11722                     return 0;
11723                   else
11724                     found_memory_cnt += num_regs;
11725                 }
11726             }
11727         }
11728       else if (VALUE_LVAL (v) != not_lval
11729                && deprecated_value_modifiable (v) == 0)
11730         return 0;       /* These are values from the history (e.g., $1).  */
11731       else if (VALUE_LVAL (v) == lval_register)
11732         return 0;       /* Cannot watch a register with a HW watchpoint.  */
11733     }
11734
11735   /* The expression itself looks suitable for using a hardware
11736      watchpoint, but give the target machine a chance to reject it.  */
11737   return found_memory_cnt;
11738 }
11739
11740 void
11741 watch_command_wrapper (char *arg, int from_tty, int internal)
11742 {
11743   watch_command_1 (arg, hw_write, from_tty, 0, internal);
11744 }
11745
11746 /* A helper function that looks for the "-location" argument and then
11747    calls watch_command_1.  */
11748
11749 static void
11750 watch_maybe_just_location (char *arg, int accessflag, int from_tty)
11751 {
11752   int just_location = 0;
11753
11754   if (arg
11755       && (check_for_argument (&arg, "-location", sizeof ("-location") - 1)
11756           || check_for_argument (&arg, "-l", sizeof ("-l") - 1)))
11757     {
11758       arg = skip_spaces (arg);
11759       just_location = 1;
11760     }
11761
11762   watch_command_1 (arg, accessflag, from_tty, just_location, 0);
11763 }
11764
11765 static void
11766 watch_command (char *arg, int from_tty)
11767 {
11768   watch_maybe_just_location (arg, hw_write, from_tty);
11769 }
11770
11771 void
11772 rwatch_command_wrapper (char *arg, int from_tty, int internal)
11773 {
11774   watch_command_1 (arg, hw_read, from_tty, 0, internal);
11775 }
11776
11777 static void
11778 rwatch_command (char *arg, int from_tty)
11779 {
11780   watch_maybe_just_location (arg, hw_read, from_tty);
11781 }
11782
11783 void
11784 awatch_command_wrapper (char *arg, int from_tty, int internal)
11785 {
11786   watch_command_1 (arg, hw_access, from_tty, 0, internal);
11787 }
11788
11789 static void
11790 awatch_command (char *arg, int from_tty)
11791 {
11792   watch_maybe_just_location (arg, hw_access, from_tty);
11793 }
11794 \f
11795
11796 /* Helper routines for the until_command routine in infcmd.c.  Here
11797    because it uses the mechanisms of breakpoints.  */
11798
11799 struct until_break_command_continuation_args
11800 {
11801   struct breakpoint *breakpoint;
11802   struct breakpoint *breakpoint2;
11803   int thread_num;
11804 };
11805
11806 /* This function is called by fetch_inferior_event via the
11807    cmd_continuation pointer, to complete the until command.  It takes
11808    care of cleaning up the temporary breakpoints set up by the until
11809    command.  */
11810 static void
11811 until_break_command_continuation (void *arg, int err)
11812 {
11813   struct until_break_command_continuation_args *a = arg;
11814
11815   delete_breakpoint (a->breakpoint);
11816   if (a->breakpoint2)
11817     delete_breakpoint (a->breakpoint2);
11818   delete_longjmp_breakpoint (a->thread_num);
11819 }
11820
11821 void
11822 until_break_command (char *arg, int from_tty, int anywhere)
11823 {
11824   struct symtabs_and_lines sals;
11825   struct symtab_and_line sal;
11826   struct frame_info *frame;
11827   struct gdbarch *frame_gdbarch;
11828   struct frame_id stack_frame_id;
11829   struct frame_id caller_frame_id;
11830   struct breakpoint *breakpoint;
11831   struct breakpoint *breakpoint2 = NULL;
11832   struct cleanup *old_chain;
11833   int thread;
11834   struct thread_info *tp;
11835
11836   clear_proceed_status (0);
11837
11838   /* Set a breakpoint where the user wants it and at return from
11839      this function.  */
11840
11841   if (last_displayed_sal_is_valid ())
11842     sals = decode_line_1 (&arg, DECODE_LINE_FUNFIRSTLINE,
11843                           get_last_displayed_symtab (),
11844                           get_last_displayed_line ());
11845   else
11846     sals = decode_line_1 (&arg, DECODE_LINE_FUNFIRSTLINE,
11847                           (struct symtab *) NULL, 0);
11848
11849   if (sals.nelts != 1)
11850     error (_("Couldn't get information on specified line."));
11851
11852   sal = sals.sals[0];
11853   xfree (sals.sals);    /* malloc'd, so freed.  */
11854
11855   if (*arg)
11856     error (_("Junk at end of arguments."));
11857
11858   resolve_sal_pc (&sal);
11859
11860   tp = inferior_thread ();
11861   thread = tp->num;
11862
11863   old_chain = make_cleanup (null_cleanup, NULL);
11864
11865   /* Note linespec handling above invalidates the frame chain.
11866      Installing a breakpoint also invalidates the frame chain (as it
11867      may need to switch threads), so do any frame handling before
11868      that.  */
11869
11870   frame = get_selected_frame (NULL);
11871   frame_gdbarch = get_frame_arch (frame);
11872   stack_frame_id = get_stack_frame_id (frame);
11873   caller_frame_id = frame_unwind_caller_id (frame);
11874
11875   /* Keep within the current frame, or in frames called by the current
11876      one.  */
11877
11878   if (frame_id_p (caller_frame_id))
11879     {
11880       struct symtab_and_line sal2;
11881
11882       sal2 = find_pc_line (frame_unwind_caller_pc (frame), 0);
11883       sal2.pc = frame_unwind_caller_pc (frame);
11884       breakpoint2 = set_momentary_breakpoint (frame_unwind_caller_arch (frame),
11885                                               sal2,
11886                                               caller_frame_id,
11887                                               bp_until);
11888       make_cleanup_delete_breakpoint (breakpoint2);
11889
11890       set_longjmp_breakpoint (tp, caller_frame_id);
11891       make_cleanup (delete_longjmp_breakpoint_cleanup, &thread);
11892     }
11893
11894   /* set_momentary_breakpoint could invalidate FRAME.  */
11895   frame = NULL;
11896
11897   if (anywhere)
11898     /* If the user told us to continue until a specified location,
11899        we don't specify a frame at which we need to stop.  */
11900     breakpoint = set_momentary_breakpoint (frame_gdbarch, sal,
11901                                            null_frame_id, bp_until);
11902   else
11903     /* Otherwise, specify the selected frame, because we want to stop
11904        only at the very same frame.  */
11905     breakpoint = set_momentary_breakpoint (frame_gdbarch, sal,
11906                                            stack_frame_id, bp_until);
11907   make_cleanup_delete_breakpoint (breakpoint);
11908
11909   proceed (-1, GDB_SIGNAL_DEFAULT, 0);
11910
11911   /* If we are running asynchronously, and proceed call above has
11912      actually managed to start the target, arrange for breakpoints to
11913      be deleted when the target stops.  Otherwise, we're already
11914      stopped and delete breakpoints via cleanup chain.  */
11915
11916   if (target_can_async_p () && is_running (inferior_ptid))
11917     {
11918       struct until_break_command_continuation_args *args;
11919       args = xmalloc (sizeof (*args));
11920
11921       args->breakpoint = breakpoint;
11922       args->breakpoint2 = breakpoint2;
11923       args->thread_num = thread;
11924
11925       discard_cleanups (old_chain);
11926       add_continuation (inferior_thread (),
11927                         until_break_command_continuation, args,
11928                         xfree);
11929     }
11930   else
11931     do_cleanups (old_chain);
11932 }
11933
11934 /* This function attempts to parse an optional "if <cond>" clause
11935    from the arg string.  If one is not found, it returns NULL.
11936
11937    Else, it returns a pointer to the condition string.  (It does not
11938    attempt to evaluate the string against a particular block.)  And,
11939    it updates arg to point to the first character following the parsed
11940    if clause in the arg string.  */
11941
11942 char *
11943 ep_parse_optional_if_clause (char **arg)
11944 {
11945   char *cond_string;
11946
11947   if (((*arg)[0] != 'i') || ((*arg)[1] != 'f') || !isspace ((*arg)[2]))
11948     return NULL;
11949
11950   /* Skip the "if" keyword.  */
11951   (*arg) += 2;
11952
11953   /* Skip any extra leading whitespace, and record the start of the
11954      condition string.  */
11955   *arg = skip_spaces (*arg);
11956   cond_string = *arg;
11957
11958   /* Assume that the condition occupies the remainder of the arg
11959      string.  */
11960   (*arg) += strlen (cond_string);
11961
11962   return cond_string;
11963 }
11964
11965 /* Commands to deal with catching events, such as signals, exceptions,
11966    process start/exit, etc.  */
11967
11968 typedef enum
11969 {
11970   catch_fork_temporary, catch_vfork_temporary,
11971   catch_fork_permanent, catch_vfork_permanent
11972 }
11973 catch_fork_kind;
11974
11975 static void
11976 catch_fork_command_1 (char *arg, int from_tty, 
11977                       struct cmd_list_element *command)
11978 {
11979   struct gdbarch *gdbarch = get_current_arch ();
11980   char *cond_string = NULL;
11981   catch_fork_kind fork_kind;
11982   int tempflag;
11983
11984   fork_kind = (catch_fork_kind) (uintptr_t) get_cmd_context (command);
11985   tempflag = (fork_kind == catch_fork_temporary
11986               || fork_kind == catch_vfork_temporary);
11987
11988   if (!arg)
11989     arg = "";
11990   arg = skip_spaces (arg);
11991
11992   /* The allowed syntax is:
11993      catch [v]fork
11994      catch [v]fork if <cond>
11995
11996      First, check if there's an if clause.  */
11997   cond_string = ep_parse_optional_if_clause (&arg);
11998
11999   if ((*arg != '\0') && !isspace (*arg))
12000     error (_("Junk at end of arguments."));
12001
12002   /* If this target supports it, create a fork or vfork catchpoint
12003      and enable reporting of such events.  */
12004   switch (fork_kind)
12005     {
12006     case catch_fork_temporary:
12007     case catch_fork_permanent:
12008       create_fork_vfork_event_catchpoint (gdbarch, tempflag, cond_string,
12009                                           &catch_fork_breakpoint_ops);
12010       break;
12011     case catch_vfork_temporary:
12012     case catch_vfork_permanent:
12013       create_fork_vfork_event_catchpoint (gdbarch, tempflag, cond_string,
12014                                           &catch_vfork_breakpoint_ops);
12015       break;
12016     default:
12017       error (_("unsupported or unknown fork kind; cannot catch it"));
12018       break;
12019     }
12020 }
12021
12022 static void
12023 catch_exec_command_1 (char *arg, int from_tty, 
12024                       struct cmd_list_element *command)
12025 {
12026   struct exec_catchpoint *c;
12027   struct gdbarch *gdbarch = get_current_arch ();
12028   int tempflag;
12029   char *cond_string = NULL;
12030
12031   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
12032
12033   if (!arg)
12034     arg = "";
12035   arg = skip_spaces (arg);
12036
12037   /* The allowed syntax is:
12038      catch exec
12039      catch exec if <cond>
12040
12041      First, check if there's an if clause.  */
12042   cond_string = ep_parse_optional_if_clause (&arg);
12043
12044   if ((*arg != '\0') && !isspace (*arg))
12045     error (_("Junk at end of arguments."));
12046
12047   c = XNEW (struct exec_catchpoint);
12048   init_catchpoint (&c->base, gdbarch, tempflag, cond_string,
12049                    &catch_exec_breakpoint_ops);
12050   c->exec_pathname = NULL;
12051
12052   install_breakpoint (0, &c->base, 1);
12053 }
12054
12055 void
12056 init_ada_exception_breakpoint (struct breakpoint *b,
12057                                struct gdbarch *gdbarch,
12058                                struct symtab_and_line sal,
12059                                char *addr_string,
12060                                const struct breakpoint_ops *ops,
12061                                int tempflag,
12062                                int enabled,
12063                                int from_tty)
12064 {
12065   if (from_tty)
12066     {
12067       struct gdbarch *loc_gdbarch = get_sal_arch (sal);
12068       if (!loc_gdbarch)
12069         loc_gdbarch = gdbarch;
12070
12071       describe_other_breakpoints (loc_gdbarch,
12072                                   sal.pspace, sal.pc, sal.section, -1);
12073       /* FIXME: brobecker/2006-12-28: Actually, re-implement a special
12074          version for exception catchpoints, because two catchpoints
12075          used for different exception names will use the same address.
12076          In this case, a "breakpoint ... also set at..." warning is
12077          unproductive.  Besides, the warning phrasing is also a bit
12078          inappropriate, we should use the word catchpoint, and tell
12079          the user what type of catchpoint it is.  The above is good
12080          enough for now, though.  */
12081     }
12082
12083   init_raw_breakpoint (b, gdbarch, sal, bp_breakpoint, ops);
12084
12085   b->enable_state = enabled ? bp_enabled : bp_disabled;
12086   b->disposition = tempflag ? disp_del : disp_donttouch;
12087   b->addr_string = addr_string;
12088   b->language = language_ada;
12089 }
12090
12091 /* Splits the argument using space as delimiter.  Returns an xmalloc'd
12092    filter list, or NULL if no filtering is required.  */
12093 static VEC(int) *
12094 catch_syscall_split_args (char *arg)
12095 {
12096   VEC(int) *result = NULL;
12097   struct cleanup *cleanup = make_cleanup (VEC_cleanup (int), &result);
12098
12099   while (*arg != '\0')
12100     {
12101       int i, syscall_number;
12102       char *endptr;
12103       char cur_name[128];
12104       struct syscall s;
12105
12106       /* Skip whitespace.  */
12107       arg = skip_spaces (arg);
12108
12109       for (i = 0; i < 127 && arg[i] && !isspace (arg[i]); ++i)
12110         cur_name[i] = arg[i];
12111       cur_name[i] = '\0';
12112       arg += i;
12113
12114       /* Check if the user provided a syscall name or a number.  */
12115       syscall_number = (int) strtol (cur_name, &endptr, 0);
12116       if (*endptr == '\0')
12117         get_syscall_by_number (syscall_number, &s);
12118       else
12119         {
12120           /* We have a name.  Let's check if it's valid and convert it
12121              to a number.  */
12122           get_syscall_by_name (cur_name, &s);
12123
12124           if (s.number == UNKNOWN_SYSCALL)
12125             /* Here we have to issue an error instead of a warning,
12126                because GDB cannot do anything useful if there's no
12127                syscall number to be caught.  */
12128             error (_("Unknown syscall name '%s'."), cur_name);
12129         }
12130
12131       /* Ok, it's valid.  */
12132       VEC_safe_push (int, result, s.number);
12133     }
12134
12135   discard_cleanups (cleanup);
12136   return result;
12137 }
12138
12139 /* Implement the "catch syscall" command.  */
12140
12141 static void
12142 catch_syscall_command_1 (char *arg, int from_tty, 
12143                          struct cmd_list_element *command)
12144 {
12145   int tempflag;
12146   VEC(int) *filter;
12147   struct syscall s;
12148   struct gdbarch *gdbarch = get_current_arch ();
12149
12150   /* Checking if the feature if supported.  */
12151   if (gdbarch_get_syscall_number_p (gdbarch) == 0)
12152     error (_("The feature 'catch syscall' is not supported on \
12153 this architecture yet."));
12154
12155   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
12156
12157   arg = skip_spaces (arg);
12158
12159   /* We need to do this first "dummy" translation in order
12160      to get the syscall XML file loaded or, most important,
12161      to display a warning to the user if there's no XML file
12162      for his/her architecture.  */
12163   get_syscall_by_number (0, &s);
12164
12165   /* The allowed syntax is:
12166      catch syscall
12167      catch syscall <name | number> [<name | number> ... <name | number>]
12168
12169      Let's check if there's a syscall name.  */
12170
12171   if (arg != NULL)
12172     filter = catch_syscall_split_args (arg);
12173   else
12174     filter = NULL;
12175
12176   create_syscall_event_catchpoint (tempflag, filter,
12177                                    &catch_syscall_breakpoint_ops);
12178 }
12179
12180 static void
12181 catch_command (char *arg, int from_tty)
12182 {
12183   error (_("Catch requires an event name."));
12184 }
12185 \f
12186
12187 static void
12188 tcatch_command (char *arg, int from_tty)
12189 {
12190   error (_("Catch requires an event name."));
12191 }
12192
12193 /* A qsort comparison function that sorts breakpoints in order.  */
12194
12195 static int
12196 compare_breakpoints (const void *a, const void *b)
12197 {
12198   const breakpoint_p *ba = a;
12199   uintptr_t ua = (uintptr_t) *ba;
12200   const breakpoint_p *bb = b;
12201   uintptr_t ub = (uintptr_t) *bb;
12202
12203   if ((*ba)->number < (*bb)->number)
12204     return -1;
12205   else if ((*ba)->number > (*bb)->number)
12206     return 1;
12207
12208   /* Now sort by address, in case we see, e..g, two breakpoints with
12209      the number 0.  */
12210   if (ua < ub)
12211     return -1;
12212   return ua > ub ? 1 : 0;
12213 }
12214
12215 /* Delete breakpoints by address or line.  */
12216
12217 static void
12218 clear_command (char *arg, int from_tty)
12219 {
12220   struct breakpoint *b, *prev;
12221   VEC(breakpoint_p) *found = 0;
12222   int ix;
12223   int default_match;
12224   struct symtabs_and_lines sals;
12225   struct symtab_and_line sal;
12226   int i;
12227   struct cleanup *cleanups = make_cleanup (null_cleanup, NULL);
12228
12229   if (arg)
12230     {
12231       sals = decode_line_with_current_source (arg,
12232                                               (DECODE_LINE_FUNFIRSTLINE
12233                                                | DECODE_LINE_LIST_MODE));
12234       make_cleanup (xfree, sals.sals);
12235       default_match = 0;
12236     }
12237   else
12238     {
12239       sals.sals = (struct symtab_and_line *)
12240         xmalloc (sizeof (struct symtab_and_line));
12241       make_cleanup (xfree, sals.sals);
12242       init_sal (&sal);          /* Initialize to zeroes.  */
12243
12244       /* Set sal's line, symtab, pc, and pspace to the values
12245          corresponding to the last call to print_frame_info.  If the
12246          codepoint is not valid, this will set all the fields to 0.  */
12247       get_last_displayed_sal (&sal);
12248       if (sal.symtab == 0)
12249         error (_("No source file specified."));
12250
12251       sals.sals[0] = sal;
12252       sals.nelts = 1;
12253
12254       default_match = 1;
12255     }
12256
12257   /* We don't call resolve_sal_pc here.  That's not as bad as it
12258      seems, because all existing breakpoints typically have both
12259      file/line and pc set.  So, if clear is given file/line, we can
12260      match this to existing breakpoint without obtaining pc at all.
12261
12262      We only support clearing given the address explicitly 
12263      present in breakpoint table.  Say, we've set breakpoint 
12264      at file:line.  There were several PC values for that file:line,
12265      due to optimization, all in one block.
12266
12267      We've picked one PC value.  If "clear" is issued with another
12268      PC corresponding to the same file:line, the breakpoint won't
12269      be cleared.  We probably can still clear the breakpoint, but 
12270      since the other PC value is never presented to user, user
12271      can only find it by guessing, and it does not seem important
12272      to support that.  */
12273
12274   /* For each line spec given, delete bps which correspond to it.  Do
12275      it in two passes, solely to preserve the current behavior that
12276      from_tty is forced true if we delete more than one
12277      breakpoint.  */
12278
12279   found = NULL;
12280   make_cleanup (VEC_cleanup (breakpoint_p), &found);
12281   for (i = 0; i < sals.nelts; i++)
12282     {
12283       const char *sal_fullname;
12284
12285       /* If exact pc given, clear bpts at that pc.
12286          If line given (pc == 0), clear all bpts on specified line.
12287          If defaulting, clear all bpts on default line
12288          or at default pc.
12289
12290          defaulting    sal.pc != 0    tests to do
12291
12292          0              1             pc
12293          1              1             pc _and_ line
12294          0              0             line
12295          1              0             <can't happen> */
12296
12297       sal = sals.sals[i];
12298       sal_fullname = (sal.symtab == NULL
12299                       ? NULL : symtab_to_fullname (sal.symtab));
12300
12301       /* Find all matching breakpoints and add them to 'found'.  */
12302       ALL_BREAKPOINTS (b)
12303         {
12304           int match = 0;
12305           /* Are we going to delete b?  */
12306           if (b->type != bp_none && !is_watchpoint (b))
12307             {
12308               struct bp_location *loc = b->loc;
12309               for (; loc; loc = loc->next)
12310                 {
12311                   /* If the user specified file:line, don't allow a PC
12312                      match.  This matches historical gdb behavior.  */
12313                   int pc_match = (!sal.explicit_line
12314                                   && sal.pc
12315                                   && (loc->pspace == sal.pspace)
12316                                   && (loc->address == sal.pc)
12317                                   && (!section_is_overlay (loc->section)
12318                                       || loc->section == sal.section));
12319                   int line_match = 0;
12320
12321                   if ((default_match || sal.explicit_line)
12322                       && loc->symtab != NULL
12323                       && sal_fullname != NULL
12324                       && sal.pspace == loc->pspace
12325                       && loc->line_number == sal.line
12326                       && filename_cmp (symtab_to_fullname (loc->symtab),
12327                                        sal_fullname) == 0)
12328                     line_match = 1;
12329
12330                   if (pc_match || line_match)
12331                     {
12332                       match = 1;
12333                       break;
12334                     }
12335                 }
12336             }
12337
12338           if (match)
12339             VEC_safe_push(breakpoint_p, found, b);
12340         }
12341     }
12342
12343   /* Now go thru the 'found' chain and delete them.  */
12344   if (VEC_empty(breakpoint_p, found))
12345     {
12346       if (arg)
12347         error (_("No breakpoint at %s."), arg);
12348       else
12349         error (_("No breakpoint at this line."));
12350     }
12351
12352   /* Remove duplicates from the vec.  */
12353   qsort (VEC_address (breakpoint_p, found),
12354          VEC_length (breakpoint_p, found),
12355          sizeof (breakpoint_p),
12356          compare_breakpoints);
12357   prev = VEC_index (breakpoint_p, found, 0);
12358   for (ix = 1; VEC_iterate (breakpoint_p, found, ix, b); ++ix)
12359     {
12360       if (b == prev)
12361         {
12362           VEC_ordered_remove (breakpoint_p, found, ix);
12363           --ix;
12364         }
12365     }
12366
12367   if (VEC_length(breakpoint_p, found) > 1)
12368     from_tty = 1;       /* Always report if deleted more than one.  */
12369   if (from_tty)
12370     {
12371       if (VEC_length(breakpoint_p, found) == 1)
12372         printf_unfiltered (_("Deleted breakpoint "));
12373       else
12374         printf_unfiltered (_("Deleted breakpoints "));
12375     }
12376
12377   for (ix = 0; VEC_iterate(breakpoint_p, found, ix, b); ix++)
12378     {
12379       if (from_tty)
12380         printf_unfiltered ("%d ", b->number);
12381       delete_breakpoint (b);
12382     }
12383   if (from_tty)
12384     putchar_unfiltered ('\n');
12385
12386   do_cleanups (cleanups);
12387 }
12388 \f
12389 /* Delete breakpoint in BS if they are `delete' breakpoints and
12390    all breakpoints that are marked for deletion, whether hit or not.
12391    This is called after any breakpoint is hit, or after errors.  */
12392
12393 void
12394 breakpoint_auto_delete (bpstat bs)
12395 {
12396   struct breakpoint *b, *b_tmp;
12397
12398   for (; bs; bs = bs->next)
12399     if (bs->breakpoint_at
12400         && bs->breakpoint_at->disposition == disp_del
12401         && bs->stop)
12402       delete_breakpoint (bs->breakpoint_at);
12403
12404   ALL_BREAKPOINTS_SAFE (b, b_tmp)
12405   {
12406     if (b->disposition == disp_del_at_next_stop)
12407       delete_breakpoint (b);
12408   }
12409 }
12410
12411 /* A comparison function for bp_location AP and BP being interfaced to
12412    qsort.  Sort elements primarily by their ADDRESS (no matter what
12413    does breakpoint_address_is_meaningful say for its OWNER),
12414    secondarily by ordering first bp_permanent OWNERed elements and
12415    terciarily just ensuring the array is sorted stable way despite
12416    qsort being an unstable algorithm.  */
12417
12418 static int
12419 bp_location_compare (const void *ap, const void *bp)
12420 {
12421   struct bp_location *a = *(void **) ap;
12422   struct bp_location *b = *(void **) bp;
12423   /* A and B come from existing breakpoints having non-NULL OWNER.  */
12424   int a_perm = a->owner->enable_state == bp_permanent;
12425   int b_perm = b->owner->enable_state == bp_permanent;
12426
12427   if (a->address != b->address)
12428     return (a->address > b->address) - (a->address < b->address);
12429
12430   /* Sort locations at the same address by their pspace number, keeping
12431      locations of the same inferior (in a multi-inferior environment)
12432      grouped.  */
12433
12434   if (a->pspace->num != b->pspace->num)
12435     return ((a->pspace->num > b->pspace->num)
12436             - (a->pspace->num < b->pspace->num));
12437
12438   /* Sort permanent breakpoints first.  */
12439   if (a_perm != b_perm)
12440     return (a_perm < b_perm) - (a_perm > b_perm);
12441
12442   /* Make the internal GDB representation stable across GDB runs
12443      where A and B memory inside GDB can differ.  Breakpoint locations of
12444      the same type at the same address can be sorted in arbitrary order.  */
12445
12446   if (a->owner->number != b->owner->number)
12447     return ((a->owner->number > b->owner->number)
12448             - (a->owner->number < b->owner->number));
12449
12450   return (a > b) - (a < b);
12451 }
12452
12453 /* Set bp_location_placed_address_before_address_max and
12454    bp_location_shadow_len_after_address_max according to the current
12455    content of the bp_location array.  */
12456
12457 static void
12458 bp_location_target_extensions_update (void)
12459 {
12460   struct bp_location *bl, **blp_tmp;
12461
12462   bp_location_placed_address_before_address_max = 0;
12463   bp_location_shadow_len_after_address_max = 0;
12464
12465   ALL_BP_LOCATIONS (bl, blp_tmp)
12466     {
12467       CORE_ADDR start, end, addr;
12468
12469       if (!bp_location_has_shadow (bl))
12470         continue;
12471
12472       start = bl->target_info.placed_address;
12473       end = start + bl->target_info.shadow_len;
12474
12475       gdb_assert (bl->address >= start);
12476       addr = bl->address - start;
12477       if (addr > bp_location_placed_address_before_address_max)
12478         bp_location_placed_address_before_address_max = addr;
12479
12480       /* Zero SHADOW_LEN would not pass bp_location_has_shadow.  */
12481
12482       gdb_assert (bl->address < end);
12483       addr = end - bl->address;
12484       if (addr > bp_location_shadow_len_after_address_max)
12485         bp_location_shadow_len_after_address_max = addr;
12486     }
12487 }
12488
12489 /* Download tracepoint locations if they haven't been.  */
12490
12491 static void
12492 download_tracepoint_locations (void)
12493 {
12494   struct breakpoint *b;
12495   struct cleanup *old_chain;
12496
12497   if (!target_can_download_tracepoint ())
12498     return;
12499
12500   old_chain = save_current_space_and_thread ();
12501
12502   ALL_TRACEPOINTS (b)
12503     {
12504       struct bp_location *bl;
12505       struct tracepoint *t;
12506       int bp_location_downloaded = 0;
12507
12508       if ((b->type == bp_fast_tracepoint
12509            ? !may_insert_fast_tracepoints
12510            : !may_insert_tracepoints))
12511         continue;
12512
12513       for (bl = b->loc; bl; bl = bl->next)
12514         {
12515           /* In tracepoint, locations are _never_ duplicated, so
12516              should_be_inserted is equivalent to
12517              unduplicated_should_be_inserted.  */
12518           if (!should_be_inserted (bl) || bl->inserted)
12519             continue;
12520
12521           switch_to_program_space_and_thread (bl->pspace);
12522
12523           target_download_tracepoint (bl);
12524
12525           bl->inserted = 1;
12526           bp_location_downloaded = 1;
12527         }
12528       t = (struct tracepoint *) b;
12529       t->number_on_target = b->number;
12530       if (bp_location_downloaded)
12531         observer_notify_breakpoint_modified (b);
12532     }
12533
12534   do_cleanups (old_chain);
12535 }
12536
12537 /* Swap the insertion/duplication state between two locations.  */
12538
12539 static void
12540 swap_insertion (struct bp_location *left, struct bp_location *right)
12541 {
12542   const int left_inserted = left->inserted;
12543   const int left_duplicate = left->duplicate;
12544   const int left_needs_update = left->needs_update;
12545   const struct bp_target_info left_target_info = left->target_info;
12546
12547   /* Locations of tracepoints can never be duplicated.  */
12548   if (is_tracepoint (left->owner))
12549     gdb_assert (!left->duplicate);
12550   if (is_tracepoint (right->owner))
12551     gdb_assert (!right->duplicate);
12552
12553   left->inserted = right->inserted;
12554   left->duplicate = right->duplicate;
12555   left->needs_update = right->needs_update;
12556   left->target_info = right->target_info;
12557   right->inserted = left_inserted;
12558   right->duplicate = left_duplicate;
12559   right->needs_update = left_needs_update;
12560   right->target_info = left_target_info;
12561 }
12562
12563 /* Force the re-insertion of the locations at ADDRESS.  This is called
12564    once a new/deleted/modified duplicate location is found and we are evaluating
12565    conditions on the target's side.  Such conditions need to be updated on
12566    the target.  */
12567
12568 static void
12569 force_breakpoint_reinsertion (struct bp_location *bl)
12570 {
12571   struct bp_location **locp = NULL, **loc2p;
12572   struct bp_location *loc;
12573   CORE_ADDR address = 0;
12574   int pspace_num;
12575
12576   address = bl->address;
12577   pspace_num = bl->pspace->num;
12578
12579   /* This is only meaningful if the target is
12580      evaluating conditions and if the user has
12581      opted for condition evaluation on the target's
12582      side.  */
12583   if (gdb_evaluates_breakpoint_condition_p ()
12584       || !target_supports_evaluation_of_breakpoint_conditions ())
12585     return;
12586
12587   /* Flag all breakpoint locations with this address and
12588      the same program space as the location
12589      as "its condition has changed".  We need to
12590      update the conditions on the target's side.  */
12591   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, address)
12592     {
12593       loc = *loc2p;
12594
12595       if (!is_breakpoint (loc->owner)
12596           || pspace_num != loc->pspace->num)
12597         continue;
12598
12599       /* Flag the location appropriately.  We use a different state to
12600          let everyone know that we already updated the set of locations
12601          with addr bl->address and program space bl->pspace.  This is so
12602          we don't have to keep calling these functions just to mark locations
12603          that have already been marked.  */
12604       loc->condition_changed = condition_updated;
12605
12606       /* Free the agent expression bytecode as well.  We will compute
12607          it later on.  */
12608       if (loc->cond_bytecode)
12609         {
12610           free_agent_expr (loc->cond_bytecode);
12611           loc->cond_bytecode = NULL;
12612         }
12613     }
12614 }
12615 /* Called whether new breakpoints are created, or existing breakpoints
12616    deleted, to update the global location list and recompute which
12617    locations are duplicate of which.
12618
12619    The INSERT_MODE flag determines whether locations may not, may, or
12620    shall be inserted now.  See 'enum ugll_insert_mode' for more
12621    info.  */
12622
12623 static void
12624 update_global_location_list (enum ugll_insert_mode insert_mode)
12625 {
12626   struct breakpoint *b;
12627   struct bp_location **locp, *loc;
12628   struct cleanup *cleanups;
12629   /* Last breakpoint location address that was marked for update.  */
12630   CORE_ADDR last_addr = 0;
12631   /* Last breakpoint location program space that was marked for update.  */
12632   int last_pspace_num = -1;
12633
12634   /* Used in the duplicates detection below.  When iterating over all
12635      bp_locations, points to the first bp_location of a given address.
12636      Breakpoints and watchpoints of different types are never
12637      duplicates of each other.  Keep one pointer for each type of
12638      breakpoint/watchpoint, so we only need to loop over all locations
12639      once.  */
12640   struct bp_location *bp_loc_first;  /* breakpoint */
12641   struct bp_location *wp_loc_first;  /* hardware watchpoint */
12642   struct bp_location *awp_loc_first; /* access watchpoint */
12643   struct bp_location *rwp_loc_first; /* read watchpoint */
12644
12645   /* Saved former bp_location array which we compare against the newly
12646      built bp_location from the current state of ALL_BREAKPOINTS.  */
12647   struct bp_location **old_location, **old_locp;
12648   unsigned old_location_count;
12649
12650   old_location = bp_location;
12651   old_location_count = bp_location_count;
12652   bp_location = NULL;
12653   bp_location_count = 0;
12654   cleanups = make_cleanup (xfree, old_location);
12655
12656   ALL_BREAKPOINTS (b)
12657     for (loc = b->loc; loc; loc = loc->next)
12658       bp_location_count++;
12659
12660   bp_location = xmalloc (sizeof (*bp_location) * bp_location_count);
12661   locp = bp_location;
12662   ALL_BREAKPOINTS (b)
12663     for (loc = b->loc; loc; loc = loc->next)
12664       *locp++ = loc;
12665   qsort (bp_location, bp_location_count, sizeof (*bp_location),
12666          bp_location_compare);
12667
12668   bp_location_target_extensions_update ();
12669
12670   /* Identify bp_location instances that are no longer present in the
12671      new list, and therefore should be freed.  Note that it's not
12672      necessary that those locations should be removed from inferior --
12673      if there's another location at the same address (previously
12674      marked as duplicate), we don't need to remove/insert the
12675      location.
12676      
12677      LOCP is kept in sync with OLD_LOCP, each pointing to the current
12678      and former bp_location array state respectively.  */
12679
12680   locp = bp_location;
12681   for (old_locp = old_location; old_locp < old_location + old_location_count;
12682        old_locp++)
12683     {
12684       struct bp_location *old_loc = *old_locp;
12685       struct bp_location **loc2p;
12686
12687       /* Tells if 'old_loc' is found among the new locations.  If
12688          not, we have to free it.  */
12689       int found_object = 0;
12690       /* Tells if the location should remain inserted in the target.  */
12691       int keep_in_target = 0;
12692       int removed = 0;
12693
12694       /* Skip LOCP entries which will definitely never be needed.
12695          Stop either at or being the one matching OLD_LOC.  */
12696       while (locp < bp_location + bp_location_count
12697              && (*locp)->address < old_loc->address)
12698         locp++;
12699
12700       for (loc2p = locp;
12701            (loc2p < bp_location + bp_location_count
12702             && (*loc2p)->address == old_loc->address);
12703            loc2p++)
12704         {
12705           /* Check if this is a new/duplicated location or a duplicated
12706              location that had its condition modified.  If so, we want to send
12707              its condition to the target if evaluation of conditions is taking
12708              place there.  */
12709           if ((*loc2p)->condition_changed == condition_modified
12710               && (last_addr != old_loc->address
12711                   || last_pspace_num != old_loc->pspace->num))
12712             {
12713               force_breakpoint_reinsertion (*loc2p);
12714               last_pspace_num = old_loc->pspace->num;
12715             }
12716
12717           if (*loc2p == old_loc)
12718             found_object = 1;
12719         }
12720
12721       /* We have already handled this address, update it so that we don't
12722          have to go through updates again.  */
12723       last_addr = old_loc->address;
12724
12725       /* Target-side condition evaluation: Handle deleted locations.  */
12726       if (!found_object)
12727         force_breakpoint_reinsertion (old_loc);
12728
12729       /* If this location is no longer present, and inserted, look if
12730          there's maybe a new location at the same address.  If so,
12731          mark that one inserted, and don't remove this one.  This is
12732          needed so that we don't have a time window where a breakpoint
12733          at certain location is not inserted.  */
12734
12735       if (old_loc->inserted)
12736         {
12737           /* If the location is inserted now, we might have to remove
12738              it.  */
12739
12740           if (found_object && should_be_inserted (old_loc))
12741             {
12742               /* The location is still present in the location list,
12743                  and still should be inserted.  Don't do anything.  */
12744               keep_in_target = 1;
12745             }
12746           else
12747             {
12748               /* This location still exists, but it won't be kept in the
12749                  target since it may have been disabled.  We proceed to
12750                  remove its target-side condition.  */
12751
12752               /* The location is either no longer present, or got
12753                  disabled.  See if there's another location at the
12754                  same address, in which case we don't need to remove
12755                  this one from the target.  */
12756
12757               /* OLD_LOC comes from existing struct breakpoint.  */
12758               if (breakpoint_address_is_meaningful (old_loc->owner))
12759                 {
12760                   for (loc2p = locp;
12761                        (loc2p < bp_location + bp_location_count
12762                         && (*loc2p)->address == old_loc->address);
12763                        loc2p++)
12764                     {
12765                       struct bp_location *loc2 = *loc2p;
12766
12767                       if (breakpoint_locations_match (loc2, old_loc))
12768                         {
12769                           /* Read watchpoint locations are switched to
12770                              access watchpoints, if the former are not
12771                              supported, but the latter are.  */
12772                           if (is_hardware_watchpoint (old_loc->owner))
12773                             {
12774                               gdb_assert (is_hardware_watchpoint (loc2->owner));
12775                               loc2->watchpoint_type = old_loc->watchpoint_type;
12776                             }
12777
12778                           /* loc2 is a duplicated location. We need to check
12779                              if it should be inserted in case it will be
12780                              unduplicated.  */
12781                           if (loc2 != old_loc
12782                               && unduplicated_should_be_inserted (loc2))
12783                             {
12784                               swap_insertion (old_loc, loc2);
12785                               keep_in_target = 1;
12786                               break;
12787                             }
12788                         }
12789                     }
12790                 }
12791             }
12792
12793           if (!keep_in_target)
12794             {
12795               if (remove_breakpoint (old_loc, mark_uninserted))
12796                 {
12797                   /* This is just about all we can do.  We could keep
12798                      this location on the global list, and try to
12799                      remove it next time, but there's no particular
12800                      reason why we will succeed next time.
12801                      
12802                      Note that at this point, old_loc->owner is still
12803                      valid, as delete_breakpoint frees the breakpoint
12804                      only after calling us.  */
12805                   printf_filtered (_("warning: Error removing "
12806                                      "breakpoint %d\n"), 
12807                                    old_loc->owner->number);
12808                 }
12809               removed = 1;
12810             }
12811         }
12812
12813       if (!found_object)
12814         {
12815           if (removed && non_stop
12816               && breakpoint_address_is_meaningful (old_loc->owner)
12817               && !is_hardware_watchpoint (old_loc->owner))
12818             {
12819               /* This location was removed from the target.  In
12820                  non-stop mode, a race condition is possible where
12821                  we've removed a breakpoint, but stop events for that
12822                  breakpoint are already queued and will arrive later.
12823                  We apply an heuristic to be able to distinguish such
12824                  SIGTRAPs from other random SIGTRAPs: we keep this
12825                  breakpoint location for a bit, and will retire it
12826                  after we see some number of events.  The theory here
12827                  is that reporting of events should, "on the average",
12828                  be fair, so after a while we'll see events from all
12829                  threads that have anything of interest, and no longer
12830                  need to keep this breakpoint location around.  We
12831                  don't hold locations forever so to reduce chances of
12832                  mistaking a non-breakpoint SIGTRAP for a breakpoint
12833                  SIGTRAP.
12834
12835                  The heuristic failing can be disastrous on
12836                  decr_pc_after_break targets.
12837
12838                  On decr_pc_after_break targets, like e.g., x86-linux,
12839                  if we fail to recognize a late breakpoint SIGTRAP,
12840                  because events_till_retirement has reached 0 too
12841                  soon, we'll fail to do the PC adjustment, and report
12842                  a random SIGTRAP to the user.  When the user resumes
12843                  the inferior, it will most likely immediately crash
12844                  with SIGILL/SIGBUS/SIGSEGV, or worse, get silently
12845                  corrupted, because of being resumed e.g., in the
12846                  middle of a multi-byte instruction, or skipped a
12847                  one-byte instruction.  This was actually seen happen
12848                  on native x86-linux, and should be less rare on
12849                  targets that do not support new thread events, like
12850                  remote, due to the heuristic depending on
12851                  thread_count.
12852
12853                  Mistaking a random SIGTRAP for a breakpoint trap
12854                  causes similar symptoms (PC adjustment applied when
12855                  it shouldn't), but then again, playing with SIGTRAPs
12856                  behind the debugger's back is asking for trouble.
12857
12858                  Since hardware watchpoint traps are always
12859                  distinguishable from other traps, so we don't need to
12860                  apply keep hardware watchpoint moribund locations
12861                  around.  We simply always ignore hardware watchpoint
12862                  traps we can no longer explain.  */
12863
12864               old_loc->events_till_retirement = 3 * (thread_count () + 1);
12865               old_loc->owner = NULL;
12866
12867               VEC_safe_push (bp_location_p, moribund_locations, old_loc);
12868             }
12869           else
12870             {
12871               old_loc->owner = NULL;
12872               decref_bp_location (&old_loc);
12873             }
12874         }
12875     }
12876
12877   /* Rescan breakpoints at the same address and section, marking the
12878      first one as "first" and any others as "duplicates".  This is so
12879      that the bpt instruction is only inserted once.  If we have a
12880      permanent breakpoint at the same place as BPT, make that one the
12881      official one, and the rest as duplicates.  Permanent breakpoints
12882      are sorted first for the same address.
12883
12884      Do the same for hardware watchpoints, but also considering the
12885      watchpoint's type (regular/access/read) and length.  */
12886
12887   bp_loc_first = NULL;
12888   wp_loc_first = NULL;
12889   awp_loc_first = NULL;
12890   rwp_loc_first = NULL;
12891   ALL_BP_LOCATIONS (loc, locp)
12892     {
12893       /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always
12894          non-NULL.  */
12895       struct bp_location **loc_first_p;
12896       b = loc->owner;
12897
12898       if (!unduplicated_should_be_inserted (loc)
12899           || !breakpoint_address_is_meaningful (b)
12900           /* Don't detect duplicate for tracepoint locations because they are
12901            never duplicated.  See the comments in field `duplicate' of
12902            `struct bp_location'.  */
12903           || is_tracepoint (b))
12904         {
12905           /* Clear the condition modification flag.  */
12906           loc->condition_changed = condition_unchanged;
12907           continue;
12908         }
12909
12910       /* Permanent breakpoint should always be inserted.  */
12911       if (b->enable_state == bp_permanent && ! loc->inserted)
12912         internal_error (__FILE__, __LINE__,
12913                         _("allegedly permanent breakpoint is not "
12914                         "actually inserted"));
12915
12916       if (b->type == bp_hardware_watchpoint)
12917         loc_first_p = &wp_loc_first;
12918       else if (b->type == bp_read_watchpoint)
12919         loc_first_p = &rwp_loc_first;
12920       else if (b->type == bp_access_watchpoint)
12921         loc_first_p = &awp_loc_first;
12922       else
12923         loc_first_p = &bp_loc_first;
12924
12925       if (*loc_first_p == NULL
12926           || (overlay_debugging && loc->section != (*loc_first_p)->section)
12927           || !breakpoint_locations_match (loc, *loc_first_p))
12928         {
12929           *loc_first_p = loc;
12930           loc->duplicate = 0;
12931
12932           if (is_breakpoint (loc->owner) && loc->condition_changed)
12933             {
12934               loc->needs_update = 1;
12935               /* Clear the condition modification flag.  */
12936               loc->condition_changed = condition_unchanged;
12937             }
12938           continue;
12939         }
12940
12941
12942       /* This and the above ensure the invariant that the first location
12943          is not duplicated, and is the inserted one.
12944          All following are marked as duplicated, and are not inserted.  */
12945       if (loc->inserted)
12946         swap_insertion (loc, *loc_first_p);
12947       loc->duplicate = 1;
12948
12949       /* Clear the condition modification flag.  */
12950       loc->condition_changed = condition_unchanged;
12951
12952       if ((*loc_first_p)->owner->enable_state == bp_permanent && loc->inserted
12953           && b->enable_state != bp_permanent)
12954         internal_error (__FILE__, __LINE__,
12955                         _("another breakpoint was inserted on top of "
12956                         "a permanent breakpoint"));
12957     }
12958
12959   if (insert_mode == UGLL_INSERT || breakpoints_should_be_inserted_now ())
12960     {
12961       if (insert_mode != UGLL_DONT_INSERT)
12962         insert_breakpoint_locations ();
12963       else
12964         {
12965           /* Even though the caller told us to not insert new
12966              locations, we may still need to update conditions on the
12967              target's side of breakpoints that were already inserted
12968              if the target is evaluating breakpoint conditions.  We
12969              only update conditions for locations that are marked
12970              "needs_update".  */
12971           update_inserted_breakpoint_locations ();
12972         }
12973     }
12974
12975   if (insert_mode != UGLL_DONT_INSERT)
12976     download_tracepoint_locations ();
12977
12978   do_cleanups (cleanups);
12979 }
12980
12981 void
12982 breakpoint_retire_moribund (void)
12983 {
12984   struct bp_location *loc;
12985   int ix;
12986
12987   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
12988     if (--(loc->events_till_retirement) == 0)
12989       {
12990         decref_bp_location (&loc);
12991         VEC_unordered_remove (bp_location_p, moribund_locations, ix);
12992         --ix;
12993       }
12994 }
12995
12996 static void
12997 update_global_location_list_nothrow (enum ugll_insert_mode insert_mode)
12998 {
12999   volatile struct gdb_exception e;
13000
13001   TRY_CATCH (e, RETURN_MASK_ERROR)
13002     update_global_location_list (insert_mode);
13003 }
13004
13005 /* Clear BKP from a BPS.  */
13006
13007 static void
13008 bpstat_remove_bp_location (bpstat bps, struct breakpoint *bpt)
13009 {
13010   bpstat bs;
13011
13012   for (bs = bps; bs; bs = bs->next)
13013     if (bs->breakpoint_at == bpt)
13014       {
13015         bs->breakpoint_at = NULL;
13016         bs->old_val = NULL;
13017         /* bs->commands will be freed later.  */
13018       }
13019 }
13020
13021 /* Callback for iterate_over_threads.  */
13022 static int
13023 bpstat_remove_breakpoint_callback (struct thread_info *th, void *data)
13024 {
13025   struct breakpoint *bpt = data;
13026
13027   bpstat_remove_bp_location (th->control.stop_bpstat, bpt);
13028   return 0;
13029 }
13030
13031 /* Helper for breakpoint and tracepoint breakpoint_ops->mention
13032    callbacks.  */
13033
13034 static void
13035 say_where (struct breakpoint *b)
13036 {
13037   struct value_print_options opts;
13038
13039   get_user_print_options (&opts);
13040
13041   /* i18n: cagney/2005-02-11: Below needs to be merged into a
13042      single string.  */
13043   if (b->loc == NULL)
13044     {
13045       printf_filtered (_(" (%s) pending."), b->addr_string);
13046     }
13047   else
13048     {
13049       if (opts.addressprint || b->loc->symtab == NULL)
13050         {
13051           printf_filtered (" at ");
13052           fputs_filtered (paddress (b->loc->gdbarch, b->loc->address),
13053                           gdb_stdout);
13054         }
13055       if (b->loc->symtab != NULL)
13056         {
13057           /* If there is a single location, we can print the location
13058              more nicely.  */
13059           if (b->loc->next == NULL)
13060             printf_filtered (": file %s, line %d.",
13061                              symtab_to_filename_for_display (b->loc->symtab),
13062                              b->loc->line_number);
13063           else
13064             /* This is not ideal, but each location may have a
13065                different file name, and this at least reflects the
13066                real situation somewhat.  */
13067             printf_filtered (": %s.", b->addr_string);
13068         }
13069
13070       if (b->loc->next)
13071         {
13072           struct bp_location *loc = b->loc;
13073           int n = 0;
13074           for (; loc; loc = loc->next)
13075             ++n;
13076           printf_filtered (" (%d locations)", n);
13077         }
13078     }
13079 }
13080
13081 /* Default bp_location_ops methods.  */
13082
13083 static void
13084 bp_location_dtor (struct bp_location *self)
13085 {
13086   xfree (self->cond);
13087   if (self->cond_bytecode)
13088     free_agent_expr (self->cond_bytecode);
13089   xfree (self->function_name);
13090
13091   VEC_free (agent_expr_p, self->target_info.conditions);
13092   VEC_free (agent_expr_p, self->target_info.tcommands);
13093 }
13094
13095 static const struct bp_location_ops bp_location_ops =
13096 {
13097   bp_location_dtor
13098 };
13099
13100 /* Default breakpoint_ops methods all breakpoint_ops ultimately
13101    inherit from.  */
13102
13103 static void
13104 base_breakpoint_dtor (struct breakpoint *self)
13105 {
13106   decref_counted_command_line (&self->commands);
13107   xfree (self->cond_string);
13108   xfree (self->extra_string);
13109   xfree (self->addr_string);
13110   xfree (self->filter);
13111   xfree (self->addr_string_range_end);
13112 }
13113
13114 static struct bp_location *
13115 base_breakpoint_allocate_location (struct breakpoint *self)
13116 {
13117   struct bp_location *loc;
13118
13119   loc = XNEW (struct bp_location);
13120   init_bp_location (loc, &bp_location_ops, self);
13121   return loc;
13122 }
13123
13124 static void
13125 base_breakpoint_re_set (struct breakpoint *b)
13126 {
13127   /* Nothing to re-set. */
13128 }
13129
13130 #define internal_error_pure_virtual_called() \
13131   gdb_assert_not_reached ("pure virtual function called")
13132
13133 static int
13134 base_breakpoint_insert_location (struct bp_location *bl)
13135 {
13136   internal_error_pure_virtual_called ();
13137 }
13138
13139 static int
13140 base_breakpoint_remove_location (struct bp_location *bl)
13141 {
13142   internal_error_pure_virtual_called ();
13143 }
13144
13145 static int
13146 base_breakpoint_breakpoint_hit (const struct bp_location *bl,
13147                                 struct address_space *aspace,
13148                                 CORE_ADDR bp_addr,
13149                                 const struct target_waitstatus *ws)
13150 {
13151   internal_error_pure_virtual_called ();
13152 }
13153
13154 static void
13155 base_breakpoint_check_status (bpstat bs)
13156 {
13157   /* Always stop.   */
13158 }
13159
13160 /* A "works_in_software_mode" breakpoint_ops method that just internal
13161    errors.  */
13162
13163 static int
13164 base_breakpoint_works_in_software_mode (const struct breakpoint *b)
13165 {
13166   internal_error_pure_virtual_called ();
13167 }
13168
13169 /* A "resources_needed" breakpoint_ops method that just internal
13170    errors.  */
13171
13172 static int
13173 base_breakpoint_resources_needed (const struct bp_location *bl)
13174 {
13175   internal_error_pure_virtual_called ();
13176 }
13177
13178 static enum print_stop_action
13179 base_breakpoint_print_it (bpstat bs)
13180 {
13181   internal_error_pure_virtual_called ();
13182 }
13183
13184 static void
13185 base_breakpoint_print_one_detail (const struct breakpoint *self,
13186                                   struct ui_out *uiout)
13187 {
13188   /* nothing */
13189 }
13190
13191 static void
13192 base_breakpoint_print_mention (struct breakpoint *b)
13193 {
13194   internal_error_pure_virtual_called ();
13195 }
13196
13197 static void
13198 base_breakpoint_print_recreate (struct breakpoint *b, struct ui_file *fp)
13199 {
13200   internal_error_pure_virtual_called ();
13201 }
13202
13203 static void
13204 base_breakpoint_create_sals_from_address (char **arg,
13205                                           struct linespec_result *canonical,
13206                                           enum bptype type_wanted,
13207                                           char *addr_start,
13208                                           char **copy_arg)
13209 {
13210   internal_error_pure_virtual_called ();
13211 }
13212
13213 static void
13214 base_breakpoint_create_breakpoints_sal (struct gdbarch *gdbarch,
13215                                         struct linespec_result *c,
13216                                         char *cond_string,
13217                                         char *extra_string,
13218                                         enum bptype type_wanted,
13219                                         enum bpdisp disposition,
13220                                         int thread,
13221                                         int task, int ignore_count,
13222                                         const struct breakpoint_ops *o,
13223                                         int from_tty, int enabled,
13224                                         int internal, unsigned flags)
13225 {
13226   internal_error_pure_virtual_called ();
13227 }
13228
13229 static void
13230 base_breakpoint_decode_linespec (struct breakpoint *b, char **s,
13231                                  struct symtabs_and_lines *sals)
13232 {
13233   internal_error_pure_virtual_called ();
13234 }
13235
13236 /* The default 'explains_signal' method.  */
13237
13238 static int
13239 base_breakpoint_explains_signal (struct breakpoint *b, enum gdb_signal sig)
13240 {
13241   return 1;
13242 }
13243
13244 /* The default "after_condition_true" method.  */
13245
13246 static void
13247 base_breakpoint_after_condition_true (struct bpstats *bs)
13248 {
13249   /* Nothing to do.   */
13250 }
13251
13252 struct breakpoint_ops base_breakpoint_ops =
13253 {
13254   base_breakpoint_dtor,
13255   base_breakpoint_allocate_location,
13256   base_breakpoint_re_set,
13257   base_breakpoint_insert_location,
13258   base_breakpoint_remove_location,
13259   base_breakpoint_breakpoint_hit,
13260   base_breakpoint_check_status,
13261   base_breakpoint_resources_needed,
13262   base_breakpoint_works_in_software_mode,
13263   base_breakpoint_print_it,
13264   NULL,
13265   base_breakpoint_print_one_detail,
13266   base_breakpoint_print_mention,
13267   base_breakpoint_print_recreate,
13268   base_breakpoint_create_sals_from_address,
13269   base_breakpoint_create_breakpoints_sal,
13270   base_breakpoint_decode_linespec,
13271   base_breakpoint_explains_signal,
13272   base_breakpoint_after_condition_true,
13273 };
13274
13275 /* Default breakpoint_ops methods.  */
13276
13277 static void
13278 bkpt_re_set (struct breakpoint *b)
13279 {
13280   /* FIXME: is this still reachable?  */
13281   if (b->addr_string == NULL)
13282     {
13283       /* Anything without a string can't be re-set.  */
13284       delete_breakpoint (b);
13285       return;
13286     }
13287
13288   breakpoint_re_set_default (b);
13289 }
13290
13291 static int
13292 bkpt_insert_location (struct bp_location *bl)
13293 {
13294   if (bl->loc_type == bp_loc_hardware_breakpoint)
13295     return target_insert_hw_breakpoint (bl->gdbarch, &bl->target_info);
13296   else
13297     return target_insert_breakpoint (bl->gdbarch, &bl->target_info);
13298 }
13299
13300 static int
13301 bkpt_remove_location (struct bp_location *bl)
13302 {
13303   if (bl->loc_type == bp_loc_hardware_breakpoint)
13304     return target_remove_hw_breakpoint (bl->gdbarch, &bl->target_info);
13305   else
13306     return target_remove_breakpoint (bl->gdbarch, &bl->target_info);
13307 }
13308
13309 static int
13310 bkpt_breakpoint_hit (const struct bp_location *bl,
13311                      struct address_space *aspace, CORE_ADDR bp_addr,
13312                      const struct target_waitstatus *ws)
13313 {
13314   if (ws->kind != TARGET_WAITKIND_STOPPED
13315       || ws->value.sig != GDB_SIGNAL_TRAP)
13316     return 0;
13317
13318   if (!breakpoint_address_match (bl->pspace->aspace, bl->address,
13319                                  aspace, bp_addr))
13320     return 0;
13321
13322   if (overlay_debugging         /* unmapped overlay section */
13323       && section_is_overlay (bl->section)
13324       && !section_is_mapped (bl->section))
13325     return 0;
13326
13327   return 1;
13328 }
13329
13330 static int
13331 dprintf_breakpoint_hit (const struct bp_location *bl,
13332                         struct address_space *aspace, CORE_ADDR bp_addr,
13333                         const struct target_waitstatus *ws)
13334 {
13335   if (dprintf_style == dprintf_style_agent
13336       && target_can_run_breakpoint_commands ())
13337     {
13338       /* An agent-style dprintf never causes a stop.  If we see a trap
13339          for this address it must be for a breakpoint that happens to
13340          be set at the same address.  */
13341       return 0;
13342     }
13343
13344   return bkpt_breakpoint_hit (bl, aspace, bp_addr, ws);
13345 }
13346
13347 static int
13348 bkpt_resources_needed (const struct bp_location *bl)
13349 {
13350   gdb_assert (bl->owner->type == bp_hardware_breakpoint);
13351
13352   return 1;
13353 }
13354
13355 static enum print_stop_action
13356 bkpt_print_it (bpstat bs)
13357 {
13358   struct breakpoint *b;
13359   const struct bp_location *bl;
13360   int bp_temp;
13361   struct ui_out *uiout = current_uiout;
13362
13363   gdb_assert (bs->bp_location_at != NULL);
13364
13365   bl = bs->bp_location_at;
13366   b = bs->breakpoint_at;
13367
13368   bp_temp = b->disposition == disp_del;
13369   if (bl->address != bl->requested_address)
13370     breakpoint_adjustment_warning (bl->requested_address,
13371                                    bl->address,
13372                                    b->number, 1);
13373   annotate_breakpoint (b->number);
13374   if (bp_temp)
13375     ui_out_text (uiout, "\nTemporary breakpoint ");
13376   else
13377     ui_out_text (uiout, "\nBreakpoint ");
13378   if (ui_out_is_mi_like_p (uiout))
13379     {
13380       ui_out_field_string (uiout, "reason",
13381                            async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
13382       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
13383     }
13384   ui_out_field_int (uiout, "bkptno", b->number);
13385   ui_out_text (uiout, ", ");
13386
13387   return PRINT_SRC_AND_LOC;
13388 }
13389
13390 static void
13391 bkpt_print_mention (struct breakpoint *b)
13392 {
13393   if (ui_out_is_mi_like_p (current_uiout))
13394     return;
13395
13396   switch (b->type)
13397     {
13398     case bp_breakpoint:
13399     case bp_gnu_ifunc_resolver:
13400       if (b->disposition == disp_del)
13401         printf_filtered (_("Temporary breakpoint"));
13402       else
13403         printf_filtered (_("Breakpoint"));
13404       printf_filtered (_(" %d"), b->number);
13405       if (b->type == bp_gnu_ifunc_resolver)
13406         printf_filtered (_(" at gnu-indirect-function resolver"));
13407       break;
13408     case bp_hardware_breakpoint:
13409       printf_filtered (_("Hardware assisted breakpoint %d"), b->number);
13410       break;
13411     case bp_dprintf:
13412       printf_filtered (_("Dprintf %d"), b->number);
13413       break;
13414     }
13415
13416   say_where (b);
13417 }
13418
13419 static void
13420 bkpt_print_recreate (struct breakpoint *tp, struct ui_file *fp)
13421 {
13422   if (tp->type == bp_breakpoint && tp->disposition == disp_del)
13423     fprintf_unfiltered (fp, "tbreak");
13424   else if (tp->type == bp_breakpoint)
13425     fprintf_unfiltered (fp, "break");
13426   else if (tp->type == bp_hardware_breakpoint
13427            && tp->disposition == disp_del)
13428     fprintf_unfiltered (fp, "thbreak");
13429   else if (tp->type == bp_hardware_breakpoint)
13430     fprintf_unfiltered (fp, "hbreak");
13431   else
13432     internal_error (__FILE__, __LINE__,
13433                     _("unhandled breakpoint type %d"), (int) tp->type);
13434
13435   fprintf_unfiltered (fp, " %s", tp->addr_string);
13436   print_recreate_thread (tp, fp);
13437 }
13438
13439 static void
13440 bkpt_create_sals_from_address (char **arg,
13441                                struct linespec_result *canonical,
13442                                enum bptype type_wanted,
13443                                char *addr_start, char **copy_arg)
13444 {
13445   create_sals_from_address_default (arg, canonical, type_wanted,
13446                                     addr_start, copy_arg);
13447 }
13448
13449 static void
13450 bkpt_create_breakpoints_sal (struct gdbarch *gdbarch,
13451                              struct linespec_result *canonical,
13452                              char *cond_string,
13453                              char *extra_string,
13454                              enum bptype type_wanted,
13455                              enum bpdisp disposition,
13456                              int thread,
13457                              int task, int ignore_count,
13458                              const struct breakpoint_ops *ops,
13459                              int from_tty, int enabled,
13460                              int internal, unsigned flags)
13461 {
13462   create_breakpoints_sal_default (gdbarch, canonical,
13463                                   cond_string, extra_string,
13464                                   type_wanted,
13465                                   disposition, thread, task,
13466                                   ignore_count, ops, from_tty,
13467                                   enabled, internal, flags);
13468 }
13469
13470 static void
13471 bkpt_decode_linespec (struct breakpoint *b, char **s,
13472                       struct symtabs_and_lines *sals)
13473 {
13474   decode_linespec_default (b, s, sals);
13475 }
13476
13477 /* Virtual table for internal breakpoints.  */
13478
13479 static void
13480 internal_bkpt_re_set (struct breakpoint *b)
13481 {
13482   switch (b->type)
13483     {
13484       /* Delete overlay event and longjmp master breakpoints; they
13485          will be reset later by breakpoint_re_set.  */
13486     case bp_overlay_event:
13487     case bp_longjmp_master:
13488     case bp_std_terminate_master:
13489     case bp_exception_master:
13490       delete_breakpoint (b);
13491       break;
13492
13493       /* This breakpoint is special, it's set up when the inferior
13494          starts and we really don't want to touch it.  */
13495     case bp_shlib_event:
13496
13497       /* Like bp_shlib_event, this breakpoint type is special.  Once
13498          it is set up, we do not want to touch it.  */
13499     case bp_thread_event:
13500       break;
13501     }
13502 }
13503
13504 static void
13505 internal_bkpt_check_status (bpstat bs)
13506 {
13507   if (bs->breakpoint_at->type == bp_shlib_event)
13508     {
13509       /* If requested, stop when the dynamic linker notifies GDB of
13510          events.  This allows the user to get control and place
13511          breakpoints in initializer routines for dynamically loaded
13512          objects (among other things).  */
13513       bs->stop = stop_on_solib_events;
13514       bs->print = stop_on_solib_events;
13515     }
13516   else
13517     bs->stop = 0;
13518 }
13519
13520 static enum print_stop_action
13521 internal_bkpt_print_it (bpstat bs)
13522 {
13523   struct breakpoint *b;
13524
13525   b = bs->breakpoint_at;
13526
13527   switch (b->type)
13528     {
13529     case bp_shlib_event:
13530       /* Did we stop because the user set the stop_on_solib_events
13531          variable?  (If so, we report this as a generic, "Stopped due
13532          to shlib event" message.) */
13533       print_solib_event (0);
13534       break;
13535
13536     case bp_thread_event:
13537       /* Not sure how we will get here.
13538          GDB should not stop for these breakpoints.  */
13539       printf_filtered (_("Thread Event Breakpoint: gdb should not stop!\n"));
13540       break;
13541
13542     case bp_overlay_event:
13543       /* By analogy with the thread event, GDB should not stop for these.  */
13544       printf_filtered (_("Overlay Event Breakpoint: gdb should not stop!\n"));
13545       break;
13546
13547     case bp_longjmp_master:
13548       /* These should never be enabled.  */
13549       printf_filtered (_("Longjmp Master Breakpoint: gdb should not stop!\n"));
13550       break;
13551
13552     case bp_std_terminate_master:
13553       /* These should never be enabled.  */
13554       printf_filtered (_("std::terminate Master Breakpoint: "
13555                          "gdb should not stop!\n"));
13556       break;
13557
13558     case bp_exception_master:
13559       /* These should never be enabled.  */
13560       printf_filtered (_("Exception Master Breakpoint: "
13561                          "gdb should not stop!\n"));
13562       break;
13563     }
13564
13565   return PRINT_NOTHING;
13566 }
13567
13568 static void
13569 internal_bkpt_print_mention (struct breakpoint *b)
13570 {
13571   /* Nothing to mention.  These breakpoints are internal.  */
13572 }
13573
13574 /* Virtual table for momentary breakpoints  */
13575
13576 static void
13577 momentary_bkpt_re_set (struct breakpoint *b)
13578 {
13579   /* Keep temporary breakpoints, which can be encountered when we step
13580      over a dlopen call and solib_add is resetting the breakpoints.
13581      Otherwise these should have been blown away via the cleanup chain
13582      or by breakpoint_init_inferior when we rerun the executable.  */
13583 }
13584
13585 static void
13586 momentary_bkpt_check_status (bpstat bs)
13587 {
13588   /* Nothing.  The point of these breakpoints is causing a stop.  */
13589 }
13590
13591 static enum print_stop_action
13592 momentary_bkpt_print_it (bpstat bs)
13593 {
13594   struct ui_out *uiout = current_uiout;
13595
13596   if (ui_out_is_mi_like_p (uiout))
13597     {
13598       struct breakpoint *b = bs->breakpoint_at;
13599
13600       switch (b->type)
13601         {
13602         case bp_finish:
13603           ui_out_field_string
13604             (uiout, "reason",
13605              async_reason_lookup (EXEC_ASYNC_FUNCTION_FINISHED));
13606           break;
13607
13608         case bp_until:
13609           ui_out_field_string
13610             (uiout, "reason",
13611              async_reason_lookup (EXEC_ASYNC_LOCATION_REACHED));
13612           break;
13613         }
13614     }
13615
13616   return PRINT_UNKNOWN;
13617 }
13618
13619 static void
13620 momentary_bkpt_print_mention (struct breakpoint *b)
13621 {
13622   /* Nothing to mention.  These breakpoints are internal.  */
13623 }
13624
13625 /* Ensure INITIATING_FRAME is cleared when no such breakpoint exists.
13626
13627    It gets cleared already on the removal of the first one of such placed
13628    breakpoints.  This is OK as they get all removed altogether.  */
13629
13630 static void
13631 longjmp_bkpt_dtor (struct breakpoint *self)
13632 {
13633   struct thread_info *tp = find_thread_id (self->thread);
13634
13635   if (tp)
13636     tp->initiating_frame = null_frame_id;
13637
13638   momentary_breakpoint_ops.dtor (self);
13639 }
13640
13641 /* Specific methods for probe breakpoints.  */
13642
13643 static int
13644 bkpt_probe_insert_location (struct bp_location *bl)
13645 {
13646   int v = bkpt_insert_location (bl);
13647
13648   if (v == 0)
13649     {
13650       /* The insertion was successful, now let's set the probe's semaphore
13651          if needed.  */
13652       if (bl->probe.probe->pops->set_semaphore != NULL)
13653         bl->probe.probe->pops->set_semaphore (bl->probe.probe,
13654                                               bl->probe.objfile,
13655                                               bl->gdbarch);
13656     }
13657
13658   return v;
13659 }
13660
13661 static int
13662 bkpt_probe_remove_location (struct bp_location *bl)
13663 {
13664   /* Let's clear the semaphore before removing the location.  */
13665   if (bl->probe.probe->pops->clear_semaphore != NULL)
13666     bl->probe.probe->pops->clear_semaphore (bl->probe.probe,
13667                                             bl->probe.objfile,
13668                                             bl->gdbarch);
13669
13670   return bkpt_remove_location (bl);
13671 }
13672
13673 static void
13674 bkpt_probe_create_sals_from_address (char **arg,
13675                                      struct linespec_result *canonical,
13676                                      enum bptype type_wanted,
13677                                      char *addr_start, char **copy_arg)
13678 {
13679   struct linespec_sals lsal;
13680
13681   lsal.sals = parse_probes (arg, canonical);
13682
13683   *copy_arg = xstrdup (canonical->addr_string);
13684   lsal.canonical = xstrdup (*copy_arg);
13685
13686   VEC_safe_push (linespec_sals, canonical->sals, &lsal);
13687 }
13688
13689 static void
13690 bkpt_probe_decode_linespec (struct breakpoint *b, char **s,
13691                             struct symtabs_and_lines *sals)
13692 {
13693   *sals = parse_probes (s, NULL);
13694   if (!sals->sals)
13695     error (_("probe not found"));
13696 }
13697
13698 /* The breakpoint_ops structure to be used in tracepoints.  */
13699
13700 static void
13701 tracepoint_re_set (struct breakpoint *b)
13702 {
13703   breakpoint_re_set_default (b);
13704 }
13705
13706 static int
13707 tracepoint_breakpoint_hit (const struct bp_location *bl,
13708                            struct address_space *aspace, CORE_ADDR bp_addr,
13709                            const struct target_waitstatus *ws)
13710 {
13711   /* By definition, the inferior does not report stops at
13712      tracepoints.  */
13713   return 0;
13714 }
13715
13716 static void
13717 tracepoint_print_one_detail (const struct breakpoint *self,
13718                              struct ui_out *uiout)
13719 {
13720   struct tracepoint *tp = (struct tracepoint *) self;
13721   if (tp->static_trace_marker_id)
13722     {
13723       gdb_assert (self->type == bp_static_tracepoint);
13724
13725       ui_out_text (uiout, "\tmarker id is ");
13726       ui_out_field_string (uiout, "static-tracepoint-marker-string-id",
13727                            tp->static_trace_marker_id);
13728       ui_out_text (uiout, "\n");
13729     }
13730 }
13731
13732 static void
13733 tracepoint_print_mention (struct breakpoint *b)
13734 {
13735   if (ui_out_is_mi_like_p (current_uiout))
13736     return;
13737
13738   switch (b->type)
13739     {
13740     case bp_tracepoint:
13741       printf_filtered (_("Tracepoint"));
13742       printf_filtered (_(" %d"), b->number);
13743       break;
13744     case bp_fast_tracepoint:
13745       printf_filtered (_("Fast tracepoint"));
13746       printf_filtered (_(" %d"), b->number);
13747       break;
13748     case bp_static_tracepoint:
13749       printf_filtered (_("Static tracepoint"));
13750       printf_filtered (_(" %d"), b->number);
13751       break;
13752     default:
13753       internal_error (__FILE__, __LINE__,
13754                       _("unhandled tracepoint type %d"), (int) b->type);
13755     }
13756
13757   say_where (b);
13758 }
13759
13760 static void
13761 tracepoint_print_recreate (struct breakpoint *self, struct ui_file *fp)
13762 {
13763   struct tracepoint *tp = (struct tracepoint *) self;
13764
13765   if (self->type == bp_fast_tracepoint)
13766     fprintf_unfiltered (fp, "ftrace");
13767   if (self->type == bp_static_tracepoint)
13768     fprintf_unfiltered (fp, "strace");
13769   else if (self->type == bp_tracepoint)
13770     fprintf_unfiltered (fp, "trace");
13771   else
13772     internal_error (__FILE__, __LINE__,
13773                     _("unhandled tracepoint type %d"), (int) self->type);
13774
13775   fprintf_unfiltered (fp, " %s", self->addr_string);
13776   print_recreate_thread (self, fp);
13777
13778   if (tp->pass_count)
13779     fprintf_unfiltered (fp, "  passcount %d\n", tp->pass_count);
13780 }
13781
13782 static void
13783 tracepoint_create_sals_from_address (char **arg,
13784                                      struct linespec_result *canonical,
13785                                      enum bptype type_wanted,
13786                                      char *addr_start, char **copy_arg)
13787 {
13788   create_sals_from_address_default (arg, canonical, type_wanted,
13789                                     addr_start, copy_arg);
13790 }
13791
13792 static void
13793 tracepoint_create_breakpoints_sal (struct gdbarch *gdbarch,
13794                                    struct linespec_result *canonical,
13795                                    char *cond_string,
13796                                    char *extra_string,
13797                                    enum bptype type_wanted,
13798                                    enum bpdisp disposition,
13799                                    int thread,
13800                                    int task, int ignore_count,
13801                                    const struct breakpoint_ops *ops,
13802                                    int from_tty, int enabled,
13803                                    int internal, unsigned flags)
13804 {
13805   create_breakpoints_sal_default (gdbarch, canonical,
13806                                   cond_string, extra_string,
13807                                   type_wanted,
13808                                   disposition, thread, task,
13809                                   ignore_count, ops, from_tty,
13810                                   enabled, internal, flags);
13811 }
13812
13813 static void
13814 tracepoint_decode_linespec (struct breakpoint *b, char **s,
13815                             struct symtabs_and_lines *sals)
13816 {
13817   decode_linespec_default (b, s, sals);
13818 }
13819
13820 struct breakpoint_ops tracepoint_breakpoint_ops;
13821
13822 /* The breakpoint_ops structure to be use on tracepoints placed in a
13823    static probe.  */
13824
13825 static void
13826 tracepoint_probe_create_sals_from_address (char **arg,
13827                                            struct linespec_result *canonical,
13828                                            enum bptype type_wanted,
13829                                            char *addr_start, char **copy_arg)
13830 {
13831   /* We use the same method for breakpoint on probes.  */
13832   bkpt_probe_create_sals_from_address (arg, canonical, type_wanted,
13833                                        addr_start, copy_arg);
13834 }
13835
13836 static void
13837 tracepoint_probe_decode_linespec (struct breakpoint *b, char **s,
13838                                   struct symtabs_and_lines *sals)
13839 {
13840   /* We use the same method for breakpoint on probes.  */
13841   bkpt_probe_decode_linespec (b, s, sals);
13842 }
13843
13844 static struct breakpoint_ops tracepoint_probe_breakpoint_ops;
13845
13846 /* Dprintf breakpoint_ops methods.  */
13847
13848 static void
13849 dprintf_re_set (struct breakpoint *b)
13850 {
13851   breakpoint_re_set_default (b);
13852
13853   /* This breakpoint could have been pending, and be resolved now, and
13854      if so, we should now have the extra string.  If we don't, the
13855      dprintf was malformed when created, but we couldn't tell because
13856      we can't extract the extra string until the location is
13857      resolved.  */
13858   if (b->loc != NULL && b->extra_string == NULL)
13859     error (_("Format string required"));
13860
13861   /* 1 - connect to target 1, that can run breakpoint commands.
13862      2 - create a dprintf, which resolves fine.
13863      3 - disconnect from target 1
13864      4 - connect to target 2, that can NOT run breakpoint commands.
13865
13866      After steps #3/#4, you'll want the dprintf command list to
13867      be updated, because target 1 and 2 may well return different
13868      answers for target_can_run_breakpoint_commands().
13869      Given absence of finer grained resetting, we get to do
13870      it all the time.  */
13871   if (b->extra_string != NULL)
13872     update_dprintf_command_list (b);
13873 }
13874
13875 /* Implement the "print_recreate" breakpoint_ops method for dprintf.  */
13876
13877 static void
13878 dprintf_print_recreate (struct breakpoint *tp, struct ui_file *fp)
13879 {
13880   fprintf_unfiltered (fp, "dprintf %s%s", tp->addr_string,
13881                       tp->extra_string);
13882   print_recreate_thread (tp, fp);
13883 }
13884
13885 /* Implement the "after_condition_true" breakpoint_ops method for
13886    dprintf.
13887
13888    dprintf's are implemented with regular commands in their command
13889    list, but we run the commands here instead of before presenting the
13890    stop to the user, as dprintf's don't actually cause a stop.  This
13891    also makes it so that the commands of multiple dprintfs at the same
13892    address are all handled.  */
13893
13894 static void
13895 dprintf_after_condition_true (struct bpstats *bs)
13896 {
13897   struct cleanup *old_chain;
13898   struct bpstats tmp_bs = { NULL };
13899   struct bpstats *tmp_bs_p = &tmp_bs;
13900
13901   /* dprintf's never cause a stop.  This wasn't set in the
13902      check_status hook instead because that would make the dprintf's
13903      condition not be evaluated.  */
13904   bs->stop = 0;
13905
13906   /* Run the command list here.  Take ownership of it instead of
13907      copying.  We never want these commands to run later in
13908      bpstat_do_actions, if a breakpoint that causes a stop happens to
13909      be set at same address as this dprintf, or even if running the
13910      commands here throws.  */
13911   tmp_bs.commands = bs->commands;
13912   bs->commands = NULL;
13913   old_chain = make_cleanup_decref_counted_command_line (&tmp_bs.commands);
13914
13915   bpstat_do_actions_1 (&tmp_bs_p);
13916
13917   /* 'tmp_bs.commands' will usually be NULL by now, but
13918      bpstat_do_actions_1 may return early without processing the whole
13919      list.  */
13920   do_cleanups (old_chain);
13921 }
13922
13923 /* The breakpoint_ops structure to be used on static tracepoints with
13924    markers (`-m').  */
13925
13926 static void
13927 strace_marker_create_sals_from_address (char **arg,
13928                                         struct linespec_result *canonical,
13929                                         enum bptype type_wanted,
13930                                         char *addr_start, char **copy_arg)
13931 {
13932   struct linespec_sals lsal;
13933
13934   lsal.sals = decode_static_tracepoint_spec (arg);
13935
13936   *copy_arg = savestring (addr_start, *arg - addr_start);
13937
13938   canonical->addr_string = xstrdup (*copy_arg);
13939   lsal.canonical = xstrdup (*copy_arg);
13940   VEC_safe_push (linespec_sals, canonical->sals, &lsal);
13941 }
13942
13943 static void
13944 strace_marker_create_breakpoints_sal (struct gdbarch *gdbarch,
13945                                       struct linespec_result *canonical,
13946                                       char *cond_string,
13947                                       char *extra_string,
13948                                       enum bptype type_wanted,
13949                                       enum bpdisp disposition,
13950                                       int thread,
13951                                       int task, int ignore_count,
13952                                       const struct breakpoint_ops *ops,
13953                                       int from_tty, int enabled,
13954                                       int internal, unsigned flags)
13955 {
13956   int i;
13957   struct linespec_sals *lsal = VEC_index (linespec_sals,
13958                                           canonical->sals, 0);
13959
13960   /* If the user is creating a static tracepoint by marker id
13961      (strace -m MARKER_ID), then store the sals index, so that
13962      breakpoint_re_set can try to match up which of the newly
13963      found markers corresponds to this one, and, don't try to
13964      expand multiple locations for each sal, given than SALS
13965      already should contain all sals for MARKER_ID.  */
13966
13967   for (i = 0; i < lsal->sals.nelts; ++i)
13968     {
13969       struct symtabs_and_lines expanded;
13970       struct tracepoint *tp;
13971       struct cleanup *old_chain;
13972       char *addr_string;
13973
13974       expanded.nelts = 1;
13975       expanded.sals = &lsal->sals.sals[i];
13976
13977       addr_string = xstrdup (canonical->addr_string);
13978       old_chain = make_cleanup (xfree, addr_string);
13979
13980       tp = XCNEW (struct tracepoint);
13981       init_breakpoint_sal (&tp->base, gdbarch, expanded,
13982                            addr_string, NULL,
13983                            cond_string, extra_string,
13984                            type_wanted, disposition,
13985                            thread, task, ignore_count, ops,
13986                            from_tty, enabled, internal, flags,
13987                            canonical->special_display);
13988       /* Given that its possible to have multiple markers with
13989          the same string id, if the user is creating a static
13990          tracepoint by marker id ("strace -m MARKER_ID"), then
13991          store the sals index, so that breakpoint_re_set can
13992          try to match up which of the newly found markers
13993          corresponds to this one  */
13994       tp->static_trace_marker_id_idx = i;
13995
13996       install_breakpoint (internal, &tp->base, 0);
13997
13998       discard_cleanups (old_chain);
13999     }
14000 }
14001
14002 static void
14003 strace_marker_decode_linespec (struct breakpoint *b, char **s,
14004                                struct symtabs_and_lines *sals)
14005 {
14006   struct tracepoint *tp = (struct tracepoint *) b;
14007
14008   *sals = decode_static_tracepoint_spec (s);
14009   if (sals->nelts > tp->static_trace_marker_id_idx)
14010     {
14011       sals->sals[0] = sals->sals[tp->static_trace_marker_id_idx];
14012       sals->nelts = 1;
14013     }
14014   else
14015     error (_("marker %s not found"), tp->static_trace_marker_id);
14016 }
14017
14018 static struct breakpoint_ops strace_marker_breakpoint_ops;
14019
14020 static int
14021 strace_marker_p (struct breakpoint *b)
14022 {
14023   return b->ops == &strace_marker_breakpoint_ops;
14024 }
14025
14026 /* Delete a breakpoint and clean up all traces of it in the data
14027    structures.  */
14028
14029 void
14030 delete_breakpoint (struct breakpoint *bpt)
14031 {
14032   struct breakpoint *b;
14033
14034   gdb_assert (bpt != NULL);
14035
14036   /* Has this bp already been deleted?  This can happen because
14037      multiple lists can hold pointers to bp's.  bpstat lists are
14038      especial culprits.
14039
14040      One example of this happening is a watchpoint's scope bp.  When
14041      the scope bp triggers, we notice that the watchpoint is out of
14042      scope, and delete it.  We also delete its scope bp.  But the
14043      scope bp is marked "auto-deleting", and is already on a bpstat.
14044      That bpstat is then checked for auto-deleting bp's, which are
14045      deleted.
14046
14047      A real solution to this problem might involve reference counts in
14048      bp's, and/or giving them pointers back to their referencing
14049      bpstat's, and teaching delete_breakpoint to only free a bp's
14050      storage when no more references were extent.  A cheaper bandaid
14051      was chosen.  */
14052   if (bpt->type == bp_none)
14053     return;
14054
14055   /* At least avoid this stale reference until the reference counting
14056      of breakpoints gets resolved.  */
14057   if (bpt->related_breakpoint != bpt)
14058     {
14059       struct breakpoint *related;
14060       struct watchpoint *w;
14061
14062       if (bpt->type == bp_watchpoint_scope)
14063         w = (struct watchpoint *) bpt->related_breakpoint;
14064       else if (bpt->related_breakpoint->type == bp_watchpoint_scope)
14065         w = (struct watchpoint *) bpt;
14066       else
14067         w = NULL;
14068       if (w != NULL)
14069         watchpoint_del_at_next_stop (w);
14070
14071       /* Unlink bpt from the bpt->related_breakpoint ring.  */
14072       for (related = bpt; related->related_breakpoint != bpt;
14073            related = related->related_breakpoint);
14074       related->related_breakpoint = bpt->related_breakpoint;
14075       bpt->related_breakpoint = bpt;
14076     }
14077
14078   /* watch_command_1 creates a watchpoint but only sets its number if
14079      update_watchpoint succeeds in creating its bp_locations.  If there's
14080      a problem in that process, we'll be asked to delete the half-created
14081      watchpoint.  In that case, don't announce the deletion.  */
14082   if (bpt->number)
14083     observer_notify_breakpoint_deleted (bpt);
14084
14085   if (breakpoint_chain == bpt)
14086     breakpoint_chain = bpt->next;
14087
14088   ALL_BREAKPOINTS (b)
14089     if (b->next == bpt)
14090     {
14091       b->next = bpt->next;
14092       break;
14093     }
14094
14095   /* Be sure no bpstat's are pointing at the breakpoint after it's
14096      been freed.  */
14097   /* FIXME, how can we find all bpstat's?  We just check stop_bpstat
14098      in all threads for now.  Note that we cannot just remove bpstats
14099      pointing at bpt from the stop_bpstat list entirely, as breakpoint
14100      commands are associated with the bpstat; if we remove it here,
14101      then the later call to bpstat_do_actions (&stop_bpstat); in
14102      event-top.c won't do anything, and temporary breakpoints with
14103      commands won't work.  */
14104
14105   iterate_over_threads (bpstat_remove_breakpoint_callback, bpt);
14106
14107   /* Now that breakpoint is removed from breakpoint list, update the
14108      global location list.  This will remove locations that used to
14109      belong to this breakpoint.  Do this before freeing the breakpoint
14110      itself, since remove_breakpoint looks at location's owner.  It
14111      might be better design to have location completely
14112      self-contained, but it's not the case now.  */
14113   update_global_location_list (UGLL_DONT_INSERT);
14114
14115   bpt->ops->dtor (bpt);
14116   /* On the chance that someone will soon try again to delete this
14117      same bp, we mark it as deleted before freeing its storage.  */
14118   bpt->type = bp_none;
14119   xfree (bpt);
14120 }
14121
14122 static void
14123 do_delete_breakpoint_cleanup (void *b)
14124 {
14125   delete_breakpoint (b);
14126 }
14127
14128 struct cleanup *
14129 make_cleanup_delete_breakpoint (struct breakpoint *b)
14130 {
14131   return make_cleanup (do_delete_breakpoint_cleanup, b);
14132 }
14133
14134 /* Iterator function to call a user-provided callback function once
14135    for each of B and its related breakpoints.  */
14136
14137 static void
14138 iterate_over_related_breakpoints (struct breakpoint *b,
14139                                   void (*function) (struct breakpoint *,
14140                                                     void *),
14141                                   void *data)
14142 {
14143   struct breakpoint *related;
14144
14145   related = b;
14146   do
14147     {
14148       struct breakpoint *next;
14149
14150       /* FUNCTION may delete RELATED.  */
14151       next = related->related_breakpoint;
14152
14153       if (next == related)
14154         {
14155           /* RELATED is the last ring entry.  */
14156           function (related, data);
14157
14158           /* FUNCTION may have deleted it, so we'd never reach back to
14159              B.  There's nothing left to do anyway, so just break
14160              out.  */
14161           break;
14162         }
14163       else
14164         function (related, data);
14165
14166       related = next;
14167     }
14168   while (related != b);
14169 }
14170
14171 static void
14172 do_delete_breakpoint (struct breakpoint *b, void *ignore)
14173 {
14174   delete_breakpoint (b);
14175 }
14176
14177 /* A callback for map_breakpoint_numbers that calls
14178    delete_breakpoint.  */
14179
14180 static void
14181 do_map_delete_breakpoint (struct breakpoint *b, void *ignore)
14182 {
14183   iterate_over_related_breakpoints (b, do_delete_breakpoint, NULL);
14184 }
14185
14186 void
14187 delete_command (char *arg, int from_tty)
14188 {
14189   struct breakpoint *b, *b_tmp;
14190
14191   dont_repeat ();
14192
14193   if (arg == 0)
14194     {
14195       int breaks_to_delete = 0;
14196
14197       /* Delete all breakpoints if no argument.  Do not delete
14198          internal breakpoints, these have to be deleted with an
14199          explicit breakpoint number argument.  */
14200       ALL_BREAKPOINTS (b)
14201         if (user_breakpoint_p (b))
14202           {
14203             breaks_to_delete = 1;
14204             break;
14205           }
14206
14207       /* Ask user only if there are some breakpoints to delete.  */
14208       if (!from_tty
14209           || (breaks_to_delete && query (_("Delete all breakpoints? "))))
14210         {
14211           ALL_BREAKPOINTS_SAFE (b, b_tmp)
14212             if (user_breakpoint_p (b))
14213               delete_breakpoint (b);
14214         }
14215     }
14216   else
14217     map_breakpoint_numbers (arg, do_map_delete_breakpoint, NULL);
14218 }
14219
14220 static int
14221 all_locations_are_pending (struct bp_location *loc)
14222 {
14223   for (; loc; loc = loc->next)
14224     if (!loc->shlib_disabled
14225         && !loc->pspace->executing_startup)
14226       return 0;
14227   return 1;
14228 }
14229
14230 /* Subroutine of update_breakpoint_locations to simplify it.
14231    Return non-zero if multiple fns in list LOC have the same name.
14232    Null names are ignored.  */
14233
14234 static int
14235 ambiguous_names_p (struct bp_location *loc)
14236 {
14237   struct bp_location *l;
14238   htab_t htab = htab_create_alloc (13, htab_hash_string,
14239                                    (int (*) (const void *, 
14240                                              const void *)) streq,
14241                                    NULL, xcalloc, xfree);
14242
14243   for (l = loc; l != NULL; l = l->next)
14244     {
14245       const char **slot;
14246       const char *name = l->function_name;
14247
14248       /* Allow for some names to be NULL, ignore them.  */
14249       if (name == NULL)
14250         continue;
14251
14252       slot = (const char **) htab_find_slot (htab, (const void *) name,
14253                                              INSERT);
14254       /* NOTE: We can assume slot != NULL here because xcalloc never
14255          returns NULL.  */
14256       if (*slot != NULL)
14257         {
14258           htab_delete (htab);
14259           return 1;
14260         }
14261       *slot = name;
14262     }
14263
14264   htab_delete (htab);
14265   return 0;
14266 }
14267
14268 /* When symbols change, it probably means the sources changed as well,
14269    and it might mean the static tracepoint markers are no longer at
14270    the same address or line numbers they used to be at last we
14271    checked.  Losing your static tracepoints whenever you rebuild is
14272    undesirable.  This function tries to resync/rematch gdb static
14273    tracepoints with the markers on the target, for static tracepoints
14274    that have not been set by marker id.  Static tracepoint that have
14275    been set by marker id are reset by marker id in breakpoint_re_set.
14276    The heuristic is:
14277
14278    1) For a tracepoint set at a specific address, look for a marker at
14279    the old PC.  If one is found there, assume to be the same marker.
14280    If the name / string id of the marker found is different from the
14281    previous known name, assume that means the user renamed the marker
14282    in the sources, and output a warning.
14283
14284    2) For a tracepoint set at a given line number, look for a marker
14285    at the new address of the old line number.  If one is found there,
14286    assume to be the same marker.  If the name / string id of the
14287    marker found is different from the previous known name, assume that
14288    means the user renamed the marker in the sources, and output a
14289    warning.
14290
14291    3) If a marker is no longer found at the same address or line, it
14292    may mean the marker no longer exists.  But it may also just mean
14293    the code changed a bit.  Maybe the user added a few lines of code
14294    that made the marker move up or down (in line number terms).  Ask
14295    the target for info about the marker with the string id as we knew
14296    it.  If found, update line number and address in the matching
14297    static tracepoint.  This will get confused if there's more than one
14298    marker with the same ID (possible in UST, although unadvised
14299    precisely because it confuses tools).  */
14300
14301 static struct symtab_and_line
14302 update_static_tracepoint (struct breakpoint *b, struct symtab_and_line sal)
14303 {
14304   struct tracepoint *tp = (struct tracepoint *) b;
14305   struct static_tracepoint_marker marker;
14306   CORE_ADDR pc;
14307
14308   pc = sal.pc;
14309   if (sal.line)
14310     find_line_pc (sal.symtab, sal.line, &pc);
14311
14312   if (target_static_tracepoint_marker_at (pc, &marker))
14313     {
14314       if (strcmp (tp->static_trace_marker_id, marker.str_id) != 0)
14315         warning (_("static tracepoint %d changed probed marker from %s to %s"),
14316                  b->number,
14317                  tp->static_trace_marker_id, marker.str_id);
14318
14319       xfree (tp->static_trace_marker_id);
14320       tp->static_trace_marker_id = xstrdup (marker.str_id);
14321       release_static_tracepoint_marker (&marker);
14322
14323       return sal;
14324     }
14325
14326   /* Old marker wasn't found on target at lineno.  Try looking it up
14327      by string ID.  */
14328   if (!sal.explicit_pc
14329       && sal.line != 0
14330       && sal.symtab != NULL
14331       && tp->static_trace_marker_id != NULL)
14332     {
14333       VEC(static_tracepoint_marker_p) *markers;
14334
14335       markers
14336         = target_static_tracepoint_markers_by_strid (tp->static_trace_marker_id);
14337
14338       if (!VEC_empty(static_tracepoint_marker_p, markers))
14339         {
14340           struct symtab_and_line sal2;
14341           struct symbol *sym;
14342           struct static_tracepoint_marker *tpmarker;
14343           struct ui_out *uiout = current_uiout;
14344
14345           tpmarker = VEC_index (static_tracepoint_marker_p, markers, 0);
14346
14347           xfree (tp->static_trace_marker_id);
14348           tp->static_trace_marker_id = xstrdup (tpmarker->str_id);
14349
14350           warning (_("marker for static tracepoint %d (%s) not "
14351                      "found at previous line number"),
14352                    b->number, tp->static_trace_marker_id);
14353
14354           init_sal (&sal2);
14355
14356           sal2.pc = tpmarker->address;
14357
14358           sal2 = find_pc_line (tpmarker->address, 0);
14359           sym = find_pc_sect_function (tpmarker->address, NULL);
14360           ui_out_text (uiout, "Now in ");
14361           if (sym)
14362             {
14363               ui_out_field_string (uiout, "func",
14364                                    SYMBOL_PRINT_NAME (sym));
14365               ui_out_text (uiout, " at ");
14366             }
14367           ui_out_field_string (uiout, "file",
14368                                symtab_to_filename_for_display (sal2.symtab));
14369           ui_out_text (uiout, ":");
14370
14371           if (ui_out_is_mi_like_p (uiout))
14372             {
14373               const char *fullname = symtab_to_fullname (sal2.symtab);
14374
14375               ui_out_field_string (uiout, "fullname", fullname);
14376             }
14377
14378           ui_out_field_int (uiout, "line", sal2.line);
14379           ui_out_text (uiout, "\n");
14380
14381           b->loc->line_number = sal2.line;
14382           b->loc->symtab = sym != NULL ? sal2.symtab : NULL;
14383
14384           xfree (b->addr_string);
14385           b->addr_string = xstrprintf ("%s:%d",
14386                                    symtab_to_filename_for_display (sal2.symtab),
14387                                        b->loc->line_number);
14388
14389           /* Might be nice to check if function changed, and warn if
14390              so.  */
14391
14392           release_static_tracepoint_marker (tpmarker);
14393         }
14394     }
14395   return sal;
14396 }
14397
14398 /* Returns 1 iff locations A and B are sufficiently same that
14399    we don't need to report breakpoint as changed.  */
14400
14401 static int
14402 locations_are_equal (struct bp_location *a, struct bp_location *b)
14403 {
14404   while (a && b)
14405     {
14406       if (a->address != b->address)
14407         return 0;
14408
14409       if (a->shlib_disabled != b->shlib_disabled)
14410         return 0;
14411
14412       if (a->enabled != b->enabled)
14413         return 0;
14414
14415       a = a->next;
14416       b = b->next;
14417     }
14418
14419   if ((a == NULL) != (b == NULL))
14420     return 0;
14421
14422   return 1;
14423 }
14424
14425 /* Create new breakpoint locations for B (a hardware or software breakpoint)
14426    based on SALS and SALS_END.  If SALS_END.NELTS is not zero, then B is
14427    a ranged breakpoint.  */
14428
14429 void
14430 update_breakpoint_locations (struct breakpoint *b,
14431                              struct symtabs_and_lines sals,
14432                              struct symtabs_and_lines sals_end)
14433 {
14434   int i;
14435   struct bp_location *existing_locations = b->loc;
14436
14437   if (sals_end.nelts != 0 && (sals.nelts != 1 || sals_end.nelts != 1))
14438     {
14439       /* Ranged breakpoints have only one start location and one end
14440          location.  */
14441       b->enable_state = bp_disabled;
14442       update_global_location_list (UGLL_MAY_INSERT);
14443       printf_unfiltered (_("Could not reset ranged breakpoint %d: "
14444                            "multiple locations found\n"),
14445                          b->number);
14446       return;
14447     }
14448
14449   /* If there's no new locations, and all existing locations are
14450      pending, don't do anything.  This optimizes the common case where
14451      all locations are in the same shared library, that was unloaded.
14452      We'd like to retain the location, so that when the library is
14453      loaded again, we don't loose the enabled/disabled status of the
14454      individual locations.  */
14455   if (all_locations_are_pending (existing_locations) && sals.nelts == 0)
14456     return;
14457
14458   b->loc = NULL;
14459
14460   for (i = 0; i < sals.nelts; ++i)
14461     {
14462       struct bp_location *new_loc;
14463
14464       switch_to_program_space_and_thread (sals.sals[i].pspace);
14465
14466       new_loc = add_location_to_breakpoint (b, &(sals.sals[i]));
14467
14468       /* Reparse conditions, they might contain references to the
14469          old symtab.  */
14470       if (b->cond_string != NULL)
14471         {
14472           const char *s;
14473           volatile struct gdb_exception e;
14474
14475           s = b->cond_string;
14476           TRY_CATCH (e, RETURN_MASK_ERROR)
14477             {
14478               new_loc->cond = parse_exp_1 (&s, sals.sals[i].pc,
14479                                            block_for_pc (sals.sals[i].pc), 
14480                                            0);
14481             }
14482           if (e.reason < 0)
14483             {
14484               warning (_("failed to reevaluate condition "
14485                          "for breakpoint %d: %s"), 
14486                        b->number, e.message);
14487               new_loc->enabled = 0;
14488             }
14489         }
14490
14491       if (sals_end.nelts)
14492         {
14493           CORE_ADDR end = find_breakpoint_range_end (sals_end.sals[0]);
14494
14495           new_loc->length = end - sals.sals[0].pc + 1;
14496         }
14497     }
14498
14499   /* Update locations of permanent breakpoints.  */
14500   if (b->enable_state == bp_permanent)
14501     make_breakpoint_permanent (b);
14502
14503   /* If possible, carry over 'disable' status from existing
14504      breakpoints.  */
14505   {
14506     struct bp_location *e = existing_locations;
14507     /* If there are multiple breakpoints with the same function name,
14508        e.g. for inline functions, comparing function names won't work.
14509        Instead compare pc addresses; this is just a heuristic as things
14510        may have moved, but in practice it gives the correct answer
14511        often enough until a better solution is found.  */
14512     int have_ambiguous_names = ambiguous_names_p (b->loc);
14513
14514     for (; e; e = e->next)
14515       {
14516         if (!e->enabled && e->function_name)
14517           {
14518             struct bp_location *l = b->loc;
14519             if (have_ambiguous_names)
14520               {
14521                 for (; l; l = l->next)
14522                   if (breakpoint_locations_match (e, l))
14523                     {
14524                       l->enabled = 0;
14525                       break;
14526                     }
14527               }
14528             else
14529               {
14530                 for (; l; l = l->next)
14531                   if (l->function_name
14532                       && strcmp (e->function_name, l->function_name) == 0)
14533                     {
14534                       l->enabled = 0;
14535                       break;
14536                     }
14537               }
14538           }
14539       }
14540   }
14541
14542   if (!locations_are_equal (existing_locations, b->loc))
14543     observer_notify_breakpoint_modified (b);
14544
14545   update_global_location_list (UGLL_MAY_INSERT);
14546 }
14547
14548 /* Find the SaL locations corresponding to the given ADDR_STRING.
14549    On return, FOUND will be 1 if any SaL was found, zero otherwise.  */
14550
14551 static struct symtabs_and_lines
14552 addr_string_to_sals (struct breakpoint *b, char *addr_string, int *found)
14553 {
14554   char *s;
14555   struct symtabs_and_lines sals = {0};
14556   volatile struct gdb_exception e;
14557
14558   gdb_assert (b->ops != NULL);
14559   s = addr_string;
14560
14561   TRY_CATCH (e, RETURN_MASK_ERROR)
14562     {
14563       b->ops->decode_linespec (b, &s, &sals);
14564     }
14565   if (e.reason < 0)
14566     {
14567       int not_found_and_ok = 0;
14568       /* For pending breakpoints, it's expected that parsing will
14569          fail until the right shared library is loaded.  User has
14570          already told to create pending breakpoints and don't need
14571          extra messages.  If breakpoint is in bp_shlib_disabled
14572          state, then user already saw the message about that
14573          breakpoint being disabled, and don't want to see more
14574          errors.  */
14575       if (e.error == NOT_FOUND_ERROR
14576           && (b->condition_not_parsed 
14577               || (b->loc && b->loc->shlib_disabled)
14578               || (b->loc && b->loc->pspace->executing_startup)
14579               || b->enable_state == bp_disabled))
14580         not_found_and_ok = 1;
14581
14582       if (!not_found_and_ok)
14583         {
14584           /* We surely don't want to warn about the same breakpoint
14585              10 times.  One solution, implemented here, is disable
14586              the breakpoint on error.  Another solution would be to
14587              have separate 'warning emitted' flag.  Since this
14588              happens only when a binary has changed, I don't know
14589              which approach is better.  */
14590           b->enable_state = bp_disabled;
14591           throw_exception (e);
14592         }
14593     }
14594
14595   if (e.reason == 0 || e.error != NOT_FOUND_ERROR)
14596     {
14597       int i;
14598
14599       for (i = 0; i < sals.nelts; ++i)
14600         resolve_sal_pc (&sals.sals[i]);
14601       if (b->condition_not_parsed && s && s[0])
14602         {
14603           char *cond_string, *extra_string;
14604           int thread, task;
14605
14606           find_condition_and_thread (s, sals.sals[0].pc,
14607                                      &cond_string, &thread, &task,
14608                                      &extra_string);
14609           if (cond_string)
14610             b->cond_string = cond_string;
14611           b->thread = thread;
14612           b->task = task;
14613           if (extra_string)
14614             b->extra_string = extra_string;
14615           b->condition_not_parsed = 0;
14616         }
14617
14618       if (b->type == bp_static_tracepoint && !strace_marker_p (b))
14619         sals.sals[0] = update_static_tracepoint (b, sals.sals[0]);
14620
14621       *found = 1;
14622     }
14623   else
14624     *found = 0;
14625
14626   return sals;
14627 }
14628
14629 /* The default re_set method, for typical hardware or software
14630    breakpoints.  Reevaluate the breakpoint and recreate its
14631    locations.  */
14632
14633 static void
14634 breakpoint_re_set_default (struct breakpoint *b)
14635 {
14636   int found;
14637   struct symtabs_and_lines sals, sals_end;
14638   struct symtabs_and_lines expanded = {0};
14639   struct symtabs_and_lines expanded_end = {0};
14640
14641   sals = addr_string_to_sals (b, b->addr_string, &found);
14642   if (found)
14643     {
14644       make_cleanup (xfree, sals.sals);
14645       expanded = sals;
14646     }
14647
14648   if (b->addr_string_range_end)
14649     {
14650       sals_end = addr_string_to_sals (b, b->addr_string_range_end, &found);
14651       if (found)
14652         {
14653           make_cleanup (xfree, sals_end.sals);
14654           expanded_end = sals_end;
14655         }
14656     }
14657
14658   update_breakpoint_locations (b, expanded, expanded_end);
14659 }
14660
14661 /* Default method for creating SALs from an address string.  It basically
14662    calls parse_breakpoint_sals.  Return 1 for success, zero for failure.  */
14663
14664 static void
14665 create_sals_from_address_default (char **arg,
14666                                   struct linespec_result *canonical,
14667                                   enum bptype type_wanted,
14668                                   char *addr_start, char **copy_arg)
14669 {
14670   parse_breakpoint_sals (arg, canonical);
14671 }
14672
14673 /* Call create_breakpoints_sal for the given arguments.  This is the default
14674    function for the `create_breakpoints_sal' method of
14675    breakpoint_ops.  */
14676
14677 static void
14678 create_breakpoints_sal_default (struct gdbarch *gdbarch,
14679                                 struct linespec_result *canonical,
14680                                 char *cond_string,
14681                                 char *extra_string,
14682                                 enum bptype type_wanted,
14683                                 enum bpdisp disposition,
14684                                 int thread,
14685                                 int task, int ignore_count,
14686                                 const struct breakpoint_ops *ops,
14687                                 int from_tty, int enabled,
14688                                 int internal, unsigned flags)
14689 {
14690   create_breakpoints_sal (gdbarch, canonical, cond_string,
14691                           extra_string,
14692                           type_wanted, disposition,
14693                           thread, task, ignore_count, ops, from_tty,
14694                           enabled, internal, flags);
14695 }
14696
14697 /* Decode the line represented by S by calling decode_line_full.  This is the
14698    default function for the `decode_linespec' method of breakpoint_ops.  */
14699
14700 static void
14701 decode_linespec_default (struct breakpoint *b, char **s,
14702                          struct symtabs_and_lines *sals)
14703 {
14704   struct linespec_result canonical;
14705
14706   init_linespec_result (&canonical);
14707   decode_line_full (s, DECODE_LINE_FUNFIRSTLINE,
14708                     (struct symtab *) NULL, 0,
14709                     &canonical, multiple_symbols_all,
14710                     b->filter);
14711
14712   /* We should get 0 or 1 resulting SALs.  */
14713   gdb_assert (VEC_length (linespec_sals, canonical.sals) < 2);
14714
14715   if (VEC_length (linespec_sals, canonical.sals) > 0)
14716     {
14717       struct linespec_sals *lsal;
14718
14719       lsal = VEC_index (linespec_sals, canonical.sals, 0);
14720       *sals = lsal->sals;
14721       /* Arrange it so the destructor does not free the
14722          contents.  */
14723       lsal->sals.sals = NULL;
14724     }
14725
14726   destroy_linespec_result (&canonical);
14727 }
14728
14729 /* Prepare the global context for a re-set of breakpoint B.  */
14730
14731 static struct cleanup *
14732 prepare_re_set_context (struct breakpoint *b)
14733 {
14734   struct cleanup *cleanups;
14735
14736   input_radix = b->input_radix;
14737   cleanups = save_current_space_and_thread ();
14738   if (b->pspace != NULL)
14739     switch_to_program_space_and_thread (b->pspace);
14740   set_language (b->language);
14741
14742   return cleanups;
14743 }
14744
14745 /* Reset a breakpoint given it's struct breakpoint * BINT.
14746    The value we return ends up being the return value from catch_errors.
14747    Unused in this case.  */
14748
14749 static int
14750 breakpoint_re_set_one (void *bint)
14751 {
14752   /* Get past catch_errs.  */
14753   struct breakpoint *b = (struct breakpoint *) bint;
14754   struct cleanup *cleanups;
14755
14756   cleanups = prepare_re_set_context (b);
14757   b->ops->re_set (b);
14758   do_cleanups (cleanups);
14759   return 0;
14760 }
14761
14762 /* Re-set all breakpoints after symbols have been re-loaded.  */
14763 void
14764 breakpoint_re_set (void)
14765 {
14766   struct breakpoint *b, *b_tmp;
14767   enum language save_language;
14768   int save_input_radix;
14769   struct cleanup *old_chain;
14770
14771   save_language = current_language->la_language;
14772   save_input_radix = input_radix;
14773   old_chain = save_current_program_space ();
14774
14775   ALL_BREAKPOINTS_SAFE (b, b_tmp)
14776   {
14777     /* Format possible error msg.  */
14778     char *message = xstrprintf ("Error in re-setting breakpoint %d: ",
14779                                 b->number);
14780     struct cleanup *cleanups = make_cleanup (xfree, message);
14781     catch_errors (breakpoint_re_set_one, b, message, RETURN_MASK_ALL);
14782     do_cleanups (cleanups);
14783   }
14784   set_language (save_language);
14785   input_radix = save_input_radix;
14786
14787   jit_breakpoint_re_set ();
14788
14789   do_cleanups (old_chain);
14790
14791   create_overlay_event_breakpoint ();
14792   create_longjmp_master_breakpoint ();
14793   create_std_terminate_master_breakpoint ();
14794   create_exception_master_breakpoint ();
14795 }
14796 \f
14797 /* Reset the thread number of this breakpoint:
14798
14799    - If the breakpoint is for all threads, leave it as-is.
14800    - Else, reset it to the current thread for inferior_ptid.  */
14801 void
14802 breakpoint_re_set_thread (struct breakpoint *b)
14803 {
14804   if (b->thread != -1)
14805     {
14806       if (in_thread_list (inferior_ptid))
14807         b->thread = pid_to_thread_id (inferior_ptid);
14808
14809       /* We're being called after following a fork.  The new fork is
14810          selected as current, and unless this was a vfork will have a
14811          different program space from the original thread.  Reset that
14812          as well.  */
14813       b->loc->pspace = current_program_space;
14814     }
14815 }
14816
14817 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
14818    If from_tty is nonzero, it prints a message to that effect,
14819    which ends with a period (no newline).  */
14820
14821 void
14822 set_ignore_count (int bptnum, int count, int from_tty)
14823 {
14824   struct breakpoint *b;
14825
14826   if (count < 0)
14827     count = 0;
14828
14829   ALL_BREAKPOINTS (b)
14830     if (b->number == bptnum)
14831     {
14832       if (is_tracepoint (b))
14833         {
14834           if (from_tty && count != 0)
14835             printf_filtered (_("Ignore count ignored for tracepoint %d."),
14836                              bptnum);
14837           return;
14838         }
14839       
14840       b->ignore_count = count;
14841       if (from_tty)
14842         {
14843           if (count == 0)
14844             printf_filtered (_("Will stop next time "
14845                                "breakpoint %d is reached."),
14846                              bptnum);
14847           else if (count == 1)
14848             printf_filtered (_("Will ignore next crossing of breakpoint %d."),
14849                              bptnum);
14850           else
14851             printf_filtered (_("Will ignore next %d "
14852                                "crossings of breakpoint %d."),
14853                              count, bptnum);
14854         }
14855       observer_notify_breakpoint_modified (b);
14856       return;
14857     }
14858
14859   error (_("No breakpoint number %d."), bptnum);
14860 }
14861
14862 /* Command to set ignore-count of breakpoint N to COUNT.  */
14863
14864 static void
14865 ignore_command (char *args, int from_tty)
14866 {
14867   char *p = args;
14868   int num;
14869
14870   if (p == 0)
14871     error_no_arg (_("a breakpoint number"));
14872
14873   num = get_number (&p);
14874   if (num == 0)
14875     error (_("bad breakpoint number: '%s'"), args);
14876   if (*p == 0)
14877     error (_("Second argument (specified ignore-count) is missing."));
14878
14879   set_ignore_count (num,
14880                     longest_to_int (value_as_long (parse_and_eval (p))),
14881                     from_tty);
14882   if (from_tty)
14883     printf_filtered ("\n");
14884 }
14885 \f
14886 /* Call FUNCTION on each of the breakpoints
14887    whose numbers are given in ARGS.  */
14888
14889 static void
14890 map_breakpoint_numbers (char *args, void (*function) (struct breakpoint *,
14891                                                       void *),
14892                         void *data)
14893 {
14894   int num;
14895   struct breakpoint *b, *tmp;
14896   int match;
14897   struct get_number_or_range_state state;
14898
14899   if (args == 0)
14900     error_no_arg (_("one or more breakpoint numbers"));
14901
14902   init_number_or_range (&state, args);
14903
14904   while (!state.finished)
14905     {
14906       const char *p = state.string;
14907
14908       match = 0;
14909
14910       num = get_number_or_range (&state);
14911       if (num == 0)
14912         {
14913           warning (_("bad breakpoint number at or near '%s'"), p);
14914         }
14915       else
14916         {
14917           ALL_BREAKPOINTS_SAFE (b, tmp)
14918             if (b->number == num)
14919               {
14920                 match = 1;
14921                 function (b, data);
14922                 break;
14923               }
14924           if (match == 0)
14925             printf_unfiltered (_("No breakpoint number %d.\n"), num);
14926         }
14927     }
14928 }
14929
14930 static struct bp_location *
14931 find_location_by_number (char *number)
14932 {
14933   char *dot = strchr (number, '.');
14934   char *p1;
14935   int bp_num;
14936   int loc_num;
14937   struct breakpoint *b;
14938   struct bp_location *loc;  
14939
14940   *dot = '\0';
14941
14942   p1 = number;
14943   bp_num = get_number (&p1);
14944   if (bp_num == 0)
14945     error (_("Bad breakpoint number '%s'"), number);
14946
14947   ALL_BREAKPOINTS (b)
14948     if (b->number == bp_num)
14949       {
14950         break;
14951       }
14952
14953   if (!b || b->number != bp_num)
14954     error (_("Bad breakpoint number '%s'"), number);
14955   
14956   p1 = dot+1;
14957   loc_num = get_number (&p1);
14958   if (loc_num == 0)
14959     error (_("Bad breakpoint location number '%s'"), number);
14960
14961   --loc_num;
14962   loc = b->loc;
14963   for (;loc_num && loc; --loc_num, loc = loc->next)
14964     ;
14965   if (!loc)
14966     error (_("Bad breakpoint location number '%s'"), dot+1);
14967     
14968   return loc;  
14969 }
14970
14971
14972 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
14973    If from_tty is nonzero, it prints a message to that effect,
14974    which ends with a period (no newline).  */
14975
14976 void
14977 disable_breakpoint (struct breakpoint *bpt)
14978 {
14979   /* Never disable a watchpoint scope breakpoint; we want to
14980      hit them when we leave scope so we can delete both the
14981      watchpoint and its scope breakpoint at that time.  */
14982   if (bpt->type == bp_watchpoint_scope)
14983     return;
14984
14985   /* You can't disable permanent breakpoints.  */
14986   if (bpt->enable_state == bp_permanent)
14987     return;
14988
14989   bpt->enable_state = bp_disabled;
14990
14991   /* Mark breakpoint locations modified.  */
14992   mark_breakpoint_modified (bpt);
14993
14994   if (target_supports_enable_disable_tracepoint ()
14995       && current_trace_status ()->running && is_tracepoint (bpt))
14996     {
14997       struct bp_location *location;
14998      
14999       for (location = bpt->loc; location; location = location->next)
15000         target_disable_tracepoint (location);
15001     }
15002
15003   update_global_location_list (UGLL_DONT_INSERT);
15004
15005   observer_notify_breakpoint_modified (bpt);
15006 }
15007
15008 /* A callback for iterate_over_related_breakpoints.  */
15009
15010 static void
15011 do_disable_breakpoint (struct breakpoint *b, void *ignore)
15012 {
15013   disable_breakpoint (b);
15014 }
15015
15016 /* A callback for map_breakpoint_numbers that calls
15017    disable_breakpoint.  */
15018
15019 static void
15020 do_map_disable_breakpoint (struct breakpoint *b, void *ignore)
15021 {
15022   iterate_over_related_breakpoints (b, do_disable_breakpoint, NULL);
15023 }
15024
15025 static void
15026 disable_command (char *args, int from_tty)
15027 {
15028   if (args == 0)
15029     {
15030       struct breakpoint *bpt;
15031
15032       ALL_BREAKPOINTS (bpt)
15033         if (user_breakpoint_p (bpt))
15034           disable_breakpoint (bpt);
15035     }
15036   else
15037     {
15038       char *num = extract_arg (&args);
15039
15040       while (num)
15041         {
15042           if (strchr (num, '.'))
15043             {
15044               struct bp_location *loc = find_location_by_number (num);
15045
15046               if (loc)
15047                 {
15048                   if (loc->enabled)
15049                     {
15050                       loc->enabled = 0;
15051                       mark_breakpoint_location_modified (loc);
15052                     }
15053                   if (target_supports_enable_disable_tracepoint ()
15054                       && current_trace_status ()->running && loc->owner
15055                       && is_tracepoint (loc->owner))
15056                     target_disable_tracepoint (loc);
15057                 }
15058               update_global_location_list (UGLL_DONT_INSERT);
15059             }
15060           else
15061             map_breakpoint_numbers (num, do_map_disable_breakpoint, NULL);
15062           num = extract_arg (&args);
15063         }
15064     }
15065 }
15066
15067 static void
15068 enable_breakpoint_disp (struct breakpoint *bpt, enum bpdisp disposition,
15069                         int count)
15070 {
15071   int target_resources_ok;
15072
15073   if (bpt->type == bp_hardware_breakpoint)
15074     {
15075       int i;
15076       i = hw_breakpoint_used_count ();
15077       target_resources_ok = 
15078         target_can_use_hardware_watchpoint (bp_hardware_breakpoint, 
15079                                             i + 1, 0);
15080       if (target_resources_ok == 0)
15081         error (_("No hardware breakpoint support in the target."));
15082       else if (target_resources_ok < 0)
15083         error (_("Hardware breakpoints used exceeds limit."));
15084     }
15085
15086   if (is_watchpoint (bpt))
15087     {
15088       /* Initialize it just to avoid a GCC false warning.  */
15089       enum enable_state orig_enable_state = 0;
15090       volatile struct gdb_exception e;
15091
15092       TRY_CATCH (e, RETURN_MASK_ALL)
15093         {
15094           struct watchpoint *w = (struct watchpoint *) bpt;
15095
15096           orig_enable_state = bpt->enable_state;
15097           bpt->enable_state = bp_enabled;
15098           update_watchpoint (w, 1 /* reparse */);
15099         }
15100       if (e.reason < 0)
15101         {
15102           bpt->enable_state = orig_enable_state;
15103           exception_fprintf (gdb_stderr, e, _("Cannot enable watchpoint %d: "),
15104                              bpt->number);
15105           return;
15106         }
15107     }
15108
15109   if (bpt->enable_state != bp_permanent)
15110     bpt->enable_state = bp_enabled;
15111
15112   bpt->enable_state = bp_enabled;
15113
15114   /* Mark breakpoint locations modified.  */
15115   mark_breakpoint_modified (bpt);
15116
15117   if (target_supports_enable_disable_tracepoint ()
15118       && current_trace_status ()->running && is_tracepoint (bpt))
15119     {
15120       struct bp_location *location;
15121
15122       for (location = bpt->loc; location; location = location->next)
15123         target_enable_tracepoint (location);
15124     }
15125
15126   bpt->disposition = disposition;
15127   bpt->enable_count = count;
15128   update_global_location_list (UGLL_MAY_INSERT);
15129
15130   observer_notify_breakpoint_modified (bpt);
15131 }
15132
15133
15134 void
15135 enable_breakpoint (struct breakpoint *bpt)
15136 {
15137   enable_breakpoint_disp (bpt, bpt->disposition, 0);
15138 }
15139
15140 static void
15141 do_enable_breakpoint (struct breakpoint *bpt, void *arg)
15142 {
15143   enable_breakpoint (bpt);
15144 }
15145
15146 /* A callback for map_breakpoint_numbers that calls
15147    enable_breakpoint.  */
15148
15149 static void
15150 do_map_enable_breakpoint (struct breakpoint *b, void *ignore)
15151 {
15152   iterate_over_related_breakpoints (b, do_enable_breakpoint, NULL);
15153 }
15154
15155 /* The enable command enables the specified breakpoints (or all defined
15156    breakpoints) so they once again become (or continue to be) effective
15157    in stopping the inferior.  */
15158
15159 static void
15160 enable_command (char *args, int from_tty)
15161 {
15162   if (args == 0)
15163     {
15164       struct breakpoint *bpt;
15165
15166       ALL_BREAKPOINTS (bpt)
15167         if (user_breakpoint_p (bpt))
15168           enable_breakpoint (bpt);
15169     }
15170   else
15171     {
15172       char *num = extract_arg (&args);
15173
15174       while (num)
15175         {
15176           if (strchr (num, '.'))
15177             {
15178               struct bp_location *loc = find_location_by_number (num);
15179
15180               if (loc)
15181                 {
15182                   if (!loc->enabled)
15183                     {
15184                       loc->enabled = 1;
15185                       mark_breakpoint_location_modified (loc);
15186                     }
15187                   if (target_supports_enable_disable_tracepoint ()
15188                       && current_trace_status ()->running && loc->owner
15189                       && is_tracepoint (loc->owner))
15190                     target_enable_tracepoint (loc);
15191                 }
15192               update_global_location_list (UGLL_MAY_INSERT);
15193             }
15194           else
15195             map_breakpoint_numbers (num, do_map_enable_breakpoint, NULL);
15196           num = extract_arg (&args);
15197         }
15198     }
15199 }
15200
15201 /* This struct packages up disposition data for application to multiple
15202    breakpoints.  */
15203
15204 struct disp_data
15205 {
15206   enum bpdisp disp;
15207   int count;
15208 };
15209
15210 static void
15211 do_enable_breakpoint_disp (struct breakpoint *bpt, void *arg)
15212 {
15213   struct disp_data disp_data = *(struct disp_data *) arg;
15214
15215   enable_breakpoint_disp (bpt, disp_data.disp, disp_data.count);
15216 }
15217
15218 static void
15219 do_map_enable_once_breakpoint (struct breakpoint *bpt, void *ignore)
15220 {
15221   struct disp_data disp = { disp_disable, 1 };
15222
15223   iterate_over_related_breakpoints (bpt, do_enable_breakpoint_disp, &disp);
15224 }
15225
15226 static void
15227 enable_once_command (char *args, int from_tty)
15228 {
15229   map_breakpoint_numbers (args, do_map_enable_once_breakpoint, NULL);
15230 }
15231
15232 static void
15233 do_map_enable_count_breakpoint (struct breakpoint *bpt, void *countptr)
15234 {
15235   struct disp_data disp = { disp_disable, *(int *) countptr };
15236
15237   iterate_over_related_breakpoints (bpt, do_enable_breakpoint_disp, &disp);
15238 }
15239
15240 static void
15241 enable_count_command (char *args, int from_tty)
15242 {
15243   int count = get_number (&args);
15244
15245   map_breakpoint_numbers (args, do_map_enable_count_breakpoint, &count);
15246 }
15247
15248 static void
15249 do_map_enable_delete_breakpoint (struct breakpoint *bpt, void *ignore)
15250 {
15251   struct disp_data disp = { disp_del, 1 };
15252
15253   iterate_over_related_breakpoints (bpt, do_enable_breakpoint_disp, &disp);
15254 }
15255
15256 static void
15257 enable_delete_command (char *args, int from_tty)
15258 {
15259   map_breakpoint_numbers (args, do_map_enable_delete_breakpoint, NULL);
15260 }
15261 \f
15262 static void
15263 set_breakpoint_cmd (char *args, int from_tty)
15264 {
15265 }
15266
15267 static void
15268 show_breakpoint_cmd (char *args, int from_tty)
15269 {
15270 }
15271
15272 /* Invalidate last known value of any hardware watchpoint if
15273    the memory which that value represents has been written to by
15274    GDB itself.  */
15275
15276 static void
15277 invalidate_bp_value_on_memory_change (struct inferior *inferior,
15278                                       CORE_ADDR addr, ssize_t len,
15279                                       const bfd_byte *data)
15280 {
15281   struct breakpoint *bp;
15282
15283   ALL_BREAKPOINTS (bp)
15284     if (bp->enable_state == bp_enabled
15285         && bp->type == bp_hardware_watchpoint)
15286       {
15287         struct watchpoint *wp = (struct watchpoint *) bp;
15288
15289         if (wp->val_valid && wp->val)
15290           {
15291             struct bp_location *loc;
15292
15293             for (loc = bp->loc; loc != NULL; loc = loc->next)
15294               if (loc->loc_type == bp_loc_hardware_watchpoint
15295                   && loc->address + loc->length > addr
15296                   && addr + len > loc->address)
15297                 {
15298                   value_free (wp->val);
15299                   wp->val = NULL;
15300                   wp->val_valid = 0;
15301                 }
15302           }
15303       }
15304 }
15305
15306 /* Create and insert a breakpoint for software single step.  */
15307
15308 void
15309 insert_single_step_breakpoint (struct gdbarch *gdbarch,
15310                                struct address_space *aspace, 
15311                                CORE_ADDR next_pc)
15312 {
15313   struct thread_info *tp = inferior_thread ();
15314   struct symtab_and_line sal;
15315   CORE_ADDR pc = next_pc;
15316
15317   if (tp->control.single_step_breakpoints == NULL)
15318     {
15319       tp->control.single_step_breakpoints
15320         = new_single_step_breakpoint (tp->num, gdbarch);
15321     }
15322
15323   sal = find_pc_line (pc, 0);
15324   sal.pc = pc;
15325   sal.section = find_pc_overlay (pc);
15326   sal.explicit_pc = 1;
15327   add_location_to_breakpoint (tp->control.single_step_breakpoints, &sal);
15328
15329   update_global_location_list (UGLL_INSERT);
15330 }
15331
15332 /* See breakpoint.h.  */
15333
15334 int
15335 breakpoint_has_location_inserted_here (struct breakpoint *bp,
15336                                        struct address_space *aspace,
15337                                        CORE_ADDR pc)
15338 {
15339   struct bp_location *loc;
15340
15341   for (loc = bp->loc; loc != NULL; loc = loc->next)
15342     if (loc->inserted
15343         && breakpoint_location_address_match (loc, aspace, pc))
15344       return 1;
15345
15346   return 0;
15347 }
15348
15349 /* Check whether a software single-step breakpoint is inserted at
15350    PC.  */
15351
15352 int
15353 single_step_breakpoint_inserted_here_p (struct address_space *aspace,
15354                                         CORE_ADDR pc)
15355 {
15356   struct breakpoint *bpt;
15357
15358   ALL_BREAKPOINTS (bpt)
15359     {
15360       if (bpt->type == bp_single_step
15361           && breakpoint_has_location_inserted_here (bpt, aspace, pc))
15362         return 1;
15363     }
15364   return 0;
15365 }
15366
15367 /* Returns 0 if 'bp' is NOT a syscall catchpoint,
15368    non-zero otherwise.  */
15369 static int
15370 is_syscall_catchpoint_enabled (struct breakpoint *bp)
15371 {
15372   if (syscall_catchpoint_p (bp)
15373       && bp->enable_state != bp_disabled
15374       && bp->enable_state != bp_call_disabled)
15375     return 1;
15376   else
15377     return 0;
15378 }
15379
15380 int
15381 catch_syscall_enabled (void)
15382 {
15383   struct catch_syscall_inferior_data *inf_data
15384     = get_catch_syscall_inferior_data (current_inferior ());
15385
15386   return inf_data->total_syscalls_count != 0;
15387 }
15388
15389 int
15390 catching_syscall_number (int syscall_number)
15391 {
15392   struct breakpoint *bp;
15393
15394   ALL_BREAKPOINTS (bp)
15395     if (is_syscall_catchpoint_enabled (bp))
15396       {
15397         struct syscall_catchpoint *c = (struct syscall_catchpoint *) bp;
15398
15399         if (c->syscalls_to_be_caught)
15400           {
15401             int i, iter;
15402             for (i = 0;
15403                  VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
15404                  i++)
15405               if (syscall_number == iter)
15406                 return 1;
15407           }
15408         else
15409           return 1;
15410       }
15411
15412   return 0;
15413 }
15414
15415 /* Complete syscall names.  Used by "catch syscall".  */
15416 static VEC (char_ptr) *
15417 catch_syscall_completer (struct cmd_list_element *cmd,
15418                          const char *text, const char *word)
15419 {
15420   const char **list = get_syscall_names ();
15421   VEC (char_ptr) *retlist
15422     = (list == NULL) ? NULL : complete_on_enum (list, word, word);
15423
15424   xfree (list);
15425   return retlist;
15426 }
15427
15428 /* Tracepoint-specific operations.  */
15429
15430 /* Set tracepoint count to NUM.  */
15431 static void
15432 set_tracepoint_count (int num)
15433 {
15434   tracepoint_count = num;
15435   set_internalvar_integer (lookup_internalvar ("tpnum"), num);
15436 }
15437
15438 static void
15439 trace_command (char *arg, int from_tty)
15440 {
15441   struct breakpoint_ops *ops;
15442   const char *arg_cp = arg;
15443
15444   if (arg && probe_linespec_to_ops (&arg_cp))
15445     ops = &tracepoint_probe_breakpoint_ops;
15446   else
15447     ops = &tracepoint_breakpoint_ops;
15448
15449   create_breakpoint (get_current_arch (),
15450                      arg,
15451                      NULL, 0, NULL, 1 /* parse arg */,
15452                      0 /* tempflag */,
15453                      bp_tracepoint /* type_wanted */,
15454                      0 /* Ignore count */,
15455                      pending_break_support,
15456                      ops,
15457                      from_tty,
15458                      1 /* enabled */,
15459                      0 /* internal */, 0);
15460 }
15461
15462 static void
15463 ftrace_command (char *arg, int from_tty)
15464 {
15465   create_breakpoint (get_current_arch (),
15466                      arg,
15467                      NULL, 0, NULL, 1 /* parse arg */,
15468                      0 /* tempflag */,
15469                      bp_fast_tracepoint /* type_wanted */,
15470                      0 /* Ignore count */,
15471                      pending_break_support,
15472                      &tracepoint_breakpoint_ops,
15473                      from_tty,
15474                      1 /* enabled */,
15475                      0 /* internal */, 0);
15476 }
15477
15478 /* strace command implementation.  Creates a static tracepoint.  */
15479
15480 static void
15481 strace_command (char *arg, int from_tty)
15482 {
15483   struct breakpoint_ops *ops;
15484
15485   /* Decide if we are dealing with a static tracepoint marker (`-m'),
15486      or with a normal static tracepoint.  */
15487   if (arg && strncmp (arg, "-m", 2) == 0 && isspace (arg[2]))
15488     ops = &strace_marker_breakpoint_ops;
15489   else
15490     ops = &tracepoint_breakpoint_ops;
15491
15492   create_breakpoint (get_current_arch (),
15493                      arg,
15494                      NULL, 0, NULL, 1 /* parse arg */,
15495                      0 /* tempflag */,
15496                      bp_static_tracepoint /* type_wanted */,
15497                      0 /* Ignore count */,
15498                      pending_break_support,
15499                      ops,
15500                      from_tty,
15501                      1 /* enabled */,
15502                      0 /* internal */, 0);
15503 }
15504
15505 /* Set up a fake reader function that gets command lines from a linked
15506    list that was acquired during tracepoint uploading.  */
15507
15508 static struct uploaded_tp *this_utp;
15509 static int next_cmd;
15510
15511 static char *
15512 read_uploaded_action (void)
15513 {
15514   char *rslt;
15515
15516   VEC_iterate (char_ptr, this_utp->cmd_strings, next_cmd, rslt);
15517
15518   next_cmd++;
15519
15520   return rslt;
15521 }
15522
15523 /* Given information about a tracepoint as recorded on a target (which
15524    can be either a live system or a trace file), attempt to create an
15525    equivalent GDB tracepoint.  This is not a reliable process, since
15526    the target does not necessarily have all the information used when
15527    the tracepoint was originally defined.  */
15528   
15529 struct tracepoint *
15530 create_tracepoint_from_upload (struct uploaded_tp *utp)
15531 {
15532   char *addr_str, small_buf[100];
15533   struct tracepoint *tp;
15534
15535   if (utp->at_string)
15536     addr_str = utp->at_string;
15537   else
15538     {
15539       /* In the absence of a source location, fall back to raw
15540          address.  Since there is no way to confirm that the address
15541          means the same thing as when the trace was started, warn the
15542          user.  */
15543       warning (_("Uploaded tracepoint %d has no "
15544                  "source location, using raw address"),
15545                utp->number);
15546       xsnprintf (small_buf, sizeof (small_buf), "*%s", hex_string (utp->addr));
15547       addr_str = small_buf;
15548     }
15549
15550   /* There's not much we can do with a sequence of bytecodes.  */
15551   if (utp->cond && !utp->cond_string)
15552     warning (_("Uploaded tracepoint %d condition "
15553                "has no source form, ignoring it"),
15554              utp->number);
15555
15556   if (!create_breakpoint (get_current_arch (),
15557                           addr_str,
15558                           utp->cond_string, -1, NULL,
15559                           0 /* parse cond/thread */,
15560                           0 /* tempflag */,
15561                           utp->type /* type_wanted */,
15562                           0 /* Ignore count */,
15563                           pending_break_support,
15564                           &tracepoint_breakpoint_ops,
15565                           0 /* from_tty */,
15566                           utp->enabled /* enabled */,
15567                           0 /* internal */,
15568                           CREATE_BREAKPOINT_FLAGS_INSERTED))
15569     return NULL;
15570
15571   /* Get the tracepoint we just created.  */
15572   tp = get_tracepoint (tracepoint_count);
15573   gdb_assert (tp != NULL);
15574
15575   if (utp->pass > 0)
15576     {
15577       xsnprintf (small_buf, sizeof (small_buf), "%d %d", utp->pass,
15578                  tp->base.number);
15579
15580       trace_pass_command (small_buf, 0);
15581     }
15582
15583   /* If we have uploaded versions of the original commands, set up a
15584      special-purpose "reader" function and call the usual command line
15585      reader, then pass the result to the breakpoint command-setting
15586      function.  */
15587   if (!VEC_empty (char_ptr, utp->cmd_strings))
15588     {
15589       struct command_line *cmd_list;
15590
15591       this_utp = utp;
15592       next_cmd = 0;
15593
15594       cmd_list = read_command_lines_1 (read_uploaded_action, 1, NULL, NULL);
15595
15596       breakpoint_set_commands (&tp->base, cmd_list);
15597     }
15598   else if (!VEC_empty (char_ptr, utp->actions)
15599            || !VEC_empty (char_ptr, utp->step_actions))
15600     warning (_("Uploaded tracepoint %d actions "
15601                "have no source form, ignoring them"),
15602              utp->number);
15603
15604   /* Copy any status information that might be available.  */
15605   tp->base.hit_count = utp->hit_count;
15606   tp->traceframe_usage = utp->traceframe_usage;
15607
15608   return tp;
15609 }
15610   
15611 /* Print information on tracepoint number TPNUM_EXP, or all if
15612    omitted.  */
15613
15614 static void
15615 tracepoints_info (char *args, int from_tty)
15616 {
15617   struct ui_out *uiout = current_uiout;
15618   int num_printed;
15619
15620   num_printed = breakpoint_1 (args, 0, is_tracepoint);
15621
15622   if (num_printed == 0)
15623     {
15624       if (args == NULL || *args == '\0')
15625         ui_out_message (uiout, 0, "No tracepoints.\n");
15626       else
15627         ui_out_message (uiout, 0, "No tracepoint matching '%s'.\n", args);
15628     }
15629
15630   default_collect_info ();
15631 }
15632
15633 /* The 'enable trace' command enables tracepoints.
15634    Not supported by all targets.  */
15635 static void
15636 enable_trace_command (char *args, int from_tty)
15637 {
15638   enable_command (args, from_tty);
15639 }
15640
15641 /* The 'disable trace' command disables tracepoints.
15642    Not supported by all targets.  */
15643 static void
15644 disable_trace_command (char *args, int from_tty)
15645 {
15646   disable_command (args, from_tty);
15647 }
15648
15649 /* Remove a tracepoint (or all if no argument).  */
15650 static void
15651 delete_trace_command (char *arg, int from_tty)
15652 {
15653   struct breakpoint *b, *b_tmp;
15654
15655   dont_repeat ();
15656
15657   if (arg == 0)
15658     {
15659       int breaks_to_delete = 0;
15660
15661       /* Delete all breakpoints if no argument.
15662          Do not delete internal or call-dummy breakpoints, these
15663          have to be deleted with an explicit breakpoint number 
15664          argument.  */
15665       ALL_TRACEPOINTS (b)
15666         if (is_tracepoint (b) && user_breakpoint_p (b))
15667           {
15668             breaks_to_delete = 1;
15669             break;
15670           }
15671
15672       /* Ask user only if there are some breakpoints to delete.  */
15673       if (!from_tty
15674           || (breaks_to_delete && query (_("Delete all tracepoints? "))))
15675         {
15676           ALL_BREAKPOINTS_SAFE (b, b_tmp)
15677             if (is_tracepoint (b) && user_breakpoint_p (b))
15678               delete_breakpoint (b);
15679         }
15680     }
15681   else
15682     map_breakpoint_numbers (arg, do_map_delete_breakpoint, NULL);
15683 }
15684
15685 /* Helper function for trace_pass_command.  */
15686
15687 static void
15688 trace_pass_set_count (struct tracepoint *tp, int count, int from_tty)
15689 {
15690   tp->pass_count = count;
15691   observer_notify_breakpoint_modified (&tp->base);
15692   if (from_tty)
15693     printf_filtered (_("Setting tracepoint %d's passcount to %d\n"),
15694                      tp->base.number, count);
15695 }
15696
15697 /* Set passcount for tracepoint.
15698
15699    First command argument is passcount, second is tracepoint number.
15700    If tracepoint number omitted, apply to most recently defined.
15701    Also accepts special argument "all".  */
15702
15703 static void
15704 trace_pass_command (char *args, int from_tty)
15705 {
15706   struct tracepoint *t1;
15707   unsigned int count;
15708
15709   if (args == 0 || *args == 0)
15710     error (_("passcount command requires an "
15711              "argument (count + optional TP num)"));
15712
15713   count = strtoul (args, &args, 10);    /* Count comes first, then TP num.  */
15714
15715   args = skip_spaces (args);
15716   if (*args && strncasecmp (args, "all", 3) == 0)
15717     {
15718       struct breakpoint *b;
15719
15720       args += 3;                        /* Skip special argument "all".  */
15721       if (*args)
15722         error (_("Junk at end of arguments."));
15723
15724       ALL_TRACEPOINTS (b)
15725       {
15726         t1 = (struct tracepoint *) b;
15727         trace_pass_set_count (t1, count, from_tty);
15728       }
15729     }
15730   else if (*args == '\0')
15731     {
15732       t1 = get_tracepoint_by_number (&args, NULL);
15733       if (t1)
15734         trace_pass_set_count (t1, count, from_tty);
15735     }
15736   else
15737     {
15738       struct get_number_or_range_state state;
15739
15740       init_number_or_range (&state, args);
15741       while (!state.finished)
15742         {
15743           t1 = get_tracepoint_by_number (&args, &state);
15744           if (t1)
15745             trace_pass_set_count (t1, count, from_tty);
15746         }
15747     }
15748 }
15749
15750 struct tracepoint *
15751 get_tracepoint (int num)
15752 {
15753   struct breakpoint *t;
15754
15755   ALL_TRACEPOINTS (t)
15756     if (t->number == num)
15757       return (struct tracepoint *) t;
15758
15759   return NULL;
15760 }
15761
15762 /* Find the tracepoint with the given target-side number (which may be
15763    different from the tracepoint number after disconnecting and
15764    reconnecting).  */
15765
15766 struct tracepoint *
15767 get_tracepoint_by_number_on_target (int num)
15768 {
15769   struct breakpoint *b;
15770
15771   ALL_TRACEPOINTS (b)
15772     {
15773       struct tracepoint *t = (struct tracepoint *) b;
15774
15775       if (t->number_on_target == num)
15776         return t;
15777     }
15778
15779   return NULL;
15780 }
15781
15782 /* Utility: parse a tracepoint number and look it up in the list.
15783    If STATE is not NULL, use, get_number_or_range_state and ignore ARG.
15784    If the argument is missing, the most recent tracepoint
15785    (tracepoint_count) is returned.  */
15786
15787 struct tracepoint *
15788 get_tracepoint_by_number (char **arg,
15789                           struct get_number_or_range_state *state)
15790 {
15791   struct breakpoint *t;
15792   int tpnum;
15793   char *instring = arg == NULL ? NULL : *arg;
15794
15795   if (state)
15796     {
15797       gdb_assert (!state->finished);
15798       tpnum = get_number_or_range (state);
15799     }
15800   else if (arg == NULL || *arg == NULL || ! **arg)
15801     tpnum = tracepoint_count;
15802   else
15803     tpnum = get_number (arg);
15804
15805   if (tpnum <= 0)
15806     {
15807       if (instring && *instring)
15808         printf_filtered (_("bad tracepoint number at or near '%s'\n"), 
15809                          instring);
15810       else
15811         printf_filtered (_("No previous tracepoint\n"));
15812       return NULL;
15813     }
15814
15815   ALL_TRACEPOINTS (t)
15816     if (t->number == tpnum)
15817     {
15818       return (struct tracepoint *) t;
15819     }
15820
15821   printf_unfiltered ("No tracepoint number %d.\n", tpnum);
15822   return NULL;
15823 }
15824
15825 void
15826 print_recreate_thread (struct breakpoint *b, struct ui_file *fp)
15827 {
15828   if (b->thread != -1)
15829     fprintf_unfiltered (fp, " thread %d", b->thread);
15830
15831   if (b->task != 0)
15832     fprintf_unfiltered (fp, " task %d", b->task);
15833
15834   fprintf_unfiltered (fp, "\n");
15835 }
15836
15837 /* Save information on user settable breakpoints (watchpoints, etc) to
15838    a new script file named FILENAME.  If FILTER is non-NULL, call it
15839    on each breakpoint and only include the ones for which it returns
15840    non-zero.  */
15841
15842 static void
15843 save_breakpoints (char *filename, int from_tty,
15844                   int (*filter) (const struct breakpoint *))
15845 {
15846   struct breakpoint *tp;
15847   int any = 0;
15848   struct cleanup *cleanup;
15849   struct ui_file *fp;
15850   int extra_trace_bits = 0;
15851
15852   if (filename == 0 || *filename == 0)
15853     error (_("Argument required (file name in which to save)"));
15854
15855   /* See if we have anything to save.  */
15856   ALL_BREAKPOINTS (tp)
15857   {
15858     /* Skip internal and momentary breakpoints.  */
15859     if (!user_breakpoint_p (tp))
15860       continue;
15861
15862     /* If we have a filter, only save the breakpoints it accepts.  */
15863     if (filter && !filter (tp))
15864       continue;
15865
15866     any = 1;
15867
15868     if (is_tracepoint (tp))
15869       {
15870         extra_trace_bits = 1;
15871
15872         /* We can stop searching.  */
15873         break;
15874       }
15875   }
15876
15877   if (!any)
15878     {
15879       warning (_("Nothing to save."));
15880       return;
15881     }
15882
15883   filename = tilde_expand (filename);
15884   cleanup = make_cleanup (xfree, filename);
15885   fp = gdb_fopen (filename, "w");
15886   if (!fp)
15887     error (_("Unable to open file '%s' for saving (%s)"),
15888            filename, safe_strerror (errno));
15889   make_cleanup_ui_file_delete (fp);
15890
15891   if (extra_trace_bits)
15892     save_trace_state_variables (fp);
15893
15894   ALL_BREAKPOINTS (tp)
15895   {
15896     /* Skip internal and momentary breakpoints.  */
15897     if (!user_breakpoint_p (tp))
15898       continue;
15899
15900     /* If we have a filter, only save the breakpoints it accepts.  */
15901     if (filter && !filter (tp))
15902       continue;
15903
15904     tp->ops->print_recreate (tp, fp);
15905
15906     /* Note, we can't rely on tp->number for anything, as we can't
15907        assume the recreated breakpoint numbers will match.  Use $bpnum
15908        instead.  */
15909
15910     if (tp->cond_string)
15911       fprintf_unfiltered (fp, "  condition $bpnum %s\n", tp->cond_string);
15912
15913     if (tp->ignore_count)
15914       fprintf_unfiltered (fp, "  ignore $bpnum %d\n", tp->ignore_count);
15915
15916     if (tp->type != bp_dprintf && tp->commands)
15917       {
15918         volatile struct gdb_exception ex;       
15919
15920         fprintf_unfiltered (fp, "  commands\n");
15921         
15922         ui_out_redirect (current_uiout, fp);
15923         TRY_CATCH (ex, RETURN_MASK_ALL)
15924           {
15925             print_command_lines (current_uiout, tp->commands->commands, 2);
15926           }
15927         ui_out_redirect (current_uiout, NULL);
15928
15929         if (ex.reason < 0)
15930           throw_exception (ex);
15931
15932         fprintf_unfiltered (fp, "  end\n");
15933       }
15934
15935     if (tp->enable_state == bp_disabled)
15936       fprintf_unfiltered (fp, "disable $bpnum\n");
15937
15938     /* If this is a multi-location breakpoint, check if the locations
15939        should be individually disabled.  Watchpoint locations are
15940        special, and not user visible.  */
15941     if (!is_watchpoint (tp) && tp->loc && tp->loc->next)
15942       {
15943         struct bp_location *loc;
15944         int n = 1;
15945
15946         for (loc = tp->loc; loc != NULL; loc = loc->next, n++)
15947           if (!loc->enabled)
15948             fprintf_unfiltered (fp, "disable $bpnum.%d\n", n);
15949       }
15950   }
15951
15952   if (extra_trace_bits && *default_collect)
15953     fprintf_unfiltered (fp, "set default-collect %s\n", default_collect);
15954
15955   if (from_tty)
15956     printf_filtered (_("Saved to file '%s'.\n"), filename);
15957   do_cleanups (cleanup);
15958 }
15959
15960 /* The `save breakpoints' command.  */
15961
15962 static void
15963 save_breakpoints_command (char *args, int from_tty)
15964 {
15965   save_breakpoints (args, from_tty, NULL);
15966 }
15967
15968 /* The `save tracepoints' command.  */
15969
15970 static void
15971 save_tracepoints_command (char *args, int from_tty)
15972 {
15973   save_breakpoints (args, from_tty, is_tracepoint);
15974 }
15975
15976 /* Create a vector of all tracepoints.  */
15977
15978 VEC(breakpoint_p) *
15979 all_tracepoints (void)
15980 {
15981   VEC(breakpoint_p) *tp_vec = 0;
15982   struct breakpoint *tp;
15983
15984   ALL_TRACEPOINTS (tp)
15985   {
15986     VEC_safe_push (breakpoint_p, tp_vec, tp);
15987   }
15988
15989   return tp_vec;
15990 }
15991
15992 \f
15993 /* This help string is used for the break, hbreak, tbreak and thbreak
15994    commands.  It is defined as a macro to prevent duplication.
15995    COMMAND should be a string constant containing the name of the
15996    command.  */
15997 #define BREAK_ARGS_HELP(command) \
15998 command" [PROBE_MODIFIER] [LOCATION] [thread THREADNUM] [if CONDITION]\n\
15999 PROBE_MODIFIER shall be present if the command is to be placed in a\n\
16000 probe point.  Accepted values are `-probe' (for a generic, automatically\n\
16001 guessed probe type) or `-probe-stap' (for a SystemTap probe).\n\
16002 LOCATION may be a line number, function name, or \"*\" and an address.\n\
16003 If a line number is specified, break at start of code for that line.\n\
16004 If a function is specified, break at start of code for that function.\n\
16005 If an address is specified, break at that exact address.\n\
16006 With no LOCATION, uses current execution address of the selected\n\
16007 stack frame.  This is useful for breaking on return to a stack frame.\n\
16008 \n\
16009 THREADNUM is the number from \"info threads\".\n\
16010 CONDITION is a boolean expression.\n\
16011 \n\
16012 Multiple breakpoints at one place are permitted, and useful if their\n\
16013 conditions are different.\n\
16014 \n\
16015 Do \"help breakpoints\" for info on other commands dealing with breakpoints."
16016
16017 /* List of subcommands for "catch".  */
16018 static struct cmd_list_element *catch_cmdlist;
16019
16020 /* List of subcommands for "tcatch".  */
16021 static struct cmd_list_element *tcatch_cmdlist;
16022
16023 void
16024 add_catch_command (char *name, char *docstring,
16025                    cmd_sfunc_ftype *sfunc,
16026                    completer_ftype *completer,
16027                    void *user_data_catch,
16028                    void *user_data_tcatch)
16029 {
16030   struct cmd_list_element *command;
16031
16032   command = add_cmd (name, class_breakpoint, NULL, docstring,
16033                      &catch_cmdlist);
16034   set_cmd_sfunc (command, sfunc);
16035   set_cmd_context (command, user_data_catch);
16036   set_cmd_completer (command, completer);
16037
16038   command = add_cmd (name, class_breakpoint, NULL, docstring,
16039                      &tcatch_cmdlist);
16040   set_cmd_sfunc (command, sfunc);
16041   set_cmd_context (command, user_data_tcatch);
16042   set_cmd_completer (command, completer);
16043 }
16044
16045 static void
16046 clear_syscall_counts (struct inferior *inf)
16047 {
16048   struct catch_syscall_inferior_data *inf_data
16049     = get_catch_syscall_inferior_data (inf);
16050
16051   inf_data->total_syscalls_count = 0;
16052   inf_data->any_syscall_count = 0;
16053   VEC_free (int, inf_data->syscalls_counts);
16054 }
16055
16056 static void
16057 save_command (char *arg, int from_tty)
16058 {
16059   printf_unfiltered (_("\"save\" must be followed by "
16060                        "the name of a save subcommand.\n"));
16061   help_list (save_cmdlist, "save ", all_commands, gdb_stdout);
16062 }
16063
16064 struct breakpoint *
16065 iterate_over_breakpoints (int (*callback) (struct breakpoint *, void *),
16066                           void *data)
16067 {
16068   struct breakpoint *b, *b_tmp;
16069
16070   ALL_BREAKPOINTS_SAFE (b, b_tmp)
16071     {
16072       if ((*callback) (b, data))
16073         return b;
16074     }
16075
16076   return NULL;
16077 }
16078
16079 /* Zero if any of the breakpoint's locations could be a location where
16080    functions have been inlined, nonzero otherwise.  */
16081
16082 static int
16083 is_non_inline_function (struct breakpoint *b)
16084 {
16085   /* The shared library event breakpoint is set on the address of a
16086      non-inline function.  */
16087   if (b->type == bp_shlib_event)
16088     return 1;
16089
16090   return 0;
16091 }
16092
16093 /* Nonzero if the specified PC cannot be a location where functions
16094    have been inlined.  */
16095
16096 int
16097 pc_at_non_inline_function (struct address_space *aspace, CORE_ADDR pc,
16098                            const struct target_waitstatus *ws)
16099 {
16100   struct breakpoint *b;
16101   struct bp_location *bl;
16102
16103   ALL_BREAKPOINTS (b)
16104     {
16105       if (!is_non_inline_function (b))
16106         continue;
16107
16108       for (bl = b->loc; bl != NULL; bl = bl->next)
16109         {
16110           if (!bl->shlib_disabled
16111               && bpstat_check_location (bl, aspace, pc, ws))
16112             return 1;
16113         }
16114     }
16115
16116   return 0;
16117 }
16118
16119 /* Remove any references to OBJFILE which is going to be freed.  */
16120
16121 void
16122 breakpoint_free_objfile (struct objfile *objfile)
16123 {
16124   struct bp_location **locp, *loc;
16125
16126   ALL_BP_LOCATIONS (loc, locp)
16127     if (loc->symtab != NULL && loc->symtab->objfile == objfile)
16128       loc->symtab = NULL;
16129 }
16130
16131 void
16132 initialize_breakpoint_ops (void)
16133 {
16134   static int initialized = 0;
16135
16136   struct breakpoint_ops *ops;
16137
16138   if (initialized)
16139     return;
16140   initialized = 1;
16141
16142   /* The breakpoint_ops structure to be inherit by all kinds of
16143      breakpoints (real breakpoints, i.e., user "break" breakpoints,
16144      internal and momentary breakpoints, etc.).  */
16145   ops = &bkpt_base_breakpoint_ops;
16146   *ops = base_breakpoint_ops;
16147   ops->re_set = bkpt_re_set;
16148   ops->insert_location = bkpt_insert_location;
16149   ops->remove_location = bkpt_remove_location;
16150   ops->breakpoint_hit = bkpt_breakpoint_hit;
16151   ops->create_sals_from_address = bkpt_create_sals_from_address;
16152   ops->create_breakpoints_sal = bkpt_create_breakpoints_sal;
16153   ops->decode_linespec = bkpt_decode_linespec;
16154
16155   /* The breakpoint_ops structure to be used in regular breakpoints.  */
16156   ops = &bkpt_breakpoint_ops;
16157   *ops = bkpt_base_breakpoint_ops;
16158   ops->re_set = bkpt_re_set;
16159   ops->resources_needed = bkpt_resources_needed;
16160   ops->print_it = bkpt_print_it;
16161   ops->print_mention = bkpt_print_mention;
16162   ops->print_recreate = bkpt_print_recreate;
16163
16164   /* Ranged breakpoints.  */
16165   ops = &ranged_breakpoint_ops;
16166   *ops = bkpt_breakpoint_ops;
16167   ops->breakpoint_hit = breakpoint_hit_ranged_breakpoint;
16168   ops->resources_needed = resources_needed_ranged_breakpoint;
16169   ops->print_it = print_it_ranged_breakpoint;
16170   ops->print_one = print_one_ranged_breakpoint;
16171   ops->print_one_detail = print_one_detail_ranged_breakpoint;
16172   ops->print_mention = print_mention_ranged_breakpoint;
16173   ops->print_recreate = print_recreate_ranged_breakpoint;
16174
16175   /* Internal breakpoints.  */
16176   ops = &internal_breakpoint_ops;
16177   *ops = bkpt_base_breakpoint_ops;
16178   ops->re_set = internal_bkpt_re_set;
16179   ops->check_status = internal_bkpt_check_status;
16180   ops->print_it = internal_bkpt_print_it;
16181   ops->print_mention = internal_bkpt_print_mention;
16182
16183   /* Momentary breakpoints.  */
16184   ops = &momentary_breakpoint_ops;
16185   *ops = bkpt_base_breakpoint_ops;
16186   ops->re_set = momentary_bkpt_re_set;
16187   ops->check_status = momentary_bkpt_check_status;
16188   ops->print_it = momentary_bkpt_print_it;
16189   ops->print_mention = momentary_bkpt_print_mention;
16190
16191   /* Momentary breakpoints for bp_longjmp and bp_exception.  */
16192   ops = &longjmp_breakpoint_ops;
16193   *ops = momentary_breakpoint_ops;
16194   ops->dtor = longjmp_bkpt_dtor;
16195
16196   /* Probe breakpoints.  */
16197   ops = &bkpt_probe_breakpoint_ops;
16198   *ops = bkpt_breakpoint_ops;
16199   ops->insert_location = bkpt_probe_insert_location;
16200   ops->remove_location = bkpt_probe_remove_location;
16201   ops->create_sals_from_address = bkpt_probe_create_sals_from_address;
16202   ops->decode_linespec = bkpt_probe_decode_linespec;
16203
16204   /* Watchpoints.  */
16205   ops = &watchpoint_breakpoint_ops;
16206   *ops = base_breakpoint_ops;
16207   ops->dtor = dtor_watchpoint;
16208   ops->re_set = re_set_watchpoint;
16209   ops->insert_location = insert_watchpoint;
16210   ops->remove_location = remove_watchpoint;
16211   ops->breakpoint_hit = breakpoint_hit_watchpoint;
16212   ops->check_status = check_status_watchpoint;
16213   ops->resources_needed = resources_needed_watchpoint;
16214   ops->works_in_software_mode = works_in_software_mode_watchpoint;
16215   ops->print_it = print_it_watchpoint;
16216   ops->print_mention = print_mention_watchpoint;
16217   ops->print_recreate = print_recreate_watchpoint;
16218   ops->explains_signal = explains_signal_watchpoint;
16219
16220   /* Masked watchpoints.  */
16221   ops = &masked_watchpoint_breakpoint_ops;
16222   *ops = watchpoint_breakpoint_ops;
16223   ops->insert_location = insert_masked_watchpoint;
16224   ops->remove_location = remove_masked_watchpoint;
16225   ops->resources_needed = resources_needed_masked_watchpoint;
16226   ops->works_in_software_mode = works_in_software_mode_masked_watchpoint;
16227   ops->print_it = print_it_masked_watchpoint;
16228   ops->print_one_detail = print_one_detail_masked_watchpoint;
16229   ops->print_mention = print_mention_masked_watchpoint;
16230   ops->print_recreate = print_recreate_masked_watchpoint;
16231
16232   /* Tracepoints.  */
16233   ops = &tracepoint_breakpoint_ops;
16234   *ops = base_breakpoint_ops;
16235   ops->re_set = tracepoint_re_set;
16236   ops->breakpoint_hit = tracepoint_breakpoint_hit;
16237   ops->print_one_detail = tracepoint_print_one_detail;
16238   ops->print_mention = tracepoint_print_mention;
16239   ops->print_recreate = tracepoint_print_recreate;
16240   ops->create_sals_from_address = tracepoint_create_sals_from_address;
16241   ops->create_breakpoints_sal = tracepoint_create_breakpoints_sal;
16242   ops->decode_linespec = tracepoint_decode_linespec;
16243
16244   /* Probe tracepoints.  */
16245   ops = &tracepoint_probe_breakpoint_ops;
16246   *ops = tracepoint_breakpoint_ops;
16247   ops->create_sals_from_address = tracepoint_probe_create_sals_from_address;
16248   ops->decode_linespec = tracepoint_probe_decode_linespec;
16249
16250   /* Static tracepoints with marker (`-m').  */
16251   ops = &strace_marker_breakpoint_ops;
16252   *ops = tracepoint_breakpoint_ops;
16253   ops->create_sals_from_address = strace_marker_create_sals_from_address;
16254   ops->create_breakpoints_sal = strace_marker_create_breakpoints_sal;
16255   ops->decode_linespec = strace_marker_decode_linespec;
16256
16257   /* Fork catchpoints.  */
16258   ops = &catch_fork_breakpoint_ops;
16259   *ops = base_breakpoint_ops;
16260   ops->insert_location = insert_catch_fork;
16261   ops->remove_location = remove_catch_fork;
16262   ops->breakpoint_hit = breakpoint_hit_catch_fork;
16263   ops->print_it = print_it_catch_fork;
16264   ops->print_one = print_one_catch_fork;
16265   ops->print_mention = print_mention_catch_fork;
16266   ops->print_recreate = print_recreate_catch_fork;
16267
16268   /* Vfork catchpoints.  */
16269   ops = &catch_vfork_breakpoint_ops;
16270   *ops = base_breakpoint_ops;
16271   ops->insert_location = insert_catch_vfork;
16272   ops->remove_location = remove_catch_vfork;
16273   ops->breakpoint_hit = breakpoint_hit_catch_vfork;
16274   ops->print_it = print_it_catch_vfork;
16275   ops->print_one = print_one_catch_vfork;
16276   ops->print_mention = print_mention_catch_vfork;
16277   ops->print_recreate = print_recreate_catch_vfork;
16278
16279   /* Exec catchpoints.  */
16280   ops = &catch_exec_breakpoint_ops;
16281   *ops = base_breakpoint_ops;
16282   ops->dtor = dtor_catch_exec;
16283   ops->insert_location = insert_catch_exec;
16284   ops->remove_location = remove_catch_exec;
16285   ops->breakpoint_hit = breakpoint_hit_catch_exec;
16286   ops->print_it = print_it_catch_exec;
16287   ops->print_one = print_one_catch_exec;
16288   ops->print_mention = print_mention_catch_exec;
16289   ops->print_recreate = print_recreate_catch_exec;
16290
16291   /* Syscall catchpoints.  */
16292   ops = &catch_syscall_breakpoint_ops;
16293   *ops = base_breakpoint_ops;
16294   ops->dtor = dtor_catch_syscall;
16295   ops->insert_location = insert_catch_syscall;
16296   ops->remove_location = remove_catch_syscall;
16297   ops->breakpoint_hit = breakpoint_hit_catch_syscall;
16298   ops->print_it = print_it_catch_syscall;
16299   ops->print_one = print_one_catch_syscall;
16300   ops->print_mention = print_mention_catch_syscall;
16301   ops->print_recreate = print_recreate_catch_syscall;
16302
16303   /* Solib-related catchpoints.  */
16304   ops = &catch_solib_breakpoint_ops;
16305   *ops = base_breakpoint_ops;
16306   ops->dtor = dtor_catch_solib;
16307   ops->insert_location = insert_catch_solib;
16308   ops->remove_location = remove_catch_solib;
16309   ops->breakpoint_hit = breakpoint_hit_catch_solib;
16310   ops->check_status = check_status_catch_solib;
16311   ops->print_it = print_it_catch_solib;
16312   ops->print_one = print_one_catch_solib;
16313   ops->print_mention = print_mention_catch_solib;
16314   ops->print_recreate = print_recreate_catch_solib;
16315
16316   ops = &dprintf_breakpoint_ops;
16317   *ops = bkpt_base_breakpoint_ops;
16318   ops->re_set = dprintf_re_set;
16319   ops->resources_needed = bkpt_resources_needed;
16320   ops->print_it = bkpt_print_it;
16321   ops->print_mention = bkpt_print_mention;
16322   ops->print_recreate = dprintf_print_recreate;
16323   ops->after_condition_true = dprintf_after_condition_true;
16324   ops->breakpoint_hit = dprintf_breakpoint_hit;
16325 }
16326
16327 /* Chain containing all defined "enable breakpoint" subcommands.  */
16328
16329 static struct cmd_list_element *enablebreaklist = NULL;
16330
16331 void
16332 _initialize_breakpoint (void)
16333 {
16334   struct cmd_list_element *c;
16335
16336   initialize_breakpoint_ops ();
16337
16338   observer_attach_solib_unloaded (disable_breakpoints_in_unloaded_shlib);
16339   observer_attach_free_objfile (disable_breakpoints_in_freed_objfile);
16340   observer_attach_inferior_exit (clear_syscall_counts);
16341   observer_attach_memory_changed (invalidate_bp_value_on_memory_change);
16342
16343   breakpoint_objfile_key
16344     = register_objfile_data_with_cleanup (NULL, free_breakpoint_probes);
16345
16346   catch_syscall_inferior_data
16347     = register_inferior_data_with_cleanup (NULL,
16348                                            catch_syscall_inferior_data_cleanup);
16349
16350   breakpoint_chain = 0;
16351   /* Don't bother to call set_breakpoint_count.  $bpnum isn't useful
16352      before a breakpoint is set.  */
16353   breakpoint_count = 0;
16354
16355   tracepoint_count = 0;
16356
16357   add_com ("ignore", class_breakpoint, ignore_command, _("\
16358 Set ignore-count of breakpoint number N to COUNT.\n\
16359 Usage is `ignore N COUNT'."));
16360   if (xdb_commands)
16361     add_com_alias ("bc", "ignore", class_breakpoint, 1);
16362
16363   add_com ("commands", class_breakpoint, commands_command, _("\
16364 Set commands to be executed when a breakpoint is hit.\n\
16365 Give breakpoint number as argument after \"commands\".\n\
16366 With no argument, the targeted breakpoint is the last one set.\n\
16367 The commands themselves follow starting on the next line.\n\
16368 Type a line containing \"end\" to indicate the end of them.\n\
16369 Give \"silent\" as the first line to make the breakpoint silent;\n\
16370 then no output is printed when it is hit, except what the commands print."));
16371
16372   c = add_com ("condition", class_breakpoint, condition_command, _("\
16373 Specify breakpoint number N to break only if COND is true.\n\
16374 Usage is `condition N COND', where N is an integer and COND is an\n\
16375 expression to be evaluated whenever breakpoint N is reached."));
16376   set_cmd_completer (c, condition_completer);
16377
16378   c = add_com ("tbreak", class_breakpoint, tbreak_command, _("\
16379 Set a temporary breakpoint.\n\
16380 Like \"break\" except the breakpoint is only temporary,\n\
16381 so it will be deleted when hit.  Equivalent to \"break\" followed\n\
16382 by using \"enable delete\" on the breakpoint number.\n\
16383 \n"
16384 BREAK_ARGS_HELP ("tbreak")));
16385   set_cmd_completer (c, location_completer);
16386
16387   c = add_com ("hbreak", class_breakpoint, hbreak_command, _("\
16388 Set a hardware assisted breakpoint.\n\
16389 Like \"break\" except the breakpoint requires hardware support,\n\
16390 some target hardware may not have this support.\n\
16391 \n"
16392 BREAK_ARGS_HELP ("hbreak")));
16393   set_cmd_completer (c, location_completer);
16394
16395   c = add_com ("thbreak", class_breakpoint, thbreak_command, _("\
16396 Set a temporary hardware assisted breakpoint.\n\
16397 Like \"hbreak\" except the breakpoint is only temporary,\n\
16398 so it will be deleted when hit.\n\
16399 \n"
16400 BREAK_ARGS_HELP ("thbreak")));
16401   set_cmd_completer (c, location_completer);
16402
16403   add_prefix_cmd ("enable", class_breakpoint, enable_command, _("\
16404 Enable some breakpoints.\n\
16405 Give breakpoint numbers (separated by spaces) as arguments.\n\
16406 With no subcommand, breakpoints are enabled until you command otherwise.\n\
16407 This is used to cancel the effect of the \"disable\" command.\n\
16408 With a subcommand you can enable temporarily."),
16409                   &enablelist, "enable ", 1, &cmdlist);
16410   if (xdb_commands)
16411     add_com ("ab", class_breakpoint, enable_command, _("\
16412 Enable some breakpoints.\n\
16413 Give breakpoint numbers (separated by spaces) as arguments.\n\
16414 With no subcommand, breakpoints are enabled until you command otherwise.\n\
16415 This is used to cancel the effect of the \"disable\" command.\n\
16416 With a subcommand you can enable temporarily."));
16417
16418   add_com_alias ("en", "enable", class_breakpoint, 1);
16419
16420   add_prefix_cmd ("breakpoints", class_breakpoint, enable_command, _("\
16421 Enable some breakpoints.\n\
16422 Give breakpoint numbers (separated by spaces) as arguments.\n\
16423 This is used to cancel the effect of the \"disable\" command.\n\
16424 May be abbreviated to simply \"enable\".\n"),
16425                    &enablebreaklist, "enable breakpoints ", 1, &enablelist);
16426
16427   add_cmd ("once", no_class, enable_once_command, _("\
16428 Enable breakpoints for one hit.  Give breakpoint numbers.\n\
16429 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
16430            &enablebreaklist);
16431
16432   add_cmd ("delete", no_class, enable_delete_command, _("\
16433 Enable breakpoints and delete when hit.  Give breakpoint numbers.\n\
16434 If a breakpoint is hit while enabled in this fashion, it is deleted."),
16435            &enablebreaklist);
16436
16437   add_cmd ("count", no_class, enable_count_command, _("\
16438 Enable breakpoints for COUNT hits.  Give count and then breakpoint numbers.\n\
16439 If a breakpoint is hit while enabled in this fashion,\n\
16440 the count is decremented; when it reaches zero, the breakpoint is disabled."),
16441            &enablebreaklist);
16442
16443   add_cmd ("delete", no_class, enable_delete_command, _("\
16444 Enable breakpoints and delete when hit.  Give breakpoint numbers.\n\
16445 If a breakpoint is hit while enabled in this fashion, it is deleted."),
16446            &enablelist);
16447
16448   add_cmd ("once", no_class, enable_once_command, _("\
16449 Enable breakpoints for one hit.  Give breakpoint numbers.\n\
16450 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
16451            &enablelist);
16452
16453   add_cmd ("count", no_class, enable_count_command, _("\
16454 Enable breakpoints for COUNT hits.  Give count and then breakpoint numbers.\n\
16455 If a breakpoint is hit while enabled in this fashion,\n\
16456 the count is decremented; when it reaches zero, the breakpoint is disabled."),
16457            &enablelist);
16458
16459   add_prefix_cmd ("disable", class_breakpoint, disable_command, _("\
16460 Disable some breakpoints.\n\
16461 Arguments are breakpoint numbers with spaces in between.\n\
16462 To disable all breakpoints, give no argument.\n\
16463 A disabled breakpoint is not forgotten, but has no effect until re-enabled."),
16464                   &disablelist, "disable ", 1, &cmdlist);
16465   add_com_alias ("dis", "disable", class_breakpoint, 1);
16466   add_com_alias ("disa", "disable", class_breakpoint, 1);
16467   if (xdb_commands)
16468     add_com ("sb", class_breakpoint, disable_command, _("\
16469 Disable some breakpoints.\n\
16470 Arguments are breakpoint numbers with spaces in between.\n\
16471 To disable all breakpoints, give no argument.\n\
16472 A disabled breakpoint is not forgotten, but has no effect until re-enabled."));
16473
16474   add_cmd ("breakpoints", class_alias, disable_command, _("\
16475 Disable some breakpoints.\n\
16476 Arguments are breakpoint numbers with spaces in between.\n\
16477 To disable all breakpoints, give no argument.\n\
16478 A disabled breakpoint is not forgotten, but has no effect until re-enabled.\n\
16479 This command may be abbreviated \"disable\"."),
16480            &disablelist);
16481
16482   add_prefix_cmd ("delete", class_breakpoint, delete_command, _("\
16483 Delete some breakpoints or auto-display expressions.\n\
16484 Arguments are breakpoint numbers with spaces in between.\n\
16485 To delete all breakpoints, give no argument.\n\
16486 \n\
16487 Also a prefix command for deletion of other GDB objects.\n\
16488 The \"unset\" command is also an alias for \"delete\"."),
16489                   &deletelist, "delete ", 1, &cmdlist);
16490   add_com_alias ("d", "delete", class_breakpoint, 1);
16491   add_com_alias ("del", "delete", class_breakpoint, 1);
16492   if (xdb_commands)
16493     add_com ("db", class_breakpoint, delete_command, _("\
16494 Delete some breakpoints.\n\
16495 Arguments are breakpoint numbers with spaces in between.\n\
16496 To delete all breakpoints, give no argument.\n"));
16497
16498   add_cmd ("breakpoints", class_alias, delete_command, _("\
16499 Delete some breakpoints or auto-display expressions.\n\
16500 Arguments are breakpoint numbers with spaces in between.\n\
16501 To delete all breakpoints, give no argument.\n\
16502 This command may be abbreviated \"delete\"."),
16503            &deletelist);
16504
16505   add_com ("clear", class_breakpoint, clear_command, _("\
16506 Clear breakpoint at specified line or function.\n\
16507 Argument may be line number, function name, or \"*\" and an address.\n\
16508 If line number is specified, all breakpoints in that line are cleared.\n\
16509 If function is specified, breakpoints at beginning of function are cleared.\n\
16510 If an address is specified, breakpoints at that address are cleared.\n\
16511 \n\
16512 With no argument, clears all breakpoints in the line that the selected frame\n\
16513 is executing in.\n\
16514 \n\
16515 See also the \"delete\" command which clears breakpoints by number."));
16516   add_com_alias ("cl", "clear", class_breakpoint, 1);
16517
16518   c = add_com ("break", class_breakpoint, break_command, _("\
16519 Set breakpoint at specified line or function.\n"
16520 BREAK_ARGS_HELP ("break")));
16521   set_cmd_completer (c, location_completer);
16522
16523   add_com_alias ("b", "break", class_run, 1);
16524   add_com_alias ("br", "break", class_run, 1);
16525   add_com_alias ("bre", "break", class_run, 1);
16526   add_com_alias ("brea", "break", class_run, 1);
16527
16528   if (xdb_commands)
16529    add_com_alias ("ba", "break", class_breakpoint, 1);
16530
16531   if (dbx_commands)
16532     {
16533       add_abbrev_prefix_cmd ("stop", class_breakpoint, stop_command, _("\
16534 Break in function/address or break at a line in the current file."),
16535                              &stoplist, "stop ", 1, &cmdlist);
16536       add_cmd ("in", class_breakpoint, stopin_command,
16537                _("Break in function or address."), &stoplist);
16538       add_cmd ("at", class_breakpoint, stopat_command,
16539                _("Break at a line in the current file."), &stoplist);
16540       add_com ("status", class_info, breakpoints_info, _("\
16541 Status of user-settable breakpoints, or breakpoint number NUMBER.\n\
16542 The \"Type\" column indicates one of:\n\
16543 \tbreakpoint     - normal breakpoint\n\
16544 \twatchpoint     - watchpoint\n\
16545 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
16546 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
16547 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
16548 address and file/line number respectively.\n\
16549 \n\
16550 Convenience variable \"$_\" and default examine address for \"x\"\n\
16551 are set to the address of the last breakpoint listed unless the command\n\
16552 is prefixed with \"server \".\n\n\
16553 Convenience variable \"$bpnum\" contains the number of the last\n\
16554 breakpoint set."));
16555     }
16556
16557   add_info ("breakpoints", breakpoints_info, _("\
16558 Status of specified breakpoints (all user-settable breakpoints if no argument).\n\
16559 The \"Type\" column indicates one of:\n\
16560 \tbreakpoint     - normal breakpoint\n\
16561 \twatchpoint     - watchpoint\n\
16562 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
16563 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
16564 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
16565 address and file/line number respectively.\n\
16566 \n\
16567 Convenience variable \"$_\" and default examine address for \"x\"\n\
16568 are set to the address of the last breakpoint listed unless the command\n\
16569 is prefixed with \"server \".\n\n\
16570 Convenience variable \"$bpnum\" contains the number of the last\n\
16571 breakpoint set."));
16572
16573   add_info_alias ("b", "breakpoints", 1);
16574
16575   if (xdb_commands)
16576     add_com ("lb", class_breakpoint, breakpoints_info, _("\
16577 Status of user-settable breakpoints, or breakpoint number NUMBER.\n\
16578 The \"Type\" column indicates one of:\n\
16579 \tbreakpoint     - normal breakpoint\n\
16580 \twatchpoint     - watchpoint\n\
16581 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
16582 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
16583 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
16584 address and file/line number respectively.\n\
16585 \n\
16586 Convenience variable \"$_\" and default examine address for \"x\"\n\
16587 are set to the address of the last breakpoint listed unless the command\n\
16588 is prefixed with \"server \".\n\n\
16589 Convenience variable \"$bpnum\" contains the number of the last\n\
16590 breakpoint set."));
16591
16592   add_cmd ("breakpoints", class_maintenance, maintenance_info_breakpoints, _("\
16593 Status of all breakpoints, or breakpoint number NUMBER.\n\
16594 The \"Type\" column indicates one of:\n\
16595 \tbreakpoint     - normal breakpoint\n\
16596 \twatchpoint     - watchpoint\n\
16597 \tlongjmp        - internal breakpoint used to step through longjmp()\n\
16598 \tlongjmp resume - internal breakpoint at the target of longjmp()\n\
16599 \tuntil          - internal breakpoint used by the \"until\" command\n\
16600 \tfinish         - internal breakpoint used by the \"finish\" command\n\
16601 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
16602 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
16603 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
16604 address and file/line number respectively.\n\
16605 \n\
16606 Convenience variable \"$_\" and default examine address for \"x\"\n\
16607 are set to the address of the last breakpoint listed unless the command\n\
16608 is prefixed with \"server \".\n\n\
16609 Convenience variable \"$bpnum\" contains the number of the last\n\
16610 breakpoint set."),
16611            &maintenanceinfolist);
16612
16613   add_prefix_cmd ("catch", class_breakpoint, catch_command, _("\
16614 Set catchpoints to catch events."),
16615                   &catch_cmdlist, "catch ",
16616                   0/*allow-unknown*/, &cmdlist);
16617
16618   add_prefix_cmd ("tcatch", class_breakpoint, tcatch_command, _("\
16619 Set temporary catchpoints to catch events."),
16620                   &tcatch_cmdlist, "tcatch ",
16621                   0/*allow-unknown*/, &cmdlist);
16622
16623   add_catch_command ("fork", _("Catch calls to fork."),
16624                      catch_fork_command_1,
16625                      NULL,
16626                      (void *) (uintptr_t) catch_fork_permanent,
16627                      (void *) (uintptr_t) catch_fork_temporary);
16628   add_catch_command ("vfork", _("Catch calls to vfork."),
16629                      catch_fork_command_1,
16630                      NULL,
16631                      (void *) (uintptr_t) catch_vfork_permanent,
16632                      (void *) (uintptr_t) catch_vfork_temporary);
16633   add_catch_command ("exec", _("Catch calls to exec."),
16634                      catch_exec_command_1,
16635                      NULL,
16636                      CATCH_PERMANENT,
16637                      CATCH_TEMPORARY);
16638   add_catch_command ("load", _("Catch loads of shared libraries.\n\
16639 Usage: catch load [REGEX]\n\
16640 If REGEX is given, only stop for libraries matching the regular expression."),
16641                      catch_load_command_1,
16642                      NULL,
16643                      CATCH_PERMANENT,
16644                      CATCH_TEMPORARY);
16645   add_catch_command ("unload", _("Catch unloads of shared libraries.\n\
16646 Usage: catch unload [REGEX]\n\
16647 If REGEX is given, only stop for libraries matching the regular expression."),
16648                      catch_unload_command_1,
16649                      NULL,
16650                      CATCH_PERMANENT,
16651                      CATCH_TEMPORARY);
16652   add_catch_command ("syscall", _("\
16653 Catch system calls by their names and/or numbers.\n\
16654 Arguments say which system calls to catch.  If no arguments\n\
16655 are given, every system call will be caught.\n\
16656 Arguments, if given, should be one or more system call names\n\
16657 (if your system supports that), or system call numbers."),
16658                      catch_syscall_command_1,
16659                      catch_syscall_completer,
16660                      CATCH_PERMANENT,
16661                      CATCH_TEMPORARY);
16662
16663   c = add_com ("watch", class_breakpoint, watch_command, _("\
16664 Set a watchpoint for an expression.\n\
16665 Usage: watch [-l|-location] EXPRESSION\n\
16666 A watchpoint stops execution of your program whenever the value of\n\
16667 an expression changes.\n\
16668 If -l or -location is given, this evaluates EXPRESSION and watches\n\
16669 the memory to which it refers."));
16670   set_cmd_completer (c, expression_completer);
16671
16672   c = add_com ("rwatch", class_breakpoint, rwatch_command, _("\
16673 Set a read watchpoint for an expression.\n\
16674 Usage: rwatch [-l|-location] EXPRESSION\n\
16675 A watchpoint stops execution of your program whenever the value of\n\
16676 an expression is read.\n\
16677 If -l or -location is given, this evaluates EXPRESSION and watches\n\
16678 the memory to which it refers."));
16679   set_cmd_completer (c, expression_completer);
16680
16681   c = add_com ("awatch", class_breakpoint, awatch_command, _("\
16682 Set a watchpoint for an expression.\n\
16683 Usage: awatch [-l|-location] EXPRESSION\n\
16684 A watchpoint stops execution of your program whenever the value of\n\
16685 an expression is either read or written.\n\
16686 If -l or -location is given, this evaluates EXPRESSION and watches\n\
16687 the memory to which it refers."));
16688   set_cmd_completer (c, expression_completer);
16689
16690   add_info ("watchpoints", watchpoints_info, _("\
16691 Status of specified watchpoints (all watchpoints if no argument)."));
16692
16693   /* XXX: cagney/2005-02-23: This should be a boolean, and should
16694      respond to changes - contrary to the description.  */
16695   add_setshow_zinteger_cmd ("can-use-hw-watchpoints", class_support,
16696                             &can_use_hw_watchpoints, _("\
16697 Set debugger's willingness to use watchpoint hardware."), _("\
16698 Show debugger's willingness to use watchpoint hardware."), _("\
16699 If zero, gdb will not use hardware for new watchpoints, even if\n\
16700 such is available.  (However, any hardware watchpoints that were\n\
16701 created before setting this to nonzero, will continue to use watchpoint\n\
16702 hardware.)"),
16703                             NULL,
16704                             show_can_use_hw_watchpoints,
16705                             &setlist, &showlist);
16706
16707   can_use_hw_watchpoints = 1;
16708
16709   /* Tracepoint manipulation commands.  */
16710
16711   c = add_com ("trace", class_breakpoint, trace_command, _("\
16712 Set a tracepoint at specified line or function.\n\
16713 \n"
16714 BREAK_ARGS_HELP ("trace") "\n\
16715 Do \"help tracepoints\" for info on other tracepoint commands."));
16716   set_cmd_completer (c, location_completer);
16717
16718   add_com_alias ("tp", "trace", class_alias, 0);
16719   add_com_alias ("tr", "trace", class_alias, 1);
16720   add_com_alias ("tra", "trace", class_alias, 1);
16721   add_com_alias ("trac", "trace", class_alias, 1);
16722
16723   c = add_com ("ftrace", class_breakpoint, ftrace_command, _("\
16724 Set a fast tracepoint at specified line or function.\n\
16725 \n"
16726 BREAK_ARGS_HELP ("ftrace") "\n\
16727 Do \"help tracepoints\" for info on other tracepoint commands."));
16728   set_cmd_completer (c, location_completer);
16729
16730   c = add_com ("strace", class_breakpoint, strace_command, _("\
16731 Set a static tracepoint at specified line, function or marker.\n\
16732 \n\
16733 strace [LOCATION] [if CONDITION]\n\
16734 LOCATION may be a line number, function name, \"*\" and an address,\n\
16735 or -m MARKER_ID.\n\
16736 If a line number is specified, probe the marker at start of code\n\
16737 for that line.  If a function is specified, probe the marker at start\n\
16738 of code for that function.  If an address is specified, probe the marker\n\
16739 at that exact address.  If a marker id is specified, probe the marker\n\
16740 with that name.  With no LOCATION, uses current execution address of\n\
16741 the selected stack frame.\n\
16742 Static tracepoints accept an extra collect action -- ``collect $_sdata''.\n\
16743 This collects arbitrary user data passed in the probe point call to the\n\
16744 tracing library.  You can inspect it when analyzing the trace buffer,\n\
16745 by printing the $_sdata variable like any other convenience variable.\n\
16746 \n\
16747 CONDITION is a boolean expression.\n\
16748 \n\
16749 Multiple tracepoints at one place are permitted, and useful if their\n\
16750 conditions are different.\n\
16751 \n\
16752 Do \"help breakpoints\" for info on other commands dealing with breakpoints.\n\
16753 Do \"help tracepoints\" for info on other tracepoint commands."));
16754   set_cmd_completer (c, location_completer);
16755
16756   add_info ("tracepoints", tracepoints_info, _("\
16757 Status of specified tracepoints (all tracepoints if no argument).\n\
16758 Convenience variable \"$tpnum\" contains the number of the\n\
16759 last tracepoint set."));
16760
16761   add_info_alias ("tp", "tracepoints", 1);
16762
16763   add_cmd ("tracepoints", class_trace, delete_trace_command, _("\
16764 Delete specified tracepoints.\n\
16765 Arguments are tracepoint numbers, separated by spaces.\n\
16766 No argument means delete all tracepoints."),
16767            &deletelist);
16768   add_alias_cmd ("tr", "tracepoints", class_trace, 1, &deletelist);
16769
16770   c = add_cmd ("tracepoints", class_trace, disable_trace_command, _("\
16771 Disable specified tracepoints.\n\
16772 Arguments are tracepoint numbers, separated by spaces.\n\
16773 No argument means disable all tracepoints."),
16774            &disablelist);
16775   deprecate_cmd (c, "disable");
16776
16777   c = add_cmd ("tracepoints", class_trace, enable_trace_command, _("\
16778 Enable specified tracepoints.\n\
16779 Arguments are tracepoint numbers, separated by spaces.\n\
16780 No argument means enable all tracepoints."),
16781            &enablelist);
16782   deprecate_cmd (c, "enable");
16783
16784   add_com ("passcount", class_trace, trace_pass_command, _("\
16785 Set the passcount for a tracepoint.\n\
16786 The trace will end when the tracepoint has been passed 'count' times.\n\
16787 Usage: passcount COUNT TPNUM, where TPNUM may also be \"all\";\n\
16788 if TPNUM is omitted, passcount refers to the last tracepoint defined."));
16789
16790   add_prefix_cmd ("save", class_breakpoint, save_command,
16791                   _("Save breakpoint definitions as a script."),
16792                   &save_cmdlist, "save ",
16793                   0/*allow-unknown*/, &cmdlist);
16794
16795   c = add_cmd ("breakpoints", class_breakpoint, save_breakpoints_command, _("\
16796 Save current breakpoint definitions as a script.\n\
16797 This includes all types of breakpoints (breakpoints, watchpoints,\n\
16798 catchpoints, tracepoints).  Use the 'source' command in another debug\n\
16799 session to restore them."),
16800                &save_cmdlist);
16801   set_cmd_completer (c, filename_completer);
16802
16803   c = add_cmd ("tracepoints", class_trace, save_tracepoints_command, _("\
16804 Save current tracepoint definitions as a script.\n\
16805 Use the 'source' command in another debug session to restore them."),
16806                &save_cmdlist);
16807   set_cmd_completer (c, filename_completer);
16808
16809   c = add_com_alias ("save-tracepoints", "save tracepoints", class_trace, 0);
16810   deprecate_cmd (c, "save tracepoints");
16811
16812   add_prefix_cmd ("breakpoint", class_maintenance, set_breakpoint_cmd, _("\
16813 Breakpoint specific settings\n\
16814 Configure various breakpoint-specific variables such as\n\
16815 pending breakpoint behavior"),
16816                   &breakpoint_set_cmdlist, "set breakpoint ",
16817                   0/*allow-unknown*/, &setlist);
16818   add_prefix_cmd ("breakpoint", class_maintenance, show_breakpoint_cmd, _("\
16819 Breakpoint specific settings\n\
16820 Configure various breakpoint-specific variables such as\n\
16821 pending breakpoint behavior"),
16822                   &breakpoint_show_cmdlist, "show breakpoint ",
16823                   0/*allow-unknown*/, &showlist);
16824
16825   add_setshow_auto_boolean_cmd ("pending", no_class,
16826                                 &pending_break_support, _("\
16827 Set debugger's behavior regarding pending breakpoints."), _("\
16828 Show debugger's behavior regarding pending breakpoints."), _("\
16829 If on, an unrecognized breakpoint location will cause gdb to create a\n\
16830 pending breakpoint.  If off, an unrecognized breakpoint location results in\n\
16831 an error.  If auto, an unrecognized breakpoint location results in a\n\
16832 user-query to see if a pending breakpoint should be created."),
16833                                 NULL,
16834                                 show_pending_break_support,
16835                                 &breakpoint_set_cmdlist,
16836                                 &breakpoint_show_cmdlist);
16837
16838   pending_break_support = AUTO_BOOLEAN_AUTO;
16839
16840   add_setshow_boolean_cmd ("auto-hw", no_class,
16841                            &automatic_hardware_breakpoints, _("\
16842 Set automatic usage of hardware breakpoints."), _("\
16843 Show automatic usage of hardware breakpoints."), _("\
16844 If set, the debugger will automatically use hardware breakpoints for\n\
16845 breakpoints set with \"break\" but falling in read-only memory.  If not set,\n\
16846 a warning will be emitted for such breakpoints."),
16847                            NULL,
16848                            show_automatic_hardware_breakpoints,
16849                            &breakpoint_set_cmdlist,
16850                            &breakpoint_show_cmdlist);
16851
16852   add_setshow_boolean_cmd ("always-inserted", class_support,
16853                            &always_inserted_mode, _("\
16854 Set mode for inserting breakpoints."), _("\
16855 Show mode for inserting breakpoints."), _("\
16856 When this mode is on, breakpoints are inserted immediately as soon as\n\
16857 they're created, kept inserted even when execution stops, and removed\n\
16858 only when the user deletes them.  When this mode is off (the default),\n\
16859 breakpoints are inserted only when execution continues, and removed\n\
16860 when execution stops."),
16861                                 NULL,
16862                                 &show_always_inserted_mode,
16863                                 &breakpoint_set_cmdlist,
16864                                 &breakpoint_show_cmdlist);
16865
16866   add_setshow_enum_cmd ("condition-evaluation", class_breakpoint,
16867                         condition_evaluation_enums,
16868                         &condition_evaluation_mode_1, _("\
16869 Set mode of breakpoint condition evaluation."), _("\
16870 Show mode of breakpoint condition evaluation."), _("\
16871 When this is set to \"host\", breakpoint conditions will be\n\
16872 evaluated on the host's side by GDB.  When it is set to \"target\",\n\
16873 breakpoint conditions will be downloaded to the target (if the target\n\
16874 supports such feature) and conditions will be evaluated on the target's side.\n\
16875 If this is set to \"auto\" (default), this will be automatically set to\n\
16876 \"target\" if it supports condition evaluation, otherwise it will\n\
16877 be set to \"gdb\""),
16878                            &set_condition_evaluation_mode,
16879                            &show_condition_evaluation_mode,
16880                            &breakpoint_set_cmdlist,
16881                            &breakpoint_show_cmdlist);
16882
16883   add_com ("break-range", class_breakpoint, break_range_command, _("\
16884 Set a breakpoint for an address range.\n\
16885 break-range START-LOCATION, END-LOCATION\n\
16886 where START-LOCATION and END-LOCATION can be one of the following:\n\
16887   LINENUM, for that line in the current file,\n\
16888   FILE:LINENUM, for that line in that file,\n\
16889   +OFFSET, for that number of lines after the current line\n\
16890            or the start of the range\n\
16891   FUNCTION, for the first line in that function,\n\
16892   FILE:FUNCTION, to distinguish among like-named static functions.\n\
16893   *ADDRESS, for the instruction at that address.\n\
16894 \n\
16895 The breakpoint will stop execution of the inferior whenever it executes\n\
16896 an instruction at any address within the [START-LOCATION, END-LOCATION]\n\
16897 range (including START-LOCATION and END-LOCATION)."));
16898
16899   c = add_com ("dprintf", class_breakpoint, dprintf_command, _("\
16900 Set a dynamic printf at specified line or function.\n\
16901 dprintf location,format string,arg1,arg2,...\n\
16902 location may be a line number, function name, or \"*\" and an address.\n\
16903 If a line number is specified, break at start of code for that line.\n\
16904 If a function is specified, break at start of code for that function."));
16905   set_cmd_completer (c, location_completer);
16906
16907   add_setshow_enum_cmd ("dprintf-style", class_support,
16908                         dprintf_style_enums, &dprintf_style, _("\
16909 Set the style of usage for dynamic printf."), _("\
16910 Show the style of usage for dynamic printf."), _("\
16911 This setting chooses how GDB will do a dynamic printf.\n\
16912 If the value is \"gdb\", then the printing is done by GDB to its own\n\
16913 console, as with the \"printf\" command.\n\
16914 If the value is \"call\", the print is done by calling a function in your\n\
16915 program; by default printf(), but you can choose a different function or\n\
16916 output stream by setting dprintf-function and dprintf-channel."),
16917                         update_dprintf_commands, NULL,
16918                         &setlist, &showlist);
16919
16920   dprintf_function = xstrdup ("printf");
16921   add_setshow_string_cmd ("dprintf-function", class_support,
16922                           &dprintf_function, _("\
16923 Set the function to use for dynamic printf"), _("\
16924 Show the function to use for dynamic printf"), NULL,
16925                           update_dprintf_commands, NULL,
16926                           &setlist, &showlist);
16927
16928   dprintf_channel = xstrdup ("");
16929   add_setshow_string_cmd ("dprintf-channel", class_support,
16930                           &dprintf_channel, _("\
16931 Set the channel to use for dynamic printf"), _("\
16932 Show the channel to use for dynamic printf"), NULL,
16933                           update_dprintf_commands, NULL,
16934                           &setlist, &showlist);
16935
16936   add_setshow_boolean_cmd ("disconnected-dprintf", no_class,
16937                            &disconnected_dprintf, _("\
16938 Set whether dprintf continues after GDB disconnects."), _("\
16939 Show whether dprintf continues after GDB disconnects."), _("\
16940 Use this to let dprintf commands continue to hit and produce output\n\
16941 even if GDB disconnects or detaches from the target."),
16942                            NULL,
16943                            NULL,
16944                            &setlist, &showlist);
16945
16946   add_com ("agent-printf", class_vars, agent_printf_command, _("\
16947 agent-printf \"printf format string\", arg1, arg2, arg3, ..., argn\n\
16948 (target agent only) This is useful for formatted output in user-defined commands."));
16949
16950   automatic_hardware_breakpoints = 1;
16951
16952   observer_attach_about_to_proceed (breakpoint_about_to_proceed);
16953   observer_attach_thread_exit (remove_threaded_breakpoints);
16954 }
This page took 0.968801 seconds and 4 git commands to generate.