2012-03-02 Tom Tromey <tromey@redhat.com>
[external/binutils.git] / gdb / breakpoint.c
1 /* Everything about breakpoints, for GDB.
2
3    Copyright (C) 1986-2012 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 "gdbthread.h"
36 #include "target.h"
37 #include "language.h"
38 #include "gdb_string.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 "gdb_assert.h"
51 #include "block.h"
52 #include "solib.h"
53 #include "solist.h"
54 #include "observer.h"
55 #include "exceptions.h"
56 #include "memattr.h"
57 #include "ada-lang.h"
58 #include "top.h"
59 #include "valprint.h"
60 #include "jit.h"
61 #include "xml-syscall.h"
62 #include "parser-defs.h"
63 #include "cli/cli-utils.h"
64 #include "continuations.h"
65 #include "stack.h"
66 #include "skip.h"
67 #include "record.h"
68 #include "gdb_regex.h"
69 #include "ax-gdb.h"
70
71 /* readline include files */
72 #include "readline/readline.h"
73 #include "readline/history.h"
74
75 /* readline defines this.  */
76 #undef savestring
77
78 #include "mi/mi-common.h"
79 #include "python/python.h"
80
81 /* Prototypes for local functions.  */
82
83 static void enable_delete_command (char *, int);
84
85 static void enable_once_command (char *, int);
86
87 static void enable_count_command (char *, int);
88
89 static void disable_command (char *, int);
90
91 static void enable_command (char *, int);
92
93 static void map_breakpoint_numbers (char *, void (*) (struct breakpoint *,
94                                                       void *),
95                                     void *);
96
97 static void ignore_command (char *, int);
98
99 static int breakpoint_re_set_one (void *);
100
101 static void breakpoint_re_set_default (struct breakpoint *);
102
103 static void create_sals_from_address_default (char **,
104                                               struct linespec_result *,
105                                               enum bptype, char *,
106                                               char **);
107
108 static void create_breakpoints_sal_default (struct gdbarch *,
109                                             struct linespec_result *,
110                                             struct linespec_sals *,
111                                             char *, enum bptype,
112                                             enum bpdisp, int, int,
113                                             int,
114                                             const struct breakpoint_ops *,
115                                             int, int, int);
116
117 static void decode_linespec_default (struct breakpoint *, char **,
118                                      struct symtabs_and_lines *);
119
120 static void clear_command (char *, int);
121
122 static void catch_command (char *, int);
123
124 static int can_use_hardware_watchpoint (struct value *);
125
126 static void break_command_1 (char *, int, int);
127
128 static void mention (struct breakpoint *);
129
130 static struct breakpoint *set_raw_breakpoint_without_location (struct gdbarch *,
131                                                                enum bptype,
132                                                                const struct breakpoint_ops *);
133 static struct bp_location *add_location_to_breakpoint (struct breakpoint *,
134                                                        const struct symtab_and_line *);
135
136 /* This function is used in gdbtk sources and thus can not be made
137    static.  */
138 struct breakpoint *set_raw_breakpoint (struct gdbarch *gdbarch,
139                                        struct symtab_and_line,
140                                        enum bptype,
141                                        const struct breakpoint_ops *);
142
143 static struct breakpoint *
144   momentary_breakpoint_from_master (struct breakpoint *orig,
145                                     enum bptype type,
146                                     const struct breakpoint_ops *ops);
147
148 static void breakpoint_adjustment_warning (CORE_ADDR, CORE_ADDR, int, int);
149
150 static CORE_ADDR adjust_breakpoint_address (struct gdbarch *gdbarch,
151                                             CORE_ADDR bpaddr,
152                                             enum bptype bptype);
153
154 static void describe_other_breakpoints (struct gdbarch *,
155                                         struct program_space *, CORE_ADDR,
156                                         struct obj_section *, int);
157
158 static int breakpoint_address_match (struct address_space *aspace1,
159                                      CORE_ADDR addr1,
160                                      struct address_space *aspace2,
161                                      CORE_ADDR addr2);
162
163 static int watchpoint_locations_match (struct bp_location *loc1,
164                                        struct bp_location *loc2);
165
166 static int breakpoint_location_address_match (struct bp_location *bl,
167                                               struct address_space *aspace,
168                                               CORE_ADDR addr);
169
170 static void breakpoints_info (char *, int);
171
172 static void watchpoints_info (char *, int);
173
174 static int breakpoint_1 (char *, int, 
175                          int (*) (const struct breakpoint *));
176
177 static int breakpoint_cond_eval (void *);
178
179 static void cleanup_executing_breakpoints (void *);
180
181 static void commands_command (char *, int);
182
183 static void condition_command (char *, int);
184
185 typedef enum
186   {
187     mark_inserted,
188     mark_uninserted
189   }
190 insertion_state_t;
191
192 static int remove_breakpoint (struct bp_location *, insertion_state_t);
193 static int remove_breakpoint_1 (struct bp_location *, insertion_state_t);
194
195 static enum print_stop_action print_bp_stop_message (bpstat bs);
196
197 static int watchpoint_check (void *);
198
199 static void maintenance_info_breakpoints (char *, int);
200
201 static int hw_breakpoint_used_count (void);
202
203 static int hw_watchpoint_use_count (struct breakpoint *);
204
205 static int hw_watchpoint_used_count_others (struct breakpoint *except,
206                                             enum bptype type,
207                                             int *other_type_used);
208
209 static void hbreak_command (char *, int);
210
211 static void thbreak_command (char *, int);
212
213 static void enable_breakpoint_disp (struct breakpoint *, enum bpdisp,
214                                     int count);
215
216 static void stop_command (char *arg, int from_tty);
217
218 static void stopin_command (char *arg, int from_tty);
219
220 static void stopat_command (char *arg, int from_tty);
221
222 static char *ep_parse_optional_if_clause (char **arg);
223
224 static void catch_exception_command_1 (enum exception_event_kind ex_event, 
225                                        char *arg, int tempflag, int from_tty);
226
227 static void tcatch_command (char *arg, int from_tty);
228
229 static void detach_single_step_breakpoints (void);
230
231 static int single_step_breakpoint_inserted_here_p (struct address_space *,
232                                                    CORE_ADDR pc);
233
234 static void free_bp_location (struct bp_location *loc);
235 static void incref_bp_location (struct bp_location *loc);
236 static void decref_bp_location (struct bp_location **loc);
237
238 static struct bp_location *allocate_bp_location (struct breakpoint *bpt);
239
240 static void update_global_location_list (int);
241
242 static void update_global_location_list_nothrow (int);
243
244 static int is_hardware_watchpoint (const struct breakpoint *bpt);
245
246 static void insert_breakpoint_locations (void);
247
248 static int syscall_catchpoint_p (struct breakpoint *b);
249
250 static void tracepoints_info (char *, int);
251
252 static void delete_trace_command (char *, int);
253
254 static void enable_trace_command (char *, int);
255
256 static void disable_trace_command (char *, int);
257
258 static void trace_pass_command (char *, int);
259
260 static int is_masked_watchpoint (const struct breakpoint *b);
261
262 static struct bp_location **get_first_locp_gte_addr (CORE_ADDR address);
263
264 /* Return 1 if B refers to a static tracepoint set by marker ("-m"), zero
265    otherwise.  */
266
267 static int strace_marker_p (struct breakpoint *b);
268
269 static void init_catchpoint (struct breakpoint *b,
270                              struct gdbarch *gdbarch, int tempflag,
271                              char *cond_string,
272                              const struct breakpoint_ops *ops);
273
274 /* The abstract base class all breakpoint_ops structures inherit
275    from.  */
276 static struct breakpoint_ops base_breakpoint_ops;
277
278 /* The breakpoint_ops structure to be inherited by all breakpoint_ops
279    that are implemented on top of software or hardware breakpoints
280    (user breakpoints, internal and momentary breakpoints, etc.).  */
281 static struct breakpoint_ops bkpt_base_breakpoint_ops;
282
283 /* Internal breakpoints class type.  */
284 static struct breakpoint_ops internal_breakpoint_ops;
285
286 /* Momentary breakpoints class type.  */
287 static struct breakpoint_ops momentary_breakpoint_ops;
288
289 /* The breakpoint_ops structure to be used in regular user created
290    breakpoints.  */
291 struct breakpoint_ops bkpt_breakpoint_ops;
292
293 /* A reference-counted struct command_line.  This lets multiple
294    breakpoints share a single command list.  */
295 struct counted_command_line
296 {
297   /* The reference count.  */
298   int refc;
299
300   /* The command list.  */
301   struct command_line *commands;
302 };
303
304 struct command_line *
305 breakpoint_commands (struct breakpoint *b)
306 {
307   return b->commands ? b->commands->commands : NULL;
308 }
309
310 /* Flag indicating that a command has proceeded the inferior past the
311    current breakpoint.  */
312
313 static int breakpoint_proceeded;
314
315 const char *
316 bpdisp_text (enum bpdisp disp)
317 {
318   /* NOTE: the following values are a part of MI protocol and
319      represent values of 'disp' field returned when inferior stops at
320      a breakpoint.  */
321   static const char * const bpdisps[] = {"del", "dstp", "dis", "keep"};
322
323   return bpdisps[(int) disp];
324 }
325
326 /* Prototypes for exported functions.  */
327 /* If FALSE, gdb will not use hardware support for watchpoints, even
328    if such is available.  */
329 static int can_use_hw_watchpoints;
330
331 static void
332 show_can_use_hw_watchpoints (struct ui_file *file, int from_tty,
333                              struct cmd_list_element *c,
334                              const char *value)
335 {
336   fprintf_filtered (file,
337                     _("Debugger's willingness to use "
338                       "watchpoint hardware is %s.\n"),
339                     value);
340 }
341
342 /* If AUTO_BOOLEAN_FALSE, gdb will not attempt to create pending breakpoints.
343    If AUTO_BOOLEAN_TRUE, gdb will automatically create pending breakpoints
344    for unrecognized breakpoint locations.
345    If AUTO_BOOLEAN_AUTO, gdb will query when breakpoints are unrecognized.  */
346 static enum auto_boolean pending_break_support;
347 static void
348 show_pending_break_support (struct ui_file *file, int from_tty,
349                             struct cmd_list_element *c,
350                             const char *value)
351 {
352   fprintf_filtered (file,
353                     _("Debugger's behavior regarding "
354                       "pending breakpoints is %s.\n"),
355                     value);
356 }
357
358 /* If 1, gdb will automatically use hardware breakpoints for breakpoints
359    set with "break" but falling in read-only memory.
360    If 0, gdb will warn about such breakpoints, but won't automatically
361    use hardware breakpoints.  */
362 static int automatic_hardware_breakpoints;
363 static void
364 show_automatic_hardware_breakpoints (struct ui_file *file, int from_tty,
365                                      struct cmd_list_element *c,
366                                      const char *value)
367 {
368   fprintf_filtered (file,
369                     _("Automatic usage of hardware breakpoints is %s.\n"),
370                     value);
371 }
372
373 /* If on, gdb will keep breakpoints inserted even as inferior is
374    stopped, and immediately insert any new breakpoints.  If off, gdb
375    will insert breakpoints into inferior only when resuming it, and
376    will remove breakpoints upon stop.  If auto, GDB will behave as ON
377    if in non-stop mode, and as OFF if all-stop mode.*/
378
379 static const char always_inserted_auto[] = "auto";
380 static const char always_inserted_on[] = "on";
381 static const char always_inserted_off[] = "off";
382 static const char *const always_inserted_enums[] = {
383   always_inserted_auto,
384   always_inserted_off,
385   always_inserted_on,
386   NULL
387 };
388 static const char *always_inserted_mode = always_inserted_auto;
389 static void
390 show_always_inserted_mode (struct ui_file *file, int from_tty,
391                      struct cmd_list_element *c, const char *value)
392 {
393   if (always_inserted_mode == always_inserted_auto)
394     fprintf_filtered (file,
395                       _("Always inserted breakpoint "
396                         "mode is %s (currently %s).\n"),
397                       value,
398                       breakpoints_always_inserted_mode () ? "on" : "off");
399   else
400     fprintf_filtered (file, _("Always inserted breakpoint mode is %s.\n"),
401                       value);
402 }
403
404 int
405 breakpoints_always_inserted_mode (void)
406 {
407   return ((always_inserted_mode == always_inserted_on
408            || (always_inserted_mode == always_inserted_auto && non_stop))
409           && !RECORD_IS_USED);
410 }
411
412 static const char condition_evaluation_both[] = "host or target";
413
414 /* Modes for breakpoint condition evaluation.  */
415 static const char condition_evaluation_auto[] = "auto";
416 static const char condition_evaluation_host[] = "host";
417 static const char condition_evaluation_target[] = "target";
418 static const char *const condition_evaluation_enums[] = {
419   condition_evaluation_auto,
420   condition_evaluation_host,
421   condition_evaluation_target,
422   NULL
423 };
424
425 /* Global that holds the current mode for breakpoint condition evaluation.  */
426 static const char *condition_evaluation_mode_1 = condition_evaluation_auto;
427
428 /* Global that we use to display information to the user (gets its value from
429    condition_evaluation_mode_1.  */
430 static const char *condition_evaluation_mode = condition_evaluation_auto;
431
432 /* Translate a condition evaluation mode MODE into either "host"
433    or "target".  This is used mostly to translate from "auto" to the
434    real setting that is being used.  It returns the translated
435    evaluation mode.  */
436
437 static const char *
438 translate_condition_evaluation_mode (const char *mode)
439 {
440   if (mode == condition_evaluation_auto)
441     {
442       if (target_supports_evaluation_of_breakpoint_conditions ())
443         return condition_evaluation_target;
444       else
445         return condition_evaluation_host;
446     }
447   else
448     return mode;
449 }
450
451 /* Discovers what condition_evaluation_auto translates to.  */
452
453 static const char *
454 breakpoint_condition_evaluation_mode (void)
455 {
456   return translate_condition_evaluation_mode (condition_evaluation_mode);
457 }
458
459 /* Return true if GDB should evaluate breakpoint conditions or false
460    otherwise.  */
461
462 static int
463 gdb_evaluates_breakpoint_condition_p (void)
464 {
465   const char *mode = breakpoint_condition_evaluation_mode ();
466
467   return (mode == condition_evaluation_host);
468 }
469
470 void _initialize_breakpoint (void);
471
472 /* Are we executing breakpoint commands?  */
473 static int executing_breakpoint_commands;
474
475 /* Are overlay event breakpoints enabled? */
476 static int overlay_events_enabled;
477
478 /* See description in breakpoint.h. */
479 int target_exact_watchpoints = 0;
480
481 /* Walk the following statement or block through all breakpoints.
482    ALL_BREAKPOINTS_SAFE does so even if the statement deletes the
483    current breakpoint.  */
484
485 #define ALL_BREAKPOINTS(B)  for (B = breakpoint_chain; B; B = B->next)
486
487 #define ALL_BREAKPOINTS_SAFE(B,TMP)     \
488         for (B = breakpoint_chain;      \
489              B ? (TMP=B->next, 1): 0;   \
490              B = TMP)
491
492 /* Similar iterator for the low-level breakpoints.  SAFE variant is
493    not provided so update_global_location_list must not be called
494    while executing the block of ALL_BP_LOCATIONS.  */
495
496 #define ALL_BP_LOCATIONS(B,BP_TMP)                                      \
497         for (BP_TMP = bp_location;                                      \
498              BP_TMP < bp_location + bp_location_count && (B = *BP_TMP); \
499              BP_TMP++)
500
501 /* Iterates through locations with address ADDRESS for the currently selected
502    program space.  BP_LOCP_TMP points to each object.  BP_LOCP_START points
503    to where the loop should start from.
504    If BP_LOCP_START is a NULL pointer, the macro automatically seeks the
505    appropriate location to start with.  */
506
507 #define ALL_BP_LOCATIONS_AT_ADDR(BP_LOCP_TMP, BP_LOCP_START, ADDRESS)   \
508         for (BP_LOCP_START = BP_LOCP_START == NULL ? get_first_locp_gte_addr (ADDRESS) : BP_LOCP_START, \
509              BP_LOCP_TMP = BP_LOCP_START;                               \
510              BP_LOCP_START                                              \
511              && (BP_LOCP_TMP < bp_location + bp_location_count          \
512              && (*BP_LOCP_TMP)->address == ADDRESS);                    \
513              BP_LOCP_TMP++)
514
515 /* Iterator for tracepoints only.  */
516
517 #define ALL_TRACEPOINTS(B)  \
518   for (B = breakpoint_chain; B; B = B->next)  \
519     if (is_tracepoint (B))
520
521 /* Chains of all breakpoints defined.  */
522
523 struct breakpoint *breakpoint_chain;
524
525 /* Array is sorted by bp_location_compare - primarily by the ADDRESS.  */
526
527 static struct bp_location **bp_location;
528
529 /* Number of elements of BP_LOCATION.  */
530
531 static unsigned bp_location_count;
532
533 /* Maximum alignment offset between bp_target_info.PLACED_ADDRESS and
534    ADDRESS for the current elements of BP_LOCATION which get a valid
535    result from bp_location_has_shadow.  You can use it for roughly
536    limiting the subrange of BP_LOCATION to scan for shadow bytes for
537    an address you need to read.  */
538
539 static CORE_ADDR bp_location_placed_address_before_address_max;
540
541 /* Maximum offset plus alignment between bp_target_info.PLACED_ADDRESS
542    + bp_target_info.SHADOW_LEN and ADDRESS for the current elements of
543    BP_LOCATION which get a valid result from bp_location_has_shadow.
544    You can use it for roughly limiting the subrange of BP_LOCATION to
545    scan for shadow bytes for an address you need to read.  */
546
547 static CORE_ADDR bp_location_shadow_len_after_address_max;
548
549 /* The locations that no longer correspond to any breakpoint, unlinked
550    from bp_location array, but for which a hit may still be reported
551    by a target.  */
552 VEC(bp_location_p) *moribund_locations = NULL;
553
554 /* Number of last breakpoint made.  */
555
556 static int breakpoint_count;
557
558 /* The value of `breakpoint_count' before the last command that
559    created breakpoints.  If the last (break-like) command created more
560    than one breakpoint, then the difference between BREAKPOINT_COUNT
561    and PREV_BREAKPOINT_COUNT is more than one.  */
562 static int prev_breakpoint_count;
563
564 /* Number of last tracepoint made.  */
565
566 static int tracepoint_count;
567
568 static struct cmd_list_element *breakpoint_set_cmdlist;
569 static struct cmd_list_element *breakpoint_show_cmdlist;
570 struct cmd_list_element *save_cmdlist;
571
572 /* Return whether a breakpoint is an active enabled breakpoint.  */
573 static int
574 breakpoint_enabled (struct breakpoint *b)
575 {
576   return (b->enable_state == bp_enabled);
577 }
578
579 /* Set breakpoint count to NUM.  */
580
581 static void
582 set_breakpoint_count (int num)
583 {
584   prev_breakpoint_count = breakpoint_count;
585   breakpoint_count = num;
586   set_internalvar_integer (lookup_internalvar ("bpnum"), num);
587 }
588
589 /* Used by `start_rbreak_breakpoints' below, to record the current
590    breakpoint count before "rbreak" creates any breakpoint.  */
591 static int rbreak_start_breakpoint_count;
592
593 /* Called at the start an "rbreak" command to record the first
594    breakpoint made.  */
595
596 void
597 start_rbreak_breakpoints (void)
598 {
599   rbreak_start_breakpoint_count = breakpoint_count;
600 }
601
602 /* Called at the end of an "rbreak" command to record the last
603    breakpoint made.  */
604
605 void
606 end_rbreak_breakpoints (void)
607 {
608   prev_breakpoint_count = rbreak_start_breakpoint_count;
609 }
610
611 /* Used in run_command to zero the hit count when a new run starts.  */
612
613 void
614 clear_breakpoint_hit_counts (void)
615 {
616   struct breakpoint *b;
617
618   ALL_BREAKPOINTS (b)
619     b->hit_count = 0;
620 }
621
622 /* Allocate a new counted_command_line with reference count of 1.
623    The new structure owns COMMANDS.  */
624
625 static struct counted_command_line *
626 alloc_counted_command_line (struct command_line *commands)
627 {
628   struct counted_command_line *result
629     = xmalloc (sizeof (struct counted_command_line));
630
631   result->refc = 1;
632   result->commands = commands;
633   return result;
634 }
635
636 /* Increment reference count.  This does nothing if CMD is NULL.  */
637
638 static void
639 incref_counted_command_line (struct counted_command_line *cmd)
640 {
641   if (cmd)
642     ++cmd->refc;
643 }
644
645 /* Decrement reference count.  If the reference count reaches 0,
646    destroy the counted_command_line.  Sets *CMDP to NULL.  This does
647    nothing if *CMDP is NULL.  */
648
649 static void
650 decref_counted_command_line (struct counted_command_line **cmdp)
651 {
652   if (*cmdp)
653     {
654       if (--(*cmdp)->refc == 0)
655         {
656           free_command_lines (&(*cmdp)->commands);
657           xfree (*cmdp);
658         }
659       *cmdp = NULL;
660     }
661 }
662
663 /* A cleanup function that calls decref_counted_command_line.  */
664
665 static void
666 do_cleanup_counted_command_line (void *arg)
667 {
668   decref_counted_command_line (arg);
669 }
670
671 /* Create a cleanup that calls decref_counted_command_line on the
672    argument.  */
673
674 static struct cleanup *
675 make_cleanup_decref_counted_command_line (struct counted_command_line **cmdp)
676 {
677   return make_cleanup (do_cleanup_counted_command_line, cmdp);
678 }
679
680 \f
681 /* Return the breakpoint with the specified number, or NULL
682    if the number does not refer to an existing breakpoint.  */
683
684 struct breakpoint *
685 get_breakpoint (int num)
686 {
687   struct breakpoint *b;
688
689   ALL_BREAKPOINTS (b)
690     if (b->number == num)
691       return b;
692   
693   return NULL;
694 }
695
696 \f
697
698 /* Mark locations as "conditions have changed" in case the target supports
699    evaluating conditions on its side.  */
700
701 static void
702 mark_breakpoint_modified (struct breakpoint *b)
703 {
704   struct bp_location *loc;
705
706   /* This is only meaningful if the target is
707      evaluating conditions and if the user has
708      opted for condition evaluation on the target's
709      side.  */
710   if (gdb_evaluates_breakpoint_condition_p ()
711       || !target_supports_evaluation_of_breakpoint_conditions ())
712     return;
713
714   if (!is_breakpoint (b))
715     return;
716
717   for (loc = b->loc; loc; loc = loc->next)
718     loc->condition_changed = condition_modified;
719 }
720
721 /* Mark location as "conditions have changed" in case the target supports
722    evaluating conditions on its side.  */
723
724 static void
725 mark_breakpoint_location_modified (struct bp_location *loc)
726 {
727   /* This is only meaningful if the target is
728      evaluating conditions and if the user has
729      opted for condition evaluation on the target's
730      side.  */
731   if (gdb_evaluates_breakpoint_condition_p ()
732       || !target_supports_evaluation_of_breakpoint_conditions ())
733
734     return;
735
736   if (!is_breakpoint (loc->owner))
737     return;
738
739   loc->condition_changed = condition_modified;
740 }
741
742 /* Sets the condition-evaluation mode using the static global
743    condition_evaluation_mode.  */
744
745 static void
746 set_condition_evaluation_mode (char *args, int from_tty,
747                                struct cmd_list_element *c)
748 {
749   struct breakpoint *b;
750   const char *old_mode, *new_mode;
751
752   if ((condition_evaluation_mode_1 == condition_evaluation_target)
753       && !target_supports_evaluation_of_breakpoint_conditions ())
754     {
755       condition_evaluation_mode_1 = condition_evaluation_mode;
756       warning (_("Target does not support breakpoint condition evaluation.\n"
757                  "Using host evaluation mode instead."));
758       return;
759     }
760
761   new_mode = translate_condition_evaluation_mode (condition_evaluation_mode_1);
762   old_mode = translate_condition_evaluation_mode (condition_evaluation_mode);
763
764   /* Only update the mode if the user picked a different one.  */
765   if (new_mode != old_mode)
766     {
767       struct bp_location *loc, **loc_tmp;
768       /* If the user switched to a different evaluation mode, we
769          need to synch the changes with the target as follows:
770
771          "host" -> "target": Send all (valid) conditions to the target.
772          "target" -> "host": Remove all the conditions from the target.
773       */
774
775       /* Flip the switch.  */
776       condition_evaluation_mode = condition_evaluation_mode_1;
777
778       if (new_mode == condition_evaluation_target)
779         {
780           /* Mark everything modified and synch conditions with the
781              target.  */
782           ALL_BP_LOCATIONS (loc, loc_tmp)
783             mark_breakpoint_location_modified (loc);
784         }
785       else
786         {
787           /* Manually mark non-duplicate locations to synch conditions
788              with the target.  We do this to remove all the conditions the
789              target knows about.  */
790           ALL_BP_LOCATIONS (loc, loc_tmp)
791             if (is_breakpoint (loc->owner) && loc->inserted)
792               loc->needs_update = 1;
793         }
794
795       /* Do the update.  */
796       update_global_location_list (1);
797     }
798
799   return;
800 }
801
802 /* Shows the current mode of breakpoint condition evaluation.  Explicitly shows
803    what "auto" is translating to.  */
804
805 static void
806 show_condition_evaluation_mode (struct ui_file *file, int from_tty,
807                                 struct cmd_list_element *c, const char *value)
808 {
809   if (condition_evaluation_mode == condition_evaluation_auto)
810     fprintf_filtered (file,
811                       _("Breakpoint condition evaluation "
812                         "mode is %s (currently %s).\n"),
813                       value,
814                       breakpoint_condition_evaluation_mode ());
815   else
816     fprintf_filtered (file, _("Breakpoint condition evaluation mode is %s.\n"),
817                       value);
818 }
819
820 /* A comparison function for bp_location AP and BP that is used by
821    bsearch.  This comparison function only cares about addresses, unlike
822    the more general bp_location_compare function.  */
823
824 static int
825 bp_location_compare_addrs (const void *ap, const void *bp)
826 {
827   struct bp_location *a = *(void **) ap;
828   struct bp_location *b = *(void **) bp;
829
830   if (a->address == b->address)
831     return 0;
832   else
833     return ((a->address > b->address) - (a->address < b->address));
834 }
835
836 /* Helper function to skip all bp_locations with addresses
837    less than ADDRESS.  It returns the first bp_location that
838    is greater than or equal to ADDRESS.  If none is found, just
839    return NULL.  */
840
841 static struct bp_location **
842 get_first_locp_gte_addr (CORE_ADDR address)
843 {
844   struct bp_location dummy_loc;
845   struct bp_location *dummy_locp = &dummy_loc;
846   struct bp_location **locp_found = NULL;
847
848   /* Initialize the dummy location's address field.  */
849   memset (&dummy_loc, 0, sizeof (struct bp_location));
850   dummy_loc.address = address;
851
852   /* Find a close match to the first location at ADDRESS.  */
853   locp_found = bsearch (&dummy_locp, bp_location, bp_location_count,
854                         sizeof (struct bp_location **),
855                         bp_location_compare_addrs);
856
857   /* Nothing was found, nothing left to do.  */
858   if (locp_found == NULL)
859     return NULL;
860
861   /* We may have found a location that is at ADDRESS but is not the first in the
862      location's list.  Go backwards (if possible) and locate the first one.  */
863   while ((locp_found - 1) >= bp_location
864          && (*(locp_found - 1))->address == address)
865     locp_found--;
866
867   return locp_found;
868 }
869
870 void
871 set_breakpoint_condition (struct breakpoint *b, char *exp,
872                           int from_tty)
873 {
874   xfree (b->cond_string);
875   b->cond_string = NULL;
876
877   if (is_watchpoint (b))
878     {
879       struct watchpoint *w = (struct watchpoint *) b;
880
881       xfree (w->cond_exp);
882       w->cond_exp = NULL;
883     }
884   else
885     {
886       struct bp_location *loc;
887
888       for (loc = b->loc; loc; loc = loc->next)
889         {
890           xfree (loc->cond);
891           loc->cond = NULL;
892
893           /* No need to free the condition agent expression
894              bytecode (if we have one).  We will handle this
895              when we go through update_global_location_list.  */
896         }
897     }
898
899   if (*exp == 0)
900     {
901       if (from_tty)
902         printf_filtered (_("Breakpoint %d now unconditional.\n"), b->number);
903     }
904   else
905     {
906       char *arg = exp;
907
908       /* I don't know if it matters whether this is the string the user
909          typed in or the decompiled expression.  */
910       b->cond_string = xstrdup (arg);
911       b->condition_not_parsed = 0;
912
913       if (is_watchpoint (b))
914         {
915           struct watchpoint *w = (struct watchpoint *) b;
916
917           innermost_block = NULL;
918           arg = exp;
919           w->cond_exp = parse_exp_1 (&arg, 0, 0);
920           if (*arg)
921             error (_("Junk at end of expression"));
922           w->cond_exp_valid_block = innermost_block;
923         }
924       else
925         {
926           struct bp_location *loc;
927
928           for (loc = b->loc; loc; loc = loc->next)
929             {
930               arg = exp;
931               loc->cond =
932                 parse_exp_1 (&arg, block_for_pc (loc->address), 0);
933               if (*arg)
934                 error (_("Junk at end of expression"));
935             }
936         }
937     }
938   mark_breakpoint_modified (b);
939
940   breakpoints_changed ();
941   observer_notify_breakpoint_modified (b);
942 }
943
944 /* condition N EXP -- set break condition of breakpoint N to EXP.  */
945
946 static void
947 condition_command (char *arg, int from_tty)
948 {
949   struct breakpoint *b;
950   char *p;
951   int bnum;
952
953   if (arg == 0)
954     error_no_arg (_("breakpoint number"));
955
956   p = arg;
957   bnum = get_number (&p);
958   if (bnum == 0)
959     error (_("Bad breakpoint argument: '%s'"), arg);
960
961   ALL_BREAKPOINTS (b)
962     if (b->number == bnum)
963       {
964         /* Check if this breakpoint has a Python object assigned to
965            it, and if it has a definition of the "stop"
966            method.  This method and conditions entered into GDB from
967            the CLI are mutually exclusive.  */
968         if (b->py_bp_object
969             && gdbpy_breakpoint_has_py_cond (b->py_bp_object))
970           error (_("Cannot set a condition where a Python 'stop' "
971                    "method has been defined in the breakpoint."));
972         set_breakpoint_condition (b, p, from_tty);
973
974         if (is_breakpoint (b))
975           update_global_location_list (1);
976
977         return;
978       }
979
980   error (_("No breakpoint number %d."), bnum);
981 }
982
983 /* Check that COMMAND do not contain commands that are suitable
984    only for tracepoints and not suitable for ordinary breakpoints.
985    Throw if any such commands is found.  */
986
987 static void
988 check_no_tracepoint_commands (struct command_line *commands)
989 {
990   struct command_line *c;
991
992   for (c = commands; c; c = c->next)
993     {
994       int i;
995
996       if (c->control_type == while_stepping_control)
997         error (_("The 'while-stepping' command can "
998                  "only be used for tracepoints"));
999
1000       for (i = 0; i < c->body_count; ++i)
1001         check_no_tracepoint_commands ((c->body_list)[i]);
1002
1003       /* Not that command parsing removes leading whitespace and comment
1004          lines and also empty lines.  So, we only need to check for
1005          command directly.  */
1006       if (strstr (c->line, "collect ") == c->line)
1007         error (_("The 'collect' command can only be used for tracepoints"));
1008
1009       if (strstr (c->line, "teval ") == c->line)
1010         error (_("The 'teval' command can only be used for tracepoints"));
1011     }
1012 }
1013
1014 /* Encapsulate tests for different types of tracepoints.  */
1015
1016 static int
1017 is_tracepoint_type (enum bptype type)
1018 {
1019   return (type == bp_tracepoint
1020           || type == bp_fast_tracepoint
1021           || type == bp_static_tracepoint);
1022 }
1023
1024 int
1025 is_tracepoint (const struct breakpoint *b)
1026 {
1027   return is_tracepoint_type (b->type);
1028 }
1029
1030 /* A helper function that validates that COMMANDS are valid for a
1031    breakpoint.  This function will throw an exception if a problem is
1032    found.  */
1033
1034 static void
1035 validate_commands_for_breakpoint (struct breakpoint *b,
1036                                   struct command_line *commands)
1037 {
1038   if (is_tracepoint (b))
1039     {
1040       /* We need to verify that each top-level element of commands is
1041          valid for tracepoints, that there's at most one
1042          while-stepping element, and that while-stepping's body has
1043          valid tracing commands excluding nested while-stepping.  */
1044       struct command_line *c;
1045       struct command_line *while_stepping = 0;
1046       for (c = commands; c; c = c->next)
1047         {
1048           if (c->control_type == while_stepping_control)
1049             {
1050               if (b->type == bp_fast_tracepoint)
1051                 error (_("The 'while-stepping' command "
1052                          "cannot be used for fast tracepoint"));
1053               else if (b->type == bp_static_tracepoint)
1054                 error (_("The 'while-stepping' command "
1055                          "cannot be used for static tracepoint"));
1056
1057               if (while_stepping)
1058                 error (_("The 'while-stepping' command "
1059                          "can be used only once"));
1060               else
1061                 while_stepping = c;
1062             }
1063         }
1064       if (while_stepping)
1065         {
1066           struct command_line *c2;
1067
1068           gdb_assert (while_stepping->body_count == 1);
1069           c2 = while_stepping->body_list[0];
1070           for (; c2; c2 = c2->next)
1071             {
1072               if (c2->control_type == while_stepping_control)
1073                 error (_("The 'while-stepping' command cannot be nested"));
1074             }
1075         }
1076     }
1077   else
1078     {
1079       check_no_tracepoint_commands (commands);
1080     }
1081 }
1082
1083 /* Return a vector of all the static tracepoints set at ADDR.  The
1084    caller is responsible for releasing the vector.  */
1085
1086 VEC(breakpoint_p) *
1087 static_tracepoints_here (CORE_ADDR addr)
1088 {
1089   struct breakpoint *b;
1090   VEC(breakpoint_p) *found = 0;
1091   struct bp_location *loc;
1092
1093   ALL_BREAKPOINTS (b)
1094     if (b->type == bp_static_tracepoint)
1095       {
1096         for (loc = b->loc; loc; loc = loc->next)
1097           if (loc->address == addr)
1098             VEC_safe_push(breakpoint_p, found, b);
1099       }
1100
1101   return found;
1102 }
1103
1104 /* Set the command list of B to COMMANDS.  If breakpoint is tracepoint,
1105    validate that only allowed commands are included.  */
1106
1107 void
1108 breakpoint_set_commands (struct breakpoint *b, 
1109                          struct command_line *commands)
1110 {
1111   validate_commands_for_breakpoint (b, commands);
1112
1113   decref_counted_command_line (&b->commands);
1114   b->commands = alloc_counted_command_line (commands);
1115   breakpoints_changed ();
1116   observer_notify_breakpoint_modified (b);
1117 }
1118
1119 /* Set the internal `silent' flag on the breakpoint.  Note that this
1120    is not the same as the "silent" that may appear in the breakpoint's
1121    commands.  */
1122
1123 void
1124 breakpoint_set_silent (struct breakpoint *b, int silent)
1125 {
1126   int old_silent = b->silent;
1127
1128   b->silent = silent;
1129   if (old_silent != silent)
1130     observer_notify_breakpoint_modified (b);
1131 }
1132
1133 /* Set the thread for this breakpoint.  If THREAD is -1, make the
1134    breakpoint work for any thread.  */
1135
1136 void
1137 breakpoint_set_thread (struct breakpoint *b, int thread)
1138 {
1139   int old_thread = b->thread;
1140
1141   b->thread = thread;
1142   if (old_thread != thread)
1143     observer_notify_breakpoint_modified (b);
1144 }
1145
1146 /* Set the task for this breakpoint.  If TASK is 0, make the
1147    breakpoint work for any task.  */
1148
1149 void
1150 breakpoint_set_task (struct breakpoint *b, int task)
1151 {
1152   int old_task = b->task;
1153
1154   b->task = task;
1155   if (old_task != task)
1156     observer_notify_breakpoint_modified (b);
1157 }
1158
1159 void
1160 check_tracepoint_command (char *line, void *closure)
1161 {
1162   struct breakpoint *b = closure;
1163
1164   validate_actionline (&line, b);
1165 }
1166
1167 /* A structure used to pass information through
1168    map_breakpoint_numbers.  */
1169
1170 struct commands_info
1171 {
1172   /* True if the command was typed at a tty.  */
1173   int from_tty;
1174
1175   /* The breakpoint range spec.  */
1176   char *arg;
1177
1178   /* Non-NULL if the body of the commands are being read from this
1179      already-parsed command.  */
1180   struct command_line *control;
1181
1182   /* The command lines read from the user, or NULL if they have not
1183      yet been read.  */
1184   struct counted_command_line *cmd;
1185 };
1186
1187 /* A callback for map_breakpoint_numbers that sets the commands for
1188    commands_command.  */
1189
1190 static void
1191 do_map_commands_command (struct breakpoint *b, void *data)
1192 {
1193   struct commands_info *info = data;
1194
1195   if (info->cmd == NULL)
1196     {
1197       struct command_line *l;
1198
1199       if (info->control != NULL)
1200         l = copy_command_lines (info->control->body_list[0]);
1201       else
1202         {
1203           struct cleanup *old_chain;
1204           char *str;
1205
1206           str = xstrprintf (_("Type commands for breakpoint(s) "
1207                               "%s, one per line."),
1208                             info->arg);
1209
1210           old_chain = make_cleanup (xfree, str);
1211
1212           l = read_command_lines (str,
1213                                   info->from_tty, 1,
1214                                   (is_tracepoint (b)
1215                                    ? check_tracepoint_command : 0),
1216                                   b);
1217
1218           do_cleanups (old_chain);
1219         }
1220
1221       info->cmd = alloc_counted_command_line (l);
1222     }
1223
1224   /* If a breakpoint was on the list more than once, we don't need to
1225      do anything.  */
1226   if (b->commands != info->cmd)
1227     {
1228       validate_commands_for_breakpoint (b, info->cmd->commands);
1229       incref_counted_command_line (info->cmd);
1230       decref_counted_command_line (&b->commands);
1231       b->commands = info->cmd;
1232       breakpoints_changed ();
1233       observer_notify_breakpoint_modified (b);
1234     }
1235 }
1236
1237 static void
1238 commands_command_1 (char *arg, int from_tty, 
1239                     struct command_line *control)
1240 {
1241   struct cleanup *cleanups;
1242   struct commands_info info;
1243
1244   info.from_tty = from_tty;
1245   info.control = control;
1246   info.cmd = NULL;
1247   /* If we read command lines from the user, then `info' will hold an
1248      extra reference to the commands that we must clean up.  */
1249   cleanups = make_cleanup_decref_counted_command_line (&info.cmd);
1250
1251   if (arg == NULL || !*arg)
1252     {
1253       if (breakpoint_count - prev_breakpoint_count > 1)
1254         arg = xstrprintf ("%d-%d", prev_breakpoint_count + 1, 
1255                           breakpoint_count);
1256       else if (breakpoint_count > 0)
1257         arg = xstrprintf ("%d", breakpoint_count);
1258       else
1259         {
1260           /* So that we don't try to free the incoming non-NULL
1261              argument in the cleanup below.  Mapping breakpoint
1262              numbers will fail in this case.  */
1263           arg = NULL;
1264         }
1265     }
1266   else
1267     /* The command loop has some static state, so we need to preserve
1268        our argument.  */
1269     arg = xstrdup (arg);
1270
1271   if (arg != NULL)
1272     make_cleanup (xfree, arg);
1273
1274   info.arg = arg;
1275
1276   map_breakpoint_numbers (arg, do_map_commands_command, &info);
1277
1278   if (info.cmd == NULL)
1279     error (_("No breakpoints specified."));
1280
1281   do_cleanups (cleanups);
1282 }
1283
1284 static void
1285 commands_command (char *arg, int from_tty)
1286 {
1287   commands_command_1 (arg, from_tty, NULL);
1288 }
1289
1290 /* Like commands_command, but instead of reading the commands from
1291    input stream, takes them from an already parsed command structure.
1292
1293    This is used by cli-script.c to DTRT with breakpoint commands
1294    that are part of if and while bodies.  */
1295 enum command_control_type
1296 commands_from_control_command (char *arg, struct command_line *cmd)
1297 {
1298   commands_command_1 (arg, 0, cmd);
1299   return simple_control;
1300 }
1301
1302 /* Return non-zero if BL->TARGET_INFO contains valid information.  */
1303
1304 static int
1305 bp_location_has_shadow (struct bp_location *bl)
1306 {
1307   if (bl->loc_type != bp_loc_software_breakpoint)
1308     return 0;
1309   if (!bl->inserted)
1310     return 0;
1311   if (bl->target_info.shadow_len == 0)
1312     /* BL isn't valid, or doesn't shadow memory.  */
1313     return 0;
1314   return 1;
1315 }
1316
1317 /* Update BUF, which is LEN bytes read from the target address MEMADDR,
1318    by replacing any memory breakpoints with their shadowed contents.
1319
1320    The range of shadowed area by each bp_location is:
1321      bl->address - bp_location_placed_address_before_address_max
1322      up to bl->address + bp_location_shadow_len_after_address_max
1323    The range we were requested to resolve shadows for is:
1324      memaddr ... memaddr + len
1325    Thus the safe cutoff boundaries for performance optimization are
1326      memaddr + len <= (bl->address
1327                        - bp_location_placed_address_before_address_max)
1328    and:
1329      bl->address + bp_location_shadow_len_after_address_max <= memaddr  */
1330
1331 void
1332 breakpoint_xfer_memory (gdb_byte *readbuf, gdb_byte *writebuf,
1333                         const gdb_byte *writebuf_org,
1334                         ULONGEST memaddr, LONGEST len)
1335 {
1336   /* Left boundary, right boundary and median element of our binary
1337      search.  */
1338   unsigned bc_l, bc_r, bc;
1339
1340   /* Find BC_L which is a leftmost element which may affect BUF
1341      content.  It is safe to report lower value but a failure to
1342      report higher one.  */
1343
1344   bc_l = 0;
1345   bc_r = bp_location_count;
1346   while (bc_l + 1 < bc_r)
1347     {
1348       struct bp_location *bl;
1349
1350       bc = (bc_l + bc_r) / 2;
1351       bl = bp_location[bc];
1352
1353       /* Check first BL->ADDRESS will not overflow due to the added
1354          constant.  Then advance the left boundary only if we are sure
1355          the BC element can in no way affect the BUF content (MEMADDR
1356          to MEMADDR + LEN range).
1357
1358          Use the BP_LOCATION_SHADOW_LEN_AFTER_ADDRESS_MAX safety
1359          offset so that we cannot miss a breakpoint with its shadow
1360          range tail still reaching MEMADDR.  */
1361
1362       if ((bl->address + bp_location_shadow_len_after_address_max
1363            >= bl->address)
1364           && (bl->address + bp_location_shadow_len_after_address_max
1365               <= memaddr))
1366         bc_l = bc;
1367       else
1368         bc_r = bc;
1369     }
1370
1371   /* Due to the binary search above, we need to make sure we pick the
1372      first location that's at BC_L's address.  E.g., if there are
1373      multiple locations at the same address, BC_L may end up pointing
1374      at a duplicate location, and miss the "master"/"inserted"
1375      location.  Say, given locations L1, L2 and L3 at addresses A and
1376      B:
1377
1378       L1@A, L2@A, L3@B, ...
1379
1380      BC_L could end up pointing at location L2, while the "master"
1381      location could be L1.  Since the `loc->inserted' flag is only set
1382      on "master" locations, we'd forget to restore the shadow of L1
1383      and L2.  */
1384   while (bc_l > 0
1385          && bp_location[bc_l]->address == bp_location[bc_l - 1]->address)
1386     bc_l--;
1387
1388   /* Now do full processing of the found relevant range of elements.  */
1389
1390   for (bc = bc_l; bc < bp_location_count; bc++)
1391   {
1392     struct bp_location *bl = bp_location[bc];
1393     CORE_ADDR bp_addr = 0;
1394     int bp_size = 0;
1395     int bptoffset = 0;
1396
1397     /* bp_location array has BL->OWNER always non-NULL.  */
1398     if (bl->owner->type == bp_none)
1399       warning (_("reading through apparently deleted breakpoint #%d?"),
1400                bl->owner->number);
1401
1402     /* Performance optimization: any further element can no longer affect BUF
1403        content.  */
1404
1405     if (bl->address >= bp_location_placed_address_before_address_max
1406         && memaddr + len <= (bl->address
1407                              - bp_location_placed_address_before_address_max))
1408       break;
1409
1410     if (!bp_location_has_shadow (bl))
1411       continue;
1412     if (!breakpoint_address_match (bl->target_info.placed_address_space, 0,
1413                                    current_program_space->aspace, 0))
1414       continue;
1415
1416     /* Addresses and length of the part of the breakpoint that
1417        we need to copy.  */
1418     bp_addr = bl->target_info.placed_address;
1419     bp_size = bl->target_info.shadow_len;
1420
1421     if (bp_addr + bp_size <= memaddr)
1422       /* The breakpoint is entirely before the chunk of memory we
1423          are reading.  */
1424       continue;
1425
1426     if (bp_addr >= memaddr + len)
1427       /* The breakpoint is entirely after the chunk of memory we are
1428          reading.  */
1429       continue;
1430
1431     /* Offset within shadow_contents.  */
1432     if (bp_addr < memaddr)
1433       {
1434         /* Only copy the second part of the breakpoint.  */
1435         bp_size -= memaddr - bp_addr;
1436         bptoffset = memaddr - bp_addr;
1437         bp_addr = memaddr;
1438       }
1439
1440     if (bp_addr + bp_size > memaddr + len)
1441       {
1442         /* Only copy the first part of the breakpoint.  */
1443         bp_size -= (bp_addr + bp_size) - (memaddr + len);
1444       }
1445
1446     if (readbuf != NULL)
1447       {
1448         /* Update the read buffer with this inserted breakpoint's
1449            shadow.  */
1450         memcpy (readbuf + bp_addr - memaddr,
1451                 bl->target_info.shadow_contents + bptoffset, bp_size);
1452       }
1453     else
1454       {
1455         struct gdbarch *gdbarch = bl->gdbarch;
1456         const unsigned char *bp;
1457         CORE_ADDR placed_address = bl->target_info.placed_address;
1458         unsigned placed_size = bl->target_info.placed_size;
1459
1460         /* Update the shadow with what we want to write to memory.  */
1461         memcpy (bl->target_info.shadow_contents + bptoffset,
1462                 writebuf_org + bp_addr - memaddr, bp_size);
1463
1464         /* Determine appropriate breakpoint contents and size for this
1465            address.  */
1466         bp = gdbarch_breakpoint_from_pc (gdbarch, &placed_address, &placed_size);
1467
1468         /* Update the final write buffer with this inserted
1469            breakpoint's INSN.  */
1470         memcpy (writebuf + bp_addr - memaddr, bp + bptoffset, bp_size);
1471       }
1472   }
1473 }
1474 \f
1475
1476 /* Return true if BPT is either a software breakpoint or a hardware
1477    breakpoint.  */
1478
1479 int
1480 is_breakpoint (const struct breakpoint *bpt)
1481 {
1482   return (bpt->type == bp_breakpoint
1483           || bpt->type == bp_hardware_breakpoint);
1484 }
1485
1486 /* Return true if BPT is of any hardware watchpoint kind.  */
1487
1488 static int
1489 is_hardware_watchpoint (const struct breakpoint *bpt)
1490 {
1491   return (bpt->type == bp_hardware_watchpoint
1492           || bpt->type == bp_read_watchpoint
1493           || bpt->type == bp_access_watchpoint);
1494 }
1495
1496 /* Return true if BPT is of any watchpoint kind, hardware or
1497    software.  */
1498
1499 int
1500 is_watchpoint (const struct breakpoint *bpt)
1501 {
1502   return (is_hardware_watchpoint (bpt)
1503           || bpt->type == bp_watchpoint);
1504 }
1505
1506 /* Returns true if the current thread and its running state are safe
1507    to evaluate or update watchpoint B.  Watchpoints on local
1508    expressions need to be evaluated in the context of the thread that
1509    was current when the watchpoint was created, and, that thread needs
1510    to be stopped to be able to select the correct frame context.
1511    Watchpoints on global expressions can be evaluated on any thread,
1512    and in any state.  It is presently left to the target allowing
1513    memory accesses when threads are running.  */
1514
1515 static int
1516 watchpoint_in_thread_scope (struct watchpoint *b)
1517 {
1518   return (b->base.pspace == current_program_space
1519           && (ptid_equal (b->watchpoint_thread, null_ptid)
1520               || (ptid_equal (inferior_ptid, b->watchpoint_thread)
1521                   && !is_executing (inferior_ptid))));
1522 }
1523
1524 /* Set watchpoint B to disp_del_at_next_stop, even including its possible
1525    associated bp_watchpoint_scope breakpoint.  */
1526
1527 static void
1528 watchpoint_del_at_next_stop (struct watchpoint *w)
1529 {
1530   struct breakpoint *b = &w->base;
1531
1532   if (b->related_breakpoint != b)
1533     {
1534       gdb_assert (b->related_breakpoint->type == bp_watchpoint_scope);
1535       gdb_assert (b->related_breakpoint->related_breakpoint == b);
1536       b->related_breakpoint->disposition = disp_del_at_next_stop;
1537       b->related_breakpoint->related_breakpoint = b->related_breakpoint;
1538       b->related_breakpoint = b;
1539     }
1540   b->disposition = disp_del_at_next_stop;
1541 }
1542
1543 /* Assuming that B is a watchpoint:
1544    - Reparse watchpoint expression, if REPARSE is non-zero
1545    - Evaluate expression and store the result in B->val
1546    - Evaluate the condition if there is one, and store the result
1547      in b->loc->cond.
1548    - Update the list of values that must be watched in B->loc.
1549
1550    If the watchpoint disposition is disp_del_at_next_stop, then do
1551    nothing.  If this is local watchpoint that is out of scope, delete
1552    it.
1553
1554    Even with `set breakpoint always-inserted on' the watchpoints are
1555    removed + inserted on each stop here.  Normal breakpoints must
1556    never be removed because they might be missed by a running thread
1557    when debugging in non-stop mode.  On the other hand, hardware
1558    watchpoints (is_hardware_watchpoint; processed here) are specific
1559    to each LWP since they are stored in each LWP's hardware debug
1560    registers.  Therefore, such LWP must be stopped first in order to
1561    be able to modify its hardware watchpoints.
1562
1563    Hardware watchpoints must be reset exactly once after being
1564    presented to the user.  It cannot be done sooner, because it would
1565    reset the data used to present the watchpoint hit to the user.  And
1566    it must not be done later because it could display the same single
1567    watchpoint hit during multiple GDB stops.  Note that the latter is
1568    relevant only to the hardware watchpoint types bp_read_watchpoint
1569    and bp_access_watchpoint.  False hit by bp_hardware_watchpoint is
1570    not user-visible - its hit is suppressed if the memory content has
1571    not changed.
1572
1573    The following constraints influence the location where we can reset
1574    hardware watchpoints:
1575
1576    * target_stopped_by_watchpoint and target_stopped_data_address are
1577      called several times when GDB stops.
1578
1579    [linux] 
1580    * Multiple hardware watchpoints can be hit at the same time,
1581      causing GDB to stop.  GDB only presents one hardware watchpoint
1582      hit at a time as the reason for stopping, and all the other hits
1583      are presented later, one after the other, each time the user
1584      requests the execution to be resumed.  Execution is not resumed
1585      for the threads still having pending hit event stored in
1586      LWP_INFO->STATUS.  While the watchpoint is already removed from
1587      the inferior on the first stop the thread hit event is kept being
1588      reported from its cached value by linux_nat_stopped_data_address
1589      until the real thread resume happens after the watchpoint gets
1590      presented and thus its LWP_INFO->STATUS gets reset.
1591
1592    Therefore the hardware watchpoint hit can get safely reset on the
1593    watchpoint removal from inferior.  */
1594
1595 static void
1596 update_watchpoint (struct watchpoint *b, int reparse)
1597 {
1598   int within_current_scope;
1599   struct frame_id saved_frame_id;
1600   int frame_saved;
1601
1602   /* If this is a local watchpoint, we only want to check if the
1603      watchpoint frame is in scope if the current thread is the thread
1604      that was used to create the watchpoint.  */
1605   if (!watchpoint_in_thread_scope (b))
1606     return;
1607
1608   if (b->base.disposition == disp_del_at_next_stop)
1609     return;
1610  
1611   frame_saved = 0;
1612
1613   /* Determine if the watchpoint is within scope.  */
1614   if (b->exp_valid_block == NULL)
1615     within_current_scope = 1;
1616   else
1617     {
1618       struct frame_info *fi = get_current_frame ();
1619       struct gdbarch *frame_arch = get_frame_arch (fi);
1620       CORE_ADDR frame_pc = get_frame_pc (fi);
1621
1622       /* If we're in a function epilogue, unwinding may not work
1623          properly, so do not attempt to recreate locations at this
1624          point.  See similar comments in watchpoint_check.  */
1625       if (gdbarch_in_function_epilogue_p (frame_arch, frame_pc))
1626         return;
1627
1628       /* Save the current frame's ID so we can restore it after
1629          evaluating the watchpoint expression on its own frame.  */
1630       /* FIXME drow/2003-09-09: It would be nice if evaluate_expression
1631          took a frame parameter, so that we didn't have to change the
1632          selected frame.  */
1633       frame_saved = 1;
1634       saved_frame_id = get_frame_id (get_selected_frame (NULL));
1635
1636       fi = frame_find_by_id (b->watchpoint_frame);
1637       within_current_scope = (fi != NULL);
1638       if (within_current_scope)
1639         select_frame (fi);
1640     }
1641
1642   /* We don't free locations.  They are stored in the bp_location array
1643      and update_global_location_list will eventually delete them and
1644      remove breakpoints if needed.  */
1645   b->base.loc = NULL;
1646
1647   if (within_current_scope && reparse)
1648     {
1649       char *s;
1650
1651       if (b->exp)
1652         {
1653           xfree (b->exp);
1654           b->exp = NULL;
1655         }
1656       s = b->exp_string_reparse ? b->exp_string_reparse : b->exp_string;
1657       b->exp = parse_exp_1 (&s, b->exp_valid_block, 0);
1658       /* If the meaning of expression itself changed, the old value is
1659          no longer relevant.  We don't want to report a watchpoint hit
1660          to the user when the old value and the new value may actually
1661          be completely different objects.  */
1662       value_free (b->val);
1663       b->val = NULL;
1664       b->val_valid = 0;
1665
1666       /* Note that unlike with breakpoints, the watchpoint's condition
1667          expression is stored in the breakpoint object, not in the
1668          locations (re)created below.  */
1669       if (b->base.cond_string != NULL)
1670         {
1671           if (b->cond_exp != NULL)
1672             {
1673               xfree (b->cond_exp);
1674               b->cond_exp = NULL;
1675             }
1676
1677           s = b->base.cond_string;
1678           b->cond_exp = parse_exp_1 (&s, b->cond_exp_valid_block, 0);
1679         }
1680     }
1681
1682   /* If we failed to parse the expression, for example because
1683      it refers to a global variable in a not-yet-loaded shared library,
1684      don't try to insert watchpoint.  We don't automatically delete
1685      such watchpoint, though, since failure to parse expression
1686      is different from out-of-scope watchpoint.  */
1687   if ( !target_has_execution)
1688     {
1689       /* Without execution, memory can't change.  No use to try and
1690          set watchpoint locations.  The watchpoint will be reset when
1691          the target gains execution, through breakpoint_re_set.  */
1692     }
1693   else if (within_current_scope && b->exp)
1694     {
1695       int pc = 0;
1696       struct value *val_chain, *v, *result, *next;
1697       struct program_space *frame_pspace;
1698
1699       fetch_subexp_value (b->exp, &pc, &v, &result, &val_chain);
1700
1701       /* Avoid setting b->val if it's already set.  The meaning of
1702          b->val is 'the last value' user saw, and we should update
1703          it only if we reported that last value to user.  As it
1704          happens, the code that reports it updates b->val directly.
1705          We don't keep track of the memory value for masked
1706          watchpoints.  */
1707       if (!b->val_valid && !is_masked_watchpoint (&b->base))
1708         {
1709           b->val = v;
1710           b->val_valid = 1;
1711         }
1712
1713       frame_pspace = get_frame_program_space (get_selected_frame (NULL));
1714
1715       /* Look at each value on the value chain.  */
1716       for (v = val_chain; v; v = value_next (v))
1717         {
1718           /* If it's a memory location, and GDB actually needed
1719              its contents to evaluate the expression, then we
1720              must watch it.  If the first value returned is
1721              still lazy, that means an error occurred reading it;
1722              watch it anyway in case it becomes readable.  */
1723           if (VALUE_LVAL (v) == lval_memory
1724               && (v == val_chain || ! value_lazy (v)))
1725             {
1726               struct type *vtype = check_typedef (value_type (v));
1727
1728               /* We only watch structs and arrays if user asked
1729                  for it explicitly, never if they just happen to
1730                  appear in the middle of some value chain.  */
1731               if (v == result
1732                   || (TYPE_CODE (vtype) != TYPE_CODE_STRUCT
1733                       && TYPE_CODE (vtype) != TYPE_CODE_ARRAY))
1734                 {
1735                   CORE_ADDR addr;
1736                   int len, type;
1737                   struct bp_location *loc, **tmp;
1738
1739                   addr = value_address (v);
1740                   len = TYPE_LENGTH (value_type (v));
1741                   type = hw_write;
1742                   if (b->base.type == bp_read_watchpoint)
1743                     type = hw_read;
1744                   else if (b->base.type == bp_access_watchpoint)
1745                     type = hw_access;
1746
1747                   loc = allocate_bp_location (&b->base);
1748                   for (tmp = &(b->base.loc); *tmp != NULL; tmp = &((*tmp)->next))
1749                     ;
1750                   *tmp = loc;
1751                   loc->gdbarch = get_type_arch (value_type (v));
1752
1753                   loc->pspace = frame_pspace;
1754                   loc->address = addr;
1755                   loc->length = len;
1756                   loc->watchpoint_type = type;
1757                 }
1758             }
1759         }
1760
1761       /* Change the type of breakpoint between hardware assisted or
1762          an ordinary watchpoint depending on the hardware support
1763          and free hardware slots.  REPARSE is set when the inferior
1764          is started.  */
1765       if (reparse)
1766         {
1767           int reg_cnt;
1768           enum bp_loc_type loc_type;
1769           struct bp_location *bl;
1770
1771           reg_cnt = can_use_hardware_watchpoint (val_chain);
1772
1773           if (reg_cnt)
1774             {
1775               int i, target_resources_ok, other_type_used;
1776               enum bptype type;
1777
1778               /* Use an exact watchpoint when there's only one memory region to be
1779                  watched, and only one debug register is needed to watch it.  */
1780               b->exact = target_exact_watchpoints && reg_cnt == 1;
1781
1782               /* We need to determine how many resources are already
1783                  used for all other hardware watchpoints plus this one
1784                  to see if we still have enough resources to also fit
1785                  this watchpoint in as well.  */
1786
1787               /* If this is a software watchpoint, we try to turn it
1788                  to a hardware one -- count resources as if B was of
1789                  hardware watchpoint type.  */
1790               type = b->base.type;
1791               if (type == bp_watchpoint)
1792                 type = bp_hardware_watchpoint;
1793
1794               /* This watchpoint may or may not have been placed on
1795                  the list yet at this point (it won't be in the list
1796                  if we're trying to create it for the first time,
1797                  through watch_command), so always account for it
1798                  manually.  */
1799
1800               /* Count resources used by all watchpoints except B.  */
1801               i = hw_watchpoint_used_count_others (&b->base, type, &other_type_used);
1802
1803               /* Add in the resources needed for B.  */
1804               i += hw_watchpoint_use_count (&b->base);
1805
1806               target_resources_ok
1807                 = target_can_use_hardware_watchpoint (type, i, other_type_used);
1808               if (target_resources_ok <= 0)
1809                 {
1810                   int sw_mode = b->base.ops->works_in_software_mode (&b->base);
1811
1812                   if (target_resources_ok == 0 && !sw_mode)
1813                     error (_("Target does not support this type of "
1814                              "hardware watchpoint."));
1815                   else if (target_resources_ok < 0 && !sw_mode)
1816                     error (_("There are not enough available hardware "
1817                              "resources for this watchpoint."));
1818
1819                   /* Downgrade to software watchpoint.  */
1820                   b->base.type = bp_watchpoint;
1821                 }
1822               else
1823                 {
1824                   /* If this was a software watchpoint, we've just
1825                      found we have enough resources to turn it to a
1826                      hardware watchpoint.  Otherwise, this is a
1827                      nop.  */
1828                   b->base.type = type;
1829                 }
1830             }
1831           else if (!b->base.ops->works_in_software_mode (&b->base))
1832             error (_("Expression cannot be implemented with "
1833                      "read/access watchpoint."));
1834           else
1835             b->base.type = bp_watchpoint;
1836
1837           loc_type = (b->base.type == bp_watchpoint? bp_loc_other
1838                       : bp_loc_hardware_watchpoint);
1839           for (bl = b->base.loc; bl; bl = bl->next)
1840             bl->loc_type = loc_type;
1841         }
1842
1843       for (v = val_chain; v; v = next)
1844         {
1845           next = value_next (v);
1846           if (v != b->val)
1847             value_free (v);
1848         }
1849
1850       /* If a software watchpoint is not watching any memory, then the
1851          above left it without any location set up.  But,
1852          bpstat_stop_status requires a location to be able to report
1853          stops, so make sure there's at least a dummy one.  */
1854       if (b->base.type == bp_watchpoint && b->base.loc == NULL)
1855         {
1856           struct breakpoint *base = &b->base;
1857           base->loc = allocate_bp_location (base);
1858           base->loc->pspace = frame_pspace;
1859           base->loc->address = -1;
1860           base->loc->length = -1;
1861           base->loc->watchpoint_type = -1;
1862         }
1863     }
1864   else if (!within_current_scope)
1865     {
1866       printf_filtered (_("\
1867 Watchpoint %d deleted because the program has left the block\n\
1868 in which its expression is valid.\n"),
1869                        b->base.number);
1870       watchpoint_del_at_next_stop (b);
1871     }
1872
1873   /* Restore the selected frame.  */
1874   if (frame_saved)
1875     select_frame (frame_find_by_id (saved_frame_id));
1876 }
1877
1878
1879 /* Returns 1 iff breakpoint location should be
1880    inserted in the inferior.  We don't differentiate the type of BL's owner
1881    (breakpoint vs. tracepoint), although insert_location in tracepoint's
1882    breakpoint_ops is not defined, because in insert_bp_location,
1883    tracepoint's insert_location will not be called.  */
1884 static int
1885 should_be_inserted (struct bp_location *bl)
1886 {
1887   if (bl->owner == NULL || !breakpoint_enabled (bl->owner))
1888     return 0;
1889
1890   if (bl->owner->disposition == disp_del_at_next_stop)
1891     return 0;
1892
1893   if (!bl->enabled || bl->shlib_disabled || bl->duplicate)
1894     return 0;
1895
1896   if (user_breakpoint_p (bl->owner) && bl->pspace->executing_startup)
1897     return 0;
1898
1899   /* This is set for example, when we're attached to the parent of a
1900      vfork, and have detached from the child.  The child is running
1901      free, and we expect it to do an exec or exit, at which point the
1902      OS makes the parent schedulable again (and the target reports
1903      that the vfork is done).  Until the child is done with the shared
1904      memory region, do not insert breakpoints in the parent, otherwise
1905      the child could still trip on the parent's breakpoints.  Since
1906      the parent is blocked anyway, it won't miss any breakpoint.  */
1907   if (bl->pspace->breakpoints_not_allowed)
1908     return 0;
1909
1910   return 1;
1911 }
1912
1913 /* Same as should_be_inserted but does the check assuming
1914    that the location is not duplicated.  */
1915
1916 static int
1917 unduplicated_should_be_inserted (struct bp_location *bl)
1918 {
1919   int result;
1920   const int save_duplicate = bl->duplicate;
1921
1922   bl->duplicate = 0;
1923   result = should_be_inserted (bl);
1924   bl->duplicate = save_duplicate;
1925   return result;
1926 }
1927
1928 /* Parses a conditional described by an expression COND into an
1929    agent expression bytecode suitable for evaluation
1930    by the bytecode interpreter.  Return NULL if there was
1931    any error during parsing.  */
1932
1933 static struct agent_expr *
1934 parse_cond_to_aexpr (CORE_ADDR scope, struct expression *cond)
1935 {
1936   struct agent_expr *aexpr = NULL;
1937   struct cleanup *old_chain = NULL;
1938   volatile struct gdb_exception ex;
1939
1940   if (!cond)
1941     return NULL;
1942
1943   /* We don't want to stop processing, so catch any errors
1944      that may show up.  */
1945   TRY_CATCH (ex, RETURN_MASK_ERROR)
1946     {
1947       aexpr = gen_eval_for_expr (scope, cond);
1948     }
1949
1950   if (ex.reason < 0)
1951     {
1952       /* If we got here, it means the condition could not be parsed to a valid
1953          bytecode expression and thus can't be evaluated on the target's side.
1954          It's no use iterating through the conditions.  */
1955       return NULL;
1956     }
1957
1958   /* We have a valid agent expression.  */
1959   return aexpr;
1960 }
1961
1962 /* Based on location BL, create a list of breakpoint conditions to be
1963    passed on to the target.  If we have duplicated locations with different
1964    conditions, we will add such conditions to the list.  The idea is that the
1965    target will evaluate the list of conditions and will only notify GDB when
1966    one of them is true.  */
1967
1968 static void
1969 build_target_condition_list (struct bp_location *bl)
1970 {
1971   struct bp_location **locp = NULL, **loc2p;
1972   int null_condition_or_parse_error = 0;
1973   int modified = bl->needs_update;
1974   struct bp_location *loc;
1975
1976   /* This is only meaningful if the target is
1977      evaluating conditions and if the user has
1978      opted for condition evaluation on the target's
1979      side.  */
1980   if (gdb_evaluates_breakpoint_condition_p ()
1981       || !target_supports_evaluation_of_breakpoint_conditions ())
1982     return;
1983
1984   /* Do a first pass to check for locations with no assigned
1985      conditions or conditions that fail to parse to a valid agent expression
1986      bytecode.  If any of these happen, then it's no use to send conditions
1987      to the target since this location will always trigger and generate a
1988      response back to GDB.  */
1989   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
1990     {
1991       loc = (*loc2p);
1992       if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
1993         {
1994           if (modified)
1995             {
1996               struct agent_expr *aexpr;
1997
1998               /* Re-parse the conditions since something changed.  In that
1999                  case we already freed the condition bytecodes (see
2000                  force_breakpoint_reinsertion).  We just
2001                  need to parse the condition to bytecodes again.  */
2002               aexpr = parse_cond_to_aexpr (bl->address, loc->cond);
2003               loc->cond_bytecode = aexpr;
2004
2005               /* Check if we managed to parse the conditional expression
2006                  correctly.  If not, we will not send this condition
2007                  to the target.  */
2008               if (aexpr)
2009                 continue;
2010             }
2011
2012           /* If we have a NULL bytecode expression, it means something
2013              went wrong or we have a null condition expression.  */
2014           if (!loc->cond_bytecode)
2015             {
2016               null_condition_or_parse_error = 1;
2017               break;
2018             }
2019         }
2020     }
2021
2022   /* If any of these happened, it means we will have to evaluate the conditions
2023      for the location's address on gdb's side.  It is no use keeping bytecodes
2024      for all the other duplicate locations, thus we free all of them here.
2025
2026      This is so we have a finer control over which locations' conditions are
2027      being evaluated by GDB or the remote stub.  */
2028   if (null_condition_or_parse_error)
2029     {
2030       ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2031         {
2032           loc = (*loc2p);
2033           if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2034             {
2035               /* Only go as far as the first NULL bytecode is
2036                  located.  */
2037               if (!loc->cond_bytecode)
2038                 return;
2039
2040               free_agent_expr (loc->cond_bytecode);
2041               loc->cond_bytecode = NULL;
2042             }
2043         }
2044     }
2045
2046   /* No NULL conditions or failed bytecode generation.  Build a condition list
2047      for this location's address.  */
2048   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2049     {
2050       loc = (*loc2p);
2051       if (loc->cond
2052           && is_breakpoint (loc->owner)
2053           && loc->pspace->num == bl->pspace->num
2054           && loc->owner->enable_state == bp_enabled
2055           && loc->enabled)
2056         /* Add the condition to the vector.  This will be used later to send the
2057            conditions to the target.  */
2058         VEC_safe_push (agent_expr_p, bl->target_info.conditions,
2059                        loc->cond_bytecode);
2060     }
2061
2062   return;
2063 }
2064
2065 /* Insert a low-level "breakpoint" of some type.  BL is the breakpoint
2066    location.  Any error messages are printed to TMP_ERROR_STREAM; and
2067    DISABLED_BREAKS, and HW_BREAKPOINT_ERROR are used to report problems.
2068    Returns 0 for success, 1 if the bp_location type is not supported or
2069    -1 for failure.
2070
2071    NOTE drow/2003-09-09: This routine could be broken down to an
2072    object-style method for each breakpoint or catchpoint type.  */
2073 static int
2074 insert_bp_location (struct bp_location *bl,
2075                     struct ui_file *tmp_error_stream,
2076                     int *disabled_breaks,
2077                     int *hw_breakpoint_error)
2078 {
2079   int val = 0;
2080
2081   if (!should_be_inserted (bl) || (bl->inserted && !bl->needs_update))
2082     return 0;
2083
2084   /* Initialize the target-specific information.  */
2085   memset (&bl->target_info, 0, sizeof (bl->target_info));
2086   bl->target_info.placed_address = bl->address;
2087   bl->target_info.placed_address_space = bl->pspace->aspace;
2088   bl->target_info.length = bl->length;
2089
2090   /* When working with target-side conditions, we must pass all the conditions
2091      for the same breakpoint address down to the target since GDB will not
2092      insert those locations.  With a list of breakpoint conditions, the target
2093      can decide when to stop and notify GDB.  */
2094
2095   if (is_breakpoint (bl->owner))
2096     {
2097       build_target_condition_list (bl);
2098       /* Reset the condition modification marker.  */
2099       bl->needs_update = 0;
2100     }
2101
2102   if (bl->loc_type == bp_loc_software_breakpoint
2103       || bl->loc_type == bp_loc_hardware_breakpoint)
2104     {
2105       if (bl->owner->type != bp_hardware_breakpoint)
2106         {
2107           /* If the explicitly specified breakpoint type
2108              is not hardware breakpoint, check the memory map to see
2109              if the breakpoint address is in read only memory or not.
2110
2111              Two important cases are:
2112              - location type is not hardware breakpoint, memory
2113              is readonly.  We change the type of the location to
2114              hardware breakpoint.
2115              - location type is hardware breakpoint, memory is
2116              read-write.  This means we've previously made the
2117              location hardware one, but then the memory map changed,
2118              so we undo.
2119              
2120              When breakpoints are removed, remove_breakpoints will use
2121              location types we've just set here, the only possible
2122              problem is that memory map has changed during running
2123              program, but it's not going to work anyway with current
2124              gdb.  */
2125           struct mem_region *mr 
2126             = lookup_mem_region (bl->target_info.placed_address);
2127           
2128           if (mr)
2129             {
2130               if (automatic_hardware_breakpoints)
2131                 {
2132                   enum bp_loc_type new_type;
2133                   
2134                   if (mr->attrib.mode != MEM_RW)
2135                     new_type = bp_loc_hardware_breakpoint;
2136                   else 
2137                     new_type = bp_loc_software_breakpoint;
2138                   
2139                   if (new_type != bl->loc_type)
2140                     {
2141                       static int said = 0;
2142
2143                       bl->loc_type = new_type;
2144                       if (!said)
2145                         {
2146                           fprintf_filtered (gdb_stdout,
2147                                             _("Note: automatically using "
2148                                               "hardware breakpoints for "
2149                                               "read-only addresses.\n"));
2150                           said = 1;
2151                         }
2152                     }
2153                 }
2154               else if (bl->loc_type == bp_loc_software_breakpoint
2155                        && mr->attrib.mode != MEM_RW)        
2156                 warning (_("cannot set software breakpoint "
2157                            "at readonly address %s"),
2158                          paddress (bl->gdbarch, bl->address));
2159             }
2160         }
2161         
2162       /* First check to see if we have to handle an overlay.  */
2163       if (overlay_debugging == ovly_off
2164           || bl->section == NULL
2165           || !(section_is_overlay (bl->section)))
2166         {
2167           /* No overlay handling: just set the breakpoint.  */
2168
2169           val = bl->owner->ops->insert_location (bl);
2170         }
2171       else
2172         {
2173           /* This breakpoint is in an overlay section.
2174              Shall we set a breakpoint at the LMA?  */
2175           if (!overlay_events_enabled)
2176             {
2177               /* Yes -- overlay event support is not active, 
2178                  so we must try to set a breakpoint at the LMA.
2179                  This will not work for a hardware breakpoint.  */
2180               if (bl->loc_type == bp_loc_hardware_breakpoint)
2181                 warning (_("hardware breakpoint %d not supported in overlay!"),
2182                          bl->owner->number);
2183               else
2184                 {
2185                   CORE_ADDR addr = overlay_unmapped_address (bl->address,
2186                                                              bl->section);
2187                   /* Set a software (trap) breakpoint at the LMA.  */
2188                   bl->overlay_target_info = bl->target_info;
2189                   bl->overlay_target_info.placed_address = addr;
2190                   val = target_insert_breakpoint (bl->gdbarch,
2191                                                   &bl->overlay_target_info);
2192                   if (val != 0)
2193                     fprintf_unfiltered (tmp_error_stream,
2194                                         "Overlay breakpoint %d "
2195                                         "failed: in ROM?\n",
2196                                         bl->owner->number);
2197                 }
2198             }
2199           /* Shall we set a breakpoint at the VMA? */
2200           if (section_is_mapped (bl->section))
2201             {
2202               /* Yes.  This overlay section is mapped into memory.  */
2203               val = bl->owner->ops->insert_location (bl);
2204             }
2205           else
2206             {
2207               /* No.  This breakpoint will not be inserted.  
2208                  No error, but do not mark the bp as 'inserted'.  */
2209               return 0;
2210             }
2211         }
2212
2213       if (val)
2214         {
2215           /* Can't set the breakpoint.  */
2216           if (solib_name_from_address (bl->pspace, bl->address))
2217             {
2218               /* See also: disable_breakpoints_in_shlibs.  */
2219               val = 0;
2220               bl->shlib_disabled = 1;
2221               observer_notify_breakpoint_modified (bl->owner);
2222               if (!*disabled_breaks)
2223                 {
2224                   fprintf_unfiltered (tmp_error_stream, 
2225                                       "Cannot insert breakpoint %d.\n", 
2226                                       bl->owner->number);
2227                   fprintf_unfiltered (tmp_error_stream, 
2228                                       "Temporarily disabling shared "
2229                                       "library breakpoints:\n");
2230                 }
2231               *disabled_breaks = 1;
2232               fprintf_unfiltered (tmp_error_stream,
2233                                   "breakpoint #%d\n", bl->owner->number);
2234             }
2235           else
2236             {
2237               if (bl->loc_type == bp_loc_hardware_breakpoint)
2238                 {
2239                   *hw_breakpoint_error = 1;
2240                   fprintf_unfiltered (tmp_error_stream,
2241                                       "Cannot insert hardware "
2242                                       "breakpoint %d.\n",
2243                                       bl->owner->number);
2244                 }
2245               else
2246                 {
2247                   fprintf_unfiltered (tmp_error_stream, 
2248                                       "Cannot insert breakpoint %d.\n", 
2249                                       bl->owner->number);
2250                   fprintf_filtered (tmp_error_stream, 
2251                                     "Error accessing memory address ");
2252                   fputs_filtered (paddress (bl->gdbarch, bl->address),
2253                                   tmp_error_stream);
2254                   fprintf_filtered (tmp_error_stream, ": %s.\n",
2255                                     safe_strerror (val));
2256                 }
2257
2258             }
2259         }
2260       else
2261         bl->inserted = 1;
2262
2263       return val;
2264     }
2265
2266   else if (bl->loc_type == bp_loc_hardware_watchpoint
2267            /* NOTE drow/2003-09-08: This state only exists for removing
2268               watchpoints.  It's not clear that it's necessary...  */
2269            && bl->owner->disposition != disp_del_at_next_stop)
2270     {
2271       gdb_assert (bl->owner->ops != NULL
2272                   && bl->owner->ops->insert_location != NULL);
2273
2274       val = bl->owner->ops->insert_location (bl);
2275
2276       /* If trying to set a read-watchpoint, and it turns out it's not
2277          supported, try emulating one with an access watchpoint.  */
2278       if (val == 1 && bl->watchpoint_type == hw_read)
2279         {
2280           struct bp_location *loc, **loc_temp;
2281
2282           /* But don't try to insert it, if there's already another
2283              hw_access location that would be considered a duplicate
2284              of this one.  */
2285           ALL_BP_LOCATIONS (loc, loc_temp)
2286             if (loc != bl
2287                 && loc->watchpoint_type == hw_access
2288                 && watchpoint_locations_match (bl, loc))
2289               {
2290                 bl->duplicate = 1;
2291                 bl->inserted = 1;
2292                 bl->target_info = loc->target_info;
2293                 bl->watchpoint_type = hw_access;
2294                 val = 0;
2295                 break;
2296               }
2297
2298           if (val == 1)
2299             {
2300               bl->watchpoint_type = hw_access;
2301               val = bl->owner->ops->insert_location (bl);
2302
2303               if (val)
2304                 /* Back to the original value.  */
2305                 bl->watchpoint_type = hw_read;
2306             }
2307         }
2308
2309       bl->inserted = (val == 0);
2310     }
2311
2312   else if (bl->owner->type == bp_catchpoint)
2313     {
2314       gdb_assert (bl->owner->ops != NULL
2315                   && bl->owner->ops->insert_location != NULL);
2316
2317       val = bl->owner->ops->insert_location (bl);
2318       if (val)
2319         {
2320           bl->owner->enable_state = bp_disabled;
2321
2322           if (val == 1)
2323             warning (_("\
2324 Error inserting catchpoint %d: Your system does not support this type\n\
2325 of catchpoint."), bl->owner->number);
2326           else
2327             warning (_("Error inserting catchpoint %d."), bl->owner->number);
2328         }
2329
2330       bl->inserted = (val == 0);
2331
2332       /* We've already printed an error message if there was a problem
2333          inserting this catchpoint, and we've disabled the catchpoint,
2334          so just return success.  */
2335       return 0;
2336     }
2337
2338   return 0;
2339 }
2340
2341 /* This function is called when program space PSPACE is about to be
2342    deleted.  It takes care of updating breakpoints to not reference
2343    PSPACE anymore.  */
2344
2345 void
2346 breakpoint_program_space_exit (struct program_space *pspace)
2347 {
2348   struct breakpoint *b, *b_temp;
2349   struct bp_location *loc, **loc_temp;
2350
2351   /* Remove any breakpoint that was set through this program space.  */
2352   ALL_BREAKPOINTS_SAFE (b, b_temp)
2353     {
2354       if (b->pspace == pspace)
2355         delete_breakpoint (b);
2356     }
2357
2358   /* Breakpoints set through other program spaces could have locations
2359      bound to PSPACE as well.  Remove those.  */
2360   ALL_BP_LOCATIONS (loc, loc_temp)
2361     {
2362       struct bp_location *tmp;
2363
2364       if (loc->pspace == pspace)
2365         {
2366           /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
2367           if (loc->owner->loc == loc)
2368             loc->owner->loc = loc->next;
2369           else
2370             for (tmp = loc->owner->loc; tmp->next != NULL; tmp = tmp->next)
2371               if (tmp->next == loc)
2372                 {
2373                   tmp->next = loc->next;
2374                   break;
2375                 }
2376         }
2377     }
2378
2379   /* Now update the global location list to permanently delete the
2380      removed locations above.  */
2381   update_global_location_list (0);
2382 }
2383
2384 /* Make sure all breakpoints are inserted in inferior.
2385    Throws exception on any error.
2386    A breakpoint that is already inserted won't be inserted
2387    again, so calling this function twice is safe.  */
2388 void
2389 insert_breakpoints (void)
2390 {
2391   struct breakpoint *bpt;
2392
2393   ALL_BREAKPOINTS (bpt)
2394     if (is_hardware_watchpoint (bpt))
2395       {
2396         struct watchpoint *w = (struct watchpoint *) bpt;
2397
2398         update_watchpoint (w, 0 /* don't reparse.  */);
2399       }
2400
2401   update_global_location_list (1);
2402
2403   /* update_global_location_list does not insert breakpoints when
2404      always_inserted_mode is not enabled.  Explicitly insert them
2405      now.  */
2406   if (!breakpoints_always_inserted_mode ())
2407     insert_breakpoint_locations ();
2408 }
2409
2410 /* This is used when we need to synch breakpoint conditions between GDB and the
2411    target.  It is the case with deleting and disabling of breakpoints when using
2412    always-inserted mode.  */
2413
2414 static void
2415 update_inserted_breakpoint_locations (void)
2416 {
2417   struct bp_location *bl, **blp_tmp;
2418   int error_flag = 0;
2419   int val = 0;
2420   int disabled_breaks = 0;
2421   int hw_breakpoint_error = 0;
2422
2423   struct ui_file *tmp_error_stream = mem_fileopen ();
2424   struct cleanup *cleanups = make_cleanup_ui_file_delete (tmp_error_stream);
2425
2426   /* Explicitly mark the warning -- this will only be printed if
2427      there was an error.  */
2428   fprintf_unfiltered (tmp_error_stream, "Warning:\n");
2429
2430   save_current_space_and_thread ();
2431
2432   ALL_BP_LOCATIONS (bl, blp_tmp)
2433     {
2434       /* We only want to update software breakpoints and hardware
2435          breakpoints.  */
2436       if (!is_breakpoint (bl->owner))
2437         continue;
2438
2439       /* We only want to update locations that are already inserted
2440          and need updating.  This is to avoid unwanted insertion during
2441          deletion of breakpoints.  */
2442       if (!bl->inserted || (bl->inserted && !bl->needs_update))
2443         continue;
2444
2445       switch_to_program_space_and_thread (bl->pspace);
2446
2447       /* For targets that support global breakpoints, there's no need
2448          to select an inferior to insert breakpoint to.  In fact, even
2449          if we aren't attached to any process yet, we should still
2450          insert breakpoints.  */
2451       if (!gdbarch_has_global_breakpoints (target_gdbarch)
2452           && ptid_equal (inferior_ptid, null_ptid))
2453         continue;
2454
2455       val = insert_bp_location (bl, tmp_error_stream, &disabled_breaks,
2456                                     &hw_breakpoint_error);
2457       if (val)
2458         error_flag = val;
2459     }
2460
2461   if (error_flag)
2462     {
2463       target_terminal_ours_for_output ();
2464       error_stream (tmp_error_stream);
2465     }
2466
2467   do_cleanups (cleanups);
2468 }
2469
2470 /* Used when starting or continuing the program.  */
2471
2472 static void
2473 insert_breakpoint_locations (void)
2474 {
2475   struct breakpoint *bpt;
2476   struct bp_location *bl, **blp_tmp;
2477   int error_flag = 0;
2478   int val = 0;
2479   int disabled_breaks = 0;
2480   int hw_breakpoint_error = 0;
2481
2482   struct ui_file *tmp_error_stream = mem_fileopen ();
2483   struct cleanup *cleanups = make_cleanup_ui_file_delete (tmp_error_stream);
2484   
2485   /* Explicitly mark the warning -- this will only be printed if
2486      there was an error.  */
2487   fprintf_unfiltered (tmp_error_stream, "Warning:\n");
2488
2489   save_current_space_and_thread ();
2490
2491   ALL_BP_LOCATIONS (bl, blp_tmp)
2492     {
2493       if (!should_be_inserted (bl) || (bl->inserted && !bl->needs_update))
2494         continue;
2495
2496       /* There is no point inserting thread-specific breakpoints if
2497          the thread no longer exists.  ALL_BP_LOCATIONS bp_location
2498          has BL->OWNER always non-NULL.  */
2499       if (bl->owner->thread != -1
2500           && !valid_thread_id (bl->owner->thread))
2501         continue;
2502
2503       switch_to_program_space_and_thread (bl->pspace);
2504
2505       /* For targets that support global breakpoints, there's no need
2506          to select an inferior to insert breakpoint to.  In fact, even
2507          if we aren't attached to any process yet, we should still
2508          insert breakpoints.  */
2509       if (!gdbarch_has_global_breakpoints (target_gdbarch)
2510           && ptid_equal (inferior_ptid, null_ptid))
2511         continue;
2512
2513       val = insert_bp_location (bl, tmp_error_stream, &disabled_breaks,
2514                                     &hw_breakpoint_error);
2515       if (val)
2516         error_flag = val;
2517     }
2518
2519   /* If we failed to insert all locations of a watchpoint, remove
2520      them, as half-inserted watchpoint is of limited use.  */
2521   ALL_BREAKPOINTS (bpt)  
2522     {
2523       int some_failed = 0;
2524       struct bp_location *loc;
2525
2526       if (!is_hardware_watchpoint (bpt))
2527         continue;
2528
2529       if (!breakpoint_enabled (bpt))
2530         continue;
2531
2532       if (bpt->disposition == disp_del_at_next_stop)
2533         continue;
2534       
2535       for (loc = bpt->loc; loc; loc = loc->next)
2536         if (!loc->inserted && should_be_inserted (loc))
2537           {
2538             some_failed = 1;
2539             break;
2540           }
2541       if (some_failed)
2542         {
2543           for (loc = bpt->loc; loc; loc = loc->next)
2544             if (loc->inserted)
2545               remove_breakpoint (loc, mark_uninserted);
2546
2547           hw_breakpoint_error = 1;
2548           fprintf_unfiltered (tmp_error_stream,
2549                               "Could not insert hardware watchpoint %d.\n", 
2550                               bpt->number);
2551           error_flag = -1;
2552         }
2553     }
2554
2555   if (error_flag)
2556     {
2557       /* If a hardware breakpoint or watchpoint was inserted, add a
2558          message about possibly exhausted resources.  */
2559       if (hw_breakpoint_error)
2560         {
2561           fprintf_unfiltered (tmp_error_stream, 
2562                               "Could not insert hardware breakpoints:\n\
2563 You may have requested too many hardware breakpoints/watchpoints.\n");
2564         }
2565       target_terminal_ours_for_output ();
2566       error_stream (tmp_error_stream);
2567     }
2568
2569   do_cleanups (cleanups);
2570 }
2571
2572 /* Used when the program stops.
2573    Returns zero if successful, or non-zero if there was a problem
2574    removing a breakpoint location.  */
2575
2576 int
2577 remove_breakpoints (void)
2578 {
2579   struct bp_location *bl, **blp_tmp;
2580   int val = 0;
2581
2582   ALL_BP_LOCATIONS (bl, blp_tmp)
2583   {
2584     if (bl->inserted && !is_tracepoint (bl->owner))
2585       val |= remove_breakpoint (bl, mark_uninserted);
2586   }
2587   return val;
2588 }
2589
2590 /* Remove breakpoints of process PID.  */
2591
2592 int
2593 remove_breakpoints_pid (int pid)
2594 {
2595   struct bp_location *bl, **blp_tmp;
2596   int val;
2597   struct inferior *inf = find_inferior_pid (pid);
2598
2599   ALL_BP_LOCATIONS (bl, blp_tmp)
2600   {
2601     if (bl->pspace != inf->pspace)
2602       continue;
2603
2604     if (bl->inserted)
2605       {
2606         val = remove_breakpoint (bl, mark_uninserted);
2607         if (val != 0)
2608           return val;
2609       }
2610   }
2611   return 0;
2612 }
2613
2614 int
2615 reattach_breakpoints (int pid)
2616 {
2617   struct cleanup *old_chain;
2618   struct bp_location *bl, **blp_tmp;
2619   int val;
2620   struct ui_file *tmp_error_stream;
2621   int dummy1 = 0, dummy2 = 0;
2622   struct inferior *inf;
2623   struct thread_info *tp;
2624
2625   tp = any_live_thread_of_process (pid);
2626   if (tp == NULL)
2627     return 1;
2628
2629   inf = find_inferior_pid (pid);
2630   old_chain = save_inferior_ptid ();
2631
2632   inferior_ptid = tp->ptid;
2633
2634   tmp_error_stream = mem_fileopen ();
2635   make_cleanup_ui_file_delete (tmp_error_stream);
2636
2637   ALL_BP_LOCATIONS (bl, blp_tmp)
2638   {
2639     if (bl->pspace != inf->pspace)
2640       continue;
2641
2642     if (bl->inserted)
2643       {
2644         bl->inserted = 0;
2645         val = insert_bp_location (bl, tmp_error_stream, &dummy1, &dummy2);
2646         if (val != 0)
2647           {
2648             do_cleanups (old_chain);
2649             return val;
2650           }
2651       }
2652   }
2653   do_cleanups (old_chain);
2654   return 0;
2655 }
2656
2657 static int internal_breakpoint_number = -1;
2658
2659 /* Set the breakpoint number of B, depending on the value of INTERNAL.
2660    If INTERNAL is non-zero, the breakpoint number will be populated
2661    from internal_breakpoint_number and that variable decremented.
2662    Otherwise the breakpoint number will be populated from
2663    breakpoint_count and that value incremented.  Internal breakpoints
2664    do not set the internal var bpnum.  */
2665 static void
2666 set_breakpoint_number (int internal, struct breakpoint *b)
2667 {
2668   if (internal)
2669     b->number = internal_breakpoint_number--;
2670   else
2671     {
2672       set_breakpoint_count (breakpoint_count + 1);
2673       b->number = breakpoint_count;
2674     }
2675 }
2676
2677 static struct breakpoint *
2678 create_internal_breakpoint (struct gdbarch *gdbarch,
2679                             CORE_ADDR address, enum bptype type,
2680                             const struct breakpoint_ops *ops)
2681 {
2682   struct symtab_and_line sal;
2683   struct breakpoint *b;
2684
2685   init_sal (&sal);              /* Initialize to zeroes.  */
2686
2687   sal.pc = address;
2688   sal.section = find_pc_overlay (sal.pc);
2689   sal.pspace = current_program_space;
2690
2691   b = set_raw_breakpoint (gdbarch, sal, type, ops);
2692   b->number = internal_breakpoint_number--;
2693   b->disposition = disp_donttouch;
2694
2695   return b;
2696 }
2697
2698 static const char *const longjmp_names[] =
2699   {
2700     "longjmp", "_longjmp", "siglongjmp", "_siglongjmp"
2701   };
2702 #define NUM_LONGJMP_NAMES ARRAY_SIZE(longjmp_names)
2703
2704 /* Per-objfile data private to breakpoint.c.  */
2705 struct breakpoint_objfile_data
2706 {
2707   /* Minimal symbol for "_ovly_debug_event" (if any).  */
2708   struct minimal_symbol *overlay_msym;
2709
2710   /* Minimal symbol(s) for "longjmp", "siglongjmp", etc. (if any).  */
2711   struct minimal_symbol *longjmp_msym[NUM_LONGJMP_NAMES];
2712
2713   /* Minimal symbol for "std::terminate()" (if any).  */
2714   struct minimal_symbol *terminate_msym;
2715
2716   /* Minimal symbol for "_Unwind_DebugHook" (if any).  */
2717   struct minimal_symbol *exception_msym;
2718 };
2719
2720 static const struct objfile_data *breakpoint_objfile_key;
2721
2722 /* Minimal symbol not found sentinel.  */
2723 static struct minimal_symbol msym_not_found;
2724
2725 /* Returns TRUE if MSYM point to the "not found" sentinel.  */
2726
2727 static int
2728 msym_not_found_p (const struct minimal_symbol *msym)
2729 {
2730   return msym == &msym_not_found;
2731 }
2732
2733 /* Return per-objfile data needed by breakpoint.c.
2734    Allocate the data if necessary.  */
2735
2736 static struct breakpoint_objfile_data *
2737 get_breakpoint_objfile_data (struct objfile *objfile)
2738 {
2739   struct breakpoint_objfile_data *bp_objfile_data;
2740
2741   bp_objfile_data = objfile_data (objfile, breakpoint_objfile_key);
2742   if (bp_objfile_data == NULL)
2743     {
2744       bp_objfile_data = obstack_alloc (&objfile->objfile_obstack,
2745                                        sizeof (*bp_objfile_data));
2746
2747       memset (bp_objfile_data, 0, sizeof (*bp_objfile_data));
2748       set_objfile_data (objfile, breakpoint_objfile_key, bp_objfile_data);
2749     }
2750   return bp_objfile_data;
2751 }
2752
2753 static void
2754 create_overlay_event_breakpoint (void)
2755 {
2756   struct objfile *objfile;
2757   const char *const func_name = "_ovly_debug_event";
2758
2759   ALL_OBJFILES (objfile)
2760     {
2761       struct breakpoint *b;
2762       struct breakpoint_objfile_data *bp_objfile_data;
2763       CORE_ADDR addr;
2764
2765       bp_objfile_data = get_breakpoint_objfile_data (objfile);
2766
2767       if (msym_not_found_p (bp_objfile_data->overlay_msym))
2768         continue;
2769
2770       if (bp_objfile_data->overlay_msym == NULL)
2771         {
2772           struct minimal_symbol *m;
2773
2774           m = lookup_minimal_symbol_text (func_name, objfile);
2775           if (m == NULL)
2776             {
2777               /* Avoid future lookups in this objfile.  */
2778               bp_objfile_data->overlay_msym = &msym_not_found;
2779               continue;
2780             }
2781           bp_objfile_data->overlay_msym = m;
2782         }
2783
2784       addr = SYMBOL_VALUE_ADDRESS (bp_objfile_data->overlay_msym);
2785       b = create_internal_breakpoint (get_objfile_arch (objfile), addr,
2786                                       bp_overlay_event,
2787                                       &internal_breakpoint_ops);
2788       b->addr_string = xstrdup (func_name);
2789
2790       if (overlay_debugging == ovly_auto)
2791         {
2792           b->enable_state = bp_enabled;
2793           overlay_events_enabled = 1;
2794         }
2795       else
2796        {
2797          b->enable_state = bp_disabled;
2798          overlay_events_enabled = 0;
2799        }
2800     }
2801   update_global_location_list (1);
2802 }
2803
2804 static void
2805 create_longjmp_master_breakpoint (void)
2806 {
2807   struct program_space *pspace;
2808   struct cleanup *old_chain;
2809
2810   old_chain = save_current_program_space ();
2811
2812   ALL_PSPACES (pspace)
2813   {
2814     struct objfile *objfile;
2815
2816     set_current_program_space (pspace);
2817
2818     ALL_OBJFILES (objfile)
2819     {
2820       int i;
2821       struct gdbarch *gdbarch;
2822       struct breakpoint_objfile_data *bp_objfile_data;
2823
2824       gdbarch = get_objfile_arch (objfile);
2825       if (!gdbarch_get_longjmp_target_p (gdbarch))
2826         continue;
2827
2828       bp_objfile_data = get_breakpoint_objfile_data (objfile);
2829
2830       for (i = 0; i < NUM_LONGJMP_NAMES; i++)
2831         {
2832           struct breakpoint *b;
2833           const char *func_name;
2834           CORE_ADDR addr;
2835
2836           if (msym_not_found_p (bp_objfile_data->longjmp_msym[i]))
2837             continue;
2838
2839           func_name = longjmp_names[i];
2840           if (bp_objfile_data->longjmp_msym[i] == NULL)
2841             {
2842               struct minimal_symbol *m;
2843
2844               m = lookup_minimal_symbol_text (func_name, objfile);
2845               if (m == NULL)
2846                 {
2847                   /* Prevent future lookups in this objfile.  */
2848                   bp_objfile_data->longjmp_msym[i] = &msym_not_found;
2849                   continue;
2850                 }
2851               bp_objfile_data->longjmp_msym[i] = m;
2852             }
2853
2854           addr = SYMBOL_VALUE_ADDRESS (bp_objfile_data->longjmp_msym[i]);
2855           b = create_internal_breakpoint (gdbarch, addr, bp_longjmp_master,
2856                                           &internal_breakpoint_ops);
2857           b->addr_string = xstrdup (func_name);
2858           b->enable_state = bp_disabled;
2859         }
2860     }
2861   }
2862   update_global_location_list (1);
2863
2864   do_cleanups (old_chain);
2865 }
2866
2867 /* Create a master std::terminate breakpoint.  */
2868 static void
2869 create_std_terminate_master_breakpoint (void)
2870 {
2871   struct program_space *pspace;
2872   struct cleanup *old_chain;
2873   const char *const func_name = "std::terminate()";
2874
2875   old_chain = save_current_program_space ();
2876
2877   ALL_PSPACES (pspace)
2878   {
2879     struct objfile *objfile;
2880     CORE_ADDR addr;
2881
2882     set_current_program_space (pspace);
2883
2884     ALL_OBJFILES (objfile)
2885     {
2886       struct breakpoint *b;
2887       struct breakpoint_objfile_data *bp_objfile_data;
2888
2889       bp_objfile_data = get_breakpoint_objfile_data (objfile);
2890
2891       if (msym_not_found_p (bp_objfile_data->terminate_msym))
2892         continue;
2893
2894       if (bp_objfile_data->terminate_msym == NULL)
2895         {
2896           struct minimal_symbol *m;
2897
2898           m = lookup_minimal_symbol (func_name, NULL, objfile);
2899           if (m == NULL || (MSYMBOL_TYPE (m) != mst_text
2900                             && MSYMBOL_TYPE (m) != mst_file_text))
2901             {
2902               /* Prevent future lookups in this objfile.  */
2903               bp_objfile_data->terminate_msym = &msym_not_found;
2904               continue;
2905             }
2906           bp_objfile_data->terminate_msym = m;
2907         }
2908
2909       addr = SYMBOL_VALUE_ADDRESS (bp_objfile_data->terminate_msym);
2910       b = create_internal_breakpoint (get_objfile_arch (objfile), addr,
2911                                       bp_std_terminate_master,
2912                                       &internal_breakpoint_ops);
2913       b->addr_string = xstrdup (func_name);
2914       b->enable_state = bp_disabled;
2915     }
2916   }
2917
2918   update_global_location_list (1);
2919
2920   do_cleanups (old_chain);
2921 }
2922
2923 /* Install a master breakpoint on the unwinder's debug hook.  */
2924
2925 static void
2926 create_exception_master_breakpoint (void)
2927 {
2928   struct objfile *objfile;
2929   const char *const func_name = "_Unwind_DebugHook";
2930
2931   ALL_OBJFILES (objfile)
2932     {
2933       struct breakpoint *b;
2934       struct gdbarch *gdbarch;
2935       struct breakpoint_objfile_data *bp_objfile_data;
2936       CORE_ADDR addr;
2937
2938       bp_objfile_data = get_breakpoint_objfile_data (objfile);
2939
2940       if (msym_not_found_p (bp_objfile_data->exception_msym))
2941         continue;
2942
2943       gdbarch = get_objfile_arch (objfile);
2944
2945       if (bp_objfile_data->exception_msym == NULL)
2946         {
2947           struct minimal_symbol *debug_hook;
2948
2949           debug_hook = lookup_minimal_symbol (func_name, NULL, objfile);
2950           if (debug_hook == NULL)
2951             {
2952               bp_objfile_data->exception_msym = &msym_not_found;
2953               continue;
2954             }
2955
2956           bp_objfile_data->exception_msym = debug_hook;
2957         }
2958
2959       addr = SYMBOL_VALUE_ADDRESS (bp_objfile_data->exception_msym);
2960       addr = gdbarch_convert_from_func_ptr_addr (gdbarch, addr,
2961                                                  &current_target);
2962       b = create_internal_breakpoint (gdbarch, addr, bp_exception_master,
2963                                       &internal_breakpoint_ops);
2964       b->addr_string = xstrdup (func_name);
2965       b->enable_state = bp_disabled;
2966     }
2967
2968   update_global_location_list (1);
2969 }
2970
2971 void
2972 update_breakpoints_after_exec (void)
2973 {
2974   struct breakpoint *b, *b_tmp;
2975   struct bp_location *bploc, **bplocp_tmp;
2976
2977   /* We're about to delete breakpoints from GDB's lists.  If the
2978      INSERTED flag is true, GDB will try to lift the breakpoints by
2979      writing the breakpoints' "shadow contents" back into memory.  The
2980      "shadow contents" are NOT valid after an exec, so GDB should not
2981      do that.  Instead, the target is responsible from marking
2982      breakpoints out as soon as it detects an exec.  We don't do that
2983      here instead, because there may be other attempts to delete
2984      breakpoints after detecting an exec and before reaching here.  */
2985   ALL_BP_LOCATIONS (bploc, bplocp_tmp)
2986     if (bploc->pspace == current_program_space)
2987       gdb_assert (!bploc->inserted);
2988
2989   ALL_BREAKPOINTS_SAFE (b, b_tmp)
2990   {
2991     if (b->pspace != current_program_space)
2992       continue;
2993
2994     /* Solib breakpoints must be explicitly reset after an exec().  */
2995     if (b->type == bp_shlib_event)
2996       {
2997         delete_breakpoint (b);
2998         continue;
2999       }
3000
3001     /* JIT breakpoints must be explicitly reset after an exec().  */
3002     if (b->type == bp_jit_event)
3003       {
3004         delete_breakpoint (b);
3005         continue;
3006       }
3007
3008     /* Thread event breakpoints must be set anew after an exec(),
3009        as must overlay event and longjmp master breakpoints.  */
3010     if (b->type == bp_thread_event || b->type == bp_overlay_event
3011         || b->type == bp_longjmp_master || b->type == bp_std_terminate_master
3012         || b->type == bp_exception_master)
3013       {
3014         delete_breakpoint (b);
3015         continue;
3016       }
3017
3018     /* Step-resume breakpoints are meaningless after an exec().  */
3019     if (b->type == bp_step_resume || b->type == bp_hp_step_resume)
3020       {
3021         delete_breakpoint (b);
3022         continue;
3023       }
3024
3025     /* Longjmp and longjmp-resume breakpoints are also meaningless
3026        after an exec.  */
3027     if (b->type == bp_longjmp || b->type == bp_longjmp_resume
3028         || b->type == bp_exception || b->type == bp_exception_resume)
3029       {
3030         delete_breakpoint (b);
3031         continue;
3032       }
3033
3034     if (b->type == bp_catchpoint)
3035       {
3036         /* For now, none of the bp_catchpoint breakpoints need to
3037            do anything at this point.  In the future, if some of
3038            the catchpoints need to something, we will need to add
3039            a new method, and call this method from here.  */
3040         continue;
3041       }
3042
3043     /* bp_finish is a special case.  The only way we ought to be able
3044        to see one of these when an exec() has happened, is if the user
3045        caught a vfork, and then said "finish".  Ordinarily a finish just
3046        carries them to the call-site of the current callee, by setting
3047        a temporary bp there and resuming.  But in this case, the finish
3048        will carry them entirely through the vfork & exec.
3049
3050        We don't want to allow a bp_finish to remain inserted now.  But
3051        we can't safely delete it, 'cause finish_command has a handle to
3052        the bp on a bpstat, and will later want to delete it.  There's a
3053        chance (and I've seen it happen) that if we delete the bp_finish
3054        here, that its storage will get reused by the time finish_command
3055        gets 'round to deleting the "use to be a bp_finish" breakpoint.
3056        We really must allow finish_command to delete a bp_finish.
3057
3058        In the absence of a general solution for the "how do we know
3059        it's safe to delete something others may have handles to?"
3060        problem, what we'll do here is just uninsert the bp_finish, and
3061        let finish_command delete it.
3062
3063        (We know the bp_finish is "doomed" in the sense that it's
3064        momentary, and will be deleted as soon as finish_command sees
3065        the inferior stopped.  So it doesn't matter that the bp's
3066        address is probably bogus in the new a.out, unlike e.g., the
3067        solib breakpoints.)  */
3068
3069     if (b->type == bp_finish)
3070       {
3071         continue;
3072       }
3073
3074     /* Without a symbolic address, we have little hope of the
3075        pre-exec() address meaning the same thing in the post-exec()
3076        a.out.  */
3077     if (b->addr_string == NULL)
3078       {
3079         delete_breakpoint (b);
3080         continue;
3081       }
3082   }
3083   /* FIXME what about longjmp breakpoints?  Re-create them here?  */
3084   create_overlay_event_breakpoint ();
3085   create_longjmp_master_breakpoint ();
3086   create_std_terminate_master_breakpoint ();
3087   create_exception_master_breakpoint ();
3088 }
3089
3090 int
3091 detach_breakpoints (int pid)
3092 {
3093   struct bp_location *bl, **blp_tmp;
3094   int val = 0;
3095   struct cleanup *old_chain = save_inferior_ptid ();
3096   struct inferior *inf = current_inferior ();
3097
3098   if (pid == PIDGET (inferior_ptid))
3099     error (_("Cannot detach breakpoints of inferior_ptid"));
3100
3101   /* Set inferior_ptid; remove_breakpoint_1 uses this global.  */
3102   inferior_ptid = pid_to_ptid (pid);
3103   ALL_BP_LOCATIONS (bl, blp_tmp)
3104   {
3105     if (bl->pspace != inf->pspace)
3106       continue;
3107
3108     if (bl->inserted)
3109       val |= remove_breakpoint_1 (bl, mark_inserted);
3110   }
3111
3112   /* Detach single-step breakpoints as well.  */
3113   detach_single_step_breakpoints ();
3114
3115   do_cleanups (old_chain);
3116   return val;
3117 }
3118
3119 /* Remove the breakpoint location BL from the current address space.
3120    Note that this is used to detach breakpoints from a child fork.
3121    When we get here, the child isn't in the inferior list, and neither
3122    do we have objects to represent its address space --- we should
3123    *not* look at bl->pspace->aspace here.  */
3124
3125 static int
3126 remove_breakpoint_1 (struct bp_location *bl, insertion_state_t is)
3127 {
3128   int val;
3129
3130   /* BL is never in moribund_locations by our callers.  */
3131   gdb_assert (bl->owner != NULL);
3132
3133   if (bl->owner->enable_state == bp_permanent)
3134     /* Permanent breakpoints cannot be inserted or removed.  */
3135     return 0;
3136
3137   /* The type of none suggests that owner is actually deleted.
3138      This should not ever happen.  */
3139   gdb_assert (bl->owner->type != bp_none);
3140
3141   if (bl->loc_type == bp_loc_software_breakpoint
3142       || bl->loc_type == bp_loc_hardware_breakpoint)
3143     {
3144       /* "Normal" instruction breakpoint: either the standard
3145          trap-instruction bp (bp_breakpoint), or a
3146          bp_hardware_breakpoint.  */
3147
3148       /* First check to see if we have to handle an overlay.  */
3149       if (overlay_debugging == ovly_off
3150           || bl->section == NULL
3151           || !(section_is_overlay (bl->section)))
3152         {
3153           /* No overlay handling: just remove the breakpoint.  */
3154           val = bl->owner->ops->remove_location (bl);
3155         }
3156       else
3157         {
3158           /* This breakpoint is in an overlay section.
3159              Did we set a breakpoint at the LMA?  */
3160           if (!overlay_events_enabled)
3161               {
3162                 /* Yes -- overlay event support is not active, so we
3163                    should have set a breakpoint at the LMA.  Remove it.  
3164                 */
3165                 /* Ignore any failures: if the LMA is in ROM, we will
3166                    have already warned when we failed to insert it.  */
3167                 if (bl->loc_type == bp_loc_hardware_breakpoint)
3168                   target_remove_hw_breakpoint (bl->gdbarch,
3169                                                &bl->overlay_target_info);
3170                 else
3171                   target_remove_breakpoint (bl->gdbarch,
3172                                             &bl->overlay_target_info);
3173               }
3174           /* Did we set a breakpoint at the VMA? 
3175              If so, we will have marked the breakpoint 'inserted'.  */
3176           if (bl->inserted)
3177             {
3178               /* Yes -- remove it.  Previously we did not bother to
3179                  remove the breakpoint if the section had been
3180                  unmapped, but let's not rely on that being safe.  We
3181                  don't know what the overlay manager might do.  */
3182
3183               /* However, we should remove *software* breakpoints only
3184                  if the section is still mapped, or else we overwrite
3185                  wrong code with the saved shadow contents.  */
3186               if (bl->loc_type == bp_loc_hardware_breakpoint
3187                   || section_is_mapped (bl->section))
3188                 val = bl->owner->ops->remove_location (bl);
3189               else
3190                 val = 0;
3191             }
3192           else
3193             {
3194               /* No -- not inserted, so no need to remove.  No error.  */
3195               val = 0;
3196             }
3197         }
3198
3199       /* In some cases, we might not be able to remove a breakpoint
3200          in a shared library that has already been removed, but we
3201          have not yet processed the shlib unload event.  */
3202       if (val && solib_name_from_address (bl->pspace, bl->address))
3203         val = 0;
3204
3205       if (val)
3206         return val;
3207       bl->inserted = (is == mark_inserted);
3208     }
3209   else if (bl->loc_type == bp_loc_hardware_watchpoint)
3210     {
3211       gdb_assert (bl->owner->ops != NULL
3212                   && bl->owner->ops->remove_location != NULL);
3213
3214       bl->inserted = (is == mark_inserted);
3215       bl->owner->ops->remove_location (bl);
3216
3217       /* Failure to remove any of the hardware watchpoints comes here.  */
3218       if ((is == mark_uninserted) && (bl->inserted))
3219         warning (_("Could not remove hardware watchpoint %d."),
3220                  bl->owner->number);
3221     }
3222   else if (bl->owner->type == bp_catchpoint
3223            && breakpoint_enabled (bl->owner)
3224            && !bl->duplicate)
3225     {
3226       gdb_assert (bl->owner->ops != NULL
3227                   && bl->owner->ops->remove_location != NULL);
3228
3229       val = bl->owner->ops->remove_location (bl);
3230       if (val)
3231         return val;
3232
3233       bl->inserted = (is == mark_inserted);
3234     }
3235
3236   return 0;
3237 }
3238
3239 static int
3240 remove_breakpoint (struct bp_location *bl, insertion_state_t is)
3241 {
3242   int ret;
3243   struct cleanup *old_chain;
3244
3245   /* BL is never in moribund_locations by our callers.  */
3246   gdb_assert (bl->owner != NULL);
3247
3248   if (bl->owner->enable_state == bp_permanent)
3249     /* Permanent breakpoints cannot be inserted or removed.  */
3250     return 0;
3251
3252   /* The type of none suggests that owner is actually deleted.
3253      This should not ever happen.  */
3254   gdb_assert (bl->owner->type != bp_none);
3255
3256   old_chain = save_current_space_and_thread ();
3257
3258   switch_to_program_space_and_thread (bl->pspace);
3259
3260   ret = remove_breakpoint_1 (bl, is);
3261
3262   do_cleanups (old_chain);
3263   return ret;
3264 }
3265
3266 /* Clear the "inserted" flag in all breakpoints.  */
3267
3268 void
3269 mark_breakpoints_out (void)
3270 {
3271   struct bp_location *bl, **blp_tmp;
3272
3273   ALL_BP_LOCATIONS (bl, blp_tmp)
3274     if (bl->pspace == current_program_space)
3275       bl->inserted = 0;
3276 }
3277
3278 /* Clear the "inserted" flag in all breakpoints and delete any
3279    breakpoints which should go away between runs of the program.
3280
3281    Plus other such housekeeping that has to be done for breakpoints
3282    between runs.
3283
3284    Note: this function gets called at the end of a run (by
3285    generic_mourn_inferior) and when a run begins (by
3286    init_wait_for_inferior).  */
3287
3288
3289
3290 void
3291 breakpoint_init_inferior (enum inf_context context)
3292 {
3293   struct breakpoint *b, *b_tmp;
3294   struct bp_location *bl, **blp_tmp;
3295   int ix;
3296   struct program_space *pspace = current_program_space;
3297
3298   /* If breakpoint locations are shared across processes, then there's
3299      nothing to do.  */
3300   if (gdbarch_has_global_breakpoints (target_gdbarch))
3301     return;
3302
3303   ALL_BP_LOCATIONS (bl, blp_tmp)
3304   {
3305     /* ALL_BP_LOCATIONS bp_location has BL->OWNER always non-NULL.  */
3306     if (bl->pspace == pspace
3307         && bl->owner->enable_state != bp_permanent)
3308       bl->inserted = 0;
3309   }
3310
3311   ALL_BREAKPOINTS_SAFE (b, b_tmp)
3312   {
3313     if (b->loc && b->loc->pspace != pspace)
3314       continue;
3315
3316     switch (b->type)
3317       {
3318       case bp_call_dummy:
3319
3320         /* If the call dummy breakpoint is at the entry point it will
3321            cause problems when the inferior is rerun, so we better get
3322            rid of it.  */
3323
3324       case bp_watchpoint_scope:
3325
3326         /* Also get rid of scope breakpoints.  */
3327
3328       case bp_shlib_event:
3329
3330         /* Also remove solib event breakpoints.  Their addresses may
3331            have changed since the last time we ran the program.
3332            Actually we may now be debugging against different target;
3333            and so the solib backend that installed this breakpoint may
3334            not be used in by the target.  E.g.,
3335
3336            (gdb) file prog-linux
3337            (gdb) run               # native linux target
3338            ...
3339            (gdb) kill
3340            (gdb) file prog-win.exe
3341            (gdb) tar rem :9999     # remote Windows gdbserver.
3342         */
3343
3344       case bp_step_resume:
3345
3346         /* Also remove step-resume breakpoints.  */
3347
3348         delete_breakpoint (b);
3349         break;
3350
3351       case bp_watchpoint:
3352       case bp_hardware_watchpoint:
3353       case bp_read_watchpoint:
3354       case bp_access_watchpoint:
3355         {
3356           struct watchpoint *w = (struct watchpoint *) b;
3357
3358           /* Likewise for watchpoints on local expressions.  */
3359           if (w->exp_valid_block != NULL)
3360             delete_breakpoint (b);
3361           else if (context == inf_starting)
3362             {
3363               /* Reset val field to force reread of starting value in
3364                  insert_breakpoints.  */
3365               if (w->val)
3366                 value_free (w->val);
3367               w->val = NULL;
3368               w->val_valid = 0;
3369           }
3370         }
3371         break;
3372       default:
3373         break;
3374       }
3375   }
3376
3377   /* Get rid of the moribund locations.  */
3378   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, bl); ++ix)
3379     decref_bp_location (&bl);
3380   VEC_free (bp_location_p, moribund_locations);
3381 }
3382
3383 /* These functions concern about actual breakpoints inserted in the
3384    target --- to e.g. check if we need to do decr_pc adjustment or if
3385    we need to hop over the bkpt --- so we check for address space
3386    match, not program space.  */
3387
3388 /* breakpoint_here_p (PC) returns non-zero if an enabled breakpoint
3389    exists at PC.  It returns ordinary_breakpoint_here if it's an
3390    ordinary breakpoint, or permanent_breakpoint_here if it's a
3391    permanent breakpoint.
3392    - When continuing from a location with an ordinary breakpoint, we
3393      actually single step once before calling insert_breakpoints.
3394    - When continuing from a location with a permanent breakpoint, we
3395      need to use the `SKIP_PERMANENT_BREAKPOINT' macro, provided by
3396      the target, to advance the PC past the breakpoint.  */
3397
3398 enum breakpoint_here
3399 breakpoint_here_p (struct address_space *aspace, CORE_ADDR pc)
3400 {
3401   struct bp_location *bl, **blp_tmp;
3402   int any_breakpoint_here = 0;
3403
3404   ALL_BP_LOCATIONS (bl, blp_tmp)
3405     {
3406       if (bl->loc_type != bp_loc_software_breakpoint
3407           && bl->loc_type != bp_loc_hardware_breakpoint)
3408         continue;
3409
3410       /* ALL_BP_LOCATIONS bp_location has BL->OWNER always non-NULL.  */
3411       if ((breakpoint_enabled (bl->owner)
3412            || bl->owner->enable_state == bp_permanent)
3413           && breakpoint_location_address_match (bl, aspace, pc))
3414         {
3415           if (overlay_debugging 
3416               && section_is_overlay (bl->section)
3417               && !section_is_mapped (bl->section))
3418             continue;           /* unmapped overlay -- can't be a match */
3419           else if (bl->owner->enable_state == bp_permanent)
3420             return permanent_breakpoint_here;
3421           else
3422             any_breakpoint_here = 1;
3423         }
3424     }
3425
3426   return any_breakpoint_here ? ordinary_breakpoint_here : 0;
3427 }
3428
3429 /* Return true if there's a moribund breakpoint at PC.  */
3430
3431 int
3432 moribund_breakpoint_here_p (struct address_space *aspace, CORE_ADDR pc)
3433 {
3434   struct bp_location *loc;
3435   int ix;
3436
3437   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
3438     if (breakpoint_location_address_match (loc, aspace, pc))
3439       return 1;
3440
3441   return 0;
3442 }
3443
3444 /* Returns non-zero if there's a breakpoint inserted at PC, which is
3445    inserted using regular breakpoint_chain / bp_location array
3446    mechanism.  This does not check for single-step breakpoints, which
3447    are inserted and removed using direct target manipulation.  */
3448
3449 int
3450 regular_breakpoint_inserted_here_p (struct address_space *aspace, 
3451                                     CORE_ADDR pc)
3452 {
3453   struct bp_location *bl, **blp_tmp;
3454
3455   ALL_BP_LOCATIONS (bl, blp_tmp)
3456     {
3457       if (bl->loc_type != bp_loc_software_breakpoint
3458           && bl->loc_type != bp_loc_hardware_breakpoint)
3459         continue;
3460
3461       if (bl->inserted
3462           && breakpoint_location_address_match (bl, aspace, pc))
3463         {
3464           if (overlay_debugging 
3465               && section_is_overlay (bl->section)
3466               && !section_is_mapped (bl->section))
3467             continue;           /* unmapped overlay -- can't be a match */
3468           else
3469             return 1;
3470         }
3471     }
3472   return 0;
3473 }
3474
3475 /* Returns non-zero iff there's either regular breakpoint
3476    or a single step breakpoint inserted at PC.  */
3477
3478 int
3479 breakpoint_inserted_here_p (struct address_space *aspace, CORE_ADDR pc)
3480 {
3481   if (regular_breakpoint_inserted_here_p (aspace, pc))
3482     return 1;
3483
3484   if (single_step_breakpoint_inserted_here_p (aspace, pc))
3485     return 1;
3486
3487   return 0;
3488 }
3489
3490 /* This function returns non-zero iff there is a software breakpoint
3491    inserted at PC.  */
3492
3493 int
3494 software_breakpoint_inserted_here_p (struct address_space *aspace,
3495                                      CORE_ADDR pc)
3496 {
3497   struct bp_location *bl, **blp_tmp;
3498
3499   ALL_BP_LOCATIONS (bl, blp_tmp)
3500     {
3501       if (bl->loc_type != bp_loc_software_breakpoint)
3502         continue;
3503
3504       if (bl->inserted
3505           && breakpoint_address_match (bl->pspace->aspace, bl->address,
3506                                        aspace, pc))
3507         {
3508           if (overlay_debugging 
3509               && section_is_overlay (bl->section)
3510               && !section_is_mapped (bl->section))
3511             continue;           /* unmapped overlay -- can't be a match */
3512           else
3513             return 1;
3514         }
3515     }
3516
3517   /* Also check for software single-step breakpoints.  */
3518   if (single_step_breakpoint_inserted_here_p (aspace, pc))
3519     return 1;
3520
3521   return 0;
3522 }
3523
3524 int
3525 hardware_watchpoint_inserted_in_range (struct address_space *aspace,
3526                                        CORE_ADDR addr, ULONGEST len)
3527 {
3528   struct breakpoint *bpt;
3529
3530   ALL_BREAKPOINTS (bpt)
3531     {
3532       struct bp_location *loc;
3533
3534       if (bpt->type != bp_hardware_watchpoint
3535           && bpt->type != bp_access_watchpoint)
3536         continue;
3537
3538       if (!breakpoint_enabled (bpt))
3539         continue;
3540
3541       for (loc = bpt->loc; loc; loc = loc->next)
3542         if (loc->pspace->aspace == aspace && loc->inserted)
3543           {
3544             CORE_ADDR l, h;
3545
3546             /* Check for intersection.  */
3547             l = max (loc->address, addr);
3548             h = min (loc->address + loc->length, addr + len);
3549             if (l < h)
3550               return 1;
3551           }
3552     }
3553   return 0;
3554 }
3555
3556 /* breakpoint_thread_match (PC, PTID) returns true if the breakpoint at
3557    PC is valid for process/thread PTID.  */
3558
3559 int
3560 breakpoint_thread_match (struct address_space *aspace, CORE_ADDR pc,
3561                          ptid_t ptid)
3562 {
3563   struct bp_location *bl, **blp_tmp;
3564   /* The thread and task IDs associated to PTID, computed lazily.  */
3565   int thread = -1;
3566   int task = 0;
3567   
3568   ALL_BP_LOCATIONS (bl, blp_tmp)
3569     {
3570       if (bl->loc_type != bp_loc_software_breakpoint
3571           && bl->loc_type != bp_loc_hardware_breakpoint)
3572         continue;
3573
3574       /* ALL_BP_LOCATIONS bp_location has bl->OWNER always non-NULL.  */
3575       if (!breakpoint_enabled (bl->owner)
3576           && bl->owner->enable_state != bp_permanent)
3577         continue;
3578
3579       if (!breakpoint_location_address_match (bl, aspace, pc))
3580         continue;
3581
3582       if (bl->owner->thread != -1)
3583         {
3584           /* This is a thread-specific breakpoint.  Check that ptid
3585              matches that thread.  If thread hasn't been computed yet,
3586              it is now time to do so.  */
3587           if (thread == -1)
3588             thread = pid_to_thread_id (ptid);
3589           if (bl->owner->thread != thread)
3590             continue;
3591         }
3592
3593       if (bl->owner->task != 0)
3594         {
3595           /* This is a task-specific breakpoint.  Check that ptid
3596              matches that task.  If task hasn't been computed yet,
3597              it is now time to do so.  */
3598           if (task == 0)
3599             task = ada_get_task_number (ptid);
3600           if (bl->owner->task != task)
3601             continue;
3602         }
3603
3604       if (overlay_debugging 
3605           && section_is_overlay (bl->section)
3606           && !section_is_mapped (bl->section))
3607         continue;           /* unmapped overlay -- can't be a match */
3608
3609       return 1;
3610     }
3611
3612   return 0;
3613 }
3614 \f
3615
3616 /* bpstat stuff.  External routines' interfaces are documented
3617    in breakpoint.h.  */
3618
3619 int
3620 ep_is_catchpoint (struct breakpoint *ep)
3621 {
3622   return (ep->type == bp_catchpoint);
3623 }
3624
3625 /* Frees any storage that is part of a bpstat.  Does not walk the
3626    'next' chain.  */
3627
3628 static void
3629 bpstat_free (bpstat bs)
3630 {
3631   if (bs->old_val != NULL)
3632     value_free (bs->old_val);
3633   decref_counted_command_line (&bs->commands);
3634   decref_bp_location (&bs->bp_location_at);
3635   xfree (bs);
3636 }
3637
3638 /* Clear a bpstat so that it says we are not at any breakpoint.
3639    Also free any storage that is part of a bpstat.  */
3640
3641 void
3642 bpstat_clear (bpstat *bsp)
3643 {
3644   bpstat p;
3645   bpstat q;
3646
3647   if (bsp == 0)
3648     return;
3649   p = *bsp;
3650   while (p != NULL)
3651     {
3652       q = p->next;
3653       bpstat_free (p);
3654       p = q;
3655     }
3656   *bsp = NULL;
3657 }
3658
3659 /* Return a copy of a bpstat.  Like "bs1 = bs2" but all storage that
3660    is part of the bpstat is copied as well.  */
3661
3662 bpstat
3663 bpstat_copy (bpstat bs)
3664 {
3665   bpstat p = NULL;
3666   bpstat tmp;
3667   bpstat retval = NULL;
3668
3669   if (bs == NULL)
3670     return bs;
3671
3672   for (; bs != NULL; bs = bs->next)
3673     {
3674       tmp = (bpstat) xmalloc (sizeof (*tmp));
3675       memcpy (tmp, bs, sizeof (*tmp));
3676       incref_counted_command_line (tmp->commands);
3677       incref_bp_location (tmp->bp_location_at);
3678       if (bs->old_val != NULL)
3679         {
3680           tmp->old_val = value_copy (bs->old_val);
3681           release_value (tmp->old_val);
3682         }
3683
3684       if (p == NULL)
3685         /* This is the first thing in the chain.  */
3686         retval = tmp;
3687       else
3688         p->next = tmp;
3689       p = tmp;
3690     }
3691   p->next = NULL;
3692   return retval;
3693 }
3694
3695 /* Find the bpstat associated with this breakpoint.  */
3696
3697 bpstat
3698 bpstat_find_breakpoint (bpstat bsp, struct breakpoint *breakpoint)
3699 {
3700   if (bsp == NULL)
3701     return NULL;
3702
3703   for (; bsp != NULL; bsp = bsp->next)
3704     {
3705       if (bsp->breakpoint_at == breakpoint)
3706         return bsp;
3707     }
3708   return NULL;
3709 }
3710
3711 /* Put in *NUM the breakpoint number of the first breakpoint we are
3712    stopped at.  *BSP upon return is a bpstat which points to the
3713    remaining breakpoints stopped at (but which is not guaranteed to be
3714    good for anything but further calls to bpstat_num).
3715
3716    Return 0 if passed a bpstat which does not indicate any breakpoints.
3717    Return -1 if stopped at a breakpoint that has been deleted since
3718    we set it.
3719    Return 1 otherwise.  */
3720
3721 int
3722 bpstat_num (bpstat *bsp, int *num)
3723 {
3724   struct breakpoint *b;
3725
3726   if ((*bsp) == NULL)
3727     return 0;                   /* No more breakpoint values */
3728
3729   /* We assume we'll never have several bpstats that correspond to a
3730      single breakpoint -- otherwise, this function might return the
3731      same number more than once and this will look ugly.  */
3732   b = (*bsp)->breakpoint_at;
3733   *bsp = (*bsp)->next;
3734   if (b == NULL)
3735     return -1;                  /* breakpoint that's been deleted since */
3736
3737   *num = b->number;             /* We have its number */
3738   return 1;
3739 }
3740
3741 /* See breakpoint.h.  */
3742
3743 void
3744 bpstat_clear_actions (void)
3745 {
3746   struct thread_info *tp;
3747   bpstat bs;
3748
3749   if (ptid_equal (inferior_ptid, null_ptid))
3750     return;
3751
3752   tp = find_thread_ptid (inferior_ptid);
3753   if (tp == NULL)
3754     return;
3755
3756   for (bs = tp->control.stop_bpstat; bs != NULL; bs = bs->next)
3757     {
3758       decref_counted_command_line (&bs->commands);
3759
3760       if (bs->old_val != NULL)
3761         {
3762           value_free (bs->old_val);
3763           bs->old_val = NULL;
3764         }
3765     }
3766 }
3767
3768 /* Called when a command is about to proceed the inferior.  */
3769
3770 static void
3771 breakpoint_about_to_proceed (void)
3772 {
3773   if (!ptid_equal (inferior_ptid, null_ptid))
3774     {
3775       struct thread_info *tp = inferior_thread ();
3776
3777       /* Allow inferior function calls in breakpoint commands to not
3778          interrupt the command list.  When the call finishes
3779          successfully, the inferior will be standing at the same
3780          breakpoint as if nothing happened.  */
3781       if (tp->control.in_infcall)
3782         return;
3783     }
3784
3785   breakpoint_proceeded = 1;
3786 }
3787
3788 /* Stub for cleaning up our state if we error-out of a breakpoint
3789    command.  */
3790 static void
3791 cleanup_executing_breakpoints (void *ignore)
3792 {
3793   executing_breakpoint_commands = 0;
3794 }
3795
3796 /* Return non-zero iff CMD as the first line of a command sequence is `silent'
3797    or its equivalent.  */
3798
3799 static int
3800 command_line_is_silent (struct command_line *cmd)
3801 {
3802   return cmd && (strcmp ("silent", cmd->line) == 0
3803                  || (xdb_commands && strcmp ("Q", cmd->line) == 0));
3804 }
3805
3806 /* Execute all the commands associated with all the breakpoints at
3807    this location.  Any of these commands could cause the process to
3808    proceed beyond this point, etc.  We look out for such changes by
3809    checking the global "breakpoint_proceeded" after each command.
3810
3811    Returns true if a breakpoint command resumed the inferior.  In that
3812    case, it is the caller's responsibility to recall it again with the
3813    bpstat of the current thread.  */
3814
3815 static int
3816 bpstat_do_actions_1 (bpstat *bsp)
3817 {
3818   bpstat bs;
3819   struct cleanup *old_chain;
3820   int again = 0;
3821
3822   /* Avoid endless recursion if a `source' command is contained
3823      in bs->commands.  */
3824   if (executing_breakpoint_commands)
3825     return 0;
3826
3827   executing_breakpoint_commands = 1;
3828   old_chain = make_cleanup (cleanup_executing_breakpoints, 0);
3829
3830   prevent_dont_repeat ();
3831
3832   /* This pointer will iterate over the list of bpstat's.  */
3833   bs = *bsp;
3834
3835   breakpoint_proceeded = 0;
3836   for (; bs != NULL; bs = bs->next)
3837     {
3838       struct counted_command_line *ccmd;
3839       struct command_line *cmd;
3840       struct cleanup *this_cmd_tree_chain;
3841
3842       /* Take ownership of the BSP's command tree, if it has one.
3843
3844          The command tree could legitimately contain commands like
3845          'step' and 'next', which call clear_proceed_status, which
3846          frees stop_bpstat's command tree.  To make sure this doesn't
3847          free the tree we're executing out from under us, we need to
3848          take ownership of the tree ourselves.  Since a given bpstat's
3849          commands are only executed once, we don't need to copy it; we
3850          can clear the pointer in the bpstat, and make sure we free
3851          the tree when we're done.  */
3852       ccmd = bs->commands;
3853       bs->commands = NULL;
3854       this_cmd_tree_chain = make_cleanup_decref_counted_command_line (&ccmd);
3855       cmd = ccmd ? ccmd->commands : NULL;
3856       if (command_line_is_silent (cmd))
3857         {
3858           /* The action has been already done by bpstat_stop_status.  */
3859           cmd = cmd->next;
3860         }
3861
3862       while (cmd != NULL)
3863         {
3864           execute_control_command (cmd);
3865
3866           if (breakpoint_proceeded)
3867             break;
3868           else
3869             cmd = cmd->next;
3870         }
3871
3872       /* We can free this command tree now.  */
3873       do_cleanups (this_cmd_tree_chain);
3874
3875       if (breakpoint_proceeded)
3876         {
3877           if (target_can_async_p ())
3878             /* If we are in async mode, then the target might be still
3879                running, not stopped at any breakpoint, so nothing for
3880                us to do here -- just return to the event loop.  */
3881             ;
3882           else
3883             /* In sync mode, when execute_control_command returns
3884                we're already standing on the next breakpoint.
3885                Breakpoint commands for that stop were not run, since
3886                execute_command does not run breakpoint commands --
3887                only command_line_handler does, but that one is not
3888                involved in execution of breakpoint commands.  So, we
3889                can now execute breakpoint commands.  It should be
3890                noted that making execute_command do bpstat actions is
3891                not an option -- in this case we'll have recursive
3892                invocation of bpstat for each breakpoint with a
3893                command, and can easily blow up GDB stack.  Instead, we
3894                return true, which will trigger the caller to recall us
3895                with the new stop_bpstat.  */
3896             again = 1;
3897           break;
3898         }
3899     }
3900   do_cleanups (old_chain);
3901   return again;
3902 }
3903
3904 void
3905 bpstat_do_actions (void)
3906 {
3907   struct cleanup *cleanup_if_error = make_bpstat_clear_actions_cleanup ();
3908
3909   /* Do any commands attached to breakpoint we are stopped at.  */
3910   while (!ptid_equal (inferior_ptid, null_ptid)
3911          && target_has_execution
3912          && !is_exited (inferior_ptid)
3913          && !is_executing (inferior_ptid))
3914     /* Since in sync mode, bpstat_do_actions may resume the inferior,
3915        and only return when it is stopped at the next breakpoint, we
3916        keep doing breakpoint actions until it returns false to
3917        indicate the inferior was not resumed.  */
3918     if (!bpstat_do_actions_1 (&inferior_thread ()->control.stop_bpstat))
3919       break;
3920
3921   discard_cleanups (cleanup_if_error);
3922 }
3923
3924 /* Print out the (old or new) value associated with a watchpoint.  */
3925
3926 static void
3927 watchpoint_value_print (struct value *val, struct ui_file *stream)
3928 {
3929   if (val == NULL)
3930     fprintf_unfiltered (stream, _("<unreadable>"));
3931   else
3932     {
3933       struct value_print_options opts;
3934       get_user_print_options (&opts);
3935       value_print (val, stream, &opts);
3936     }
3937 }
3938
3939 /* Generic routine for printing messages indicating why we
3940    stopped.  The behavior of this function depends on the value
3941    'print_it' in the bpstat structure.  Under some circumstances we
3942    may decide not to print anything here and delegate the task to
3943    normal_stop().  */
3944
3945 static enum print_stop_action
3946 print_bp_stop_message (bpstat bs)
3947 {
3948   switch (bs->print_it)
3949     {
3950     case print_it_noop:
3951       /* Nothing should be printed for this bpstat entry.  */
3952       return PRINT_UNKNOWN;
3953       break;
3954
3955     case print_it_done:
3956       /* We still want to print the frame, but we already printed the
3957          relevant messages.  */
3958       return PRINT_SRC_AND_LOC;
3959       break;
3960
3961     case print_it_normal:
3962       {
3963         struct breakpoint *b = bs->breakpoint_at;
3964
3965         /* bs->breakpoint_at can be NULL if it was a momentary breakpoint
3966            which has since been deleted.  */
3967         if (b == NULL)
3968           return PRINT_UNKNOWN;
3969
3970         /* Normal case.  Call the breakpoint's print_it method.  */
3971         return b->ops->print_it (bs);
3972       }
3973       break;
3974
3975     default:
3976       internal_error (__FILE__, __LINE__,
3977                       _("print_bp_stop_message: unrecognized enum value"));
3978       break;
3979     }
3980 }
3981
3982 /* A helper function that prints a shared library stopped event.  */
3983
3984 static void
3985 print_solib_event (int is_catchpoint)
3986 {
3987   int any_deleted
3988     = !VEC_empty (char_ptr, current_program_space->deleted_solibs);
3989   int any_added
3990     = !VEC_empty (so_list_ptr, current_program_space->added_solibs);
3991
3992   if (!is_catchpoint)
3993     {
3994       if (any_added || any_deleted)
3995         ui_out_text (current_uiout,
3996                      _("Stopped due to shared library event:\n"));
3997       else
3998         ui_out_text (current_uiout,
3999                      _("Stopped due to shared library event (no "
4000                        "libraries added or removed)\n"));
4001     }
4002
4003   if (ui_out_is_mi_like_p (current_uiout))
4004     ui_out_field_string (current_uiout, "reason",
4005                          async_reason_lookup (EXEC_ASYNC_SOLIB_EVENT));
4006
4007   if (any_deleted)
4008     {
4009       struct cleanup *cleanup;
4010       char *name;
4011       int ix;
4012
4013       ui_out_text (current_uiout, _("  Inferior unloaded "));
4014       cleanup = make_cleanup_ui_out_list_begin_end (current_uiout,
4015                                                     "removed");
4016       for (ix = 0;
4017            VEC_iterate (char_ptr, current_program_space->deleted_solibs,
4018                         ix, name);
4019            ++ix)
4020         {
4021           if (ix > 0)
4022             ui_out_text (current_uiout, "    ");
4023           ui_out_field_string (current_uiout, "library", name);
4024           ui_out_text (current_uiout, "\n");
4025         }
4026
4027       do_cleanups (cleanup);
4028     }
4029
4030   if (any_added)
4031     {
4032       struct so_list *iter;
4033       int ix;
4034       struct cleanup *cleanup;
4035
4036       ui_out_text (current_uiout, _("  Inferior loaded "));
4037       cleanup = make_cleanup_ui_out_list_begin_end (current_uiout,
4038                                                     "added");
4039       for (ix = 0;
4040            VEC_iterate (so_list_ptr, current_program_space->added_solibs,
4041                         ix, iter);
4042            ++ix)
4043         {
4044           if (ix > 0)
4045             ui_out_text (current_uiout, "    ");
4046           ui_out_field_string (current_uiout, "library", iter->so_name);
4047           ui_out_text (current_uiout, "\n");
4048         }
4049
4050       do_cleanups (cleanup);
4051     }
4052 }
4053
4054 /* Print a message indicating what happened.  This is called from
4055    normal_stop().  The input to this routine is the head of the bpstat
4056    list - a list of the eventpoints that caused this stop.  KIND is
4057    the target_waitkind for the stopping event.  This
4058    routine calls the generic print routine for printing a message
4059    about reasons for stopping.  This will print (for example) the
4060    "Breakpoint n," part of the output.  The return value of this
4061    routine is one of:
4062
4063    PRINT_UNKNOWN: Means we printed nothing.
4064    PRINT_SRC_AND_LOC: Means we printed something, and expect subsequent
4065    code to print the location.  An example is 
4066    "Breakpoint 1, " which should be followed by
4067    the location.
4068    PRINT_SRC_ONLY: Means we printed something, but there is no need
4069    to also print the location part of the message.
4070    An example is the catch/throw messages, which
4071    don't require a location appended to the end.
4072    PRINT_NOTHING: We have done some printing and we don't need any 
4073    further info to be printed.  */
4074
4075 enum print_stop_action
4076 bpstat_print (bpstat bs, int kind)
4077 {
4078   int val;
4079
4080   /* Maybe another breakpoint in the chain caused us to stop.
4081      (Currently all watchpoints go on the bpstat whether hit or not.
4082      That probably could (should) be changed, provided care is taken
4083      with respect to bpstat_explains_signal).  */
4084   for (; bs; bs = bs->next)
4085     {
4086       val = print_bp_stop_message (bs);
4087       if (val == PRINT_SRC_ONLY 
4088           || val == PRINT_SRC_AND_LOC 
4089           || val == PRINT_NOTHING)
4090         return val;
4091     }
4092
4093   /* If we had hit a shared library event breakpoint,
4094      print_bp_stop_message would print out this message.  If we hit an
4095      OS-level shared library event, do the same thing.  */
4096   if (kind == TARGET_WAITKIND_LOADED)
4097     {
4098       print_solib_event (0);
4099       return PRINT_NOTHING;
4100     }
4101
4102   /* We reached the end of the chain, or we got a null BS to start
4103      with and nothing was printed.  */
4104   return PRINT_UNKNOWN;
4105 }
4106
4107 /* Evaluate the expression EXP and return 1 if value is zero.  This is
4108    used inside a catch_errors to evaluate the breakpoint condition.
4109    The argument is a "struct expression *" that has been cast to a
4110    "char *" to make it pass through catch_errors.  */
4111
4112 static int
4113 breakpoint_cond_eval (void *exp)
4114 {
4115   struct value *mark = value_mark ();
4116   int i = !value_true (evaluate_expression ((struct expression *) exp));
4117
4118   value_free_to_mark (mark);
4119   return i;
4120 }
4121
4122 /* Allocate a new bpstat.  Link it to the FIFO list by BS_LINK_POINTER.  */
4123
4124 static bpstat
4125 bpstat_alloc (struct bp_location *bl, bpstat **bs_link_pointer)
4126 {
4127   bpstat bs;
4128
4129   bs = (bpstat) xmalloc (sizeof (*bs));
4130   bs->next = NULL;
4131   **bs_link_pointer = bs;
4132   *bs_link_pointer = &bs->next;
4133   bs->breakpoint_at = bl->owner;
4134   bs->bp_location_at = bl;
4135   incref_bp_location (bl);
4136   /* If the condition is false, etc., don't do the commands.  */
4137   bs->commands = NULL;
4138   bs->old_val = NULL;
4139   bs->print_it = print_it_normal;
4140   return bs;
4141 }
4142 \f
4143 /* The target has stopped with waitstatus WS.  Check if any hardware
4144    watchpoints have triggered, according to the target.  */
4145
4146 int
4147 watchpoints_triggered (struct target_waitstatus *ws)
4148 {
4149   int stopped_by_watchpoint = target_stopped_by_watchpoint ();
4150   CORE_ADDR addr;
4151   struct breakpoint *b;
4152
4153   if (!stopped_by_watchpoint)
4154     {
4155       /* We were not stopped by a watchpoint.  Mark all watchpoints
4156          as not triggered.  */
4157       ALL_BREAKPOINTS (b)
4158         if (is_hardware_watchpoint (b))
4159           {
4160             struct watchpoint *w = (struct watchpoint *) b;
4161
4162             w->watchpoint_triggered = watch_triggered_no;
4163           }
4164
4165       return 0;
4166     }
4167
4168   if (!target_stopped_data_address (&current_target, &addr))
4169     {
4170       /* We were stopped by a watchpoint, but we don't know where.
4171          Mark all watchpoints as unknown.  */
4172       ALL_BREAKPOINTS (b)
4173         if (is_hardware_watchpoint (b))
4174           {
4175             struct watchpoint *w = (struct watchpoint *) b;
4176
4177             w->watchpoint_triggered = watch_triggered_unknown;
4178           }
4179
4180       return stopped_by_watchpoint;
4181     }
4182
4183   /* The target could report the data address.  Mark watchpoints
4184      affected by this data address as triggered, and all others as not
4185      triggered.  */
4186
4187   ALL_BREAKPOINTS (b)
4188     if (is_hardware_watchpoint (b))
4189       {
4190         struct watchpoint *w = (struct watchpoint *) b;
4191         struct bp_location *loc;
4192
4193         w->watchpoint_triggered = watch_triggered_no;
4194         for (loc = b->loc; loc; loc = loc->next)
4195           {
4196             if (is_masked_watchpoint (b))
4197               {
4198                 CORE_ADDR newaddr = addr & w->hw_wp_mask;
4199                 CORE_ADDR start = loc->address & w->hw_wp_mask;
4200
4201                 if (newaddr == start)
4202                   {
4203                     w->watchpoint_triggered = watch_triggered_yes;
4204                     break;
4205                   }
4206               }
4207             /* Exact match not required.  Within range is sufficient.  */
4208             else if (target_watchpoint_addr_within_range (&current_target,
4209                                                          addr, loc->address,
4210                                                          loc->length))
4211               {
4212                 w->watchpoint_triggered = watch_triggered_yes;
4213                 break;
4214               }
4215           }
4216       }
4217
4218   return 1;
4219 }
4220
4221 /* Possible return values for watchpoint_check (this can't be an enum
4222    because of check_errors).  */
4223 /* The watchpoint has been deleted.  */
4224 #define WP_DELETED 1
4225 /* The value has changed.  */
4226 #define WP_VALUE_CHANGED 2
4227 /* The value has not changed.  */
4228 #define WP_VALUE_NOT_CHANGED 3
4229 /* Ignore this watchpoint, no matter if the value changed or not.  */
4230 #define WP_IGNORE 4
4231
4232 #define BP_TEMPFLAG 1
4233 #define BP_HARDWAREFLAG 2
4234
4235 /* Evaluate watchpoint condition expression and check if its value
4236    changed.
4237
4238    P should be a pointer to struct bpstat, but is defined as a void *
4239    in order for this function to be usable with catch_errors.  */
4240
4241 static int
4242 watchpoint_check (void *p)
4243 {
4244   bpstat bs = (bpstat) p;
4245   struct watchpoint *b;
4246   struct frame_info *fr;
4247   int within_current_scope;
4248
4249   /* BS is built from an existing struct breakpoint.  */
4250   gdb_assert (bs->breakpoint_at != NULL);
4251   b = (struct watchpoint *) bs->breakpoint_at;
4252
4253   /* If this is a local watchpoint, we only want to check if the
4254      watchpoint frame is in scope if the current thread is the thread
4255      that was used to create the watchpoint.  */
4256   if (!watchpoint_in_thread_scope (b))
4257     return WP_IGNORE;
4258
4259   if (b->exp_valid_block == NULL)
4260     within_current_scope = 1;
4261   else
4262     {
4263       struct frame_info *frame = get_current_frame ();
4264       struct gdbarch *frame_arch = get_frame_arch (frame);
4265       CORE_ADDR frame_pc = get_frame_pc (frame);
4266
4267       /* in_function_epilogue_p() returns a non-zero value if we're
4268          still in the function but the stack frame has already been
4269          invalidated.  Since we can't rely on the values of local
4270          variables after the stack has been destroyed, we are treating
4271          the watchpoint in that state as `not changed' without further
4272          checking.  Don't mark watchpoints as changed if the current
4273          frame is in an epilogue - even if they are in some other
4274          frame, our view of the stack is likely to be wrong and
4275          frame_find_by_id could error out.  */
4276       if (gdbarch_in_function_epilogue_p (frame_arch, frame_pc))
4277         return WP_IGNORE;
4278
4279       fr = frame_find_by_id (b->watchpoint_frame);
4280       within_current_scope = (fr != NULL);
4281
4282       /* If we've gotten confused in the unwinder, we might have
4283          returned a frame that can't describe this variable.  */
4284       if (within_current_scope)
4285         {
4286           struct symbol *function;
4287
4288           function = get_frame_function (fr);
4289           if (function == NULL
4290               || !contained_in (b->exp_valid_block,
4291                                 SYMBOL_BLOCK_VALUE (function)))
4292             within_current_scope = 0;
4293         }
4294
4295       if (within_current_scope)
4296         /* If we end up stopping, the current frame will get selected
4297            in normal_stop.  So this call to select_frame won't affect
4298            the user.  */
4299         select_frame (fr);
4300     }
4301
4302   if (within_current_scope)
4303     {
4304       /* We use value_{,free_to_}mark because it could be a *long*
4305          time before we return to the command level and call
4306          free_all_values.  We can't call free_all_values because we
4307          might be in the middle of evaluating a function call.  */
4308
4309       int pc = 0;
4310       struct value *mark;
4311       struct value *new_val;
4312
4313       if (is_masked_watchpoint (&b->base))
4314         /* Since we don't know the exact trigger address (from
4315            stopped_data_address), just tell the user we've triggered
4316            a mask watchpoint.  */
4317         return WP_VALUE_CHANGED;
4318
4319       mark = value_mark ();
4320       fetch_subexp_value (b->exp, &pc, &new_val, NULL, NULL);
4321
4322       /* We use value_equal_contents instead of value_equal because
4323          the latter coerces an array to a pointer, thus comparing just
4324          the address of the array instead of its contents.  This is
4325          not what we want.  */
4326       if ((b->val != NULL) != (new_val != NULL)
4327           || (b->val != NULL && !value_equal_contents (b->val, new_val)))
4328         {
4329           if (new_val != NULL)
4330             {
4331               release_value (new_val);
4332               value_free_to_mark (mark);
4333             }
4334           bs->old_val = b->val;
4335           b->val = new_val;
4336           b->val_valid = 1;
4337           return WP_VALUE_CHANGED;
4338         }
4339       else
4340         {
4341           /* Nothing changed.  */
4342           value_free_to_mark (mark);
4343           return WP_VALUE_NOT_CHANGED;
4344         }
4345     }
4346   else
4347     {
4348       struct ui_out *uiout = current_uiout;
4349
4350       /* This seems like the only logical thing to do because
4351          if we temporarily ignored the watchpoint, then when
4352          we reenter the block in which it is valid it contains
4353          garbage (in the case of a function, it may have two
4354          garbage values, one before and one after the prologue).
4355          So we can't even detect the first assignment to it and
4356          watch after that (since the garbage may or may not equal
4357          the first value assigned).  */
4358       /* We print all the stop information in
4359          breakpoint_ops->print_it, but in this case, by the time we
4360          call breakpoint_ops->print_it this bp will be deleted
4361          already.  So we have no choice but print the information
4362          here.  */
4363       if (ui_out_is_mi_like_p (uiout))
4364         ui_out_field_string
4365           (uiout, "reason", async_reason_lookup (EXEC_ASYNC_WATCHPOINT_SCOPE));
4366       ui_out_text (uiout, "\nWatchpoint ");
4367       ui_out_field_int (uiout, "wpnum", b->base.number);
4368       ui_out_text (uiout,
4369                    " deleted because the program has left the block in\n\
4370 which its expression is valid.\n");     
4371
4372       /* Make sure the watchpoint's commands aren't executed.  */
4373       decref_counted_command_line (&b->base.commands);
4374       watchpoint_del_at_next_stop (b);
4375
4376       return WP_DELETED;
4377     }
4378 }
4379
4380 /* Return true if it looks like target has stopped due to hitting
4381    breakpoint location BL.  This function does not check if we should
4382    stop, only if BL explains the stop.  */
4383
4384 static int
4385 bpstat_check_location (const struct bp_location *bl,
4386                        struct address_space *aspace, CORE_ADDR bp_addr,
4387                        const struct target_waitstatus *ws)
4388 {
4389   struct breakpoint *b = bl->owner;
4390
4391   /* BL is from an existing breakpoint.  */
4392   gdb_assert (b != NULL);
4393
4394   return b->ops->breakpoint_hit (bl, aspace, bp_addr, ws);
4395 }
4396
4397 /* Determine if the watched values have actually changed, and we
4398    should stop.  If not, set BS->stop to 0.  */
4399
4400 static void
4401 bpstat_check_watchpoint (bpstat bs)
4402 {
4403   const struct bp_location *bl;
4404   struct watchpoint *b;
4405
4406   /* BS is built for existing struct breakpoint.  */
4407   bl = bs->bp_location_at;
4408   gdb_assert (bl != NULL);
4409   b = (struct watchpoint *) bs->breakpoint_at;
4410   gdb_assert (b != NULL);
4411
4412     {
4413       int must_check_value = 0;
4414       
4415       if (b->base.type == bp_watchpoint)
4416         /* For a software watchpoint, we must always check the
4417            watched value.  */
4418         must_check_value = 1;
4419       else if (b->watchpoint_triggered == watch_triggered_yes)
4420         /* We have a hardware watchpoint (read, write, or access)
4421            and the target earlier reported an address watched by
4422            this watchpoint.  */
4423         must_check_value = 1;
4424       else if (b->watchpoint_triggered == watch_triggered_unknown
4425                && b->base.type == bp_hardware_watchpoint)
4426         /* We were stopped by a hardware watchpoint, but the target could
4427            not report the data address.  We must check the watchpoint's
4428            value.  Access and read watchpoints are out of luck; without
4429            a data address, we can't figure it out.  */
4430         must_check_value = 1;
4431
4432       if (must_check_value)
4433         {
4434           char *message
4435             = xstrprintf ("Error evaluating expression for watchpoint %d\n",
4436                           b->base.number);
4437           struct cleanup *cleanups = make_cleanup (xfree, message);
4438           int e = catch_errors (watchpoint_check, bs, message,
4439                                 RETURN_MASK_ALL);
4440           do_cleanups (cleanups);
4441           switch (e)
4442             {
4443             case WP_DELETED:
4444               /* We've already printed what needs to be printed.  */
4445               bs->print_it = print_it_done;
4446               /* Stop.  */
4447               break;
4448             case WP_IGNORE:
4449               bs->print_it = print_it_noop;
4450               bs->stop = 0;
4451               break;
4452             case WP_VALUE_CHANGED:
4453               if (b->base.type == bp_read_watchpoint)
4454                 {
4455                   /* There are two cases to consider here:
4456
4457                      1. We're watching the triggered memory for reads.
4458                      In that case, trust the target, and always report
4459                      the watchpoint hit to the user.  Even though
4460                      reads don't cause value changes, the value may
4461                      have changed since the last time it was read, and
4462                      since we're not trapping writes, we will not see
4463                      those, and as such we should ignore our notion of
4464                      old value.
4465
4466                      2. We're watching the triggered memory for both
4467                      reads and writes.  There are two ways this may
4468                      happen:
4469
4470                      2.1. This is a target that can't break on data
4471                      reads only, but can break on accesses (reads or
4472                      writes), such as e.g., x86.  We detect this case
4473                      at the time we try to insert read watchpoints.
4474
4475                      2.2. Otherwise, the target supports read
4476                      watchpoints, but, the user set an access or write
4477                      watchpoint watching the same memory as this read
4478                      watchpoint.
4479
4480                      If we're watching memory writes as well as reads,
4481                      ignore watchpoint hits when we find that the
4482                      value hasn't changed, as reads don't cause
4483                      changes.  This still gives false positives when
4484                      the program writes the same value to memory as
4485                      what there was already in memory (we will confuse
4486                      it for a read), but it's much better than
4487                      nothing.  */
4488
4489                   int other_write_watchpoint = 0;
4490
4491                   if (bl->watchpoint_type == hw_read)
4492                     {
4493                       struct breakpoint *other_b;
4494
4495                       ALL_BREAKPOINTS (other_b)
4496                         if (other_b->type == bp_hardware_watchpoint
4497                             || other_b->type == bp_access_watchpoint)
4498                           {
4499                             struct watchpoint *other_w =
4500                               (struct watchpoint *) other_b;
4501
4502                             if (other_w->watchpoint_triggered
4503                                 == watch_triggered_yes)
4504                               {
4505                                 other_write_watchpoint = 1;
4506                                 break;
4507                               }
4508                           }
4509                     }
4510
4511                   if (other_write_watchpoint
4512                       || bl->watchpoint_type == hw_access)
4513                     {
4514                       /* We're watching the same memory for writes,
4515                          and the value changed since the last time we
4516                          updated it, so this trap must be for a write.
4517                          Ignore it.  */
4518                       bs->print_it = print_it_noop;
4519                       bs->stop = 0;
4520                     }
4521                 }
4522               break;
4523             case WP_VALUE_NOT_CHANGED:
4524               if (b->base.type == bp_hardware_watchpoint
4525                   || b->base.type == bp_watchpoint)
4526                 {
4527                   /* Don't stop: write watchpoints shouldn't fire if
4528                      the value hasn't changed.  */
4529                   bs->print_it = print_it_noop;
4530                   bs->stop = 0;
4531                 }
4532               /* Stop.  */
4533               break;
4534             default:
4535               /* Can't happen.  */
4536             case 0:
4537               /* Error from catch_errors.  */
4538               printf_filtered (_("Watchpoint %d deleted.\n"), b->base.number);
4539               watchpoint_del_at_next_stop (b);
4540               /* We've already printed what needs to be printed.  */
4541               bs->print_it = print_it_done;
4542               break;
4543             }
4544         }
4545       else      /* must_check_value == 0 */
4546         {
4547           /* This is a case where some watchpoint(s) triggered, but
4548              not at the address of this watchpoint, or else no
4549              watchpoint triggered after all.  So don't print
4550              anything for this watchpoint.  */
4551           bs->print_it = print_it_noop;
4552           bs->stop = 0;
4553         }
4554     }
4555 }
4556
4557
4558 /* Check conditions (condition proper, frame, thread and ignore count)
4559    of breakpoint referred to by BS.  If we should not stop for this
4560    breakpoint, set BS->stop to 0.  */
4561
4562 static void
4563 bpstat_check_breakpoint_conditions (bpstat bs, ptid_t ptid)
4564 {
4565   int thread_id = pid_to_thread_id (ptid);
4566   const struct bp_location *bl;
4567   struct breakpoint *b;
4568
4569   /* BS is built for existing struct breakpoint.  */
4570   bl = bs->bp_location_at;
4571   gdb_assert (bl != NULL);
4572   b = bs->breakpoint_at;
4573   gdb_assert (b != NULL);
4574
4575   /* Even if the target evaluated the condition on its end and notified GDB, we
4576      need to do so again since GDB does not know if we stopped due to a
4577      breakpoint or a single step breakpoint.  */
4578
4579   if (frame_id_p (b->frame_id)
4580       && !frame_id_eq (b->frame_id, get_stack_frame_id (get_current_frame ())))
4581     bs->stop = 0;
4582   else if (bs->stop)
4583     {
4584       int value_is_zero = 0;
4585       struct expression *cond;
4586
4587       /* Evaluate Python breakpoints that have a "stop"
4588          method implemented.  */
4589       if (b->py_bp_object)
4590         bs->stop = gdbpy_should_stop (b->py_bp_object);
4591
4592       if (is_watchpoint (b))
4593         {
4594           struct watchpoint *w = (struct watchpoint *) b;
4595
4596           cond = w->cond_exp;
4597         }
4598       else
4599         cond = bl->cond;
4600
4601       if (cond && b->disposition != disp_del_at_next_stop)
4602         {
4603           int within_current_scope = 1;
4604           struct watchpoint * w;
4605
4606           /* We use value_mark and value_free_to_mark because it could
4607              be a long time before we return to the command level and
4608              call free_all_values.  We can't call free_all_values
4609              because we might be in the middle of evaluating a
4610              function call.  */
4611           struct value *mark = value_mark ();
4612
4613           if (is_watchpoint (b))
4614             w = (struct watchpoint *) b;
4615           else
4616             w = NULL;
4617
4618           /* Need to select the frame, with all that implies so that
4619              the conditions will have the right context.  Because we
4620              use the frame, we will not see an inlined function's
4621              variables when we arrive at a breakpoint at the start
4622              of the inlined function; the current frame will be the
4623              call site.  */
4624           if (w == NULL || w->cond_exp_valid_block == NULL)
4625             select_frame (get_current_frame ());
4626           else
4627             {
4628               struct frame_info *frame;
4629
4630               /* For local watchpoint expressions, which particular
4631                  instance of a local is being watched matters, so we
4632                  keep track of the frame to evaluate the expression
4633                  in.  To evaluate the condition however, it doesn't
4634                  really matter which instantiation of the function
4635                  where the condition makes sense triggers the
4636                  watchpoint.  This allows an expression like "watch
4637                  global if q > 10" set in `func', catch writes to
4638                  global on all threads that call `func', or catch
4639                  writes on all recursive calls of `func' by a single
4640                  thread.  We simply always evaluate the condition in
4641                  the innermost frame that's executing where it makes
4642                  sense to evaluate the condition.  It seems
4643                  intuitive.  */
4644               frame = block_innermost_frame (w->cond_exp_valid_block);
4645               if (frame != NULL)
4646                 select_frame (frame);
4647               else
4648                 within_current_scope = 0;
4649             }
4650           if (within_current_scope)
4651             value_is_zero
4652               = catch_errors (breakpoint_cond_eval, cond,
4653                               "Error in testing breakpoint condition:\n",
4654                               RETURN_MASK_ALL);
4655           else
4656             {
4657               warning (_("Watchpoint condition cannot be tested "
4658                          "in the current scope"));
4659               /* If we failed to set the right context for this
4660                  watchpoint, unconditionally report it.  */
4661               value_is_zero = 0;
4662             }
4663           /* FIXME-someday, should give breakpoint #.  */
4664           value_free_to_mark (mark);
4665         }
4666
4667       if (cond && value_is_zero)
4668         {
4669           bs->stop = 0;
4670         }
4671       else if (b->thread != -1 && b->thread != thread_id)
4672         {
4673           bs->stop = 0;
4674         }
4675       else if (b->ignore_count > 0)
4676         {
4677           b->ignore_count--;
4678           annotate_ignore_count_change ();
4679           bs->stop = 0;
4680           /* Increase the hit count even though we don't stop.  */
4681           ++(b->hit_count);
4682           observer_notify_breakpoint_modified (b);
4683         }       
4684     }
4685 }
4686
4687
4688 /* Get a bpstat associated with having just stopped at address
4689    BP_ADDR in thread PTID.
4690
4691    Determine whether we stopped at a breakpoint, etc, or whether we
4692    don't understand this stop.  Result is a chain of bpstat's such
4693    that:
4694
4695    if we don't understand the stop, the result is a null pointer.
4696
4697    if we understand why we stopped, the result is not null.
4698
4699    Each element of the chain refers to a particular breakpoint or
4700    watchpoint at which we have stopped.  (We may have stopped for
4701    several reasons concurrently.)
4702
4703    Each element of the chain has valid next, breakpoint_at,
4704    commands, FIXME??? fields.  */
4705
4706 bpstat
4707 bpstat_stop_status (struct address_space *aspace,
4708                     CORE_ADDR bp_addr, ptid_t ptid,
4709                     const struct target_waitstatus *ws)
4710 {
4711   struct breakpoint *b = NULL;
4712   struct bp_location *bl;
4713   struct bp_location *loc;
4714   /* First item of allocated bpstat's.  */
4715   bpstat bs_head = NULL, *bs_link = &bs_head;
4716   /* Pointer to the last thing in the chain currently.  */
4717   bpstat bs;
4718   int ix;
4719   int need_remove_insert;
4720   int removed_any;
4721
4722   /* First, build the bpstat chain with locations that explain a
4723      target stop, while being careful to not set the target running,
4724      as that may invalidate locations (in particular watchpoint
4725      locations are recreated).  Resuming will happen here with
4726      breakpoint conditions or watchpoint expressions that include
4727      inferior function calls.  */
4728
4729   ALL_BREAKPOINTS (b)
4730     {
4731       if (!breakpoint_enabled (b) && b->enable_state != bp_permanent)
4732         continue;
4733
4734       for (bl = b->loc; bl != NULL; bl = bl->next)
4735         {
4736           /* For hardware watchpoints, we look only at the first
4737              location.  The watchpoint_check function will work on the
4738              entire expression, not the individual locations.  For
4739              read watchpoints, the watchpoints_triggered function has
4740              checked all locations already.  */
4741           if (b->type == bp_hardware_watchpoint && bl != b->loc)
4742             break;
4743
4744           if (bl->shlib_disabled)
4745             continue;
4746
4747           if (!bpstat_check_location (bl, aspace, bp_addr, ws))
4748             continue;
4749
4750           /* Come here if it's a watchpoint, or if the break address
4751              matches.  */
4752
4753           bs = bpstat_alloc (bl, &bs_link);     /* Alloc a bpstat to
4754                                                    explain stop.  */
4755
4756           /* Assume we stop.  Should we find a watchpoint that is not
4757              actually triggered, or if the condition of the breakpoint
4758              evaluates as false, we'll reset 'stop' to 0.  */
4759           bs->stop = 1;
4760           bs->print = 1;
4761
4762           /* If this is a scope breakpoint, mark the associated
4763              watchpoint as triggered so that we will handle the
4764              out-of-scope event.  We'll get to the watchpoint next
4765              iteration.  */
4766           if (b->type == bp_watchpoint_scope && b->related_breakpoint != b)
4767             {
4768               struct watchpoint *w = (struct watchpoint *) b->related_breakpoint;
4769
4770               w->watchpoint_triggered = watch_triggered_yes;
4771             }
4772         }
4773     }
4774
4775   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
4776     {
4777       if (breakpoint_location_address_match (loc, aspace, bp_addr))
4778         {
4779           bs = bpstat_alloc (loc, &bs_link);
4780           /* For hits of moribund locations, we should just proceed.  */
4781           bs->stop = 0;
4782           bs->print = 0;
4783           bs->print_it = print_it_noop;
4784         }
4785     }
4786
4787   /* A bit of special processing for shlib breakpoints.  We need to
4788      process solib loading here, so that the lists of loaded and
4789      unloaded libraries are correct before we handle "catch load" and
4790      "catch unload".  */
4791   for (bs = bs_head; bs != NULL; bs = bs->next)
4792     {
4793       if (bs->breakpoint_at && bs->breakpoint_at->type == bp_shlib_event)
4794         {
4795           handle_solib_event ();
4796           break;
4797         }
4798     }
4799
4800   /* Now go through the locations that caused the target to stop, and
4801      check whether we're interested in reporting this stop to higher
4802      layers, or whether we should resume the target transparently.  */
4803
4804   removed_any = 0;
4805
4806   for (bs = bs_head; bs != NULL; bs = bs->next)
4807     {
4808       if (!bs->stop)
4809         continue;
4810
4811       b = bs->breakpoint_at;
4812       b->ops->check_status (bs);
4813       if (bs->stop)
4814         {
4815           bpstat_check_breakpoint_conditions (bs, ptid);
4816
4817           if (bs->stop)
4818             {
4819               ++(b->hit_count);
4820               observer_notify_breakpoint_modified (b);
4821
4822               /* We will stop here.  */
4823               if (b->disposition == disp_disable)
4824                 {
4825                   --(b->enable_count);
4826                   if (b->enable_count <= 0
4827                       && b->enable_state != bp_permanent)
4828                     b->enable_state = bp_disabled;
4829                   removed_any = 1;
4830                 }
4831               if (b->silent)
4832                 bs->print = 0;
4833               bs->commands = b->commands;
4834               incref_counted_command_line (bs->commands);
4835               if (command_line_is_silent (bs->commands
4836                                           ? bs->commands->commands : NULL))
4837                 bs->print = 0;
4838             }
4839
4840         }
4841
4842       /* Print nothing for this entry if we don't stop or don't
4843          print.  */
4844       if (!bs->stop || !bs->print)
4845         bs->print_it = print_it_noop;
4846     }
4847
4848   /* If we aren't stopping, the value of some hardware watchpoint may
4849      not have changed, but the intermediate memory locations we are
4850      watching may have.  Don't bother if we're stopping; this will get
4851      done later.  */
4852   need_remove_insert = 0;
4853   if (! bpstat_causes_stop (bs_head))
4854     for (bs = bs_head; bs != NULL; bs = bs->next)
4855       if (!bs->stop
4856           && bs->breakpoint_at
4857           && is_hardware_watchpoint (bs->breakpoint_at))
4858         {
4859           struct watchpoint *w = (struct watchpoint *) bs->breakpoint_at;
4860
4861           update_watchpoint (w, 0 /* don't reparse.  */);
4862           need_remove_insert = 1;
4863         }
4864
4865   if (need_remove_insert)
4866     update_global_location_list (1);
4867   else if (removed_any)
4868     update_global_location_list (0);
4869
4870   return bs_head;
4871 }
4872
4873 static void
4874 handle_jit_event (void)
4875 {
4876   struct frame_info *frame;
4877   struct gdbarch *gdbarch;
4878
4879   /* Switch terminal for any messages produced by
4880      breakpoint_re_set.  */
4881   target_terminal_ours_for_output ();
4882
4883   frame = get_current_frame ();
4884   gdbarch = get_frame_arch (frame);
4885
4886   jit_event_handler (gdbarch);
4887
4888   target_terminal_inferior ();
4889 }
4890
4891 /* Handle an solib event by calling solib_add.  */
4892
4893 void
4894 handle_solib_event (void)
4895 {
4896   clear_program_space_solib_cache (current_inferior ()->pspace);
4897
4898   /* Check for any newly added shared libraries if we're supposed to
4899      be adding them automatically.  Switch terminal for any messages
4900      produced by breakpoint_re_set.  */
4901   target_terminal_ours_for_output ();
4902 #ifdef SOLIB_ADD
4903   SOLIB_ADD (NULL, 0, &current_target, auto_solib_add);
4904 #else
4905   solib_add (NULL, 0, &current_target, auto_solib_add);
4906 #endif
4907   target_terminal_inferior ();
4908 }
4909
4910 /* Prepare WHAT final decision for infrun.  */
4911
4912 /* Decide what infrun needs to do with this bpstat.  */
4913
4914 struct bpstat_what
4915 bpstat_what (bpstat bs_head)
4916 {
4917   struct bpstat_what retval;
4918   int jit_event = 0;
4919   bpstat bs;
4920
4921   retval.main_action = BPSTAT_WHAT_KEEP_CHECKING;
4922   retval.call_dummy = STOP_NONE;
4923   retval.is_longjmp = 0;
4924
4925   for (bs = bs_head; bs != NULL; bs = bs->next)
4926     {
4927       /* Extract this BS's action.  After processing each BS, we check
4928          if its action overrides all we've seem so far.  */
4929       enum bpstat_what_main_action this_action = BPSTAT_WHAT_KEEP_CHECKING;
4930       enum bptype bptype;
4931
4932       if (bs->breakpoint_at == NULL)
4933         {
4934           /* I suspect this can happen if it was a momentary
4935              breakpoint which has since been deleted.  */
4936           bptype = bp_none;
4937         }
4938       else
4939         bptype = bs->breakpoint_at->type;
4940
4941       switch (bptype)
4942         {
4943         case bp_none:
4944           break;
4945         case bp_breakpoint:
4946         case bp_hardware_breakpoint:
4947         case bp_until:
4948         case bp_finish:
4949         case bp_shlib_event:
4950           if (bs->stop)
4951             {
4952               if (bs->print)
4953                 this_action = BPSTAT_WHAT_STOP_NOISY;
4954               else
4955                 this_action = BPSTAT_WHAT_STOP_SILENT;
4956             }
4957           else
4958             this_action = BPSTAT_WHAT_SINGLE;
4959           break;
4960         case bp_watchpoint:
4961         case bp_hardware_watchpoint:
4962         case bp_read_watchpoint:
4963         case bp_access_watchpoint:
4964           if (bs->stop)
4965             {
4966               if (bs->print)
4967                 this_action = BPSTAT_WHAT_STOP_NOISY;
4968               else
4969                 this_action = BPSTAT_WHAT_STOP_SILENT;
4970             }
4971           else
4972             {
4973               /* There was a watchpoint, but we're not stopping.
4974                  This requires no further action.  */
4975             }
4976           break;
4977         case bp_longjmp:
4978         case bp_exception:
4979           this_action = BPSTAT_WHAT_SET_LONGJMP_RESUME;
4980           retval.is_longjmp = bptype == bp_longjmp;
4981           break;
4982         case bp_longjmp_resume:
4983         case bp_exception_resume:
4984           this_action = BPSTAT_WHAT_CLEAR_LONGJMP_RESUME;
4985           retval.is_longjmp = bptype == bp_longjmp_resume;
4986           break;
4987         case bp_step_resume:
4988           if (bs->stop)
4989             this_action = BPSTAT_WHAT_STEP_RESUME;
4990           else
4991             {
4992               /* It is for the wrong frame.  */
4993               this_action = BPSTAT_WHAT_SINGLE;
4994             }
4995           break;
4996         case bp_hp_step_resume:
4997           if (bs->stop)
4998             this_action = BPSTAT_WHAT_HP_STEP_RESUME;
4999           else
5000             {
5001               /* It is for the wrong frame.  */
5002               this_action = BPSTAT_WHAT_SINGLE;
5003             }
5004           break;
5005         case bp_watchpoint_scope:
5006         case bp_thread_event:
5007         case bp_overlay_event:
5008         case bp_longjmp_master:
5009         case bp_std_terminate_master:
5010         case bp_exception_master:
5011           this_action = BPSTAT_WHAT_SINGLE;
5012           break;
5013         case bp_catchpoint:
5014           if (bs->stop)
5015             {
5016               if (bs->print)
5017                 this_action = BPSTAT_WHAT_STOP_NOISY;
5018               else
5019                 this_action = BPSTAT_WHAT_STOP_SILENT;
5020             }
5021           else
5022             {
5023               /* There was a catchpoint, but we're not stopping.
5024                  This requires no further action.  */
5025             }
5026           break;
5027         case bp_jit_event:
5028           jit_event = 1;
5029           this_action = BPSTAT_WHAT_SINGLE;
5030           break;
5031         case bp_call_dummy:
5032           /* Make sure the action is stop (silent or noisy),
5033              so infrun.c pops the dummy frame.  */
5034           retval.call_dummy = STOP_STACK_DUMMY;
5035           this_action = BPSTAT_WHAT_STOP_SILENT;
5036           break;
5037         case bp_std_terminate:
5038           /* Make sure the action is stop (silent or noisy),
5039              so infrun.c pops the dummy frame.  */
5040           retval.call_dummy = STOP_STD_TERMINATE;
5041           this_action = BPSTAT_WHAT_STOP_SILENT;
5042           break;
5043         case bp_tracepoint:
5044         case bp_fast_tracepoint:
5045         case bp_static_tracepoint:
5046           /* Tracepoint hits should not be reported back to GDB, and
5047              if one got through somehow, it should have been filtered
5048              out already.  */
5049           internal_error (__FILE__, __LINE__,
5050                           _("bpstat_what: tracepoint encountered"));
5051           break;
5052         case bp_gnu_ifunc_resolver:
5053           /* Step over it (and insert bp_gnu_ifunc_resolver_return).  */
5054           this_action = BPSTAT_WHAT_SINGLE;
5055           break;
5056         case bp_gnu_ifunc_resolver_return:
5057           /* The breakpoint will be removed, execution will restart from the
5058              PC of the former breakpoint.  */
5059           this_action = BPSTAT_WHAT_KEEP_CHECKING;
5060           break;
5061         default:
5062           internal_error (__FILE__, __LINE__,
5063                           _("bpstat_what: unhandled bptype %d"), (int) bptype);
5064         }
5065
5066       retval.main_action = max (retval.main_action, this_action);
5067     }
5068
5069   /* These operations may affect the bs->breakpoint_at state so they are
5070      delayed after MAIN_ACTION is decided above.  */
5071
5072   if (jit_event)
5073     {
5074       if (debug_infrun)
5075         fprintf_unfiltered (gdb_stdlog, "bpstat_what: bp_jit_event\n");
5076
5077       handle_jit_event ();
5078     }
5079
5080   for (bs = bs_head; bs != NULL; bs = bs->next)
5081     {
5082       struct breakpoint *b = bs->breakpoint_at;
5083
5084       if (b == NULL)
5085         continue;
5086       switch (b->type)
5087         {
5088         case bp_gnu_ifunc_resolver:
5089           gnu_ifunc_resolver_stop (b);
5090           break;
5091         case bp_gnu_ifunc_resolver_return:
5092           gnu_ifunc_resolver_return_stop (b);
5093           break;
5094         }
5095     }
5096
5097   return retval;
5098 }
5099
5100 /* Nonzero if we should step constantly (e.g. watchpoints on machines
5101    without hardware support).  This isn't related to a specific bpstat,
5102    just to things like whether watchpoints are set.  */
5103
5104 int
5105 bpstat_should_step (void)
5106 {
5107   struct breakpoint *b;
5108
5109   ALL_BREAKPOINTS (b)
5110     if (breakpoint_enabled (b) && b->type == bp_watchpoint && b->loc != NULL)
5111       return 1;
5112   return 0;
5113 }
5114
5115 int
5116 bpstat_causes_stop (bpstat bs)
5117 {
5118   for (; bs != NULL; bs = bs->next)
5119     if (bs->stop)
5120       return 1;
5121
5122   return 0;
5123 }
5124
5125 \f
5126
5127 /* Compute a string of spaces suitable to indent the next line
5128    so it starts at the position corresponding to the table column
5129    named COL_NAME in the currently active table of UIOUT.  */
5130
5131 static char *
5132 wrap_indent_at_field (struct ui_out *uiout, const char *col_name)
5133 {
5134   static char wrap_indent[80];
5135   int i, total_width, width, align;
5136   char *text;
5137
5138   total_width = 0;
5139   for (i = 1; ui_out_query_field (uiout, i, &width, &align, &text); i++)
5140     {
5141       if (strcmp (text, col_name) == 0)
5142         {
5143           gdb_assert (total_width < sizeof wrap_indent);
5144           memset (wrap_indent, ' ', total_width);
5145           wrap_indent[total_width] = 0;
5146
5147           return wrap_indent;
5148         }
5149
5150       total_width += width + 1;
5151     }
5152
5153   return NULL;
5154 }
5155
5156 /* Determine if the locations of this breakpoint will have their conditions
5157    evaluated by the target, host or a mix of both.  Returns the following:
5158
5159     "host": Host evals condition.
5160     "host or target": Host or Target evals condition.
5161     "target": Target evals condition.
5162 */
5163
5164 static const char *
5165 bp_condition_evaluator (struct breakpoint *b)
5166 {
5167   struct bp_location *bl;
5168   char host_evals = 0;
5169   char target_evals = 0;
5170
5171   if (!b)
5172     return NULL;
5173
5174   if (!is_breakpoint (b))
5175     return NULL;
5176
5177   if (gdb_evaluates_breakpoint_condition_p ()
5178       || !target_supports_evaluation_of_breakpoint_conditions ())
5179     return condition_evaluation_host;
5180
5181   for (bl = b->loc; bl; bl = bl->next)
5182     {
5183       if (bl->cond_bytecode)
5184         target_evals++;
5185       else
5186         host_evals++;
5187     }
5188
5189   if (host_evals && target_evals)
5190     return condition_evaluation_both;
5191   else if (target_evals)
5192     return condition_evaluation_target;
5193   else
5194     return condition_evaluation_host;
5195 }
5196
5197 /* Determine the breakpoint location's condition evaluator.  This is
5198    similar to bp_condition_evaluator, but for locations.  */
5199
5200 static const char *
5201 bp_location_condition_evaluator (struct bp_location *bl)
5202 {
5203   if (bl && !is_breakpoint (bl->owner))
5204     return NULL;
5205
5206   if (gdb_evaluates_breakpoint_condition_p ()
5207       || !target_supports_evaluation_of_breakpoint_conditions ())
5208     return condition_evaluation_host;
5209
5210   if (bl && bl->cond_bytecode)
5211     return condition_evaluation_target;
5212   else
5213     return condition_evaluation_host;
5214 }
5215
5216 /* Print the LOC location out of the list of B->LOC locations.  */
5217
5218 static void
5219 print_breakpoint_location (struct breakpoint *b,
5220                            struct bp_location *loc)
5221 {
5222   struct ui_out *uiout = current_uiout;
5223   struct cleanup *old_chain = save_current_program_space ();
5224
5225   if (loc != NULL && loc->shlib_disabled)
5226     loc = NULL;
5227
5228   if (loc != NULL)
5229     set_current_program_space (loc->pspace);
5230
5231   if (b->display_canonical)
5232     ui_out_field_string (uiout, "what", b->addr_string);
5233   else if (loc && loc->source_file)
5234     {
5235       struct symbol *sym 
5236         = find_pc_sect_function (loc->address, loc->section);
5237       if (sym)
5238         {
5239           ui_out_text (uiout, "in ");
5240           ui_out_field_string (uiout, "func",
5241                                SYMBOL_PRINT_NAME (sym));
5242           ui_out_text (uiout, " ");
5243           ui_out_wrap_hint (uiout, wrap_indent_at_field (uiout, "what"));
5244           ui_out_text (uiout, "at ");
5245         }
5246       ui_out_field_string (uiout, "file", loc->source_file);
5247       ui_out_text (uiout, ":");
5248       
5249       if (ui_out_is_mi_like_p (uiout))
5250         {
5251           struct symtab_and_line sal = find_pc_line (loc->address, 0);
5252           char *fullname = symtab_to_fullname (sal.symtab);
5253           
5254           if (fullname)
5255             ui_out_field_string (uiout, "fullname", fullname);
5256         }
5257       
5258       ui_out_field_int (uiout, "line", loc->line_number);
5259     }
5260   else if (loc)
5261     {
5262       struct ui_stream *stb = ui_out_stream_new (uiout);
5263       struct cleanup *stb_chain = make_cleanup_ui_out_stream_delete (stb);
5264
5265       print_address_symbolic (loc->gdbarch, loc->address, stb->stream,
5266                               demangle, "");
5267       ui_out_field_stream (uiout, "at", stb);
5268
5269       do_cleanups (stb_chain);
5270     }
5271   else
5272     ui_out_field_string (uiout, "pending", b->addr_string);
5273
5274   if (loc && is_breakpoint (b)
5275       && breakpoint_condition_evaluation_mode () == condition_evaluation_target
5276       && bp_condition_evaluator (b) == condition_evaluation_both)
5277     {
5278       ui_out_text (uiout, " (");
5279       ui_out_field_string (uiout, "evaluated-by",
5280                            bp_location_condition_evaluator (loc));
5281       ui_out_text (uiout, ")");
5282     }
5283
5284   do_cleanups (old_chain);
5285 }
5286
5287 static const char *
5288 bptype_string (enum bptype type)
5289 {
5290   struct ep_type_description
5291     {
5292       enum bptype type;
5293       char *description;
5294     };
5295   static struct ep_type_description bptypes[] =
5296   {
5297     {bp_none, "?deleted?"},
5298     {bp_breakpoint, "breakpoint"},
5299     {bp_hardware_breakpoint, "hw breakpoint"},
5300     {bp_until, "until"},
5301     {bp_finish, "finish"},
5302     {bp_watchpoint, "watchpoint"},
5303     {bp_hardware_watchpoint, "hw watchpoint"},
5304     {bp_read_watchpoint, "read watchpoint"},
5305     {bp_access_watchpoint, "acc watchpoint"},
5306     {bp_longjmp, "longjmp"},
5307     {bp_longjmp_resume, "longjmp resume"},
5308     {bp_exception, "exception"},
5309     {bp_exception_resume, "exception resume"},
5310     {bp_step_resume, "step resume"},
5311     {bp_hp_step_resume, "high-priority step resume"},
5312     {bp_watchpoint_scope, "watchpoint scope"},
5313     {bp_call_dummy, "call dummy"},
5314     {bp_std_terminate, "std::terminate"},
5315     {bp_shlib_event, "shlib events"},
5316     {bp_thread_event, "thread events"},
5317     {bp_overlay_event, "overlay events"},
5318     {bp_longjmp_master, "longjmp master"},
5319     {bp_std_terminate_master, "std::terminate master"},
5320     {bp_exception_master, "exception master"},
5321     {bp_catchpoint, "catchpoint"},
5322     {bp_tracepoint, "tracepoint"},
5323     {bp_fast_tracepoint, "fast tracepoint"},
5324     {bp_static_tracepoint, "static tracepoint"},
5325     {bp_jit_event, "jit events"},
5326     {bp_gnu_ifunc_resolver, "STT_GNU_IFUNC resolver"},
5327     {bp_gnu_ifunc_resolver_return, "STT_GNU_IFUNC resolver return"},
5328   };
5329
5330   if (((int) type >= (sizeof (bptypes) / sizeof (bptypes[0])))
5331       || ((int) type != bptypes[(int) type].type))
5332     internal_error (__FILE__, __LINE__,
5333                     _("bptypes table does not describe type #%d."),
5334                     (int) type);
5335
5336   return bptypes[(int) type].description;
5337 }
5338
5339 /* Print B to gdb_stdout.  */
5340
5341 static void
5342 print_one_breakpoint_location (struct breakpoint *b,
5343                                struct bp_location *loc,
5344                                int loc_number,
5345                                struct bp_location **last_loc,
5346                                int allflag)
5347 {
5348   struct command_line *l;
5349   static char bpenables[] = "nynny";
5350
5351   struct ui_out *uiout = current_uiout;
5352   int header_of_multiple = 0;
5353   int part_of_multiple = (loc != NULL);
5354   struct value_print_options opts;
5355
5356   get_user_print_options (&opts);
5357
5358   gdb_assert (!loc || loc_number != 0);
5359   /* See comment in print_one_breakpoint concerning treatment of
5360      breakpoints with single disabled location.  */
5361   if (loc == NULL 
5362       && (b->loc != NULL 
5363           && (b->loc->next != NULL || !b->loc->enabled)))
5364     header_of_multiple = 1;
5365   if (loc == NULL)
5366     loc = b->loc;
5367
5368   annotate_record ();
5369
5370   /* 1 */
5371   annotate_field (0);
5372   if (part_of_multiple)
5373     {
5374       char *formatted;
5375       formatted = xstrprintf ("%d.%d", b->number, loc_number);
5376       ui_out_field_string (uiout, "number", formatted);
5377       xfree (formatted);
5378     }
5379   else
5380     {
5381       ui_out_field_int (uiout, "number", b->number);
5382     }
5383
5384   /* 2 */
5385   annotate_field (1);
5386   if (part_of_multiple)
5387     ui_out_field_skip (uiout, "type");
5388   else
5389     ui_out_field_string (uiout, "type", bptype_string (b->type));
5390
5391   /* 3 */
5392   annotate_field (2);
5393   if (part_of_multiple)
5394     ui_out_field_skip (uiout, "disp");
5395   else
5396     ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
5397
5398
5399   /* 4 */
5400   annotate_field (3);
5401   if (part_of_multiple)
5402     ui_out_field_string (uiout, "enabled", loc->enabled ? "y" : "n");
5403   else
5404     ui_out_field_fmt (uiout, "enabled", "%c", 
5405                       bpenables[(int) b->enable_state]);
5406   ui_out_spaces (uiout, 2);
5407
5408   
5409   /* 5 and 6 */
5410   if (b->ops != NULL && b->ops->print_one != NULL)
5411     {
5412       /* Although the print_one can possibly print all locations,
5413          calling it here is not likely to get any nice result.  So,
5414          make sure there's just one location.  */
5415       gdb_assert (b->loc == NULL || b->loc->next == NULL);
5416       b->ops->print_one (b, last_loc);
5417     }
5418   else
5419     switch (b->type)
5420       {
5421       case bp_none:
5422         internal_error (__FILE__, __LINE__,
5423                         _("print_one_breakpoint: bp_none encountered\n"));
5424         break;
5425
5426       case bp_watchpoint:
5427       case bp_hardware_watchpoint:
5428       case bp_read_watchpoint:
5429       case bp_access_watchpoint:
5430         {
5431           struct watchpoint *w = (struct watchpoint *) b;
5432
5433           /* Field 4, the address, is omitted (which makes the columns
5434              not line up too nicely with the headers, but the effect
5435              is relatively readable).  */
5436           if (opts.addressprint)
5437             ui_out_field_skip (uiout, "addr");
5438           annotate_field (5);
5439           ui_out_field_string (uiout, "what", w->exp_string);
5440         }
5441         break;
5442
5443       case bp_breakpoint:
5444       case bp_hardware_breakpoint:
5445       case bp_until:
5446       case bp_finish:
5447       case bp_longjmp:
5448       case bp_longjmp_resume:
5449       case bp_exception:
5450       case bp_exception_resume:
5451       case bp_step_resume:
5452       case bp_hp_step_resume:
5453       case bp_watchpoint_scope:
5454       case bp_call_dummy:
5455       case bp_std_terminate:
5456       case bp_shlib_event:
5457       case bp_thread_event:
5458       case bp_overlay_event:
5459       case bp_longjmp_master:
5460       case bp_std_terminate_master:
5461       case bp_exception_master:
5462       case bp_tracepoint:
5463       case bp_fast_tracepoint:
5464       case bp_static_tracepoint:
5465       case bp_jit_event:
5466       case bp_gnu_ifunc_resolver:
5467       case bp_gnu_ifunc_resolver_return:
5468         if (opts.addressprint)
5469           {
5470             annotate_field (4);
5471             if (header_of_multiple)
5472               ui_out_field_string (uiout, "addr", "<MULTIPLE>");
5473             else if (b->loc == NULL || loc->shlib_disabled)
5474               ui_out_field_string (uiout, "addr", "<PENDING>");
5475             else
5476               ui_out_field_core_addr (uiout, "addr",
5477                                       loc->gdbarch, loc->address);
5478           }
5479         annotate_field (5);
5480         if (!header_of_multiple)
5481           print_breakpoint_location (b, loc);
5482         if (b->loc)
5483           *last_loc = b->loc;
5484         break;
5485       }
5486
5487
5488   /* For backward compatibility, don't display inferiors unless there
5489      are several.  */
5490   if (loc != NULL
5491       && !header_of_multiple
5492       && (allflag
5493           || (!gdbarch_has_global_breakpoints (target_gdbarch)
5494               && (number_of_program_spaces () > 1
5495                   || number_of_inferiors () > 1)
5496               /* LOC is for existing B, it cannot be in
5497                  moribund_locations and thus having NULL OWNER.  */
5498               && loc->owner->type != bp_catchpoint)))
5499     {
5500       struct inferior *inf;
5501       int first = 1;
5502
5503       for (inf = inferior_list; inf != NULL; inf = inf->next)
5504         {
5505           if (inf->pspace == loc->pspace)
5506             {
5507               if (first)
5508                 {
5509                   first = 0;
5510                   ui_out_text (uiout, " inf ");
5511                 }
5512               else
5513                 ui_out_text (uiout, ", ");
5514               ui_out_text (uiout, plongest (inf->num));
5515             }
5516         }
5517     }
5518
5519   if (!part_of_multiple)
5520     {
5521       if (b->thread != -1)
5522         {
5523           /* FIXME: This seems to be redundant and lost here; see the
5524              "stop only in" line a little further down.  */
5525           ui_out_text (uiout, " thread ");
5526           ui_out_field_int (uiout, "thread", b->thread);
5527         }
5528       else if (b->task != 0)
5529         {
5530           ui_out_text (uiout, " task ");
5531           ui_out_field_int (uiout, "task", b->task);
5532         }
5533     }
5534
5535   ui_out_text (uiout, "\n");
5536
5537   if (!part_of_multiple)
5538     b->ops->print_one_detail (b, uiout);
5539
5540   if (part_of_multiple && frame_id_p (b->frame_id))
5541     {
5542       annotate_field (6);
5543       ui_out_text (uiout, "\tstop only in stack frame at ");
5544       /* FIXME: cagney/2002-12-01: Shouldn't be poking around inside
5545          the frame ID.  */
5546       ui_out_field_core_addr (uiout, "frame",
5547                               b->gdbarch, b->frame_id.stack_addr);
5548       ui_out_text (uiout, "\n");
5549     }
5550   
5551   if (!part_of_multiple && b->cond_string)
5552     {
5553       annotate_field (7);
5554       if (is_tracepoint (b))
5555         ui_out_text (uiout, "\ttrace only if ");
5556       else
5557         ui_out_text (uiout, "\tstop only if ");
5558       ui_out_field_string (uiout, "cond", b->cond_string);
5559
5560       /* Print whether the target is doing the breakpoint's condition
5561          evaluation.  If GDB is doing the evaluation, don't print anything.  */
5562       if (is_breakpoint (b)
5563           && breakpoint_condition_evaluation_mode ()
5564           == condition_evaluation_target)
5565         {
5566           ui_out_text (uiout, " (");
5567           ui_out_field_string (uiout, "evaluated-by",
5568                                bp_condition_evaluator (b));
5569           ui_out_text (uiout, " evals)");
5570         }
5571       ui_out_text (uiout, "\n");
5572     }
5573
5574   if (!part_of_multiple && b->thread != -1)
5575     {
5576       /* FIXME should make an annotation for this.  */
5577       ui_out_text (uiout, "\tstop only in thread ");
5578       ui_out_field_int (uiout, "thread", b->thread);
5579       ui_out_text (uiout, "\n");
5580     }
5581   
5582   if (!part_of_multiple && b->hit_count)
5583     {
5584       /* FIXME should make an annotation for this.  */
5585       if (ep_is_catchpoint (b))
5586         ui_out_text (uiout, "\tcatchpoint");
5587       else if (is_tracepoint (b))
5588         ui_out_text (uiout, "\ttracepoint");
5589       else
5590         ui_out_text (uiout, "\tbreakpoint");
5591       ui_out_text (uiout, " already hit ");
5592       ui_out_field_int (uiout, "times", b->hit_count);
5593       if (b->hit_count == 1)
5594         ui_out_text (uiout, " time\n");
5595       else
5596         ui_out_text (uiout, " times\n");
5597     }
5598   
5599   /* Output the count also if it is zero, but only if this is mi.
5600      FIXME: Should have a better test for this.  */
5601   if (ui_out_is_mi_like_p (uiout))
5602     if (!part_of_multiple && b->hit_count == 0)
5603       ui_out_field_int (uiout, "times", b->hit_count);
5604
5605   if (!part_of_multiple && b->ignore_count)
5606     {
5607       annotate_field (8);
5608       ui_out_text (uiout, "\tignore next ");
5609       ui_out_field_int (uiout, "ignore", b->ignore_count);
5610       ui_out_text (uiout, " hits\n");
5611     }
5612
5613   /* Note that an enable count of 1 corresponds to "enable once"
5614      behavior, which is reported by the combination of enablement and
5615      disposition, so we don't need to mention it here.  */
5616   if (!part_of_multiple && b->enable_count > 1)
5617     {
5618       annotate_field (8);
5619       ui_out_text (uiout, "\tdisable after ");
5620       /* Tweak the wording to clarify that ignore and enable counts
5621          are distinct, and have additive effect.  */
5622       if (b->ignore_count)
5623         ui_out_text (uiout, "additional ");
5624       else
5625         ui_out_text (uiout, "next ");
5626       ui_out_field_int (uiout, "enable", b->enable_count);
5627       ui_out_text (uiout, " hits\n");
5628     }
5629
5630   if (!part_of_multiple && is_tracepoint (b))
5631     {
5632       struct tracepoint *tp = (struct tracepoint *) b;
5633
5634       if (tp->traceframe_usage)
5635         {
5636           ui_out_text (uiout, "\ttrace buffer usage ");
5637           ui_out_field_int (uiout, "traceframe-usage", tp->traceframe_usage);
5638           ui_out_text (uiout, " bytes\n");
5639         }
5640     }
5641   
5642   l = b->commands ? b->commands->commands : NULL;
5643   if (!part_of_multiple && l)
5644     {
5645       struct cleanup *script_chain;
5646
5647       annotate_field (9);
5648       script_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "script");
5649       print_command_lines (uiout, l, 4);
5650       do_cleanups (script_chain);
5651     }
5652
5653   if (is_tracepoint (b))
5654     {
5655       struct tracepoint *t = (struct tracepoint *) b;
5656
5657       if (!part_of_multiple && t->pass_count)
5658         {
5659           annotate_field (10);
5660           ui_out_text (uiout, "\tpass count ");
5661           ui_out_field_int (uiout, "pass", t->pass_count);
5662           ui_out_text (uiout, " \n");
5663         }
5664     }
5665
5666   if (ui_out_is_mi_like_p (uiout) && !part_of_multiple)
5667     {
5668       if (is_watchpoint (b))
5669         {
5670           struct watchpoint *w = (struct watchpoint *) b;
5671
5672           ui_out_field_string (uiout, "original-location", w->exp_string);
5673         }
5674       else if (b->addr_string)
5675         ui_out_field_string (uiout, "original-location", b->addr_string);
5676     }
5677 }
5678
5679 static void
5680 print_one_breakpoint (struct breakpoint *b,
5681                       struct bp_location **last_loc, 
5682                       int allflag)
5683 {
5684   struct cleanup *bkpt_chain;
5685   struct ui_out *uiout = current_uiout;
5686
5687   bkpt_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "bkpt");
5688
5689   print_one_breakpoint_location (b, NULL, 0, last_loc, allflag);
5690   do_cleanups (bkpt_chain);
5691
5692   /* If this breakpoint has custom print function,
5693      it's already printed.  Otherwise, print individual
5694      locations, if any.  */
5695   if (b->ops == NULL || b->ops->print_one == NULL)
5696     {
5697       /* If breakpoint has a single location that is disabled, we
5698          print it as if it had several locations, since otherwise it's
5699          hard to represent "breakpoint enabled, location disabled"
5700          situation.
5701
5702          Note that while hardware watchpoints have several locations
5703          internally, that's not a property exposed to user.  */
5704       if (b->loc 
5705           && !is_hardware_watchpoint (b)
5706           && (b->loc->next || !b->loc->enabled))
5707         {
5708           struct bp_location *loc;
5709           int n = 1;
5710
5711           for (loc = b->loc; loc; loc = loc->next, ++n)
5712             {
5713               struct cleanup *inner2 =
5714                 make_cleanup_ui_out_tuple_begin_end (uiout, NULL);
5715               print_one_breakpoint_location (b, loc, n, last_loc, allflag);
5716               do_cleanups (inner2);
5717             }
5718         }
5719     }
5720 }
5721
5722 static int
5723 breakpoint_address_bits (struct breakpoint *b)
5724 {
5725   int print_address_bits = 0;
5726   struct bp_location *loc;
5727
5728   for (loc = b->loc; loc; loc = loc->next)
5729     {
5730       int addr_bit;
5731
5732       /* Software watchpoints that aren't watching memory don't have
5733          an address to print.  */
5734       if (b->type == bp_watchpoint && loc->watchpoint_type == -1)
5735         continue;
5736
5737       addr_bit = gdbarch_addr_bit (loc->gdbarch);
5738       if (addr_bit > print_address_bits)
5739         print_address_bits = addr_bit;
5740     }
5741
5742   return print_address_bits;
5743 }
5744
5745 struct captured_breakpoint_query_args
5746   {
5747     int bnum;
5748   };
5749
5750 static int
5751 do_captured_breakpoint_query (struct ui_out *uiout, void *data)
5752 {
5753   struct captured_breakpoint_query_args *args = data;
5754   struct breakpoint *b;
5755   struct bp_location *dummy_loc = NULL;
5756
5757   ALL_BREAKPOINTS (b)
5758     {
5759       if (args->bnum == b->number)
5760         {
5761           print_one_breakpoint (b, &dummy_loc, 0);
5762           return GDB_RC_OK;
5763         }
5764     }
5765   return GDB_RC_NONE;
5766 }
5767
5768 enum gdb_rc
5769 gdb_breakpoint_query (struct ui_out *uiout, int bnum, 
5770                       char **error_message)
5771 {
5772   struct captured_breakpoint_query_args args;
5773
5774   args.bnum = bnum;
5775   /* For the moment we don't trust print_one_breakpoint() to not throw
5776      an error.  */
5777   if (catch_exceptions_with_msg (uiout, do_captured_breakpoint_query, &args,
5778                                  error_message, RETURN_MASK_ALL) < 0)
5779     return GDB_RC_FAIL;
5780   else
5781     return GDB_RC_OK;
5782 }
5783
5784 /* Return true if this breakpoint was set by the user, false if it is
5785    internal or momentary.  */
5786
5787 int
5788 user_breakpoint_p (struct breakpoint *b)
5789 {
5790   return b->number > 0;
5791 }
5792
5793 /* Print information on user settable breakpoint (watchpoint, etc)
5794    number BNUM.  If BNUM is -1 print all user-settable breakpoints.
5795    If ALLFLAG is non-zero, include non-user-settable breakpoints.  If
5796    FILTER is non-NULL, call it on each breakpoint and only include the
5797    ones for which it returns non-zero.  Return the total number of
5798    breakpoints listed.  */
5799
5800 static int
5801 breakpoint_1 (char *args, int allflag, 
5802               int (*filter) (const struct breakpoint *))
5803 {
5804   struct breakpoint *b;
5805   struct bp_location *last_loc = NULL;
5806   int nr_printable_breakpoints;
5807   struct cleanup *bkpttbl_chain;
5808   struct value_print_options opts;
5809   int print_address_bits = 0;
5810   int print_type_col_width = 14;
5811   struct ui_out *uiout = current_uiout;
5812
5813   get_user_print_options (&opts);
5814
5815   /* Compute the number of rows in the table, as well as the size
5816      required for address fields.  */
5817   nr_printable_breakpoints = 0;
5818   ALL_BREAKPOINTS (b)
5819     {
5820       /* If we have a filter, only list the breakpoints it accepts.  */
5821       if (filter && !filter (b))
5822         continue;
5823
5824       /* If we have an "args" string, it is a list of breakpoints to 
5825          accept.  Skip the others.  */
5826       if (args != NULL && *args != '\0')
5827         {
5828           if (allflag && parse_and_eval_long (args) != b->number)
5829             continue;
5830           if (!allflag && !number_is_in_list (args, b->number))
5831             continue;
5832         }
5833
5834       if (allflag || user_breakpoint_p (b))
5835         {
5836           int addr_bit, type_len;
5837
5838           addr_bit = breakpoint_address_bits (b);
5839           if (addr_bit > print_address_bits)
5840             print_address_bits = addr_bit;
5841
5842           type_len = strlen (bptype_string (b->type));
5843           if (type_len > print_type_col_width)
5844             print_type_col_width = type_len;
5845
5846           nr_printable_breakpoints++;
5847         }
5848     }
5849
5850   if (opts.addressprint)
5851     bkpttbl_chain 
5852       = make_cleanup_ui_out_table_begin_end (uiout, 6,
5853                                              nr_printable_breakpoints,
5854                                              "BreakpointTable");
5855   else
5856     bkpttbl_chain 
5857       = make_cleanup_ui_out_table_begin_end (uiout, 5,
5858                                              nr_printable_breakpoints,
5859                                              "BreakpointTable");
5860
5861   if (nr_printable_breakpoints > 0)
5862     annotate_breakpoints_headers ();
5863   if (nr_printable_breakpoints > 0)
5864     annotate_field (0);
5865   ui_out_table_header (uiout, 7, ui_left, "number", "Num");     /* 1 */
5866   if (nr_printable_breakpoints > 0)
5867     annotate_field (1);
5868   ui_out_table_header (uiout, print_type_col_width, ui_left,
5869                        "type", "Type");                         /* 2 */
5870   if (nr_printable_breakpoints > 0)
5871     annotate_field (2);
5872   ui_out_table_header (uiout, 4, ui_left, "disp", "Disp");      /* 3 */
5873   if (nr_printable_breakpoints > 0)
5874     annotate_field (3);
5875   ui_out_table_header (uiout, 3, ui_left, "enabled", "Enb");    /* 4 */
5876   if (opts.addressprint)
5877     {
5878       if (nr_printable_breakpoints > 0)
5879         annotate_field (4);
5880       if (print_address_bits <= 32)
5881         ui_out_table_header (uiout, 10, ui_left, 
5882                              "addr", "Address");                /* 5 */
5883       else
5884         ui_out_table_header (uiout, 18, ui_left, 
5885                              "addr", "Address");                /* 5 */
5886     }
5887   if (nr_printable_breakpoints > 0)
5888     annotate_field (5);
5889   ui_out_table_header (uiout, 40, ui_noalign, "what", "What");  /* 6 */
5890   ui_out_table_body (uiout);
5891   if (nr_printable_breakpoints > 0)
5892     annotate_breakpoints_table ();
5893
5894   ALL_BREAKPOINTS (b)
5895     {
5896       QUIT;
5897       /* If we have a filter, only list the breakpoints it accepts.  */
5898       if (filter && !filter (b))
5899         continue;
5900
5901       /* If we have an "args" string, it is a list of breakpoints to 
5902          accept.  Skip the others.  */
5903
5904       if (args != NULL && *args != '\0')
5905         {
5906           if (allflag)  /* maintenance info breakpoint */
5907             {
5908               if (parse_and_eval_long (args) != b->number)
5909                 continue;
5910             }
5911           else          /* all others */
5912             {
5913               if (!number_is_in_list (args, b->number))
5914                 continue;
5915             }
5916         }
5917       /* We only print out user settable breakpoints unless the
5918          allflag is set.  */
5919       if (allflag || user_breakpoint_p (b))
5920         print_one_breakpoint (b, &last_loc, allflag);
5921     }
5922
5923   do_cleanups (bkpttbl_chain);
5924
5925   if (nr_printable_breakpoints == 0)
5926     {
5927       /* If there's a filter, let the caller decide how to report
5928          empty list.  */
5929       if (!filter)
5930         {
5931           if (args == NULL || *args == '\0')
5932             ui_out_message (uiout, 0, "No breakpoints or watchpoints.\n");
5933           else
5934             ui_out_message (uiout, 0, 
5935                             "No breakpoint or watchpoint matching '%s'.\n",
5936                             args);
5937         }
5938     }
5939   else
5940     {
5941       if (last_loc && !server_command)
5942         set_next_address (last_loc->gdbarch, last_loc->address);
5943     }
5944
5945   /* FIXME?  Should this be moved up so that it is only called when
5946      there have been breakpoints? */
5947   annotate_breakpoints_table_end ();
5948
5949   return nr_printable_breakpoints;
5950 }
5951
5952 /* Display the value of default-collect in a way that is generally
5953    compatible with the breakpoint list.  */
5954
5955 static void
5956 default_collect_info (void)
5957 {
5958   struct ui_out *uiout = current_uiout;
5959
5960   /* If it has no value (which is frequently the case), say nothing; a
5961      message like "No default-collect." gets in user's face when it's
5962      not wanted.  */
5963   if (!*default_collect)
5964     return;
5965
5966   /* The following phrase lines up nicely with per-tracepoint collect
5967      actions.  */
5968   ui_out_text (uiout, "default collect ");
5969   ui_out_field_string (uiout, "default-collect", default_collect);
5970   ui_out_text (uiout, " \n");
5971 }
5972   
5973 static void
5974 breakpoints_info (char *args, int from_tty)
5975 {
5976   breakpoint_1 (args, 0, NULL);
5977
5978   default_collect_info ();
5979 }
5980
5981 static void
5982 watchpoints_info (char *args, int from_tty)
5983 {
5984   int num_printed = breakpoint_1 (args, 0, is_watchpoint);
5985   struct ui_out *uiout = current_uiout;
5986
5987   if (num_printed == 0)
5988     {
5989       if (args == NULL || *args == '\0')
5990         ui_out_message (uiout, 0, "No watchpoints.\n");
5991       else
5992         ui_out_message (uiout, 0, "No watchpoint matching '%s'.\n", args);
5993     }
5994 }
5995
5996 static void
5997 maintenance_info_breakpoints (char *args, int from_tty)
5998 {
5999   breakpoint_1 (args, 1, NULL);
6000
6001   default_collect_info ();
6002 }
6003
6004 static int
6005 breakpoint_has_pc (struct breakpoint *b,
6006                    struct program_space *pspace,
6007                    CORE_ADDR pc, struct obj_section *section)
6008 {
6009   struct bp_location *bl = b->loc;
6010
6011   for (; bl; bl = bl->next)
6012     {
6013       if (bl->pspace == pspace
6014           && bl->address == pc
6015           && (!overlay_debugging || bl->section == section))
6016         return 1;         
6017     }
6018   return 0;
6019 }
6020
6021 /* Print a message describing any user-breakpoints set at PC.  This
6022    concerns with logical breakpoints, so we match program spaces, not
6023    address spaces.  */
6024
6025 static void
6026 describe_other_breakpoints (struct gdbarch *gdbarch,
6027                             struct program_space *pspace, CORE_ADDR pc,
6028                             struct obj_section *section, int thread)
6029 {
6030   int others = 0;
6031   struct breakpoint *b;
6032
6033   ALL_BREAKPOINTS (b)
6034     others += (user_breakpoint_p (b)
6035                && breakpoint_has_pc (b, pspace, pc, section));
6036   if (others > 0)
6037     {
6038       if (others == 1)
6039         printf_filtered (_("Note: breakpoint "));
6040       else /* if (others == ???) */
6041         printf_filtered (_("Note: breakpoints "));
6042       ALL_BREAKPOINTS (b)
6043         if (user_breakpoint_p (b) && breakpoint_has_pc (b, pspace, pc, section))
6044           {
6045             others--;
6046             printf_filtered ("%d", b->number);
6047             if (b->thread == -1 && thread != -1)
6048               printf_filtered (" (all threads)");
6049             else if (b->thread != -1)
6050               printf_filtered (" (thread %d)", b->thread);
6051             printf_filtered ("%s%s ",
6052                              ((b->enable_state == bp_disabled
6053                                || b->enable_state == bp_call_disabled)
6054                               ? " (disabled)"
6055                               : b->enable_state == bp_permanent 
6056                               ? " (permanent)"
6057                               : ""),
6058                              (others > 1) ? "," 
6059                              : ((others == 1) ? " and" : ""));
6060           }
6061       printf_filtered (_("also set at pc "));
6062       fputs_filtered (paddress (gdbarch, pc), gdb_stdout);
6063       printf_filtered (".\n");
6064     }
6065 }
6066 \f
6067
6068 /* Return true iff it is meaningful to use the address member of
6069    BPT.  For some breakpoint types, the address member is irrelevant
6070    and it makes no sense to attempt to compare it to other addresses
6071    (or use it for any other purpose either).
6072
6073    More specifically, each of the following breakpoint types will
6074    always have a zero valued address and we don't want to mark
6075    breakpoints of any of these types to be a duplicate of an actual
6076    breakpoint at address zero:
6077
6078       bp_watchpoint
6079       bp_catchpoint
6080
6081 */
6082
6083 static int
6084 breakpoint_address_is_meaningful (struct breakpoint *bpt)
6085 {
6086   enum bptype type = bpt->type;
6087
6088   return (type != bp_watchpoint && type != bp_catchpoint);
6089 }
6090
6091 /* Assuming LOC1 and LOC2's owners are hardware watchpoints, returns
6092    true if LOC1 and LOC2 represent the same watchpoint location.  */
6093
6094 static int
6095 watchpoint_locations_match (struct bp_location *loc1, 
6096                             struct bp_location *loc2)
6097 {
6098   struct watchpoint *w1 = (struct watchpoint *) loc1->owner;
6099   struct watchpoint *w2 = (struct watchpoint *) loc2->owner;
6100
6101   /* Both of them must exist.  */
6102   gdb_assert (w1 != NULL);
6103   gdb_assert (w2 != NULL);
6104
6105   /* If the target can evaluate the condition expression in hardware,
6106      then we we need to insert both watchpoints even if they are at
6107      the same place.  Otherwise the watchpoint will only trigger when
6108      the condition of whichever watchpoint was inserted evaluates to
6109      true, not giving a chance for GDB to check the condition of the
6110      other watchpoint.  */
6111   if ((w1->cond_exp
6112        && target_can_accel_watchpoint_condition (loc1->address, 
6113                                                  loc1->length,
6114                                                  loc1->watchpoint_type,
6115                                                  w1->cond_exp))
6116       || (w2->cond_exp
6117           && target_can_accel_watchpoint_condition (loc2->address, 
6118                                                     loc2->length,
6119                                                     loc2->watchpoint_type,
6120                                                     w2->cond_exp)))
6121     return 0;
6122
6123   /* Note that this checks the owner's type, not the location's.  In
6124      case the target does not support read watchpoints, but does
6125      support access watchpoints, we'll have bp_read_watchpoint
6126      watchpoints with hw_access locations.  Those should be considered
6127      duplicates of hw_read locations.  The hw_read locations will
6128      become hw_access locations later.  */
6129   return (loc1->owner->type == loc2->owner->type
6130           && loc1->pspace->aspace == loc2->pspace->aspace
6131           && loc1->address == loc2->address
6132           && loc1->length == loc2->length);
6133 }
6134
6135 /* Returns true if {ASPACE1,ADDR1} and {ASPACE2,ADDR2} represent the
6136    same breakpoint location.  In most targets, this can only be true
6137    if ASPACE1 matches ASPACE2.  On targets that have global
6138    breakpoints, the address space doesn't really matter.  */
6139
6140 static int
6141 breakpoint_address_match (struct address_space *aspace1, CORE_ADDR addr1,
6142                           struct address_space *aspace2, CORE_ADDR addr2)
6143 {
6144   return ((gdbarch_has_global_breakpoints (target_gdbarch)
6145            || aspace1 == aspace2)
6146           && addr1 == addr2);
6147 }
6148
6149 /* Returns true if {ASPACE2,ADDR2} falls within the range determined by
6150    {ASPACE1,ADDR1,LEN1}.  In most targets, this can only be true if ASPACE1
6151    matches ASPACE2.  On targets that have global breakpoints, the address
6152    space doesn't really matter.  */
6153
6154 static int
6155 breakpoint_address_match_range (struct address_space *aspace1, CORE_ADDR addr1,
6156                                 int len1, struct address_space *aspace2,
6157                                 CORE_ADDR addr2)
6158 {
6159   return ((gdbarch_has_global_breakpoints (target_gdbarch)
6160            || aspace1 == aspace2)
6161           && addr2 >= addr1 && addr2 < addr1 + len1);
6162 }
6163
6164 /* Returns true if {ASPACE,ADDR} matches the breakpoint BL.  BL may be
6165    a ranged breakpoint.  In most targets, a match happens only if ASPACE
6166    matches the breakpoint's address space.  On targets that have global
6167    breakpoints, the address space doesn't really matter.  */
6168
6169 static int
6170 breakpoint_location_address_match (struct bp_location *bl,
6171                                    struct address_space *aspace,
6172                                    CORE_ADDR addr)
6173 {
6174   return (breakpoint_address_match (bl->pspace->aspace, bl->address,
6175                                     aspace, addr)
6176           || (bl->length
6177               && breakpoint_address_match_range (bl->pspace->aspace,
6178                                                  bl->address, bl->length,
6179                                                  aspace, addr)));
6180 }
6181
6182 /* If LOC1 and LOC2's owners are not tracepoints, returns false directly.
6183    Then, if LOC1 and LOC2 represent the same tracepoint location, returns
6184    true, otherwise returns false.  */
6185
6186 static int
6187 tracepoint_locations_match (struct bp_location *loc1,
6188                             struct bp_location *loc2)
6189 {
6190   if (is_tracepoint (loc1->owner) && is_tracepoint (loc2->owner))
6191     /* Since tracepoint locations are never duplicated with others', tracepoint
6192        locations at the same address of different tracepoints are regarded as
6193        different locations.  */
6194     return (loc1->address == loc2->address && loc1->owner == loc2->owner);
6195   else
6196     return 0;
6197 }
6198
6199 /* Assuming LOC1 and LOC2's types' have meaningful target addresses
6200    (breakpoint_address_is_meaningful), returns true if LOC1 and LOC2
6201    represent the same location.  */
6202
6203 static int
6204 breakpoint_locations_match (struct bp_location *loc1, 
6205                             struct bp_location *loc2)
6206 {
6207   int hw_point1, hw_point2;
6208
6209   /* Both of them must not be in moribund_locations.  */
6210   gdb_assert (loc1->owner != NULL);
6211   gdb_assert (loc2->owner != NULL);
6212
6213   hw_point1 = is_hardware_watchpoint (loc1->owner);
6214   hw_point2 = is_hardware_watchpoint (loc2->owner);
6215
6216   if (hw_point1 != hw_point2)
6217     return 0;
6218   else if (hw_point1)
6219     return watchpoint_locations_match (loc1, loc2);
6220   else if (is_tracepoint (loc1->owner) || is_tracepoint (loc2->owner))
6221     return tracepoint_locations_match (loc1, loc2);
6222   else
6223     /* We compare bp_location.length in order to cover ranged breakpoints.  */
6224     return (breakpoint_address_match (loc1->pspace->aspace, loc1->address,
6225                                      loc2->pspace->aspace, loc2->address)
6226             && loc1->length == loc2->length);
6227 }
6228
6229 static void
6230 breakpoint_adjustment_warning (CORE_ADDR from_addr, CORE_ADDR to_addr,
6231                                int bnum, int have_bnum)
6232 {
6233   /* The longest string possibly returned by hex_string_custom
6234      is 50 chars.  These must be at least that big for safety.  */
6235   char astr1[64];
6236   char astr2[64];
6237
6238   strcpy (astr1, hex_string_custom ((unsigned long) from_addr, 8));
6239   strcpy (astr2, hex_string_custom ((unsigned long) to_addr, 8));
6240   if (have_bnum)
6241     warning (_("Breakpoint %d address previously adjusted from %s to %s."),
6242              bnum, astr1, astr2);
6243   else
6244     warning (_("Breakpoint address adjusted from %s to %s."), astr1, astr2);
6245 }
6246
6247 /* Adjust a breakpoint's address to account for architectural
6248    constraints on breakpoint placement.  Return the adjusted address.
6249    Note: Very few targets require this kind of adjustment.  For most
6250    targets, this function is simply the identity function.  */
6251
6252 static CORE_ADDR
6253 adjust_breakpoint_address (struct gdbarch *gdbarch,
6254                            CORE_ADDR bpaddr, enum bptype bptype)
6255 {
6256   if (!gdbarch_adjust_breakpoint_address_p (gdbarch))
6257     {
6258       /* Very few targets need any kind of breakpoint adjustment.  */
6259       return bpaddr;
6260     }
6261   else if (bptype == bp_watchpoint
6262            || bptype == bp_hardware_watchpoint
6263            || bptype == bp_read_watchpoint
6264            || bptype == bp_access_watchpoint
6265            || bptype == bp_catchpoint)
6266     {
6267       /* Watchpoints and the various bp_catch_* eventpoints should not
6268          have their addresses modified.  */
6269       return bpaddr;
6270     }
6271   else
6272     {
6273       CORE_ADDR adjusted_bpaddr;
6274
6275       /* Some targets have architectural constraints on the placement
6276          of breakpoint instructions.  Obtain the adjusted address.  */
6277       adjusted_bpaddr = gdbarch_adjust_breakpoint_address (gdbarch, bpaddr);
6278
6279       /* An adjusted breakpoint address can significantly alter
6280          a user's expectations.  Print a warning if an adjustment
6281          is required.  */
6282       if (adjusted_bpaddr != bpaddr)
6283         breakpoint_adjustment_warning (bpaddr, adjusted_bpaddr, 0, 0);
6284
6285       return adjusted_bpaddr;
6286     }
6287 }
6288
6289 void
6290 init_bp_location (struct bp_location *loc, const struct bp_location_ops *ops,
6291                   struct breakpoint *owner)
6292 {
6293   memset (loc, 0, sizeof (*loc));
6294
6295   gdb_assert (ops != NULL);
6296
6297   loc->ops = ops;
6298   loc->owner = owner;
6299   loc->cond = NULL;
6300   loc->cond_bytecode = NULL;
6301   loc->shlib_disabled = 0;
6302   loc->enabled = 1;
6303
6304   switch (owner->type)
6305     {
6306     case bp_breakpoint:
6307     case bp_until:
6308     case bp_finish:
6309     case bp_longjmp:
6310     case bp_longjmp_resume:
6311     case bp_exception:
6312     case bp_exception_resume:
6313     case bp_step_resume:
6314     case bp_hp_step_resume:
6315     case bp_watchpoint_scope:
6316     case bp_call_dummy:
6317     case bp_std_terminate:
6318     case bp_shlib_event:
6319     case bp_thread_event:
6320     case bp_overlay_event:
6321     case bp_jit_event:
6322     case bp_longjmp_master:
6323     case bp_std_terminate_master:
6324     case bp_exception_master:
6325     case bp_gnu_ifunc_resolver:
6326     case bp_gnu_ifunc_resolver_return:
6327       loc->loc_type = bp_loc_software_breakpoint;
6328       mark_breakpoint_location_modified (loc);
6329       break;
6330     case bp_hardware_breakpoint:
6331       loc->loc_type = bp_loc_hardware_breakpoint;
6332       mark_breakpoint_location_modified (loc);
6333       break;
6334     case bp_hardware_watchpoint:
6335     case bp_read_watchpoint:
6336     case bp_access_watchpoint:
6337       loc->loc_type = bp_loc_hardware_watchpoint;
6338       break;
6339     case bp_watchpoint:
6340     case bp_catchpoint:
6341     case bp_tracepoint:
6342     case bp_fast_tracepoint:
6343     case bp_static_tracepoint:
6344       loc->loc_type = bp_loc_other;
6345       break;
6346     default:
6347       internal_error (__FILE__, __LINE__, _("unknown breakpoint type"));
6348     }
6349
6350   loc->refc = 1;
6351 }
6352
6353 /* Allocate a struct bp_location.  */
6354
6355 static struct bp_location *
6356 allocate_bp_location (struct breakpoint *bpt)
6357 {
6358   return bpt->ops->allocate_location (bpt);
6359 }
6360
6361 static void
6362 free_bp_location (struct bp_location *loc)
6363 {
6364   loc->ops->dtor (loc);
6365   xfree (loc);
6366 }
6367
6368 /* Increment reference count.  */
6369
6370 static void
6371 incref_bp_location (struct bp_location *bl)
6372 {
6373   ++bl->refc;
6374 }
6375
6376 /* Decrement reference count.  If the reference count reaches 0,
6377    destroy the bp_location.  Sets *BLP to NULL.  */
6378
6379 static void
6380 decref_bp_location (struct bp_location **blp)
6381 {
6382   gdb_assert ((*blp)->refc > 0);
6383
6384   if (--(*blp)->refc == 0)
6385     free_bp_location (*blp);
6386   *blp = NULL;
6387 }
6388
6389 /* Add breakpoint B at the end of the global breakpoint chain.  */
6390
6391 static void
6392 add_to_breakpoint_chain (struct breakpoint *b)
6393 {
6394   struct breakpoint *b1;
6395
6396   /* Add this breakpoint to the end of the chain so that a list of
6397      breakpoints will come out in order of increasing numbers.  */
6398
6399   b1 = breakpoint_chain;
6400   if (b1 == 0)
6401     breakpoint_chain = b;
6402   else
6403     {
6404       while (b1->next)
6405         b1 = b1->next;
6406       b1->next = b;
6407     }
6408 }
6409
6410 /* Initializes breakpoint B with type BPTYPE and no locations yet.  */
6411
6412 static void
6413 init_raw_breakpoint_without_location (struct breakpoint *b,
6414                                       struct gdbarch *gdbarch,
6415                                       enum bptype bptype,
6416                                       const struct breakpoint_ops *ops)
6417 {
6418   memset (b, 0, sizeof (*b));
6419
6420   gdb_assert (ops != NULL);
6421
6422   b->ops = ops;
6423   b->type = bptype;
6424   b->gdbarch = gdbarch;
6425   b->language = current_language->la_language;
6426   b->input_radix = input_radix;
6427   b->thread = -1;
6428   b->enable_state = bp_enabled;
6429   b->next = 0;
6430   b->silent = 0;
6431   b->ignore_count = 0;
6432   b->commands = NULL;
6433   b->frame_id = null_frame_id;
6434   b->condition_not_parsed = 0;
6435   b->py_bp_object = NULL;
6436   b->related_breakpoint = b;
6437 }
6438
6439 /* Helper to set_raw_breakpoint below.  Creates a breakpoint
6440    that has type BPTYPE and has no locations as yet.  */
6441
6442 static struct breakpoint *
6443 set_raw_breakpoint_without_location (struct gdbarch *gdbarch,
6444                                      enum bptype bptype,
6445                                      const struct breakpoint_ops *ops)
6446 {
6447   struct breakpoint *b = XNEW (struct breakpoint);
6448
6449   init_raw_breakpoint_without_location (b, gdbarch, bptype, ops);
6450   add_to_breakpoint_chain (b);
6451   return b;
6452 }
6453
6454 /* Initialize loc->function_name.  EXPLICIT_LOC says no indirect function
6455    resolutions should be made as the user specified the location explicitly
6456    enough.  */
6457
6458 static void
6459 set_breakpoint_location_function (struct bp_location *loc, int explicit_loc)
6460 {
6461   gdb_assert (loc->owner != NULL);
6462
6463   if (loc->owner->type == bp_breakpoint
6464       || loc->owner->type == bp_hardware_breakpoint
6465       || is_tracepoint (loc->owner))
6466     {
6467       int is_gnu_ifunc;
6468       const char *function_name;
6469
6470       find_pc_partial_function_gnu_ifunc (loc->address, &function_name,
6471                                           NULL, NULL, &is_gnu_ifunc);
6472
6473       if (is_gnu_ifunc && !explicit_loc)
6474         {
6475           struct breakpoint *b = loc->owner;
6476
6477           gdb_assert (loc->pspace == current_program_space);
6478           if (gnu_ifunc_resolve_name (function_name,
6479                                       &loc->requested_address))
6480             {
6481               /* Recalculate ADDRESS based on new REQUESTED_ADDRESS.  */
6482               loc->address = adjust_breakpoint_address (loc->gdbarch,
6483                                                         loc->requested_address,
6484                                                         b->type);
6485             }
6486           else if (b->type == bp_breakpoint && b->loc == loc
6487                    && loc->next == NULL && b->related_breakpoint == b)
6488             {
6489               /* Create only the whole new breakpoint of this type but do not
6490                  mess more complicated breakpoints with multiple locations.  */
6491               b->type = bp_gnu_ifunc_resolver;
6492             }
6493         }
6494
6495       if (function_name)
6496         loc->function_name = xstrdup (function_name);
6497     }
6498 }
6499
6500 /* Attempt to determine architecture of location identified by SAL.  */
6501 struct gdbarch *
6502 get_sal_arch (struct symtab_and_line sal)
6503 {
6504   if (sal.section)
6505     return get_objfile_arch (sal.section->objfile);
6506   if (sal.symtab)
6507     return get_objfile_arch (sal.symtab->objfile);
6508
6509   return NULL;
6510 }
6511
6512 /* Low level routine for partially initializing a breakpoint of type
6513    BPTYPE.  The newly created breakpoint's address, section, source
6514    file name, and line number are provided by SAL.
6515
6516    It is expected that the caller will complete the initialization of
6517    the newly created breakpoint struct as well as output any status
6518    information regarding the creation of a new breakpoint.  */
6519
6520 static void
6521 init_raw_breakpoint (struct breakpoint *b, struct gdbarch *gdbarch,
6522                      struct symtab_and_line sal, enum bptype bptype,
6523                      const struct breakpoint_ops *ops)
6524 {
6525   init_raw_breakpoint_without_location (b, gdbarch, bptype, ops);
6526
6527   add_location_to_breakpoint (b, &sal);
6528
6529   if (bptype != bp_catchpoint)
6530     gdb_assert (sal.pspace != NULL);
6531
6532   /* Store the program space that was used to set the breakpoint,
6533      except for ordinary breakpoints, which are independent of the
6534      program space.  */
6535   if (bptype != bp_breakpoint && bptype != bp_hardware_breakpoint)
6536     b->pspace = sal.pspace;
6537
6538   breakpoints_changed ();
6539 }
6540
6541 /* set_raw_breakpoint is a low level routine for allocating and
6542    partially initializing a breakpoint of type BPTYPE.  The newly
6543    created breakpoint's address, section, source file name, and line
6544    number are provided by SAL.  The newly created and partially
6545    initialized breakpoint is added to the breakpoint chain and
6546    is also returned as the value of this function.
6547
6548    It is expected that the caller will complete the initialization of
6549    the newly created breakpoint struct as well as output any status
6550    information regarding the creation of a new breakpoint.  In
6551    particular, set_raw_breakpoint does NOT set the breakpoint
6552    number!  Care should be taken to not allow an error to occur
6553    prior to completing the initialization of the breakpoint.  If this
6554    should happen, a bogus breakpoint will be left on the chain.  */
6555
6556 struct breakpoint *
6557 set_raw_breakpoint (struct gdbarch *gdbarch,
6558                     struct symtab_and_line sal, enum bptype bptype,
6559                     const struct breakpoint_ops *ops)
6560 {
6561   struct breakpoint *b = XNEW (struct breakpoint);
6562
6563   init_raw_breakpoint (b, gdbarch, sal, bptype, ops);
6564   add_to_breakpoint_chain (b);
6565   return b;
6566 }
6567
6568
6569 /* Note that the breakpoint object B describes a permanent breakpoint
6570    instruction, hard-wired into the inferior's code.  */
6571 void
6572 make_breakpoint_permanent (struct breakpoint *b)
6573 {
6574   struct bp_location *bl;
6575
6576   b->enable_state = bp_permanent;
6577
6578   /* By definition, permanent breakpoints are already present in the
6579      code.  Mark all locations as inserted.  For now,
6580      make_breakpoint_permanent is called in just one place, so it's
6581      hard to say if it's reasonable to have permanent breakpoint with
6582      multiple locations or not, but it's easy to implement.  */
6583   for (bl = b->loc; bl; bl = bl->next)
6584     bl->inserted = 1;
6585 }
6586
6587 /* Call this routine when stepping and nexting to enable a breakpoint
6588    if we do a longjmp() or 'throw' in TP.  FRAME is the frame which
6589    initiated the operation.  */
6590
6591 void
6592 set_longjmp_breakpoint (struct thread_info *tp, struct frame_id frame)
6593 {
6594   struct breakpoint *b, *b_tmp;
6595   int thread = tp->num;
6596
6597   /* To avoid having to rescan all objfile symbols at every step,
6598      we maintain a list of continually-inserted but always disabled
6599      longjmp "master" breakpoints.  Here, we simply create momentary
6600      clones of those and enable them for the requested thread.  */
6601   ALL_BREAKPOINTS_SAFE (b, b_tmp)
6602     if (b->pspace == current_program_space
6603         && (b->type == bp_longjmp_master
6604             || b->type == bp_exception_master))
6605       {
6606         enum bptype type = b->type == bp_longjmp_master ? bp_longjmp : bp_exception;
6607         struct breakpoint *clone;
6608
6609         clone = momentary_breakpoint_from_master (b, type,
6610                                                   &momentary_breakpoint_ops);
6611         clone->thread = thread;
6612       }
6613
6614   tp->initiating_frame = frame;
6615 }
6616
6617 /* Delete all longjmp breakpoints from THREAD.  */
6618 void
6619 delete_longjmp_breakpoint (int thread)
6620 {
6621   struct breakpoint *b, *b_tmp;
6622
6623   ALL_BREAKPOINTS_SAFE (b, b_tmp)
6624     if (b->type == bp_longjmp || b->type == bp_exception)
6625       {
6626         if (b->thread == thread)
6627           delete_breakpoint (b);
6628       }
6629 }
6630
6631 void
6632 delete_longjmp_breakpoint_at_next_stop (int thread)
6633 {
6634   struct breakpoint *b, *b_tmp;
6635
6636   ALL_BREAKPOINTS_SAFE (b, b_tmp)
6637     if (b->type == bp_longjmp || b->type == bp_exception)
6638       {
6639         if (b->thread == thread)
6640           b->disposition = disp_del_at_next_stop;
6641       }
6642 }
6643
6644 void
6645 enable_overlay_breakpoints (void)
6646 {
6647   struct breakpoint *b;
6648
6649   ALL_BREAKPOINTS (b)
6650     if (b->type == bp_overlay_event)
6651     {
6652       b->enable_state = bp_enabled;
6653       update_global_location_list (1);
6654       overlay_events_enabled = 1;
6655     }
6656 }
6657
6658 void
6659 disable_overlay_breakpoints (void)
6660 {
6661   struct breakpoint *b;
6662
6663   ALL_BREAKPOINTS (b)
6664     if (b->type == bp_overlay_event)
6665     {
6666       b->enable_state = bp_disabled;
6667       update_global_location_list (0);
6668       overlay_events_enabled = 0;
6669     }
6670 }
6671
6672 /* Set an active std::terminate breakpoint for each std::terminate
6673    master breakpoint.  */
6674 void
6675 set_std_terminate_breakpoint (void)
6676 {
6677   struct breakpoint *b, *b_tmp;
6678
6679   ALL_BREAKPOINTS_SAFE (b, b_tmp)
6680     if (b->pspace == current_program_space
6681         && b->type == bp_std_terminate_master)
6682       {
6683         momentary_breakpoint_from_master (b, bp_std_terminate,
6684                                           &momentary_breakpoint_ops);
6685       }
6686 }
6687
6688 /* Delete all the std::terminate breakpoints.  */
6689 void
6690 delete_std_terminate_breakpoint (void)
6691 {
6692   struct breakpoint *b, *b_tmp;
6693
6694   ALL_BREAKPOINTS_SAFE (b, b_tmp)
6695     if (b->type == bp_std_terminate)
6696       delete_breakpoint (b);
6697 }
6698
6699 struct breakpoint *
6700 create_thread_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
6701 {
6702   struct breakpoint *b;
6703
6704   b = create_internal_breakpoint (gdbarch, address, bp_thread_event,
6705                                   &internal_breakpoint_ops);
6706
6707   b->enable_state = bp_enabled;
6708   /* addr_string has to be used or breakpoint_re_set will delete me.  */
6709   b->addr_string
6710     = xstrprintf ("*%s", paddress (b->loc->gdbarch, b->loc->address));
6711
6712   update_global_location_list_nothrow (1);
6713
6714   return b;
6715 }
6716
6717 void
6718 remove_thread_event_breakpoints (void)
6719 {
6720   struct breakpoint *b, *b_tmp;
6721
6722   ALL_BREAKPOINTS_SAFE (b, b_tmp)
6723     if (b->type == bp_thread_event
6724         && b->loc->pspace == current_program_space)
6725       delete_breakpoint (b);
6726 }
6727
6728 struct lang_and_radix
6729   {
6730     enum language lang;
6731     int radix;
6732   };
6733
6734 /* Create a breakpoint for JIT code registration and unregistration.  */
6735
6736 struct breakpoint *
6737 create_jit_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
6738 {
6739   struct breakpoint *b;
6740
6741   b = create_internal_breakpoint (gdbarch, address, bp_jit_event,
6742                                   &internal_breakpoint_ops);
6743   update_global_location_list_nothrow (1);
6744   return b;
6745 }
6746
6747 /* Remove JIT code registration and unregistration breakpoint(s).  */
6748
6749 void
6750 remove_jit_event_breakpoints (void)
6751 {
6752   struct breakpoint *b, *b_tmp;
6753
6754   ALL_BREAKPOINTS_SAFE (b, b_tmp)
6755     if (b->type == bp_jit_event
6756         && b->loc->pspace == current_program_space)
6757       delete_breakpoint (b);
6758 }
6759
6760 void
6761 remove_solib_event_breakpoints (void)
6762 {
6763   struct breakpoint *b, *b_tmp;
6764
6765   ALL_BREAKPOINTS_SAFE (b, b_tmp)
6766     if (b->type == bp_shlib_event
6767         && b->loc->pspace == current_program_space)
6768       delete_breakpoint (b);
6769 }
6770
6771 struct breakpoint *
6772 create_solib_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
6773 {
6774   struct breakpoint *b;
6775
6776   b = create_internal_breakpoint (gdbarch, address, bp_shlib_event,
6777                                   &internal_breakpoint_ops);
6778   update_global_location_list_nothrow (1);
6779   return b;
6780 }
6781
6782 /* Disable any breakpoints that are on code in shared libraries.  Only
6783    apply to enabled breakpoints, disabled ones can just stay disabled.  */
6784
6785 void
6786 disable_breakpoints_in_shlibs (void)
6787 {
6788   struct bp_location *loc, **locp_tmp;
6789
6790   ALL_BP_LOCATIONS (loc, locp_tmp)
6791   {
6792     /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
6793     struct breakpoint *b = loc->owner;
6794
6795     /* We apply the check to all breakpoints, including disabled for
6796        those with loc->duplicate set.  This is so that when breakpoint
6797        becomes enabled, or the duplicate is removed, gdb will try to
6798        insert all breakpoints.  If we don't set shlib_disabled here,
6799        we'll try to insert those breakpoints and fail.  */
6800     if (((b->type == bp_breakpoint)
6801          || (b->type == bp_jit_event)
6802          || (b->type == bp_hardware_breakpoint)
6803          || (is_tracepoint (b)))
6804         && loc->pspace == current_program_space
6805         && !loc->shlib_disabled
6806 #ifdef PC_SOLIB
6807         && PC_SOLIB (loc->address)
6808 #else
6809         && solib_name_from_address (loc->pspace, loc->address)
6810 #endif
6811         )
6812       {
6813         loc->shlib_disabled = 1;
6814       }
6815   }
6816 }
6817
6818 /* Disable any breakpoints and tracepoints that are in an unloaded shared
6819    library.  Only apply to enabled breakpoints, disabled ones can just stay
6820    disabled.  */
6821
6822 static void
6823 disable_breakpoints_in_unloaded_shlib (struct so_list *solib)
6824 {
6825   struct bp_location *loc, **locp_tmp;
6826   int disabled_shlib_breaks = 0;
6827
6828   /* SunOS a.out shared libraries are always mapped, so do not
6829      disable breakpoints; they will only be reported as unloaded
6830      through clear_solib when GDB discards its shared library
6831      list.  See clear_solib for more information.  */
6832   if (exec_bfd != NULL
6833       && bfd_get_flavour (exec_bfd) == bfd_target_aout_flavour)
6834     return;
6835
6836   ALL_BP_LOCATIONS (loc, locp_tmp)
6837   {
6838     /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
6839     struct breakpoint *b = loc->owner;
6840
6841     if (solib->pspace == loc->pspace
6842         && !loc->shlib_disabled
6843         && (((b->type == bp_breakpoint
6844               || b->type == bp_jit_event
6845               || b->type == bp_hardware_breakpoint)
6846              && (loc->loc_type == bp_loc_hardware_breakpoint
6847                  || loc->loc_type == bp_loc_software_breakpoint))
6848             || is_tracepoint (b))
6849         && solib_contains_address_p (solib, loc->address))
6850       {
6851         loc->shlib_disabled = 1;
6852         /* At this point, we cannot rely on remove_breakpoint
6853            succeeding so we must mark the breakpoint as not inserted
6854            to prevent future errors occurring in remove_breakpoints.  */
6855         loc->inserted = 0;
6856
6857         /* This may cause duplicate notifications for the same breakpoint.  */
6858         observer_notify_breakpoint_modified (b);
6859
6860         if (!disabled_shlib_breaks)
6861           {
6862             target_terminal_ours_for_output ();
6863             warning (_("Temporarily disabling breakpoints "
6864                        "for unloaded shared library \"%s\""),
6865                      solib->so_name);
6866           }
6867         disabled_shlib_breaks = 1;
6868       }
6869   }
6870 }
6871
6872 /* FORK & VFORK catchpoints.  */
6873
6874 /* An instance of this type is used to represent a fork or vfork
6875    catchpoint.  It includes a "struct breakpoint" as a kind of base
6876    class; users downcast to "struct breakpoint *" when needed.  A
6877    breakpoint is really of this type iff its ops pointer points to
6878    CATCH_FORK_BREAKPOINT_OPS.  */
6879
6880 struct fork_catchpoint
6881 {
6882   /* The base class.  */
6883   struct breakpoint base;
6884
6885   /* Process id of a child process whose forking triggered this
6886      catchpoint.  This field is only valid immediately after this
6887      catchpoint has triggered.  */
6888   ptid_t forked_inferior_pid;
6889 };
6890
6891 /* Implement the "insert" breakpoint_ops method for fork
6892    catchpoints.  */
6893
6894 static int
6895 insert_catch_fork (struct bp_location *bl)
6896 {
6897   return target_insert_fork_catchpoint (PIDGET (inferior_ptid));
6898 }
6899
6900 /* Implement the "remove" breakpoint_ops method for fork
6901    catchpoints.  */
6902
6903 static int
6904 remove_catch_fork (struct bp_location *bl)
6905 {
6906   return target_remove_fork_catchpoint (PIDGET (inferior_ptid));
6907 }
6908
6909 /* Implement the "breakpoint_hit" breakpoint_ops method for fork
6910    catchpoints.  */
6911
6912 static int
6913 breakpoint_hit_catch_fork (const struct bp_location *bl,
6914                            struct address_space *aspace, CORE_ADDR bp_addr,
6915                            const struct target_waitstatus *ws)
6916 {
6917   struct fork_catchpoint *c = (struct fork_catchpoint *) bl->owner;
6918
6919   if (ws->kind != TARGET_WAITKIND_FORKED)
6920     return 0;
6921
6922   c->forked_inferior_pid = ws->value.related_pid;
6923   return 1;
6924 }
6925
6926 /* Implement the "print_it" breakpoint_ops method for fork
6927    catchpoints.  */
6928
6929 static enum print_stop_action
6930 print_it_catch_fork (bpstat bs)
6931 {
6932   struct ui_out *uiout = current_uiout;
6933   struct breakpoint *b = bs->breakpoint_at;
6934   struct fork_catchpoint *c = (struct fork_catchpoint *) bs->breakpoint_at;
6935
6936   annotate_catchpoint (b->number);
6937   if (b->disposition == disp_del)
6938     ui_out_text (uiout, "\nTemporary catchpoint ");
6939   else
6940     ui_out_text (uiout, "\nCatchpoint ");
6941   if (ui_out_is_mi_like_p (uiout))
6942     {
6943       ui_out_field_string (uiout, "reason",
6944                            async_reason_lookup (EXEC_ASYNC_FORK));
6945       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
6946     }
6947   ui_out_field_int (uiout, "bkptno", b->number);
6948   ui_out_text (uiout, " (forked process ");
6949   ui_out_field_int (uiout, "newpid", ptid_get_pid (c->forked_inferior_pid));
6950   ui_out_text (uiout, "), ");
6951   return PRINT_SRC_AND_LOC;
6952 }
6953
6954 /* Implement the "print_one" breakpoint_ops method for fork
6955    catchpoints.  */
6956
6957 static void
6958 print_one_catch_fork (struct breakpoint *b, struct bp_location **last_loc)
6959 {
6960   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
6961   struct value_print_options opts;
6962   struct ui_out *uiout = current_uiout;
6963
6964   get_user_print_options (&opts);
6965
6966   /* Field 4, the address, is omitted (which makes the columns not
6967      line up too nicely with the headers, but the effect is relatively
6968      readable).  */
6969   if (opts.addressprint)
6970     ui_out_field_skip (uiout, "addr");
6971   annotate_field (5);
6972   ui_out_text (uiout, "fork");
6973   if (!ptid_equal (c->forked_inferior_pid, null_ptid))
6974     {
6975       ui_out_text (uiout, ", process ");
6976       ui_out_field_int (uiout, "what",
6977                         ptid_get_pid (c->forked_inferior_pid));
6978       ui_out_spaces (uiout, 1);
6979     }
6980 }
6981
6982 /* Implement the "print_mention" breakpoint_ops method for fork
6983    catchpoints.  */
6984
6985 static void
6986 print_mention_catch_fork (struct breakpoint *b)
6987 {
6988   printf_filtered (_("Catchpoint %d (fork)"), b->number);
6989 }
6990
6991 /* Implement the "print_recreate" breakpoint_ops method for fork
6992    catchpoints.  */
6993
6994 static void
6995 print_recreate_catch_fork (struct breakpoint *b, struct ui_file *fp)
6996 {
6997   fprintf_unfiltered (fp, "catch fork");
6998   print_recreate_thread (b, fp);
6999 }
7000
7001 /* The breakpoint_ops structure to be used in fork catchpoints.  */
7002
7003 static struct breakpoint_ops catch_fork_breakpoint_ops;
7004
7005 /* Implement the "insert" breakpoint_ops method for vfork
7006    catchpoints.  */
7007
7008 static int
7009 insert_catch_vfork (struct bp_location *bl)
7010 {
7011   return target_insert_vfork_catchpoint (PIDGET (inferior_ptid));
7012 }
7013
7014 /* Implement the "remove" breakpoint_ops method for vfork
7015    catchpoints.  */
7016
7017 static int
7018 remove_catch_vfork (struct bp_location *bl)
7019 {
7020   return target_remove_vfork_catchpoint (PIDGET (inferior_ptid));
7021 }
7022
7023 /* Implement the "breakpoint_hit" breakpoint_ops method for vfork
7024    catchpoints.  */
7025
7026 static int
7027 breakpoint_hit_catch_vfork (const struct bp_location *bl,
7028                             struct address_space *aspace, CORE_ADDR bp_addr,
7029                             const struct target_waitstatus *ws)
7030 {
7031   struct fork_catchpoint *c = (struct fork_catchpoint *) bl->owner;
7032
7033   if (ws->kind != TARGET_WAITKIND_VFORKED)
7034     return 0;
7035
7036   c->forked_inferior_pid = ws->value.related_pid;
7037   return 1;
7038 }
7039
7040 /* Implement the "print_it" breakpoint_ops method for vfork
7041    catchpoints.  */
7042
7043 static enum print_stop_action
7044 print_it_catch_vfork (bpstat bs)
7045 {
7046   struct ui_out *uiout = current_uiout;
7047   struct breakpoint *b = bs->breakpoint_at;
7048   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
7049
7050   annotate_catchpoint (b->number);
7051   if (b->disposition == disp_del)
7052     ui_out_text (uiout, "\nTemporary catchpoint ");
7053   else
7054     ui_out_text (uiout, "\nCatchpoint ");
7055   if (ui_out_is_mi_like_p (uiout))
7056     {
7057       ui_out_field_string (uiout, "reason",
7058                            async_reason_lookup (EXEC_ASYNC_VFORK));
7059       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
7060     }
7061   ui_out_field_int (uiout, "bkptno", b->number);
7062   ui_out_text (uiout, " (vforked process ");
7063   ui_out_field_int (uiout, "newpid", ptid_get_pid (c->forked_inferior_pid));
7064   ui_out_text (uiout, "), ");
7065   return PRINT_SRC_AND_LOC;
7066 }
7067
7068 /* Implement the "print_one" breakpoint_ops method for vfork
7069    catchpoints.  */
7070
7071 static void
7072 print_one_catch_vfork (struct breakpoint *b, struct bp_location **last_loc)
7073 {
7074   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
7075   struct value_print_options opts;
7076   struct ui_out *uiout = current_uiout;
7077
7078   get_user_print_options (&opts);
7079   /* Field 4, the address, is omitted (which makes the columns not
7080      line up too nicely with the headers, but the effect is relatively
7081      readable).  */
7082   if (opts.addressprint)
7083     ui_out_field_skip (uiout, "addr");
7084   annotate_field (5);
7085   ui_out_text (uiout, "vfork");
7086   if (!ptid_equal (c->forked_inferior_pid, null_ptid))
7087     {
7088       ui_out_text (uiout, ", process ");
7089       ui_out_field_int (uiout, "what",
7090                         ptid_get_pid (c->forked_inferior_pid));
7091       ui_out_spaces (uiout, 1);
7092     }
7093 }
7094
7095 /* Implement the "print_mention" breakpoint_ops method for vfork
7096    catchpoints.  */
7097
7098 static void
7099 print_mention_catch_vfork (struct breakpoint *b)
7100 {
7101   printf_filtered (_("Catchpoint %d (vfork)"), b->number);
7102 }
7103
7104 /* Implement the "print_recreate" breakpoint_ops method for vfork
7105    catchpoints.  */
7106
7107 static void
7108 print_recreate_catch_vfork (struct breakpoint *b, struct ui_file *fp)
7109 {
7110   fprintf_unfiltered (fp, "catch vfork");
7111   print_recreate_thread (b, fp);
7112 }
7113
7114 /* The breakpoint_ops structure to be used in vfork catchpoints.  */
7115
7116 static struct breakpoint_ops catch_vfork_breakpoint_ops;
7117
7118 /* An instance of this type is used to represent an solib catchpoint.
7119    It includes a "struct breakpoint" as a kind of base class; users
7120    downcast to "struct breakpoint *" when needed.  A breakpoint is
7121    really of this type iff its ops pointer points to
7122    CATCH_SOLIB_BREAKPOINT_OPS.  */
7123
7124 struct solib_catchpoint
7125 {
7126   /* The base class.  */
7127   struct breakpoint base;
7128
7129   /* True for "catch load", false for "catch unload".  */
7130   unsigned char is_load;
7131
7132   /* Regular expression to match, if any.  COMPILED is only valid when
7133      REGEX is non-NULL.  */
7134   char *regex;
7135   regex_t compiled;
7136 };
7137
7138 static void
7139 dtor_catch_solib (struct breakpoint *b)
7140 {
7141   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
7142
7143   if (self->regex)
7144     regfree (&self->compiled);
7145   xfree (self->regex);
7146
7147   base_breakpoint_ops.dtor (b);
7148 }
7149
7150 static int
7151 insert_catch_solib (struct bp_location *ignore)
7152 {
7153   return 0;
7154 }
7155
7156 static int
7157 remove_catch_solib (struct bp_location *ignore)
7158 {
7159   return 0;
7160 }
7161
7162 static int
7163 breakpoint_hit_catch_solib (const struct bp_location *bl,
7164                             struct address_space *aspace,
7165                             CORE_ADDR bp_addr,
7166                             const struct target_waitstatus *ws)
7167 {
7168   struct solib_catchpoint *self = (struct solib_catchpoint *) bl->owner;
7169   struct breakpoint *other;
7170
7171   if (ws->kind == TARGET_WAITKIND_LOADED)
7172     return 1;
7173
7174   ALL_BREAKPOINTS (other)
7175   {
7176     struct bp_location *other_bl;
7177
7178     if (other == bl->owner)
7179       continue;
7180
7181     if (other->type != bp_shlib_event)
7182       continue;
7183
7184     if (self->base.pspace != NULL && other->pspace != self->base.pspace)
7185       continue;
7186
7187     for (other_bl = other->loc; other_bl != NULL; other_bl = other_bl->next)
7188       {
7189         if (other->ops->breakpoint_hit (other_bl, aspace, bp_addr, ws))
7190           return 1;
7191       }
7192   }
7193
7194   return 0;
7195 }
7196
7197 static void
7198 check_status_catch_solib (struct bpstats *bs)
7199 {
7200   struct solib_catchpoint *self
7201     = (struct solib_catchpoint *) bs->breakpoint_at;
7202   int ix;
7203
7204   if (self->is_load)
7205     {
7206       struct so_list *iter;
7207
7208       for (ix = 0;
7209            VEC_iterate (so_list_ptr, current_program_space->added_solibs,
7210                         ix, iter);
7211            ++ix)
7212         {
7213           if (!self->regex
7214               || regexec (&self->compiled, iter->so_name, 0, NULL, 0) == 0)
7215             return;
7216         }
7217     }
7218   else
7219     {
7220       char *iter;
7221
7222       for (ix = 0;
7223            VEC_iterate (char_ptr, current_program_space->deleted_solibs,
7224                         ix, iter);
7225            ++ix)
7226         {
7227           if (!self->regex
7228               || regexec (&self->compiled, iter, 0, NULL, 0) == 0)
7229             return;
7230         }
7231     }
7232
7233   bs->stop = 0;
7234   bs->print_it = print_it_noop;
7235 }
7236
7237 static enum print_stop_action
7238 print_it_catch_solib (bpstat bs)
7239 {
7240   struct breakpoint *b = bs->breakpoint_at;
7241   struct ui_out *uiout = current_uiout;
7242
7243   annotate_catchpoint (b->number);
7244   if (b->disposition == disp_del)
7245     ui_out_text (uiout, "\nTemporary catchpoint ");
7246   else
7247     ui_out_text (uiout, "\nCatchpoint ");
7248   ui_out_field_int (uiout, "bkptno", b->number);
7249   ui_out_text (uiout, "\n");
7250   if (ui_out_is_mi_like_p (uiout))
7251     ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
7252   print_solib_event (1);
7253   return PRINT_SRC_AND_LOC;
7254 }
7255
7256 static void
7257 print_one_catch_solib (struct breakpoint *b, struct bp_location **locs)
7258 {
7259   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
7260   struct value_print_options opts;
7261   struct ui_out *uiout = current_uiout;
7262   char *msg;
7263
7264   get_user_print_options (&opts);
7265   /* Field 4, the address, is omitted (which makes the columns not
7266      line up too nicely with the headers, but the effect is relatively
7267      readable).  */
7268   if (opts.addressprint)
7269     {
7270       annotate_field (4);
7271       ui_out_field_skip (uiout, "addr");
7272     }
7273
7274   annotate_field (5);
7275   if (self->is_load)
7276     {
7277       if (self->regex)
7278         msg = xstrprintf (_("load of library matching %s"), self->regex);
7279       else
7280         msg = xstrdup (_("load of library"));
7281     }
7282   else
7283     {
7284       if (self->regex)
7285         msg = xstrprintf (_("unload of library matching %s"), self->regex);
7286       else
7287         msg = xstrdup (_("unload of library"));
7288     }
7289   ui_out_field_string (uiout, "what", msg);
7290   xfree (msg);
7291 }
7292
7293 static void
7294 print_mention_catch_solib (struct breakpoint *b)
7295 {
7296   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
7297
7298   printf_filtered (_("Catchpoint %d (%s)"), b->number,
7299                    self->is_load ? "load" : "unload");
7300 }
7301
7302 static void
7303 print_recreate_catch_solib (struct breakpoint *b, struct ui_file *fp)
7304 {
7305   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
7306
7307   fprintf_unfiltered (fp, "%s %s",
7308                       b->disposition == disp_del ? "tcatch" : "catch",
7309                       self->is_load ? "load" : "unload");
7310   if (self->regex)
7311     fprintf_unfiltered (fp, " %s", self->regex);
7312   fprintf_unfiltered (fp, "\n");
7313 }
7314
7315 static struct breakpoint_ops catch_solib_breakpoint_ops;
7316
7317 /* A helper function that does all the work for "catch load" and
7318    "catch unload".  */
7319
7320 static void
7321 catch_load_or_unload (char *arg, int from_tty, int is_load,
7322                       struct cmd_list_element *command)
7323 {
7324   struct solib_catchpoint *c;
7325   struct gdbarch *gdbarch = get_current_arch ();
7326   int tempflag;
7327   regex_t compiled;
7328   struct cleanup *cleanup;
7329
7330   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
7331
7332   if (!arg)
7333     arg = "";
7334   arg = skip_spaces (arg);
7335
7336   c = XCNEW (struct solib_catchpoint);
7337   cleanup = make_cleanup (xfree, c);
7338
7339   if (*arg != '\0')
7340     {
7341       int errcode;
7342
7343       errcode = regcomp (&c->compiled, arg, REG_NOSUB);
7344       if (errcode != 0)
7345         {
7346           char *err = get_regcomp_error (errcode, &c->compiled);
7347
7348           make_cleanup (xfree, err);
7349           error (_("Invalid regexp (%s): %s"), err, arg);
7350         }
7351       c->regex = xstrdup (arg);
7352     }
7353
7354   c->is_load = is_load;
7355   init_catchpoint (&c->base, gdbarch, tempflag, NULL,
7356                    &catch_solib_breakpoint_ops);
7357
7358   discard_cleanups (cleanup);
7359   install_breakpoint (0, &c->base, 1);
7360 }
7361
7362 static void
7363 catch_load_command_1 (char *arg, int from_tty,
7364                       struct cmd_list_element *command)
7365 {
7366   catch_load_or_unload (arg, from_tty, 1, command);
7367 }
7368
7369 static void
7370 catch_unload_command_1 (char *arg, int from_tty,
7371                         struct cmd_list_element *command)
7372 {
7373   catch_load_or_unload (arg, from_tty, 0, command);
7374 }
7375
7376 /* An instance of this type is used to represent a syscall catchpoint.
7377    It includes a "struct breakpoint" as a kind of base class; users
7378    downcast to "struct breakpoint *" when needed.  A breakpoint is
7379    really of this type iff its ops pointer points to
7380    CATCH_SYSCALL_BREAKPOINT_OPS.  */
7381
7382 struct syscall_catchpoint
7383 {
7384   /* The base class.  */
7385   struct breakpoint base;
7386
7387   /* Syscall numbers used for the 'catch syscall' feature.  If no
7388      syscall has been specified for filtering, its value is NULL.
7389      Otherwise, it holds a list of all syscalls to be caught.  The
7390      list elements are allocated with xmalloc.  */
7391   VEC(int) *syscalls_to_be_caught;
7392 };
7393
7394 /* Implement the "dtor" breakpoint_ops method for syscall
7395    catchpoints.  */
7396
7397 static void
7398 dtor_catch_syscall (struct breakpoint *b)
7399 {
7400   struct syscall_catchpoint *c = (struct syscall_catchpoint *) b;
7401
7402   VEC_free (int, c->syscalls_to_be_caught);
7403
7404   base_breakpoint_ops.dtor (b);
7405 }
7406
7407 /* Implement the "insert" breakpoint_ops method for syscall
7408    catchpoints.  */
7409
7410 static int
7411 insert_catch_syscall (struct bp_location *bl)
7412 {
7413   struct syscall_catchpoint *c = (struct syscall_catchpoint *) bl->owner;
7414   struct inferior *inf = current_inferior ();
7415
7416   ++inf->total_syscalls_count;
7417   if (!c->syscalls_to_be_caught)
7418     ++inf->any_syscall_count;
7419   else
7420     {
7421       int i, iter;
7422
7423       for (i = 0;
7424            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
7425            i++)
7426         {
7427           int elem;
7428
7429           if (iter >= VEC_length (int, inf->syscalls_counts))
7430             {
7431               int old_size = VEC_length (int, inf->syscalls_counts);
7432               uintptr_t vec_addr_offset
7433                 = old_size * ((uintptr_t) sizeof (int));
7434               uintptr_t vec_addr;
7435               VEC_safe_grow (int, inf->syscalls_counts, iter + 1);
7436               vec_addr = (uintptr_t) VEC_address (int, inf->syscalls_counts) +
7437                 vec_addr_offset;
7438               memset ((void *) vec_addr, 0,
7439                       (iter + 1 - old_size) * sizeof (int));
7440             }
7441           elem = VEC_index (int, inf->syscalls_counts, iter);
7442           VEC_replace (int, inf->syscalls_counts, iter, ++elem);
7443         }
7444     }
7445
7446   return target_set_syscall_catchpoint (PIDGET (inferior_ptid),
7447                                         inf->total_syscalls_count != 0,
7448                                         inf->any_syscall_count,
7449                                         VEC_length (int, inf->syscalls_counts),
7450                                         VEC_address (int, inf->syscalls_counts));
7451 }
7452
7453 /* Implement the "remove" breakpoint_ops method for syscall
7454    catchpoints.  */
7455
7456 static int
7457 remove_catch_syscall (struct bp_location *bl)
7458 {
7459   struct syscall_catchpoint *c = (struct syscall_catchpoint *) bl->owner;
7460   struct inferior *inf = current_inferior ();
7461
7462   --inf->total_syscalls_count;
7463   if (!c->syscalls_to_be_caught)
7464     --inf->any_syscall_count;
7465   else
7466     {
7467       int i, iter;
7468
7469       for (i = 0;
7470            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
7471            i++)
7472         {
7473           int elem;
7474           if (iter >= VEC_length (int, inf->syscalls_counts))
7475             /* Shouldn't happen.  */
7476             continue;
7477           elem = VEC_index (int, inf->syscalls_counts, iter);
7478           VEC_replace (int, inf->syscalls_counts, iter, --elem);
7479         }
7480     }
7481
7482   return target_set_syscall_catchpoint (PIDGET (inferior_ptid),
7483                                         inf->total_syscalls_count != 0,
7484                                         inf->any_syscall_count,
7485                                         VEC_length (int, inf->syscalls_counts),
7486                                         VEC_address (int,
7487                                                      inf->syscalls_counts));
7488 }
7489
7490 /* Implement the "breakpoint_hit" breakpoint_ops method for syscall
7491    catchpoints.  */
7492
7493 static int
7494 breakpoint_hit_catch_syscall (const struct bp_location *bl,
7495                               struct address_space *aspace, CORE_ADDR bp_addr,
7496                               const struct target_waitstatus *ws)
7497 {
7498   /* We must check if we are catching specific syscalls in this
7499      breakpoint.  If we are, then we must guarantee that the called
7500      syscall is the same syscall we are catching.  */
7501   int syscall_number = 0;
7502   const struct syscall_catchpoint *c
7503     = (const struct syscall_catchpoint *) bl->owner;
7504
7505   if (ws->kind != TARGET_WAITKIND_SYSCALL_ENTRY
7506       && ws->kind != TARGET_WAITKIND_SYSCALL_RETURN)
7507     return 0;
7508
7509   syscall_number = ws->value.syscall_number;
7510
7511   /* Now, checking if the syscall is the same.  */
7512   if (c->syscalls_to_be_caught)
7513     {
7514       int i, iter;
7515
7516       for (i = 0;
7517            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
7518            i++)
7519         if (syscall_number == iter)
7520           break;
7521       /* Not the same.  */
7522       if (!iter)
7523         return 0;
7524     }
7525
7526   return 1;
7527 }
7528
7529 /* Implement the "print_it" breakpoint_ops method for syscall
7530    catchpoints.  */
7531
7532 static enum print_stop_action
7533 print_it_catch_syscall (bpstat bs)
7534 {
7535   struct ui_out *uiout = current_uiout;
7536   struct breakpoint *b = bs->breakpoint_at;
7537   /* These are needed because we want to know in which state a
7538      syscall is.  It can be in the TARGET_WAITKIND_SYSCALL_ENTRY
7539      or TARGET_WAITKIND_SYSCALL_RETURN, and depending on it we
7540      must print "called syscall" or "returned from syscall".  */
7541   ptid_t ptid;
7542   struct target_waitstatus last;
7543   struct syscall s;
7544   char *syscall_id;
7545
7546   get_last_target_status (&ptid, &last);
7547
7548   get_syscall_by_number (last.value.syscall_number, &s);
7549
7550   annotate_catchpoint (b->number);
7551
7552   if (b->disposition == disp_del)
7553     ui_out_text (uiout, "\nTemporary catchpoint ");
7554   else
7555     ui_out_text (uiout, "\nCatchpoint ");
7556   if (ui_out_is_mi_like_p (uiout))
7557     {
7558       ui_out_field_string (uiout, "reason",
7559                            async_reason_lookup (last.kind == TARGET_WAITKIND_SYSCALL_ENTRY
7560                                                 ? EXEC_ASYNC_SYSCALL_ENTRY
7561                                                 : EXEC_ASYNC_SYSCALL_RETURN));
7562       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
7563     }
7564   ui_out_field_int (uiout, "bkptno", b->number);
7565
7566   if (last.kind == TARGET_WAITKIND_SYSCALL_ENTRY)
7567     ui_out_text (uiout, " (call to syscall ");
7568   else
7569     ui_out_text (uiout, " (returned from syscall ");
7570
7571   if (s.name == NULL || ui_out_is_mi_like_p (uiout))
7572     ui_out_field_int (uiout, "syscall-number", last.value.syscall_number);
7573   if (s.name != NULL)
7574     ui_out_field_string (uiout, "syscall-name", s.name);
7575
7576   ui_out_text (uiout, "), ");
7577
7578   return PRINT_SRC_AND_LOC;
7579 }
7580
7581 /* Implement the "print_one" breakpoint_ops method for syscall
7582    catchpoints.  */
7583
7584 static void
7585 print_one_catch_syscall (struct breakpoint *b,
7586                          struct bp_location **last_loc)
7587 {
7588   struct syscall_catchpoint *c = (struct syscall_catchpoint *) b;
7589   struct value_print_options opts;
7590   struct ui_out *uiout = current_uiout;
7591
7592   get_user_print_options (&opts);
7593   /* Field 4, the address, is omitted (which makes the columns not
7594      line up too nicely with the headers, but the effect is relatively
7595      readable).  */
7596   if (opts.addressprint)
7597     ui_out_field_skip (uiout, "addr");
7598   annotate_field (5);
7599
7600   if (c->syscalls_to_be_caught
7601       && VEC_length (int, c->syscalls_to_be_caught) > 1)
7602     ui_out_text (uiout, "syscalls \"");
7603   else
7604     ui_out_text (uiout, "syscall \"");
7605
7606   if (c->syscalls_to_be_caught)
7607     {
7608       int i, iter;
7609       char *text = xstrprintf ("%s", "");
7610
7611       for (i = 0;
7612            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
7613            i++)
7614         {
7615           char *x = text;
7616           struct syscall s;
7617           get_syscall_by_number (iter, &s);
7618
7619           if (s.name != NULL)
7620             text = xstrprintf ("%s%s, ", text, s.name);
7621           else
7622             text = xstrprintf ("%s%d, ", text, iter);
7623
7624           /* We have to xfree the last 'text' (now stored at 'x')
7625              because xstrprintf dynamically allocates new space for it
7626              on every call.  */
7627           xfree (x);
7628         }
7629       /* Remove the last comma.  */
7630       text[strlen (text) - 2] = '\0';
7631       ui_out_field_string (uiout, "what", text);
7632     }
7633   else
7634     ui_out_field_string (uiout, "what", "<any syscall>");
7635   ui_out_text (uiout, "\" ");
7636 }
7637
7638 /* Implement the "print_mention" breakpoint_ops method for syscall
7639    catchpoints.  */
7640
7641 static void
7642 print_mention_catch_syscall (struct breakpoint *b)
7643 {
7644   struct syscall_catchpoint *c = (struct syscall_catchpoint *) b;
7645
7646   if (c->syscalls_to_be_caught)
7647     {
7648       int i, iter;
7649
7650       if (VEC_length (int, c->syscalls_to_be_caught) > 1)
7651         printf_filtered (_("Catchpoint %d (syscalls"), b->number);
7652       else
7653         printf_filtered (_("Catchpoint %d (syscall"), b->number);
7654
7655       for (i = 0;
7656            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
7657            i++)
7658         {
7659           struct syscall s;
7660           get_syscall_by_number (iter, &s);
7661
7662           if (s.name)
7663             printf_filtered (" '%s' [%d]", s.name, s.number);
7664           else
7665             printf_filtered (" %d", s.number);
7666         }
7667       printf_filtered (")");
7668     }
7669   else
7670     printf_filtered (_("Catchpoint %d (any syscall)"),
7671                      b->number);
7672 }
7673
7674 /* Implement the "print_recreate" breakpoint_ops method for syscall
7675    catchpoints.  */
7676
7677 static void
7678 print_recreate_catch_syscall (struct breakpoint *b, struct ui_file *fp)
7679 {
7680   struct syscall_catchpoint *c = (struct syscall_catchpoint *) b;
7681
7682   fprintf_unfiltered (fp, "catch syscall");
7683
7684   if (c->syscalls_to_be_caught)
7685     {
7686       int i, iter;
7687
7688       for (i = 0;
7689            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
7690            i++)
7691         {
7692           struct syscall s;
7693
7694           get_syscall_by_number (iter, &s);
7695           if (s.name)
7696             fprintf_unfiltered (fp, " %s", s.name);
7697           else
7698             fprintf_unfiltered (fp, " %d", s.number);
7699         }
7700     }
7701   print_recreate_thread (b, fp);
7702 }
7703
7704 /* The breakpoint_ops structure to be used in syscall catchpoints.  */
7705
7706 static struct breakpoint_ops catch_syscall_breakpoint_ops;
7707
7708 /* Returns non-zero if 'b' is a syscall catchpoint.  */
7709
7710 static int
7711 syscall_catchpoint_p (struct breakpoint *b)
7712 {
7713   return (b->ops == &catch_syscall_breakpoint_ops);
7714 }
7715
7716 /* Initialize a new breakpoint of the bp_catchpoint kind.  If TEMPFLAG
7717    is non-zero, then make the breakpoint temporary.  If COND_STRING is
7718    not NULL, then store it in the breakpoint.  OPS, if not NULL, is
7719    the breakpoint_ops structure associated to the catchpoint.  */
7720
7721 static void
7722 init_catchpoint (struct breakpoint *b,
7723                  struct gdbarch *gdbarch, int tempflag,
7724                  char *cond_string,
7725                  const struct breakpoint_ops *ops)
7726 {
7727   struct symtab_and_line sal;
7728
7729   init_sal (&sal);
7730   sal.pspace = current_program_space;
7731
7732   init_raw_breakpoint (b, gdbarch, sal, bp_catchpoint, ops);
7733
7734   b->cond_string = (cond_string == NULL) ? NULL : xstrdup (cond_string);
7735   b->disposition = tempflag ? disp_del : disp_donttouch;
7736 }
7737
7738 void
7739 install_breakpoint (int internal, struct breakpoint *b, int update_gll)
7740 {
7741   add_to_breakpoint_chain (b);
7742   set_breakpoint_number (internal, b);
7743   if (!internal)
7744     mention (b);
7745   observer_notify_breakpoint_created (b);
7746
7747   if (update_gll)
7748     update_global_location_list (1);
7749 }
7750
7751 static void
7752 create_fork_vfork_event_catchpoint (struct gdbarch *gdbarch,
7753                                     int tempflag, char *cond_string,
7754                                     const struct breakpoint_ops *ops)
7755 {
7756   struct fork_catchpoint *c = XNEW (struct fork_catchpoint);
7757
7758   init_catchpoint (&c->base, gdbarch, tempflag, cond_string, ops);
7759
7760   c->forked_inferior_pid = null_ptid;
7761
7762   install_breakpoint (0, &c->base, 1);
7763 }
7764
7765 /* Exec catchpoints.  */
7766
7767 /* An instance of this type is used to represent an exec catchpoint.
7768    It includes a "struct breakpoint" as a kind of base class; users
7769    downcast to "struct breakpoint *" when needed.  A breakpoint is
7770    really of this type iff its ops pointer points to
7771    CATCH_EXEC_BREAKPOINT_OPS.  */
7772
7773 struct exec_catchpoint
7774 {
7775   /* The base class.  */
7776   struct breakpoint base;
7777
7778   /* Filename of a program whose exec triggered this catchpoint.
7779      This field is only valid immediately after this catchpoint has
7780      triggered.  */
7781   char *exec_pathname;
7782 };
7783
7784 /* Implement the "dtor" breakpoint_ops method for exec
7785    catchpoints.  */
7786
7787 static void
7788 dtor_catch_exec (struct breakpoint *b)
7789 {
7790   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
7791
7792   xfree (c->exec_pathname);
7793
7794   base_breakpoint_ops.dtor (b);
7795 }
7796
7797 static int
7798 insert_catch_exec (struct bp_location *bl)
7799 {
7800   return target_insert_exec_catchpoint (PIDGET (inferior_ptid));
7801 }
7802
7803 static int
7804 remove_catch_exec (struct bp_location *bl)
7805 {
7806   return target_remove_exec_catchpoint (PIDGET (inferior_ptid));
7807 }
7808
7809 static int
7810 breakpoint_hit_catch_exec (const struct bp_location *bl,
7811                            struct address_space *aspace, CORE_ADDR bp_addr,
7812                            const struct target_waitstatus *ws)
7813 {
7814   struct exec_catchpoint *c = (struct exec_catchpoint *) bl->owner;
7815
7816   if (ws->kind != TARGET_WAITKIND_EXECD)
7817     return 0;
7818
7819   c->exec_pathname = xstrdup (ws->value.execd_pathname);
7820   return 1;
7821 }
7822
7823 static enum print_stop_action
7824 print_it_catch_exec (bpstat bs)
7825 {
7826   struct ui_out *uiout = current_uiout;
7827   struct breakpoint *b = bs->breakpoint_at;
7828   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
7829
7830   annotate_catchpoint (b->number);
7831   if (b->disposition == disp_del)
7832     ui_out_text (uiout, "\nTemporary catchpoint ");
7833   else
7834     ui_out_text (uiout, "\nCatchpoint ");
7835   if (ui_out_is_mi_like_p (uiout))
7836     {
7837       ui_out_field_string (uiout, "reason",
7838                            async_reason_lookup (EXEC_ASYNC_EXEC));
7839       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
7840     }
7841   ui_out_field_int (uiout, "bkptno", b->number);
7842   ui_out_text (uiout, " (exec'd ");
7843   ui_out_field_string (uiout, "new-exec", c->exec_pathname);
7844   ui_out_text (uiout, "), ");
7845
7846   return PRINT_SRC_AND_LOC;
7847 }
7848
7849 static void
7850 print_one_catch_exec (struct breakpoint *b, struct bp_location **last_loc)
7851 {
7852   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
7853   struct value_print_options opts;
7854   struct ui_out *uiout = current_uiout;
7855
7856   get_user_print_options (&opts);
7857
7858   /* Field 4, the address, is omitted (which makes the columns
7859      not line up too nicely with the headers, but the effect
7860      is relatively readable).  */
7861   if (opts.addressprint)
7862     ui_out_field_skip (uiout, "addr");
7863   annotate_field (5);
7864   ui_out_text (uiout, "exec");
7865   if (c->exec_pathname != NULL)
7866     {
7867       ui_out_text (uiout, ", program \"");
7868       ui_out_field_string (uiout, "what", c->exec_pathname);
7869       ui_out_text (uiout, "\" ");
7870     }
7871 }
7872
7873 static void
7874 print_mention_catch_exec (struct breakpoint *b)
7875 {
7876   printf_filtered (_("Catchpoint %d (exec)"), b->number);
7877 }
7878
7879 /* Implement the "print_recreate" breakpoint_ops method for exec
7880    catchpoints.  */
7881
7882 static void
7883 print_recreate_catch_exec (struct breakpoint *b, struct ui_file *fp)
7884 {
7885   fprintf_unfiltered (fp, "catch exec");
7886   print_recreate_thread (b, fp);
7887 }
7888
7889 static struct breakpoint_ops catch_exec_breakpoint_ops;
7890
7891 static void
7892 create_syscall_event_catchpoint (int tempflag, VEC(int) *filter,
7893                                  const struct breakpoint_ops *ops)
7894 {
7895   struct syscall_catchpoint *c;
7896   struct gdbarch *gdbarch = get_current_arch ();
7897
7898   c = XNEW (struct syscall_catchpoint);
7899   init_catchpoint (&c->base, gdbarch, tempflag, NULL, ops);
7900   c->syscalls_to_be_caught = filter;
7901
7902   install_breakpoint (0, &c->base, 1);
7903 }
7904
7905 static int
7906 hw_breakpoint_used_count (void)
7907 {
7908   int i = 0;
7909   struct breakpoint *b;
7910   struct bp_location *bl;
7911
7912   ALL_BREAKPOINTS (b)
7913   {
7914     if (b->type == bp_hardware_breakpoint && breakpoint_enabled (b))
7915       for (bl = b->loc; bl; bl = bl->next)
7916         {
7917           /* Special types of hardware breakpoints may use more than
7918              one register.  */
7919           i += b->ops->resources_needed (bl);
7920         }
7921   }
7922
7923   return i;
7924 }
7925
7926 /* Returns the resources B would use if it were a hardware
7927    watchpoint.  */
7928
7929 static int
7930 hw_watchpoint_use_count (struct breakpoint *b)
7931 {
7932   int i = 0;
7933   struct bp_location *bl;
7934
7935   if (!breakpoint_enabled (b))
7936     return 0;
7937
7938   for (bl = b->loc; bl; bl = bl->next)
7939     {
7940       /* Special types of hardware watchpoints may use more than
7941          one register.  */
7942       i += b->ops->resources_needed (bl);
7943     }
7944
7945   return i;
7946 }
7947
7948 /* Returns the sum the used resources of all hardware watchpoints of
7949    type TYPE in the breakpoints list.  Also returns in OTHER_TYPE_USED
7950    the sum of the used resources of all hardware watchpoints of other
7951    types _not_ TYPE.  */
7952
7953 static int
7954 hw_watchpoint_used_count_others (struct breakpoint *except,
7955                                  enum bptype type, int *other_type_used)
7956 {
7957   int i = 0;
7958   struct breakpoint *b;
7959
7960   *other_type_used = 0;
7961   ALL_BREAKPOINTS (b)
7962     {
7963       if (b == except)
7964         continue;
7965       if (!breakpoint_enabled (b))
7966         continue;
7967
7968       if (b->type == type)
7969         i += hw_watchpoint_use_count (b);
7970       else if (is_hardware_watchpoint (b))
7971         *other_type_used = 1;
7972     }
7973
7974   return i;
7975 }
7976
7977 void
7978 disable_watchpoints_before_interactive_call_start (void)
7979 {
7980   struct breakpoint *b;
7981
7982   ALL_BREAKPOINTS (b)
7983   {
7984     if (is_watchpoint (b) && breakpoint_enabled (b))
7985       {
7986         b->enable_state = bp_call_disabled;
7987         update_global_location_list (0);
7988       }
7989   }
7990 }
7991
7992 void
7993 enable_watchpoints_after_interactive_call_stop (void)
7994 {
7995   struct breakpoint *b;
7996
7997   ALL_BREAKPOINTS (b)
7998   {
7999     if (is_watchpoint (b) && b->enable_state == bp_call_disabled)
8000       {
8001         b->enable_state = bp_enabled;
8002         update_global_location_list (1);
8003       }
8004   }
8005 }
8006
8007 void
8008 disable_breakpoints_before_startup (void)
8009 {
8010   current_program_space->executing_startup = 1;
8011   update_global_location_list (0);
8012 }
8013
8014 void
8015 enable_breakpoints_after_startup (void)
8016 {
8017   current_program_space->executing_startup = 0;
8018   breakpoint_re_set ();
8019 }
8020
8021
8022 /* Set a breakpoint that will evaporate an end of command
8023    at address specified by SAL.
8024    Restrict it to frame FRAME if FRAME is nonzero.  */
8025
8026 struct breakpoint *
8027 set_momentary_breakpoint (struct gdbarch *gdbarch, struct symtab_and_line sal,
8028                           struct frame_id frame_id, enum bptype type)
8029 {
8030   struct breakpoint *b;
8031
8032   /* If FRAME_ID is valid, it should be a real frame, not an inlined
8033      one.  */
8034   gdb_assert (!frame_id_inlined_p (frame_id));
8035
8036   b = set_raw_breakpoint (gdbarch, sal, type, &momentary_breakpoint_ops);
8037   b->enable_state = bp_enabled;
8038   b->disposition = disp_donttouch;
8039   b->frame_id = frame_id;
8040
8041   /* If we're debugging a multi-threaded program, then we want
8042      momentary breakpoints to be active in only a single thread of
8043      control.  */
8044   if (in_thread_list (inferior_ptid))
8045     b->thread = pid_to_thread_id (inferior_ptid);
8046
8047   update_global_location_list_nothrow (1);
8048
8049   return b;
8050 }
8051
8052 /* Make a momentary breakpoint based on the master breakpoint ORIG.
8053    The new breakpoint will have type TYPE, and use OPS as it
8054    breakpoint_ops.  */
8055
8056 static struct breakpoint *
8057 momentary_breakpoint_from_master (struct breakpoint *orig,
8058                                   enum bptype type,
8059                                   const struct breakpoint_ops *ops)
8060 {
8061   struct breakpoint *copy;
8062
8063   copy = set_raw_breakpoint_without_location (orig->gdbarch, type, ops);
8064   copy->loc = allocate_bp_location (copy);
8065   set_breakpoint_location_function (copy->loc, 1);
8066
8067   copy->loc->gdbarch = orig->loc->gdbarch;
8068   copy->loc->requested_address = orig->loc->requested_address;
8069   copy->loc->address = orig->loc->address;
8070   copy->loc->section = orig->loc->section;
8071   copy->loc->pspace = orig->loc->pspace;
8072
8073   if (orig->loc->source_file != NULL)
8074     copy->loc->source_file = xstrdup (orig->loc->source_file);
8075
8076   copy->loc->line_number = orig->loc->line_number;
8077   copy->frame_id = orig->frame_id;
8078   copy->thread = orig->thread;
8079   copy->pspace = orig->pspace;
8080
8081   copy->enable_state = bp_enabled;
8082   copy->disposition = disp_donttouch;
8083   copy->number = internal_breakpoint_number--;
8084
8085   update_global_location_list_nothrow (0);
8086   return copy;
8087 }
8088
8089 /* Make a deep copy of momentary breakpoint ORIG.  Returns NULL if
8090    ORIG is NULL.  */
8091
8092 struct breakpoint *
8093 clone_momentary_breakpoint (struct breakpoint *orig)
8094 {
8095   /* If there's nothing to clone, then return nothing.  */
8096   if (orig == NULL)
8097     return NULL;
8098
8099   return momentary_breakpoint_from_master (orig, orig->type, orig->ops);
8100 }
8101
8102 struct breakpoint *
8103 set_momentary_breakpoint_at_pc (struct gdbarch *gdbarch, CORE_ADDR pc,
8104                                 enum bptype type)
8105 {
8106   struct symtab_and_line sal;
8107
8108   sal = find_pc_line (pc, 0);
8109   sal.pc = pc;
8110   sal.section = find_pc_overlay (pc);
8111   sal.explicit_pc = 1;
8112
8113   return set_momentary_breakpoint (gdbarch, sal, null_frame_id, type);
8114 }
8115 \f
8116
8117 /* Tell the user we have just set a breakpoint B.  */
8118
8119 static void
8120 mention (struct breakpoint *b)
8121 {
8122   b->ops->print_mention (b);
8123   if (ui_out_is_mi_like_p (current_uiout))
8124     return;
8125   printf_filtered ("\n");
8126 }
8127 \f
8128
8129 static struct bp_location *
8130 add_location_to_breakpoint (struct breakpoint *b,
8131                             const struct symtab_and_line *sal)
8132 {
8133   struct bp_location *loc, **tmp;
8134   CORE_ADDR adjusted_address;
8135   struct gdbarch *loc_gdbarch = get_sal_arch (*sal);
8136
8137   if (loc_gdbarch == NULL)
8138     loc_gdbarch = b->gdbarch;
8139
8140   /* Adjust the breakpoint's address prior to allocating a location.
8141      Once we call allocate_bp_location(), that mostly uninitialized
8142      location will be placed on the location chain.  Adjustment of the
8143      breakpoint may cause target_read_memory() to be called and we do
8144      not want its scan of the location chain to find a breakpoint and
8145      location that's only been partially initialized.  */
8146   adjusted_address = adjust_breakpoint_address (loc_gdbarch,
8147                                                 sal->pc, b->type);
8148
8149   loc = allocate_bp_location (b);
8150   for (tmp = &(b->loc); *tmp != NULL; tmp = &((*tmp)->next))
8151     ;
8152   *tmp = loc;
8153
8154   loc->requested_address = sal->pc;
8155   loc->address = adjusted_address;
8156   loc->pspace = sal->pspace;
8157   gdb_assert (loc->pspace != NULL);
8158   loc->section = sal->section;
8159   loc->gdbarch = loc_gdbarch;
8160
8161   if (sal->symtab != NULL)
8162     loc->source_file = xstrdup (sal->symtab->filename);
8163   loc->line_number = sal->line;
8164
8165   set_breakpoint_location_function (loc,
8166                                     sal->explicit_pc || sal->explicit_line);
8167   return loc;
8168 }
8169 \f
8170
8171 /* Return 1 if LOC is pointing to a permanent breakpoint, 
8172    return 0 otherwise.  */
8173
8174 static int
8175 bp_loc_is_permanent (struct bp_location *loc)
8176 {
8177   int len;
8178   CORE_ADDR addr;
8179   const gdb_byte *bpoint;
8180   gdb_byte *target_mem;
8181   struct cleanup *cleanup;
8182   int retval = 0;
8183
8184   gdb_assert (loc != NULL);
8185
8186   addr = loc->address;
8187   bpoint = gdbarch_breakpoint_from_pc (loc->gdbarch, &addr, &len);
8188
8189   /* Software breakpoints unsupported?  */
8190   if (bpoint == NULL)
8191     return 0;
8192
8193   target_mem = alloca (len);
8194
8195   /* Enable the automatic memory restoration from breakpoints while
8196      we read the memory.  Otherwise we could say about our temporary
8197      breakpoints they are permanent.  */
8198   cleanup = save_current_space_and_thread ();
8199
8200   switch_to_program_space_and_thread (loc->pspace);
8201   make_show_memory_breakpoints_cleanup (0);
8202
8203   if (target_read_memory (loc->address, target_mem, len) == 0
8204       && memcmp (target_mem, bpoint, len) == 0)
8205     retval = 1;
8206
8207   do_cleanups (cleanup);
8208
8209   return retval;
8210 }
8211
8212
8213
8214 /* Create a breakpoint with SAL as location.  Use ADDR_STRING
8215    as textual description of the location, and COND_STRING
8216    as condition expression.  */
8217
8218 static void
8219 init_breakpoint_sal (struct breakpoint *b, struct gdbarch *gdbarch,
8220                      struct symtabs_and_lines sals, char *addr_string,
8221                      char *filter, char *cond_string,
8222                      enum bptype type, enum bpdisp disposition,
8223                      int thread, int task, int ignore_count,
8224                      const struct breakpoint_ops *ops, int from_tty,
8225                      int enabled, int internal, int display_canonical)
8226 {
8227   int i;
8228
8229   if (type == bp_hardware_breakpoint)
8230     {
8231       int target_resources_ok;
8232
8233       i = hw_breakpoint_used_count ();
8234       target_resources_ok =
8235         target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
8236                                             i + 1, 0);
8237       if (target_resources_ok == 0)
8238         error (_("No hardware breakpoint support in the target."));
8239       else if (target_resources_ok < 0)
8240         error (_("Hardware breakpoints used exceeds limit."));
8241     }
8242
8243   gdb_assert (sals.nelts > 0);
8244
8245   for (i = 0; i < sals.nelts; ++i)
8246     {
8247       struct symtab_and_line sal = sals.sals[i];
8248       struct bp_location *loc;
8249
8250       if (from_tty)
8251         {
8252           struct gdbarch *loc_gdbarch = get_sal_arch (sal);
8253           if (!loc_gdbarch)
8254             loc_gdbarch = gdbarch;
8255
8256           describe_other_breakpoints (loc_gdbarch,
8257                                       sal.pspace, sal.pc, sal.section, thread);
8258         }
8259
8260       if (i == 0)
8261         {
8262           init_raw_breakpoint (b, gdbarch, sal, type, ops);
8263           b->thread = thread;
8264           b->task = task;
8265   
8266           b->cond_string = cond_string;
8267           b->ignore_count = ignore_count;
8268           b->enable_state = enabled ? bp_enabled : bp_disabled;
8269           b->disposition = disposition;
8270
8271           if (type == bp_static_tracepoint)
8272             {
8273               struct tracepoint *t = (struct tracepoint *) b;
8274               struct static_tracepoint_marker marker;
8275
8276               if (strace_marker_p (b))
8277                 {
8278                   /* We already know the marker exists, otherwise, we
8279                      wouldn't see a sal for it.  */
8280                   char *p = &addr_string[3];
8281                   char *endp;
8282                   char *marker_str;
8283
8284                   p = skip_spaces (p);
8285
8286                   endp = skip_to_space (p);
8287
8288                   marker_str = savestring (p, endp - p);
8289                   t->static_trace_marker_id = marker_str;
8290
8291                   printf_filtered (_("Probed static tracepoint "
8292                                      "marker \"%s\"\n"),
8293                                    t->static_trace_marker_id);
8294                 }
8295               else if (target_static_tracepoint_marker_at (sal.pc, &marker))
8296                 {
8297                   t->static_trace_marker_id = xstrdup (marker.str_id);
8298                   release_static_tracepoint_marker (&marker);
8299
8300                   printf_filtered (_("Probed static tracepoint "
8301                                      "marker \"%s\"\n"),
8302                                    t->static_trace_marker_id);
8303                 }
8304               else
8305                 warning (_("Couldn't determine the static "
8306                            "tracepoint marker to probe"));
8307             }
8308
8309           loc = b->loc;
8310         }
8311       else
8312         {
8313           loc = add_location_to_breakpoint (b, &sal);
8314         }
8315
8316       if (bp_loc_is_permanent (loc))
8317         make_breakpoint_permanent (b);
8318
8319       if (b->cond_string)
8320         {
8321           char *arg = b->cond_string;
8322           loc->cond = parse_exp_1 (&arg, block_for_pc (loc->address), 0);
8323           if (*arg)
8324               error (_("Garbage %s follows condition"), arg);
8325         }
8326     }   
8327
8328   b->display_canonical = display_canonical;
8329   if (addr_string)
8330     b->addr_string = addr_string;
8331   else
8332     /* addr_string has to be used or breakpoint_re_set will delete
8333        me.  */
8334     b->addr_string
8335       = xstrprintf ("*%s", paddress (b->loc->gdbarch, b->loc->address));
8336   b->filter = filter;
8337 }
8338
8339 static void
8340 create_breakpoint_sal (struct gdbarch *gdbarch,
8341                        struct symtabs_and_lines sals, char *addr_string,
8342                        char *filter, char *cond_string,
8343                        enum bptype type, enum bpdisp disposition,
8344                        int thread, int task, int ignore_count,
8345                        const struct breakpoint_ops *ops, int from_tty,
8346                        int enabled, int internal, int display_canonical)
8347 {
8348   struct breakpoint *b;
8349   struct cleanup *old_chain;
8350
8351   if (is_tracepoint_type (type))
8352     {
8353       struct tracepoint *t;
8354
8355       t = XCNEW (struct tracepoint);
8356       b = &t->base;
8357     }
8358   else
8359     b = XNEW (struct breakpoint);
8360
8361   old_chain = make_cleanup (xfree, b);
8362
8363   init_breakpoint_sal (b, gdbarch,
8364                        sals, addr_string,
8365                        filter, cond_string,
8366                        type, disposition,
8367                        thread, task, ignore_count,
8368                        ops, from_tty,
8369                        enabled, internal, display_canonical);
8370   discard_cleanups (old_chain);
8371
8372   install_breakpoint (internal, b, 0);
8373 }
8374
8375 /* Add SALS.nelts breakpoints to the breakpoint table.  For each
8376    SALS.sal[i] breakpoint, include the corresponding ADDR_STRING[i]
8377    value.  COND_STRING, if not NULL, specified the condition to be
8378    used for all breakpoints.  Essentially the only case where
8379    SALS.nelts is not 1 is when we set a breakpoint on an overloaded
8380    function.  In that case, it's still not possible to specify
8381    separate conditions for different overloaded functions, so
8382    we take just a single condition string.
8383    
8384    NOTE: If the function succeeds, the caller is expected to cleanup
8385    the arrays ADDR_STRING, COND_STRING, and SALS (but not the
8386    array contents).  If the function fails (error() is called), the
8387    caller is expected to cleanups both the ADDR_STRING, COND_STRING,
8388    COND and SALS arrays and each of those arrays contents.  */
8389
8390 static void
8391 create_breakpoints_sal (struct gdbarch *gdbarch,
8392                         struct linespec_result *canonical,
8393                         char *cond_string,
8394                         enum bptype type, enum bpdisp disposition,
8395                         int thread, int task, int ignore_count,
8396                         const struct breakpoint_ops *ops, int from_tty,
8397                         int enabled, int internal)
8398 {
8399   int i;
8400   struct linespec_sals *lsal;
8401
8402   if (canonical->pre_expanded)
8403     gdb_assert (VEC_length (linespec_sals, canonical->sals) == 1);
8404
8405   for (i = 0; VEC_iterate (linespec_sals, canonical->sals, i, lsal); ++i)
8406     {
8407       /* Note that 'addr_string' can be NULL in the case of a plain
8408          'break', without arguments.  */
8409       char *addr_string = (canonical->addr_string
8410                            ? xstrdup (canonical->addr_string)
8411                            : NULL);
8412       char *filter_string = lsal->canonical ? xstrdup (lsal->canonical) : NULL;
8413       struct cleanup *inner = make_cleanup (xfree, addr_string);
8414
8415       make_cleanup (xfree, filter_string);
8416       create_breakpoint_sal (gdbarch, lsal->sals,
8417                              addr_string,
8418                              filter_string,
8419                              cond_string, type, disposition,
8420                              thread, task, ignore_count, ops,
8421                              from_tty, enabled, internal,
8422                              canonical->special_display);
8423       discard_cleanups (inner);
8424     }
8425 }
8426
8427 /* Parse ADDRESS which is assumed to be a SAL specification possibly
8428    followed by conditionals.  On return, SALS contains an array of SAL
8429    addresses found.  ADDR_STRING contains a vector of (canonical)
8430    address strings.  ADDRESS points to the end of the SAL.
8431
8432    The array and the line spec strings are allocated on the heap, it is
8433    the caller's responsibility to free them.  */
8434
8435 static void
8436 parse_breakpoint_sals (char **address,
8437                        struct linespec_result *canonical)
8438 {
8439   char *addr_start = *address;
8440
8441   /* If no arg given, or if first arg is 'if ', use the default
8442      breakpoint.  */
8443   if ((*address) == NULL
8444       || (strncmp ((*address), "if", 2) == 0 && isspace ((*address)[2])))
8445     {
8446       /* The last displayed codepoint, if it's valid, is our default breakpoint
8447          address.  */
8448       if (last_displayed_sal_is_valid ())
8449         {
8450           struct linespec_sals lsal;
8451           struct symtab_and_line sal;
8452
8453           init_sal (&sal);              /* Initialize to zeroes.  */
8454           lsal.sals.sals = (struct symtab_and_line *)
8455             xmalloc (sizeof (struct symtab_and_line));
8456
8457           /* Set sal's pspace, pc, symtab, and line to the values
8458              corresponding to the last call to print_frame_info.  */
8459           get_last_displayed_sal (&sal);
8460           sal.section = find_pc_overlay (sal.pc);
8461
8462           /* "break" without arguments is equivalent to "break *PC"
8463              where PC is the last displayed codepoint's address.  So
8464              make sure to set sal.explicit_pc to prevent GDB from
8465              trying to expand the list of sals to include all other
8466              instances with the same symtab and line.  */
8467           sal.explicit_pc = 1;
8468
8469           lsal.sals.sals[0] = sal;
8470           lsal.sals.nelts = 1;
8471           lsal.canonical = NULL;
8472
8473           VEC_safe_push (linespec_sals, canonical->sals, &lsal);
8474         }
8475       else
8476         error (_("No default breakpoint address now."));
8477     }
8478   else
8479     {
8480       /* Force almost all breakpoints to be in terms of the
8481          current_source_symtab (which is decode_line_1's default).
8482          This should produce the results we want almost all of the
8483          time while leaving default_breakpoint_* alone.  */
8484       if (last_displayed_sal_is_valid ())
8485         decode_line_full (address, DECODE_LINE_FUNFIRSTLINE,
8486                           get_last_displayed_symtab (),
8487                           get_last_displayed_line (),
8488                           canonical, NULL, NULL);
8489       else
8490         decode_line_full (address, DECODE_LINE_FUNFIRSTLINE,
8491                           (struct symtab *) NULL, 0,
8492                           canonical, NULL, NULL);
8493     }
8494 }
8495
8496
8497 /* Convert each SAL into a real PC.  Verify that the PC can be
8498    inserted as a breakpoint.  If it can't throw an error.  */
8499
8500 static void
8501 breakpoint_sals_to_pc (struct symtabs_and_lines *sals)
8502 {    
8503   int i;
8504
8505   for (i = 0; i < sals->nelts; i++)
8506     resolve_sal_pc (&sals->sals[i]);
8507 }
8508
8509 /* Fast tracepoints may have restrictions on valid locations.  For
8510    instance, a fast tracepoint using a jump instead of a trap will
8511    likely have to overwrite more bytes than a trap would, and so can
8512    only be placed where the instruction is longer than the jump, or a
8513    multi-instruction sequence does not have a jump into the middle of
8514    it, etc.  */
8515
8516 static void
8517 check_fast_tracepoint_sals (struct gdbarch *gdbarch,
8518                             struct symtabs_and_lines *sals)
8519 {
8520   int i, rslt;
8521   struct symtab_and_line *sal;
8522   char *msg;
8523   struct cleanup *old_chain;
8524
8525   for (i = 0; i < sals->nelts; i++)
8526     {
8527       struct gdbarch *sarch;
8528
8529       sal = &sals->sals[i];
8530
8531       sarch = get_sal_arch (*sal);
8532       /* We fall back to GDBARCH if there is no architecture
8533          associated with SAL.  */
8534       if (sarch == NULL)
8535         sarch = gdbarch;
8536       rslt = gdbarch_fast_tracepoint_valid_at (sarch, sal->pc,
8537                                                NULL, &msg);
8538       old_chain = make_cleanup (xfree, msg);
8539
8540       if (!rslt)
8541         error (_("May not have a fast tracepoint at 0x%s%s"),
8542                paddress (sarch, sal->pc), (msg ? msg : ""));
8543
8544       do_cleanups (old_chain);
8545     }
8546 }
8547
8548 /* Given TOK, a string specification of condition and thread, as
8549    accepted by the 'break' command, extract the condition
8550    string and thread number and set *COND_STRING and *THREAD.
8551    PC identifies the context at which the condition should be parsed.
8552    If no condition is found, *COND_STRING is set to NULL.
8553    If no thread is found, *THREAD is set to -1.  */
8554 static void 
8555 find_condition_and_thread (char *tok, CORE_ADDR pc, 
8556                            char **cond_string, int *thread, int *task)
8557 {
8558   *cond_string = NULL;
8559   *thread = -1;
8560   while (tok && *tok)
8561     {
8562       char *end_tok;
8563       int toklen;
8564       char *cond_start = NULL;
8565       char *cond_end = NULL;
8566
8567       tok = skip_spaces (tok);
8568       
8569       end_tok = skip_to_space (tok);
8570       
8571       toklen = end_tok - tok;
8572       
8573       if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
8574         {
8575           struct expression *expr;
8576
8577           tok = cond_start = end_tok + 1;
8578           expr = parse_exp_1 (&tok, block_for_pc (pc), 0);
8579           xfree (expr);
8580           cond_end = tok;
8581           *cond_string = savestring (cond_start, 
8582                                      cond_end - cond_start);
8583         }
8584       else if (toklen >= 1 && strncmp (tok, "thread", toklen) == 0)
8585         {
8586           char *tmptok;
8587           
8588           tok = end_tok + 1;
8589           tmptok = tok;
8590           *thread = strtol (tok, &tok, 0);
8591           if (tok == tmptok)
8592             error (_("Junk after thread keyword."));
8593           if (!valid_thread_id (*thread))
8594             error (_("Unknown thread %d."), *thread);
8595         }
8596       else if (toklen >= 1 && strncmp (tok, "task", toklen) == 0)
8597         {
8598           char *tmptok;
8599
8600           tok = end_tok + 1;
8601           tmptok = tok;
8602           *task = strtol (tok, &tok, 0);
8603           if (tok == tmptok)
8604             error (_("Junk after task keyword."));
8605           if (!valid_task_id (*task))
8606             error (_("Unknown task %d."), *task);
8607         }
8608       else
8609         error (_("Junk at end of arguments."));
8610     }
8611 }
8612
8613 /* Decode a static tracepoint marker spec.  */
8614
8615 static struct symtabs_and_lines
8616 decode_static_tracepoint_spec (char **arg_p)
8617 {
8618   VEC(static_tracepoint_marker_p) *markers = NULL;
8619   struct symtabs_and_lines sals;
8620   struct symtab_and_line sal;
8621   struct symbol *sym;
8622   struct cleanup *old_chain;
8623   char *p = &(*arg_p)[3];
8624   char *endp;
8625   char *marker_str;
8626   int i;
8627
8628   p = skip_spaces (p);
8629
8630   endp = skip_to_space (p);
8631
8632   marker_str = savestring (p, endp - p);
8633   old_chain = make_cleanup (xfree, marker_str);
8634
8635   markers = target_static_tracepoint_markers_by_strid (marker_str);
8636   if (VEC_empty(static_tracepoint_marker_p, markers))
8637     error (_("No known static tracepoint marker named %s"), marker_str);
8638
8639   sals.nelts = VEC_length(static_tracepoint_marker_p, markers);
8640   sals.sals = xmalloc (sizeof *sals.sals * sals.nelts);
8641
8642   for (i = 0; i < sals.nelts; i++)
8643     {
8644       struct static_tracepoint_marker *marker;
8645
8646       marker = VEC_index (static_tracepoint_marker_p, markers, i);
8647
8648       init_sal (&sals.sals[i]);
8649
8650       sals.sals[i] = find_pc_line (marker->address, 0);
8651       sals.sals[i].pc = marker->address;
8652
8653       release_static_tracepoint_marker (marker);
8654     }
8655
8656   do_cleanups (old_chain);
8657
8658   *arg_p = endp;
8659   return sals;
8660 }
8661
8662 /* Set a breakpoint.  This function is shared between CLI and MI
8663    functions for setting a breakpoint.  This function has two major
8664    modes of operations, selected by the PARSE_CONDITION_AND_THREAD
8665    parameter.  If non-zero, the function will parse arg, extracting
8666    breakpoint location, address and thread.  Otherwise, ARG is just
8667    the location of breakpoint, with condition and thread specified by
8668    the COND_STRING and THREAD parameters.  If INTERNAL is non-zero,
8669    the breakpoint number will be allocated from the internal
8670    breakpoint count.  Returns true if any breakpoint was created;
8671    false otherwise.  */
8672
8673 int
8674 create_breakpoint (struct gdbarch *gdbarch,
8675                    char *arg, char *cond_string, int thread,
8676                    int parse_condition_and_thread,
8677                    int tempflag, enum bptype type_wanted,
8678                    int ignore_count,
8679                    enum auto_boolean pending_break_support,
8680                    const struct breakpoint_ops *ops,
8681                    int from_tty, int enabled, int internal)
8682 {
8683   volatile struct gdb_exception e;
8684   char *copy_arg = NULL;
8685   char *addr_start = arg;
8686   struct linespec_result canonical;
8687   struct cleanup *old_chain;
8688   struct cleanup *bkpt_chain = NULL;
8689   int i;
8690   int pending = 0;
8691   int task = 0;
8692   int prev_bkpt_count = breakpoint_count;
8693
8694   gdb_assert (ops != NULL);
8695
8696   init_linespec_result (&canonical);
8697
8698   TRY_CATCH (e, RETURN_MASK_ALL)
8699     {
8700       ops->create_sals_from_address (&arg, &canonical, type_wanted,
8701                                      addr_start, &copy_arg);
8702     }
8703
8704   /* If caller is interested in rc value from parse, set value.  */
8705   switch (e.reason)
8706     {
8707     case GDB_NO_ERROR:
8708       if (VEC_empty (linespec_sals, canonical.sals))
8709         return 0;
8710       break;
8711     case RETURN_ERROR:
8712       switch (e.error)
8713         {
8714         case NOT_FOUND_ERROR:
8715
8716           /* If pending breakpoint support is turned off, throw
8717              error.  */
8718
8719           if (pending_break_support == AUTO_BOOLEAN_FALSE)
8720             throw_exception (e);
8721
8722           exception_print (gdb_stderr, e);
8723
8724           /* If pending breakpoint support is auto query and the user
8725              selects no, then simply return the error code.  */
8726           if (pending_break_support == AUTO_BOOLEAN_AUTO
8727               && !nquery (_("Make %s pending on future shared library load? "),
8728                           bptype_string (type_wanted)))
8729             return 0;
8730
8731           /* At this point, either the user was queried about setting
8732              a pending breakpoint and selected yes, or pending
8733              breakpoint behavior is on and thus a pending breakpoint
8734              is defaulted on behalf of the user.  */
8735           {
8736             struct linespec_sals lsal;
8737
8738             copy_arg = xstrdup (addr_start);
8739             lsal.canonical = xstrdup (copy_arg);
8740             lsal.sals.nelts = 1;
8741             lsal.sals.sals = XNEW (struct symtab_and_line);
8742             init_sal (&lsal.sals.sals[0]);
8743             pending = 1;
8744             VEC_safe_push (linespec_sals, canonical.sals, &lsal);
8745           }
8746           break;
8747         default:
8748           throw_exception (e);
8749         }
8750       break;
8751     default:
8752       throw_exception (e);
8753     }
8754
8755   /* Create a chain of things that always need to be cleaned up.  */
8756   old_chain = make_cleanup_destroy_linespec_result (&canonical);
8757
8758   /* ----------------------------- SNIP -----------------------------
8759      Anything added to the cleanup chain beyond this point is assumed
8760      to be part of a breakpoint.  If the breakpoint create succeeds
8761      then the memory is not reclaimed.  */
8762   bkpt_chain = make_cleanup (null_cleanup, 0);
8763
8764   /* Resolve all line numbers to PC's and verify that the addresses
8765      are ok for the target.  */
8766   if (!pending)
8767     {
8768       int ix;
8769       struct linespec_sals *iter;
8770
8771       for (ix = 0; VEC_iterate (linespec_sals, canonical.sals, ix, iter); ++ix)
8772         breakpoint_sals_to_pc (&iter->sals);
8773     }
8774
8775   /* Fast tracepoints may have additional restrictions on location.  */
8776   if (!pending && type_wanted == bp_fast_tracepoint)
8777     {
8778       int ix;
8779       struct linespec_sals *iter;
8780
8781       for (ix = 0; VEC_iterate (linespec_sals, canonical.sals, ix, iter); ++ix)
8782         check_fast_tracepoint_sals (gdbarch, &iter->sals);
8783     }
8784
8785   /* Verify that condition can be parsed, before setting any
8786      breakpoints.  Allocate a separate condition expression for each
8787      breakpoint.  */
8788   if (!pending)
8789     {
8790       struct linespec_sals *lsal;
8791
8792       lsal = VEC_index (linespec_sals, canonical.sals, 0);
8793
8794       if (parse_condition_and_thread)
8795         {
8796             /* Here we only parse 'arg' to separate condition
8797                from thread number, so parsing in context of first
8798                sal is OK.  When setting the breakpoint we'll 
8799                re-parse it in context of each sal.  */
8800             cond_string = NULL;
8801             thread = -1;
8802             find_condition_and_thread (arg, lsal->sals.sals[0].pc, &cond_string,
8803                                        &thread, &task);
8804             if (cond_string)
8805                 make_cleanup (xfree, cond_string);
8806         }
8807       else
8808         {
8809             /* Create a private copy of condition string.  */
8810             if (cond_string)
8811             {
8812                 cond_string = xstrdup (cond_string);
8813                 make_cleanup (xfree, cond_string);
8814             }
8815         }
8816
8817       ops->create_breakpoints_sal (gdbarch, &canonical, lsal,
8818                                    cond_string, type_wanted,
8819                                    tempflag ? disp_del : disp_donttouch,
8820                                    thread, task, ignore_count, ops,
8821                                    from_tty, enabled, internal);
8822     }
8823   else
8824     {
8825       struct breakpoint *b;
8826
8827       make_cleanup (xfree, copy_arg);
8828
8829       if (is_tracepoint_type (type_wanted))
8830         {
8831           struct tracepoint *t;
8832
8833           t = XCNEW (struct tracepoint);
8834           b = &t->base;
8835         }
8836       else
8837         b = XNEW (struct breakpoint);
8838
8839       init_raw_breakpoint_without_location (b, gdbarch, type_wanted, ops);
8840
8841       b->addr_string = copy_arg;
8842       b->cond_string = NULL;
8843       b->ignore_count = ignore_count;
8844       b->disposition = tempflag ? disp_del : disp_donttouch;
8845       b->condition_not_parsed = 1;
8846       b->enable_state = enabled ? bp_enabled : bp_disabled;
8847       if ((type_wanted != bp_breakpoint
8848            && type_wanted != bp_hardware_breakpoint) || thread != -1)
8849         b->pspace = current_program_space;
8850
8851       install_breakpoint (internal, b, 0);
8852     }
8853   
8854   if (VEC_length (linespec_sals, canonical.sals) > 1)
8855     {
8856       warning (_("Multiple breakpoints were set.\nUse the "
8857                  "\"delete\" command to delete unwanted breakpoints."));
8858       prev_breakpoint_count = prev_bkpt_count;
8859     }
8860
8861   /* That's it.  Discard the cleanups for data inserted into the
8862      breakpoint.  */
8863   discard_cleanups (bkpt_chain);
8864   /* But cleanup everything else.  */
8865   do_cleanups (old_chain);
8866
8867   /* error call may happen here - have BKPT_CHAIN already discarded.  */
8868   update_global_location_list (1);
8869
8870   return 1;
8871 }
8872
8873 /* Set a breakpoint.
8874    ARG is a string describing breakpoint address,
8875    condition, and thread.
8876    FLAG specifies if a breakpoint is hardware on,
8877    and if breakpoint is temporary, using BP_HARDWARE_FLAG
8878    and BP_TEMPFLAG.  */
8879
8880 static void
8881 break_command_1 (char *arg, int flag, int from_tty)
8882 {
8883   int tempflag = flag & BP_TEMPFLAG;
8884   enum bptype type_wanted = (flag & BP_HARDWAREFLAG
8885                              ? bp_hardware_breakpoint
8886                              : bp_breakpoint);
8887
8888   create_breakpoint (get_current_arch (),
8889                      arg,
8890                      NULL, 0, 1 /* parse arg */,
8891                      tempflag, type_wanted,
8892                      0 /* Ignore count */,
8893                      pending_break_support,
8894                      &bkpt_breakpoint_ops,
8895                      from_tty,
8896                      1 /* enabled */,
8897                      0 /* internal */);
8898 }
8899
8900 /* Helper function for break_command_1 and disassemble_command.  */
8901
8902 void
8903 resolve_sal_pc (struct symtab_and_line *sal)
8904 {
8905   CORE_ADDR pc;
8906
8907   if (sal->pc == 0 && sal->symtab != NULL)
8908     {
8909       if (!find_line_pc (sal->symtab, sal->line, &pc))
8910         error (_("No line %d in file \"%s\"."),
8911                sal->line, sal->symtab->filename);
8912       sal->pc = pc;
8913
8914       /* If this SAL corresponds to a breakpoint inserted using a line
8915          number, then skip the function prologue if necessary.  */
8916       if (sal->explicit_line)
8917         skip_prologue_sal (sal);
8918     }
8919
8920   if (sal->section == 0 && sal->symtab != NULL)
8921     {
8922       struct blockvector *bv;
8923       struct block *b;
8924       struct symbol *sym;
8925
8926       bv = blockvector_for_pc_sect (sal->pc, 0, &b, sal->symtab);
8927       if (bv != NULL)
8928         {
8929           sym = block_linkage_function (b);
8930           if (sym != NULL)
8931             {
8932               fixup_symbol_section (sym, sal->symtab->objfile);
8933               sal->section = SYMBOL_OBJ_SECTION (sym);
8934             }
8935           else
8936             {
8937               /* It really is worthwhile to have the section, so we'll
8938                  just have to look harder. This case can be executed
8939                  if we have line numbers but no functions (as can
8940                  happen in assembly source).  */
8941
8942               struct minimal_symbol *msym;
8943               struct cleanup *old_chain = save_current_space_and_thread ();
8944
8945               switch_to_program_space_and_thread (sal->pspace);
8946
8947               msym = lookup_minimal_symbol_by_pc (sal->pc);
8948               if (msym)
8949                 sal->section = SYMBOL_OBJ_SECTION (msym);
8950
8951               do_cleanups (old_chain);
8952             }
8953         }
8954     }
8955 }
8956
8957 void
8958 break_command (char *arg, int from_tty)
8959 {
8960   break_command_1 (arg, 0, from_tty);
8961 }
8962
8963 void
8964 tbreak_command (char *arg, int from_tty)
8965 {
8966   break_command_1 (arg, BP_TEMPFLAG, from_tty);
8967 }
8968
8969 static void
8970 hbreak_command (char *arg, int from_tty)
8971 {
8972   break_command_1 (arg, BP_HARDWAREFLAG, from_tty);
8973 }
8974
8975 static void
8976 thbreak_command (char *arg, int from_tty)
8977 {
8978   break_command_1 (arg, (BP_TEMPFLAG | BP_HARDWAREFLAG), from_tty);
8979 }
8980
8981 static void
8982 stop_command (char *arg, int from_tty)
8983 {
8984   printf_filtered (_("Specify the type of breakpoint to set.\n\
8985 Usage: stop in <function | address>\n\
8986        stop at <line>\n"));
8987 }
8988
8989 static void
8990 stopin_command (char *arg, int from_tty)
8991 {
8992   int badInput = 0;
8993
8994   if (arg == (char *) NULL)
8995     badInput = 1;
8996   else if (*arg != '*')
8997     {
8998       char *argptr = arg;
8999       int hasColon = 0;
9000
9001       /* Look for a ':'.  If this is a line number specification, then
9002          say it is bad, otherwise, it should be an address or
9003          function/method name.  */
9004       while (*argptr && !hasColon)
9005         {
9006           hasColon = (*argptr == ':');
9007           argptr++;
9008         }
9009
9010       if (hasColon)
9011         badInput = (*argptr != ':');    /* Not a class::method */
9012       else
9013         badInput = isdigit (*arg);      /* a simple line number */
9014     }
9015
9016   if (badInput)
9017     printf_filtered (_("Usage: stop in <function | address>\n"));
9018   else
9019     break_command_1 (arg, 0, from_tty);
9020 }
9021
9022 static void
9023 stopat_command (char *arg, int from_tty)
9024 {
9025   int badInput = 0;
9026
9027   if (arg == (char *) NULL || *arg == '*')      /* no line number */
9028     badInput = 1;
9029   else
9030     {
9031       char *argptr = arg;
9032       int hasColon = 0;
9033
9034       /* Look for a ':'.  If there is a '::' then get out, otherwise
9035          it is probably a line number.  */
9036       while (*argptr && !hasColon)
9037         {
9038           hasColon = (*argptr == ':');
9039           argptr++;
9040         }
9041
9042       if (hasColon)
9043         badInput = (*argptr == ':');    /* we have class::method */
9044       else
9045         badInput = !isdigit (*arg);     /* not a line number */
9046     }
9047
9048   if (badInput)
9049     printf_filtered (_("Usage: stop at <line>\n"));
9050   else
9051     break_command_1 (arg, 0, from_tty);
9052 }
9053
9054 /* Implement the "breakpoint_hit" breakpoint_ops method for
9055    ranged breakpoints.  */
9056
9057 static int
9058 breakpoint_hit_ranged_breakpoint (const struct bp_location *bl,
9059                                   struct address_space *aspace,
9060                                   CORE_ADDR bp_addr,
9061                                   const struct target_waitstatus *ws)
9062 {
9063   if (ws->kind != TARGET_WAITKIND_STOPPED
9064       || ws->value.sig != TARGET_SIGNAL_TRAP)
9065     return 0;
9066
9067   return breakpoint_address_match_range (bl->pspace->aspace, bl->address,
9068                                          bl->length, aspace, bp_addr);
9069 }
9070
9071 /* Implement the "resources_needed" breakpoint_ops method for
9072    ranged breakpoints.  */
9073
9074 static int
9075 resources_needed_ranged_breakpoint (const struct bp_location *bl)
9076 {
9077   return target_ranged_break_num_registers ();
9078 }
9079
9080 /* Implement the "print_it" breakpoint_ops method for
9081    ranged breakpoints.  */
9082
9083 static enum print_stop_action
9084 print_it_ranged_breakpoint (bpstat bs)
9085 {
9086   struct breakpoint *b = bs->breakpoint_at;
9087   struct bp_location *bl = b->loc;
9088   struct ui_out *uiout = current_uiout;
9089
9090   gdb_assert (b->type == bp_hardware_breakpoint);
9091
9092   /* Ranged breakpoints have only one location.  */
9093   gdb_assert (bl && bl->next == NULL);
9094
9095   annotate_breakpoint (b->number);
9096   if (b->disposition == disp_del)
9097     ui_out_text (uiout, "\nTemporary ranged breakpoint ");
9098   else
9099     ui_out_text (uiout, "\nRanged breakpoint ");
9100   if (ui_out_is_mi_like_p (uiout))
9101     {
9102       ui_out_field_string (uiout, "reason",
9103                       async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
9104       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
9105     }
9106   ui_out_field_int (uiout, "bkptno", b->number);
9107   ui_out_text (uiout, ", ");
9108
9109   return PRINT_SRC_AND_LOC;
9110 }
9111
9112 /* Implement the "print_one" breakpoint_ops method for
9113    ranged breakpoints.  */
9114
9115 static void
9116 print_one_ranged_breakpoint (struct breakpoint *b,
9117                              struct bp_location **last_loc)
9118 {
9119   struct bp_location *bl = b->loc;
9120   struct value_print_options opts;
9121   struct ui_out *uiout = current_uiout;
9122
9123   /* Ranged breakpoints have only one location.  */
9124   gdb_assert (bl && bl->next == NULL);
9125
9126   get_user_print_options (&opts);
9127
9128   if (opts.addressprint)
9129     /* We don't print the address range here, it will be printed later
9130        by print_one_detail_ranged_breakpoint.  */
9131     ui_out_field_skip (uiout, "addr");
9132   annotate_field (5);
9133   print_breakpoint_location (b, bl);
9134   *last_loc = bl;
9135 }
9136
9137 /* Implement the "print_one_detail" breakpoint_ops method for
9138    ranged breakpoints.  */
9139
9140 static void
9141 print_one_detail_ranged_breakpoint (const struct breakpoint *b,
9142                                     struct ui_out *uiout)
9143 {
9144   CORE_ADDR address_start, address_end;
9145   struct bp_location *bl = b->loc;
9146   struct ui_stream *stb = ui_out_stream_new (uiout);
9147   struct cleanup *cleanup = make_cleanup_ui_out_stream_delete (stb);
9148
9149   gdb_assert (bl);
9150
9151   address_start = bl->address;
9152   address_end = address_start + bl->length - 1;
9153
9154   ui_out_text (uiout, "\taddress range: ");
9155   fprintf_unfiltered (stb->stream, "[%s, %s]",
9156                       print_core_address (bl->gdbarch, address_start),
9157                       print_core_address (bl->gdbarch, address_end));
9158   ui_out_field_stream (uiout, "addr", stb);
9159   ui_out_text (uiout, "\n");
9160
9161   do_cleanups (cleanup);
9162 }
9163
9164 /* Implement the "print_mention" breakpoint_ops method for
9165    ranged breakpoints.  */
9166
9167 static void
9168 print_mention_ranged_breakpoint (struct breakpoint *b)
9169 {
9170   struct bp_location *bl = b->loc;
9171   struct ui_out *uiout = current_uiout;
9172
9173   gdb_assert (bl);
9174   gdb_assert (b->type == bp_hardware_breakpoint);
9175
9176   if (ui_out_is_mi_like_p (uiout))
9177     return;
9178
9179   printf_filtered (_("Hardware assisted ranged breakpoint %d from %s to %s."),
9180                    b->number, paddress (bl->gdbarch, bl->address),
9181                    paddress (bl->gdbarch, bl->address + bl->length - 1));
9182 }
9183
9184 /* Implement the "print_recreate" breakpoint_ops method for
9185    ranged breakpoints.  */
9186
9187 static void
9188 print_recreate_ranged_breakpoint (struct breakpoint *b, struct ui_file *fp)
9189 {
9190   fprintf_unfiltered (fp, "break-range %s, %s", b->addr_string,
9191                       b->addr_string_range_end);
9192   print_recreate_thread (b, fp);
9193 }
9194
9195 /* The breakpoint_ops structure to be used in ranged breakpoints.  */
9196
9197 static struct breakpoint_ops ranged_breakpoint_ops;
9198
9199 /* Find the address where the end of the breakpoint range should be
9200    placed, given the SAL of the end of the range.  This is so that if
9201    the user provides a line number, the end of the range is set to the
9202    last instruction of the given line.  */
9203
9204 static CORE_ADDR
9205 find_breakpoint_range_end (struct symtab_and_line sal)
9206 {
9207   CORE_ADDR end;
9208
9209   /* If the user provided a PC value, use it.  Otherwise,
9210      find the address of the end of the given location.  */
9211   if (sal.explicit_pc)
9212     end = sal.pc;
9213   else
9214     {
9215       int ret;
9216       CORE_ADDR start;
9217
9218       ret = find_line_pc_range (sal, &start, &end);
9219       if (!ret)
9220         error (_("Could not find location of the end of the range."));
9221
9222       /* find_line_pc_range returns the start of the next line.  */
9223       end--;
9224     }
9225
9226   return end;
9227 }
9228
9229 /* Implement the "break-range" CLI command.  */
9230
9231 static void
9232 break_range_command (char *arg, int from_tty)
9233 {
9234   char *arg_start, *addr_string_start, *addr_string_end;
9235   struct linespec_result canonical_start, canonical_end;
9236   int bp_count, can_use_bp, length;
9237   CORE_ADDR end;
9238   struct breakpoint *b;
9239   struct symtab_and_line sal_start, sal_end;
9240   struct cleanup *cleanup_bkpt;
9241   struct linespec_sals *lsal_start, *lsal_end;
9242
9243   /* We don't support software ranged breakpoints.  */
9244   if (target_ranged_break_num_registers () < 0)
9245     error (_("This target does not support hardware ranged breakpoints."));
9246
9247   bp_count = hw_breakpoint_used_count ();
9248   bp_count += target_ranged_break_num_registers ();
9249   can_use_bp = target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
9250                                                    bp_count, 0);
9251   if (can_use_bp < 0)
9252     error (_("Hardware breakpoints used exceeds limit."));
9253
9254   arg = skip_spaces (arg);
9255   if (arg == NULL || arg[0] == '\0')
9256     error(_("No address range specified."));
9257
9258   init_linespec_result (&canonical_start);
9259
9260   arg_start = arg;
9261   parse_breakpoint_sals (&arg, &canonical_start);
9262
9263   cleanup_bkpt = make_cleanup_destroy_linespec_result (&canonical_start);
9264
9265   if (arg[0] != ',')
9266     error (_("Too few arguments."));
9267   else if (VEC_empty (linespec_sals, canonical_start.sals))
9268     error (_("Could not find location of the beginning of the range."));
9269
9270   lsal_start = VEC_index (linespec_sals, canonical_start.sals, 0);
9271
9272   if (VEC_length (linespec_sals, canonical_start.sals) > 1
9273       || lsal_start->sals.nelts != 1)
9274     error (_("Cannot create a ranged breakpoint with multiple locations."));
9275
9276   sal_start = lsal_start->sals.sals[0];
9277   addr_string_start = savestring (arg_start, arg - arg_start);
9278   make_cleanup (xfree, addr_string_start);
9279
9280   arg++;        /* Skip the comma.  */
9281   arg = skip_spaces (arg);
9282
9283   /* Parse the end location.  */
9284
9285   init_linespec_result (&canonical_end);
9286   arg_start = arg;
9287
9288   /* We call decode_line_full directly here instead of using
9289      parse_breakpoint_sals because we need to specify the start location's
9290      symtab and line as the default symtab and line for the end of the
9291      range.  This makes it possible to have ranges like "foo.c:27, +14",
9292      where +14 means 14 lines from the start location.  */
9293   decode_line_full (&arg, DECODE_LINE_FUNFIRSTLINE,
9294                     sal_start.symtab, sal_start.line,
9295                     &canonical_end, NULL, NULL);
9296
9297   make_cleanup_destroy_linespec_result (&canonical_end);
9298
9299   if (VEC_empty (linespec_sals, canonical_end.sals))
9300     error (_("Could not find location of the end of the range."));
9301
9302   lsal_end = VEC_index (linespec_sals, canonical_end.sals, 0);
9303   if (VEC_length (linespec_sals, canonical_end.sals) > 1
9304       || lsal_end->sals.nelts != 1)
9305     error (_("Cannot create a ranged breakpoint with multiple locations."));
9306
9307   sal_end = lsal_end->sals.sals[0];
9308   addr_string_end = savestring (arg_start, arg - arg_start);
9309   make_cleanup (xfree, addr_string_end);
9310
9311   end = find_breakpoint_range_end (sal_end);
9312   if (sal_start.pc > end)
9313     error (_("Invalid address range, end precedes start."));
9314
9315   length = end - sal_start.pc + 1;
9316   if (length < 0)
9317     /* Length overflowed.  */
9318     error (_("Address range too large."));
9319   else if (length == 1)
9320     {
9321       /* This range is simple enough to be handled by
9322          the `hbreak' command.  */
9323       hbreak_command (addr_string_start, 1);
9324
9325       do_cleanups (cleanup_bkpt);
9326
9327       return;
9328     }
9329
9330   /* Now set up the breakpoint.  */
9331   b = set_raw_breakpoint (get_current_arch (), sal_start,
9332                           bp_hardware_breakpoint, &ranged_breakpoint_ops);
9333   set_breakpoint_count (breakpoint_count + 1);
9334   b->number = breakpoint_count;
9335   b->disposition = disp_donttouch;
9336   b->addr_string = xstrdup (addr_string_start);
9337   b->addr_string_range_end = xstrdup (addr_string_end);
9338   b->loc->length = length;
9339
9340   do_cleanups (cleanup_bkpt);
9341
9342   mention (b);
9343   observer_notify_breakpoint_created (b);
9344   update_global_location_list (1);
9345 }
9346
9347 /*  Return non-zero if EXP is verified as constant.  Returned zero
9348     means EXP is variable.  Also the constant detection may fail for
9349     some constant expressions and in such case still falsely return
9350     zero.  */
9351
9352 static int
9353 watchpoint_exp_is_const (const struct expression *exp)
9354 {
9355   int i = exp->nelts;
9356
9357   while (i > 0)
9358     {
9359       int oplenp, argsp;
9360
9361       /* We are only interested in the descriptor of each element.  */
9362       operator_length (exp, i, &oplenp, &argsp);
9363       i -= oplenp;
9364
9365       switch (exp->elts[i].opcode)
9366         {
9367         case BINOP_ADD:
9368         case BINOP_SUB:
9369         case BINOP_MUL:
9370         case BINOP_DIV:
9371         case BINOP_REM:
9372         case BINOP_MOD:
9373         case BINOP_LSH:
9374         case BINOP_RSH:
9375         case BINOP_LOGICAL_AND:
9376         case BINOP_LOGICAL_OR:
9377         case BINOP_BITWISE_AND:
9378         case BINOP_BITWISE_IOR:
9379         case BINOP_BITWISE_XOR:
9380         case BINOP_EQUAL:
9381         case BINOP_NOTEQUAL:
9382         case BINOP_LESS:
9383         case BINOP_GTR:
9384         case BINOP_LEQ:
9385         case BINOP_GEQ:
9386         case BINOP_REPEAT:
9387         case BINOP_COMMA:
9388         case BINOP_EXP:
9389         case BINOP_MIN:
9390         case BINOP_MAX:
9391         case BINOP_INTDIV:
9392         case BINOP_CONCAT:
9393         case BINOP_IN:
9394         case BINOP_RANGE:
9395         case TERNOP_COND:
9396         case TERNOP_SLICE:
9397         case TERNOP_SLICE_COUNT:
9398
9399         case OP_LONG:
9400         case OP_DOUBLE:
9401         case OP_DECFLOAT:
9402         case OP_LAST:
9403         case OP_COMPLEX:
9404         case OP_STRING:
9405         case OP_BITSTRING:
9406         case OP_ARRAY:
9407         case OP_TYPE:
9408         case OP_NAME:
9409         case OP_OBJC_NSSTRING:
9410
9411         case UNOP_NEG:
9412         case UNOP_LOGICAL_NOT:
9413         case UNOP_COMPLEMENT:
9414         case UNOP_ADDR:
9415         case UNOP_HIGH:
9416         case UNOP_CAST:
9417           /* Unary, binary and ternary operators: We have to check
9418              their operands.  If they are constant, then so is the
9419              result of that operation.  For instance, if A and B are
9420              determined to be constants, then so is "A + B".
9421
9422              UNOP_IND is one exception to the rule above, because the
9423              value of *ADDR is not necessarily a constant, even when
9424              ADDR is.  */
9425           break;
9426
9427         case OP_VAR_VALUE:
9428           /* Check whether the associated symbol is a constant.
9429
9430              We use SYMBOL_CLASS rather than TYPE_CONST because it's
9431              possible that a buggy compiler could mark a variable as
9432              constant even when it is not, and TYPE_CONST would return
9433              true in this case, while SYMBOL_CLASS wouldn't.
9434
9435              We also have to check for function symbols because they
9436              are always constant.  */
9437           {
9438             struct symbol *s = exp->elts[i + 2].symbol;
9439
9440             if (SYMBOL_CLASS (s) != LOC_BLOCK
9441                 && SYMBOL_CLASS (s) != LOC_CONST
9442                 && SYMBOL_CLASS (s) != LOC_CONST_BYTES)
9443               return 0;
9444             break;
9445           }
9446
9447         /* The default action is to return 0 because we are using
9448            the optimistic approach here: If we don't know something,
9449            then it is not a constant.  */
9450         default:
9451           return 0;
9452         }
9453     }
9454
9455   return 1;
9456 }
9457
9458 /* Implement the "dtor" breakpoint_ops method for watchpoints.  */
9459
9460 static void
9461 dtor_watchpoint (struct breakpoint *self)
9462 {
9463   struct watchpoint *w = (struct watchpoint *) self;
9464
9465   xfree (w->cond_exp);
9466   xfree (w->exp);
9467   xfree (w->exp_string);
9468   xfree (w->exp_string_reparse);
9469   value_free (w->val);
9470
9471   base_breakpoint_ops.dtor (self);
9472 }
9473
9474 /* Implement the "re_set" breakpoint_ops method for watchpoints.  */
9475
9476 static void
9477 re_set_watchpoint (struct breakpoint *b)
9478 {
9479   struct watchpoint *w = (struct watchpoint *) b;
9480
9481   /* Watchpoint can be either on expression using entirely global
9482      variables, or it can be on local variables.
9483
9484      Watchpoints of the first kind are never auto-deleted, and even
9485      persist across program restarts.  Since they can use variables
9486      from shared libraries, we need to reparse expression as libraries
9487      are loaded and unloaded.
9488
9489      Watchpoints on local variables can also change meaning as result
9490      of solib event.  For example, if a watchpoint uses both a local
9491      and a global variables in expression, it's a local watchpoint,
9492      but unloading of a shared library will make the expression
9493      invalid.  This is not a very common use case, but we still
9494      re-evaluate expression, to avoid surprises to the user.
9495
9496      Note that for local watchpoints, we re-evaluate it only if
9497      watchpoints frame id is still valid.  If it's not, it means the
9498      watchpoint is out of scope and will be deleted soon.  In fact,
9499      I'm not sure we'll ever be called in this case.
9500
9501      If a local watchpoint's frame id is still valid, then
9502      w->exp_valid_block is likewise valid, and we can safely use it.
9503
9504      Don't do anything about disabled watchpoints, since they will be
9505      reevaluated again when enabled.  */
9506   update_watchpoint (w, 1 /* reparse */);
9507 }
9508
9509 /* Implement the "insert" breakpoint_ops method for hardware watchpoints.  */
9510
9511 static int
9512 insert_watchpoint (struct bp_location *bl)
9513 {
9514   struct watchpoint *w = (struct watchpoint *) bl->owner;
9515   int length = w->exact ? 1 : bl->length;
9516
9517   return target_insert_watchpoint (bl->address, length, bl->watchpoint_type,
9518                                    w->cond_exp);
9519 }
9520
9521 /* Implement the "remove" breakpoint_ops method for hardware watchpoints.  */
9522
9523 static int
9524 remove_watchpoint (struct bp_location *bl)
9525 {
9526   struct watchpoint *w = (struct watchpoint *) bl->owner;
9527   int length = w->exact ? 1 : bl->length;
9528
9529   return target_remove_watchpoint (bl->address, length, bl->watchpoint_type,
9530                                    w->cond_exp);
9531 }
9532
9533 static int
9534 breakpoint_hit_watchpoint (const struct bp_location *bl,
9535                            struct address_space *aspace, CORE_ADDR bp_addr,
9536                            const struct target_waitstatus *ws)
9537 {
9538   struct breakpoint *b = bl->owner;
9539   struct watchpoint *w = (struct watchpoint *) b;
9540
9541   /* Continuable hardware watchpoints are treated as non-existent if the
9542      reason we stopped wasn't a hardware watchpoint (we didn't stop on
9543      some data address).  Otherwise gdb won't stop on a break instruction
9544      in the code (not from a breakpoint) when a hardware watchpoint has
9545      been defined.  Also skip watchpoints which we know did not trigger
9546      (did not match the data address).  */
9547   if (is_hardware_watchpoint (b)
9548       && w->watchpoint_triggered == watch_triggered_no)
9549     return 0;
9550
9551   return 1;
9552 }
9553
9554 static void
9555 check_status_watchpoint (bpstat bs)
9556 {
9557   gdb_assert (is_watchpoint (bs->breakpoint_at));
9558
9559   bpstat_check_watchpoint (bs);
9560 }
9561
9562 /* Implement the "resources_needed" breakpoint_ops method for
9563    hardware watchpoints.  */
9564
9565 static int
9566 resources_needed_watchpoint (const struct bp_location *bl)
9567 {
9568   struct watchpoint *w = (struct watchpoint *) bl->owner;
9569   int length = w->exact? 1 : bl->length;
9570
9571   return target_region_ok_for_hw_watchpoint (bl->address, length);
9572 }
9573
9574 /* Implement the "works_in_software_mode" breakpoint_ops method for
9575    hardware watchpoints.  */
9576
9577 static int
9578 works_in_software_mode_watchpoint (const struct breakpoint *b)
9579 {
9580   /* Read and access watchpoints only work with hardware support.  */
9581   return b->type == bp_watchpoint || b->type == bp_hardware_watchpoint;
9582 }
9583
9584 static enum print_stop_action
9585 print_it_watchpoint (bpstat bs)
9586 {
9587   struct cleanup *old_chain;
9588   struct breakpoint *b;
9589   const struct bp_location *bl;
9590   struct ui_stream *stb;
9591   enum print_stop_action result;
9592   struct watchpoint *w;
9593   struct ui_out *uiout = current_uiout;
9594
9595   gdb_assert (bs->bp_location_at != NULL);
9596
9597   bl = bs->bp_location_at;
9598   b = bs->breakpoint_at;
9599   w = (struct watchpoint *) b;
9600
9601   stb = ui_out_stream_new (uiout);
9602   old_chain = make_cleanup_ui_out_stream_delete (stb);
9603
9604   switch (b->type)
9605     {
9606     case bp_watchpoint:
9607     case bp_hardware_watchpoint:
9608       annotate_watchpoint (b->number);
9609       if (ui_out_is_mi_like_p (uiout))
9610         ui_out_field_string
9611           (uiout, "reason",
9612            async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
9613       mention (b);
9614       make_cleanup_ui_out_tuple_begin_end (uiout, "value");
9615       ui_out_text (uiout, "\nOld value = ");
9616       watchpoint_value_print (bs->old_val, stb->stream);
9617       ui_out_field_stream (uiout, "old", stb);
9618       ui_out_text (uiout, "\nNew value = ");
9619       watchpoint_value_print (w->val, stb->stream);
9620       ui_out_field_stream (uiout, "new", stb);
9621       ui_out_text (uiout, "\n");
9622       /* More than one watchpoint may have been triggered.  */
9623       result = PRINT_UNKNOWN;
9624       break;
9625
9626     case bp_read_watchpoint:
9627       if (ui_out_is_mi_like_p (uiout))
9628         ui_out_field_string
9629           (uiout, "reason",
9630            async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
9631       mention (b);
9632       make_cleanup_ui_out_tuple_begin_end (uiout, "value");
9633       ui_out_text (uiout, "\nValue = ");
9634       watchpoint_value_print (w->val, stb->stream);
9635       ui_out_field_stream (uiout, "value", stb);
9636       ui_out_text (uiout, "\n");
9637       result = PRINT_UNKNOWN;
9638       break;
9639
9640     case bp_access_watchpoint:
9641       if (bs->old_val != NULL)
9642         {
9643           annotate_watchpoint (b->number);
9644           if (ui_out_is_mi_like_p (uiout))
9645             ui_out_field_string
9646               (uiout, "reason",
9647                async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
9648           mention (b);
9649           make_cleanup_ui_out_tuple_begin_end (uiout, "value");
9650           ui_out_text (uiout, "\nOld value = ");
9651           watchpoint_value_print (bs->old_val, stb->stream);
9652           ui_out_field_stream (uiout, "old", stb);
9653           ui_out_text (uiout, "\nNew value = ");
9654         }
9655       else
9656         {
9657           mention (b);
9658           if (ui_out_is_mi_like_p (uiout))
9659             ui_out_field_string
9660               (uiout, "reason",
9661                async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
9662           make_cleanup_ui_out_tuple_begin_end (uiout, "value");
9663           ui_out_text (uiout, "\nValue = ");
9664         }
9665       watchpoint_value_print (w->val, stb->stream);
9666       ui_out_field_stream (uiout, "new", stb);
9667       ui_out_text (uiout, "\n");
9668       result = PRINT_UNKNOWN;
9669       break;
9670     default:
9671       result = PRINT_UNKNOWN;
9672     }
9673
9674   do_cleanups (old_chain);
9675   return result;
9676 }
9677
9678 /* Implement the "print_mention" breakpoint_ops method for hardware
9679    watchpoints.  */
9680
9681 static void
9682 print_mention_watchpoint (struct breakpoint *b)
9683 {
9684   struct cleanup *ui_out_chain;
9685   struct watchpoint *w = (struct watchpoint *) b;
9686   struct ui_out *uiout = current_uiout;
9687
9688   switch (b->type)
9689     {
9690     case bp_watchpoint:
9691       ui_out_text (uiout, "Watchpoint ");
9692       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "wpt");
9693       break;
9694     case bp_hardware_watchpoint:
9695       ui_out_text (uiout, "Hardware watchpoint ");
9696       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "wpt");
9697       break;
9698     case bp_read_watchpoint:
9699       ui_out_text (uiout, "Hardware read watchpoint ");
9700       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-rwpt");
9701       break;
9702     case bp_access_watchpoint:
9703       ui_out_text (uiout, "Hardware access (read/write) watchpoint ");
9704       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-awpt");
9705       break;
9706     default:
9707       internal_error (__FILE__, __LINE__,
9708                       _("Invalid hardware watchpoint type."));
9709     }
9710
9711   ui_out_field_int (uiout, "number", b->number);
9712   ui_out_text (uiout, ": ");
9713   ui_out_field_string (uiout, "exp", w->exp_string);
9714   do_cleanups (ui_out_chain);
9715 }
9716
9717 /* Implement the "print_recreate" breakpoint_ops method for
9718    watchpoints.  */
9719
9720 static void
9721 print_recreate_watchpoint (struct breakpoint *b, struct ui_file *fp)
9722 {
9723   struct watchpoint *w = (struct watchpoint *) b;
9724
9725   switch (b->type)
9726     {
9727     case bp_watchpoint:
9728     case bp_hardware_watchpoint:
9729       fprintf_unfiltered (fp, "watch");
9730       break;
9731     case bp_read_watchpoint:
9732       fprintf_unfiltered (fp, "rwatch");
9733       break;
9734     case bp_access_watchpoint:
9735       fprintf_unfiltered (fp, "awatch");
9736       break;
9737     default:
9738       internal_error (__FILE__, __LINE__,
9739                       _("Invalid watchpoint type."));
9740     }
9741
9742   fprintf_unfiltered (fp, " %s", w->exp_string);
9743   print_recreate_thread (b, fp);
9744 }
9745
9746 /* The breakpoint_ops structure to be used in hardware watchpoints.  */
9747
9748 static struct breakpoint_ops watchpoint_breakpoint_ops;
9749
9750 /* Implement the "insert" breakpoint_ops method for
9751    masked hardware watchpoints.  */
9752
9753 static int
9754 insert_masked_watchpoint (struct bp_location *bl)
9755 {
9756   struct watchpoint *w = (struct watchpoint *) bl->owner;
9757
9758   return target_insert_mask_watchpoint (bl->address, w->hw_wp_mask,
9759                                         bl->watchpoint_type);
9760 }
9761
9762 /* Implement the "remove" breakpoint_ops method for
9763    masked hardware watchpoints.  */
9764
9765 static int
9766 remove_masked_watchpoint (struct bp_location *bl)
9767 {
9768   struct watchpoint *w = (struct watchpoint *) bl->owner;
9769
9770   return target_remove_mask_watchpoint (bl->address, w->hw_wp_mask,
9771                                         bl->watchpoint_type);
9772 }
9773
9774 /* Implement the "resources_needed" breakpoint_ops method for
9775    masked hardware watchpoints.  */
9776
9777 static int
9778 resources_needed_masked_watchpoint (const struct bp_location *bl)
9779 {
9780   struct watchpoint *w = (struct watchpoint *) bl->owner;
9781
9782   return target_masked_watch_num_registers (bl->address, w->hw_wp_mask);
9783 }
9784
9785 /* Implement the "works_in_software_mode" breakpoint_ops method for
9786    masked hardware watchpoints.  */
9787
9788 static int
9789 works_in_software_mode_masked_watchpoint (const struct breakpoint *b)
9790 {
9791   return 0;
9792 }
9793
9794 /* Implement the "print_it" breakpoint_ops method for
9795    masked hardware watchpoints.  */
9796
9797 static enum print_stop_action
9798 print_it_masked_watchpoint (bpstat bs)
9799 {
9800   struct breakpoint *b = bs->breakpoint_at;
9801   struct ui_out *uiout = current_uiout;
9802
9803   /* Masked watchpoints have only one location.  */
9804   gdb_assert (b->loc && b->loc->next == NULL);
9805
9806   switch (b->type)
9807     {
9808     case bp_hardware_watchpoint:
9809       annotate_watchpoint (b->number);
9810       if (ui_out_is_mi_like_p (uiout))
9811         ui_out_field_string
9812           (uiout, "reason",
9813            async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
9814       break;
9815
9816     case bp_read_watchpoint:
9817       if (ui_out_is_mi_like_p (uiout))
9818         ui_out_field_string
9819           (uiout, "reason",
9820            async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
9821       break;
9822
9823     case bp_access_watchpoint:
9824       if (ui_out_is_mi_like_p (uiout))
9825         ui_out_field_string
9826           (uiout, "reason",
9827            async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
9828       break;
9829     default:
9830       internal_error (__FILE__, __LINE__,
9831                       _("Invalid hardware watchpoint type."));
9832     }
9833
9834   mention (b);
9835   ui_out_text (uiout, _("\n\
9836 Check the underlying instruction at PC for the memory\n\
9837 address and value which triggered this watchpoint.\n"));
9838   ui_out_text (uiout, "\n");
9839
9840   /* More than one watchpoint may have been triggered.  */
9841   return PRINT_UNKNOWN;
9842 }
9843
9844 /* Implement the "print_one_detail" breakpoint_ops method for
9845    masked hardware watchpoints.  */
9846
9847 static void
9848 print_one_detail_masked_watchpoint (const struct breakpoint *b,
9849                                     struct ui_out *uiout)
9850 {
9851   struct watchpoint *w = (struct watchpoint *) b;
9852
9853   /* Masked watchpoints have only one location.  */
9854   gdb_assert (b->loc && b->loc->next == NULL);
9855
9856   ui_out_text (uiout, "\tmask ");
9857   ui_out_field_core_addr (uiout, "mask", b->loc->gdbarch, w->hw_wp_mask);
9858   ui_out_text (uiout, "\n");
9859 }
9860
9861 /* Implement the "print_mention" breakpoint_ops method for
9862    masked hardware watchpoints.  */
9863
9864 static void
9865 print_mention_masked_watchpoint (struct breakpoint *b)
9866 {
9867   struct watchpoint *w = (struct watchpoint *) b;
9868   struct ui_out *uiout = current_uiout;
9869   struct cleanup *ui_out_chain;
9870
9871   switch (b->type)
9872     {
9873     case bp_hardware_watchpoint:
9874       ui_out_text (uiout, "Masked hardware watchpoint ");
9875       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "wpt");
9876       break;
9877     case bp_read_watchpoint:
9878       ui_out_text (uiout, "Masked hardware read watchpoint ");
9879       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-rwpt");
9880       break;
9881     case bp_access_watchpoint:
9882       ui_out_text (uiout, "Masked hardware access (read/write) watchpoint ");
9883       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-awpt");
9884       break;
9885     default:
9886       internal_error (__FILE__, __LINE__,
9887                       _("Invalid hardware watchpoint type."));
9888     }
9889
9890   ui_out_field_int (uiout, "number", b->number);
9891   ui_out_text (uiout, ": ");
9892   ui_out_field_string (uiout, "exp", w->exp_string);
9893   do_cleanups (ui_out_chain);
9894 }
9895
9896 /* Implement the "print_recreate" breakpoint_ops method for
9897    masked hardware watchpoints.  */
9898
9899 static void
9900 print_recreate_masked_watchpoint (struct breakpoint *b, struct ui_file *fp)
9901 {
9902   struct watchpoint *w = (struct watchpoint *) b;
9903   char tmp[40];
9904
9905   switch (b->type)
9906     {
9907     case bp_hardware_watchpoint:
9908       fprintf_unfiltered (fp, "watch");
9909       break;
9910     case bp_read_watchpoint:
9911       fprintf_unfiltered (fp, "rwatch");
9912       break;
9913     case bp_access_watchpoint:
9914       fprintf_unfiltered (fp, "awatch");
9915       break;
9916     default:
9917       internal_error (__FILE__, __LINE__,
9918                       _("Invalid hardware watchpoint type."));
9919     }
9920
9921   sprintf_vma (tmp, w->hw_wp_mask);
9922   fprintf_unfiltered (fp, " %s mask 0x%s", w->exp_string, tmp);
9923   print_recreate_thread (b, fp);
9924 }
9925
9926 /* The breakpoint_ops structure to be used in masked hardware watchpoints.  */
9927
9928 static struct breakpoint_ops masked_watchpoint_breakpoint_ops;
9929
9930 /* Tell whether the given watchpoint is a masked hardware watchpoint.  */
9931
9932 static int
9933 is_masked_watchpoint (const struct breakpoint *b)
9934 {
9935   return b->ops == &masked_watchpoint_breakpoint_ops;
9936 }
9937
9938 /* accessflag:  hw_write:  watch write, 
9939                 hw_read:   watch read, 
9940                 hw_access: watch access (read or write) */
9941 static void
9942 watch_command_1 (char *arg, int accessflag, int from_tty,
9943                  int just_location, int internal)
9944 {
9945   volatile struct gdb_exception e;
9946   struct breakpoint *b, *scope_breakpoint = NULL;
9947   struct expression *exp;
9948   struct block *exp_valid_block = NULL, *cond_exp_valid_block = NULL;
9949   struct value *val, *mark, *result;
9950   struct frame_info *frame;
9951   char *exp_start = NULL;
9952   char *exp_end = NULL;
9953   char *tok, *end_tok;
9954   int toklen = -1;
9955   char *cond_start = NULL;
9956   char *cond_end = NULL;
9957   enum bptype bp_type;
9958   int thread = -1;
9959   int pc = 0;
9960   /* Flag to indicate whether we are going to use masks for
9961      the hardware watchpoint.  */
9962   int use_mask = 0;
9963   CORE_ADDR mask = 0;
9964   struct watchpoint *w;
9965
9966   /* Make sure that we actually have parameters to parse.  */
9967   if (arg != NULL && arg[0] != '\0')
9968     {
9969       char *value_start;
9970
9971       /* Look for "parameter value" pairs at the end
9972          of the arguments string.  */
9973       for (tok = arg + strlen (arg) - 1; tok > arg; tok--)
9974         {
9975           /* Skip whitespace at the end of the argument list.  */
9976           while (tok > arg && (*tok == ' ' || *tok == '\t'))
9977             tok--;
9978
9979           /* Find the beginning of the last token.
9980              This is the value of the parameter.  */
9981           while (tok > arg && (*tok != ' ' && *tok != '\t'))
9982             tok--;
9983           value_start = tok + 1;
9984
9985           /* Skip whitespace.  */
9986           while (tok > arg && (*tok == ' ' || *tok == '\t'))
9987             tok--;
9988
9989           end_tok = tok;
9990
9991           /* Find the beginning of the second to last token.
9992              This is the parameter itself.  */
9993           while (tok > arg && (*tok != ' ' && *tok != '\t'))
9994             tok--;
9995           tok++;
9996           toklen = end_tok - tok + 1;
9997
9998           if (toklen == 6 && !strncmp (tok, "thread", 6))
9999             {
10000               /* At this point we've found a "thread" token, which means
10001                  the user is trying to set a watchpoint that triggers
10002                  only in a specific thread.  */
10003               char *endp;
10004
10005               if (thread != -1)
10006                 error(_("You can specify only one thread."));
10007
10008               /* Extract the thread ID from the next token.  */
10009               thread = strtol (value_start, &endp, 0);
10010
10011               /* Check if the user provided a valid numeric value for the
10012                  thread ID.  */
10013               if (*endp != ' ' && *endp != '\t' && *endp != '\0')
10014                 error (_("Invalid thread ID specification %s."), value_start);
10015
10016               /* Check if the thread actually exists.  */
10017               if (!valid_thread_id (thread))
10018                 error (_("Unknown thread %d."), thread);
10019             }
10020           else if (toklen == 4 && !strncmp (tok, "mask", 4))
10021             {
10022               /* We've found a "mask" token, which means the user wants to
10023                  create a hardware watchpoint that is going to have the mask
10024                  facility.  */
10025               struct value *mask_value, *mark;
10026
10027               if (use_mask)
10028                 error(_("You can specify only one mask."));
10029
10030               use_mask = just_location = 1;
10031
10032               mark = value_mark ();
10033               mask_value = parse_to_comma_and_eval (&value_start);
10034               mask = value_as_address (mask_value);
10035               value_free_to_mark (mark);
10036             }
10037           else
10038             /* We didn't recognize what we found.  We should stop here.  */
10039             break;
10040
10041           /* Truncate the string and get rid of the "parameter value" pair before
10042              the arguments string is parsed by the parse_exp_1 function.  */
10043           *tok = '\0';
10044         }
10045     }
10046
10047   /* Parse the rest of the arguments.  */
10048   innermost_block = NULL;
10049   exp_start = arg;
10050   exp = parse_exp_1 (&arg, 0, 0);
10051   exp_end = arg;
10052   /* Remove trailing whitespace from the expression before saving it.
10053      This makes the eventual display of the expression string a bit
10054      prettier.  */
10055   while (exp_end > exp_start && (exp_end[-1] == ' ' || exp_end[-1] == '\t'))
10056     --exp_end;
10057
10058   /* Checking if the expression is not constant.  */
10059   if (watchpoint_exp_is_const (exp))
10060     {
10061       int len;
10062
10063       len = exp_end - exp_start;
10064       while (len > 0 && isspace (exp_start[len - 1]))
10065         len--;
10066       error (_("Cannot watch constant value `%.*s'."), len, exp_start);
10067     }
10068
10069   exp_valid_block = innermost_block;
10070   mark = value_mark ();
10071   fetch_subexp_value (exp, &pc, &val, &result, NULL);
10072
10073   if (just_location)
10074     {
10075       int ret;
10076
10077       exp_valid_block = NULL;
10078       val = value_addr (result);
10079       release_value (val);
10080       value_free_to_mark (mark);
10081
10082       if (use_mask)
10083         {
10084           ret = target_masked_watch_num_registers (value_as_address (val),
10085                                                    mask);
10086           if (ret == -1)
10087             error (_("This target does not support masked watchpoints."));
10088           else if (ret == -2)
10089             error (_("Invalid mask or memory region."));
10090         }
10091     }
10092   else if (val != NULL)
10093     release_value (val);
10094
10095   tok = skip_spaces (arg);
10096   end_tok = skip_to_space (tok);
10097
10098   toklen = end_tok - tok;
10099   if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
10100     {
10101       struct expression *cond;
10102
10103       innermost_block = NULL;
10104       tok = cond_start = end_tok + 1;
10105       cond = parse_exp_1 (&tok, 0, 0);
10106
10107       /* The watchpoint expression may not be local, but the condition
10108          may still be.  E.g.: `watch global if local > 0'.  */
10109       cond_exp_valid_block = innermost_block;
10110
10111       xfree (cond);
10112       cond_end = tok;
10113     }
10114   if (*tok)
10115     error (_("Junk at end of command."));
10116
10117   if (accessflag == hw_read)
10118     bp_type = bp_read_watchpoint;
10119   else if (accessflag == hw_access)
10120     bp_type = bp_access_watchpoint;
10121   else
10122     bp_type = bp_hardware_watchpoint;
10123
10124   frame = block_innermost_frame (exp_valid_block);
10125
10126   /* If the expression is "local", then set up a "watchpoint scope"
10127      breakpoint at the point where we've left the scope of the watchpoint
10128      expression.  Create the scope breakpoint before the watchpoint, so
10129      that we will encounter it first in bpstat_stop_status.  */
10130   if (exp_valid_block && frame)
10131     {
10132       if (frame_id_p (frame_unwind_caller_id (frame)))
10133         {
10134           scope_breakpoint
10135             = create_internal_breakpoint (frame_unwind_caller_arch (frame),
10136                                           frame_unwind_caller_pc (frame),
10137                                           bp_watchpoint_scope,
10138                                           &momentary_breakpoint_ops);
10139
10140           scope_breakpoint->enable_state = bp_enabled;
10141
10142           /* Automatically delete the breakpoint when it hits.  */
10143           scope_breakpoint->disposition = disp_del;
10144
10145           /* Only break in the proper frame (help with recursion).  */
10146           scope_breakpoint->frame_id = frame_unwind_caller_id (frame);
10147
10148           /* Set the address at which we will stop.  */
10149           scope_breakpoint->loc->gdbarch
10150             = frame_unwind_caller_arch (frame);
10151           scope_breakpoint->loc->requested_address
10152             = frame_unwind_caller_pc (frame);
10153           scope_breakpoint->loc->address
10154             = adjust_breakpoint_address (scope_breakpoint->loc->gdbarch,
10155                                          scope_breakpoint->loc->requested_address,
10156                                          scope_breakpoint->type);
10157         }
10158     }
10159
10160   /* Now set up the breakpoint.  */
10161
10162   w = XCNEW (struct watchpoint);
10163   b = &w->base;
10164   if (use_mask)
10165     init_raw_breakpoint_without_location (b, NULL, bp_type,
10166                                           &masked_watchpoint_breakpoint_ops);
10167   else
10168     init_raw_breakpoint_without_location (b, NULL, bp_type,
10169                                           &watchpoint_breakpoint_ops);
10170   b->thread = thread;
10171   b->disposition = disp_donttouch;
10172   b->pspace = current_program_space;
10173   w->exp = exp;
10174   w->exp_valid_block = exp_valid_block;
10175   w->cond_exp_valid_block = cond_exp_valid_block;
10176   if (just_location)
10177     {
10178       struct type *t = value_type (val);
10179       CORE_ADDR addr = value_as_address (val);
10180       char *name;
10181
10182       t = check_typedef (TYPE_TARGET_TYPE (check_typedef (t)));
10183       name = type_to_string (t);
10184
10185       w->exp_string_reparse = xstrprintf ("* (%s *) %s", name,
10186                                           core_addr_to_string (addr));
10187       xfree (name);
10188
10189       w->exp_string = xstrprintf ("-location %.*s",
10190                                   (int) (exp_end - exp_start), exp_start);
10191
10192       /* The above expression is in C.  */
10193       b->language = language_c;
10194     }
10195   else
10196     w->exp_string = savestring (exp_start, exp_end - exp_start);
10197
10198   if (use_mask)
10199     {
10200       w->hw_wp_mask = mask;
10201     }
10202   else
10203     {
10204       w->val = val;
10205       w->val_valid = 1;
10206     }
10207
10208   if (cond_start)
10209     b->cond_string = savestring (cond_start, cond_end - cond_start);
10210   else
10211     b->cond_string = 0;
10212
10213   if (frame)
10214     {
10215       w->watchpoint_frame = get_frame_id (frame);
10216       w->watchpoint_thread = inferior_ptid;
10217     }
10218   else
10219     {
10220       w->watchpoint_frame = null_frame_id;
10221       w->watchpoint_thread = null_ptid;
10222     }
10223
10224   if (scope_breakpoint != NULL)
10225     {
10226       /* The scope breakpoint is related to the watchpoint.  We will
10227          need to act on them together.  */
10228       b->related_breakpoint = scope_breakpoint;
10229       scope_breakpoint->related_breakpoint = b;
10230     }
10231
10232   if (!just_location)
10233     value_free_to_mark (mark);
10234
10235   TRY_CATCH (e, RETURN_MASK_ALL)
10236     {
10237       /* Finally update the new watchpoint.  This creates the locations
10238          that should be inserted.  */
10239       update_watchpoint (w, 1);
10240     }
10241   if (e.reason < 0)
10242     {
10243       delete_breakpoint (b);
10244       throw_exception (e);
10245     }
10246
10247   install_breakpoint (internal, b, 1);
10248 }
10249
10250 /* Return count of debug registers needed to watch the given expression.
10251    If the watchpoint cannot be handled in hardware return zero.  */
10252
10253 static int
10254 can_use_hardware_watchpoint (struct value *v)
10255 {
10256   int found_memory_cnt = 0;
10257   struct value *head = v;
10258
10259   /* Did the user specifically forbid us to use hardware watchpoints? */
10260   if (!can_use_hw_watchpoints)
10261     return 0;
10262
10263   /* Make sure that the value of the expression depends only upon
10264      memory contents, and values computed from them within GDB.  If we
10265      find any register references or function calls, we can't use a
10266      hardware watchpoint.
10267
10268      The idea here is that evaluating an expression generates a series
10269      of values, one holding the value of every subexpression.  (The
10270      expression a*b+c has five subexpressions: a, b, a*b, c, and
10271      a*b+c.)  GDB's values hold almost enough information to establish
10272      the criteria given above --- they identify memory lvalues,
10273      register lvalues, computed values, etcetera.  So we can evaluate
10274      the expression, and then scan the chain of values that leaves
10275      behind to decide whether we can detect any possible change to the
10276      expression's final value using only hardware watchpoints.
10277
10278      However, I don't think that the values returned by inferior
10279      function calls are special in any way.  So this function may not
10280      notice that an expression involving an inferior function call
10281      can't be watched with hardware watchpoints.  FIXME.  */
10282   for (; v; v = value_next (v))
10283     {
10284       if (VALUE_LVAL (v) == lval_memory)
10285         {
10286           if (v != head && value_lazy (v))
10287             /* A lazy memory lvalue in the chain is one that GDB never
10288                needed to fetch; we either just used its address (e.g.,
10289                `a' in `a.b') or we never needed it at all (e.g., `a'
10290                in `a,b').  This doesn't apply to HEAD; if that is
10291                lazy then it was not readable, but watch it anyway.  */
10292             ;
10293           else
10294             {
10295               /* Ahh, memory we actually used!  Check if we can cover
10296                  it with hardware watchpoints.  */
10297               struct type *vtype = check_typedef (value_type (v));
10298
10299               /* We only watch structs and arrays if user asked for it
10300                  explicitly, never if they just happen to appear in a
10301                  middle of some value chain.  */
10302               if (v == head
10303                   || (TYPE_CODE (vtype) != TYPE_CODE_STRUCT
10304                       && TYPE_CODE (vtype) != TYPE_CODE_ARRAY))
10305                 {
10306                   CORE_ADDR vaddr = value_address (v);
10307                   int len;
10308                   int num_regs;
10309
10310                   len = (target_exact_watchpoints
10311                          && is_scalar_type_recursive (vtype))?
10312                     1 : TYPE_LENGTH (value_type (v));
10313
10314                   num_regs = target_region_ok_for_hw_watchpoint (vaddr, len);
10315                   if (!num_regs)
10316                     return 0;
10317                   else
10318                     found_memory_cnt += num_regs;
10319                 }
10320             }
10321         }
10322       else if (VALUE_LVAL (v) != not_lval
10323                && deprecated_value_modifiable (v) == 0)
10324         return 0;       /* These are values from the history (e.g., $1).  */
10325       else if (VALUE_LVAL (v) == lval_register)
10326         return 0;       /* Cannot watch a register with a HW watchpoint.  */
10327     }
10328
10329   /* The expression itself looks suitable for using a hardware
10330      watchpoint, but give the target machine a chance to reject it.  */
10331   return found_memory_cnt;
10332 }
10333
10334 void
10335 watch_command_wrapper (char *arg, int from_tty, int internal)
10336 {
10337   watch_command_1 (arg, hw_write, from_tty, 0, internal);
10338 }
10339
10340 /* A helper function that looks for an argument at the start of a
10341    string.  The argument must also either be at the end of the string,
10342    or be followed by whitespace.  Returns 1 if it finds the argument,
10343    0 otherwise.  If the argument is found, it updates *STR.  */
10344
10345 static int
10346 check_for_argument (char **str, char *arg, int arg_len)
10347 {
10348   if (strncmp (*str, arg, arg_len) == 0
10349       && ((*str)[arg_len] == '\0' || isspace ((*str)[arg_len])))
10350     {
10351       *str += arg_len;
10352       return 1;
10353     }
10354   return 0;
10355 }
10356
10357 /* A helper function that looks for the "-location" argument and then
10358    calls watch_command_1.  */
10359
10360 static void
10361 watch_maybe_just_location (char *arg, int accessflag, int from_tty)
10362 {
10363   int just_location = 0;
10364
10365   if (arg
10366       && (check_for_argument (&arg, "-location", sizeof ("-location") - 1)
10367           || check_for_argument (&arg, "-l", sizeof ("-l") - 1)))
10368     {
10369       arg = skip_spaces (arg);
10370       just_location = 1;
10371     }
10372
10373   watch_command_1 (arg, accessflag, from_tty, just_location, 0);
10374 }
10375
10376 static void
10377 watch_command (char *arg, int from_tty)
10378 {
10379   watch_maybe_just_location (arg, hw_write, from_tty);
10380 }
10381
10382 void
10383 rwatch_command_wrapper (char *arg, int from_tty, int internal)
10384 {
10385   watch_command_1 (arg, hw_read, from_tty, 0, internal);
10386 }
10387
10388 static void
10389 rwatch_command (char *arg, int from_tty)
10390 {
10391   watch_maybe_just_location (arg, hw_read, from_tty);
10392 }
10393
10394 void
10395 awatch_command_wrapper (char *arg, int from_tty, int internal)
10396 {
10397   watch_command_1 (arg, hw_access, from_tty, 0, internal);
10398 }
10399
10400 static void
10401 awatch_command (char *arg, int from_tty)
10402 {
10403   watch_maybe_just_location (arg, hw_access, from_tty);
10404 }
10405 \f
10406
10407 /* Helper routines for the until_command routine in infcmd.c.  Here
10408    because it uses the mechanisms of breakpoints.  */
10409
10410 struct until_break_command_continuation_args
10411 {
10412   struct breakpoint *breakpoint;
10413   struct breakpoint *breakpoint2;
10414   int thread_num;
10415 };
10416
10417 /* This function is called by fetch_inferior_event via the
10418    cmd_continuation pointer, to complete the until command.  It takes
10419    care of cleaning up the temporary breakpoints set up by the until
10420    command.  */
10421 static void
10422 until_break_command_continuation (void *arg, int err)
10423 {
10424   struct until_break_command_continuation_args *a = arg;
10425
10426   delete_breakpoint (a->breakpoint);
10427   if (a->breakpoint2)
10428     delete_breakpoint (a->breakpoint2);
10429   delete_longjmp_breakpoint (a->thread_num);
10430 }
10431
10432 void
10433 until_break_command (char *arg, int from_tty, int anywhere)
10434 {
10435   struct symtabs_and_lines sals;
10436   struct symtab_and_line sal;
10437   struct frame_info *frame = get_selected_frame (NULL);
10438   struct gdbarch *frame_gdbarch = get_frame_arch (frame);
10439   struct frame_id stack_frame_id = get_stack_frame_id (frame);
10440   struct frame_id caller_frame_id = frame_unwind_caller_id (frame);
10441   struct breakpoint *breakpoint;
10442   struct breakpoint *breakpoint2 = NULL;
10443   struct cleanup *old_chain;
10444   int thread;
10445   struct thread_info *tp;
10446
10447   clear_proceed_status ();
10448
10449   /* Set a breakpoint where the user wants it and at return from
10450      this function.  */
10451
10452   if (last_displayed_sal_is_valid ())
10453     sals = decode_line_1 (&arg, DECODE_LINE_FUNFIRSTLINE,
10454                           get_last_displayed_symtab (),
10455                           get_last_displayed_line ());
10456   else
10457     sals = decode_line_1 (&arg, DECODE_LINE_FUNFIRSTLINE,
10458                           (struct symtab *) NULL, 0);
10459
10460   if (sals.nelts != 1)
10461     error (_("Couldn't get information on specified line."));
10462
10463   sal = sals.sals[0];
10464   xfree (sals.sals);    /* malloc'd, so freed.  */
10465
10466   if (*arg)
10467     error (_("Junk at end of arguments."));
10468
10469   resolve_sal_pc (&sal);
10470
10471   tp = inferior_thread ();
10472   thread = tp->num;
10473
10474   old_chain = make_cleanup (null_cleanup, NULL);
10475
10476   /* Installing a breakpoint invalidates the frame chain (as it may
10477      need to switch threads), so do any frame handling first.  */
10478
10479   /* Keep within the current frame, or in frames called by the current
10480      one.  */
10481
10482   if (frame_id_p (caller_frame_id))
10483     {
10484       struct symtab_and_line sal2;
10485
10486       sal2 = find_pc_line (frame_unwind_caller_pc (frame), 0);
10487       sal2.pc = frame_unwind_caller_pc (frame);
10488       breakpoint2 = set_momentary_breakpoint (frame_unwind_caller_arch (frame),
10489                                               sal2,
10490                                               caller_frame_id,
10491                                               bp_until);
10492       make_cleanup_delete_breakpoint (breakpoint2);
10493
10494       set_longjmp_breakpoint (tp, caller_frame_id);
10495       make_cleanup (delete_longjmp_breakpoint_cleanup, &thread);
10496     }
10497
10498   /* set_momentary_breakpoint could invalidate FRAME.  */
10499   frame = NULL;
10500
10501   if (anywhere)
10502     /* If the user told us to continue until a specified location,
10503        we don't specify a frame at which we need to stop.  */
10504     breakpoint = set_momentary_breakpoint (frame_gdbarch, sal,
10505                                            null_frame_id, bp_until);
10506   else
10507     /* Otherwise, specify the selected frame, because we want to stop
10508        only at the very same frame.  */
10509     breakpoint = set_momentary_breakpoint (frame_gdbarch, sal,
10510                                            stack_frame_id, bp_until);
10511   make_cleanup_delete_breakpoint (breakpoint);
10512
10513   proceed (-1, TARGET_SIGNAL_DEFAULT, 0);
10514
10515   /* If we are running asynchronously, and proceed call above has
10516      actually managed to start the target, arrange for breakpoints to
10517      be deleted when the target stops.  Otherwise, we're already
10518      stopped and delete breakpoints via cleanup chain.  */
10519
10520   if (target_can_async_p () && is_running (inferior_ptid))
10521     {
10522       struct until_break_command_continuation_args *args;
10523       args = xmalloc (sizeof (*args));
10524
10525       args->breakpoint = breakpoint;
10526       args->breakpoint2 = breakpoint2;
10527       args->thread_num = thread;
10528
10529       discard_cleanups (old_chain);
10530       add_continuation (inferior_thread (),
10531                         until_break_command_continuation, args,
10532                         xfree);
10533     }
10534   else
10535     do_cleanups (old_chain);
10536 }
10537
10538 /* This function attempts to parse an optional "if <cond>" clause
10539    from the arg string.  If one is not found, it returns NULL.
10540
10541    Else, it returns a pointer to the condition string.  (It does not
10542    attempt to evaluate the string against a particular block.)  And,
10543    it updates arg to point to the first character following the parsed
10544    if clause in the arg string.  */
10545
10546 static char *
10547 ep_parse_optional_if_clause (char **arg)
10548 {
10549   char *cond_string;
10550
10551   if (((*arg)[0] != 'i') || ((*arg)[1] != 'f') || !isspace ((*arg)[2]))
10552     return NULL;
10553
10554   /* Skip the "if" keyword.  */
10555   (*arg) += 2;
10556
10557   /* Skip any extra leading whitespace, and record the start of the
10558      condition string.  */
10559   *arg = skip_spaces (*arg);
10560   cond_string = *arg;
10561
10562   /* Assume that the condition occupies the remainder of the arg
10563      string.  */
10564   (*arg) += strlen (cond_string);
10565
10566   return cond_string;
10567 }
10568
10569 /* Commands to deal with catching events, such as signals, exceptions,
10570    process start/exit, etc.  */
10571
10572 typedef enum
10573 {
10574   catch_fork_temporary, catch_vfork_temporary,
10575   catch_fork_permanent, catch_vfork_permanent
10576 }
10577 catch_fork_kind;
10578
10579 static void
10580 catch_fork_command_1 (char *arg, int from_tty, 
10581                       struct cmd_list_element *command)
10582 {
10583   struct gdbarch *gdbarch = get_current_arch ();
10584   char *cond_string = NULL;
10585   catch_fork_kind fork_kind;
10586   int tempflag;
10587
10588   fork_kind = (catch_fork_kind) (uintptr_t) get_cmd_context (command);
10589   tempflag = (fork_kind == catch_fork_temporary
10590               || fork_kind == catch_vfork_temporary);
10591
10592   if (!arg)
10593     arg = "";
10594   arg = skip_spaces (arg);
10595
10596   /* The allowed syntax is:
10597      catch [v]fork
10598      catch [v]fork if <cond>
10599
10600      First, check if there's an if clause.  */
10601   cond_string = ep_parse_optional_if_clause (&arg);
10602
10603   if ((*arg != '\0') && !isspace (*arg))
10604     error (_("Junk at end of arguments."));
10605
10606   /* If this target supports it, create a fork or vfork catchpoint
10607      and enable reporting of such events.  */
10608   switch (fork_kind)
10609     {
10610     case catch_fork_temporary:
10611     case catch_fork_permanent:
10612       create_fork_vfork_event_catchpoint (gdbarch, tempflag, cond_string,
10613                                           &catch_fork_breakpoint_ops);
10614       break;
10615     case catch_vfork_temporary:
10616     case catch_vfork_permanent:
10617       create_fork_vfork_event_catchpoint (gdbarch, tempflag, cond_string,
10618                                           &catch_vfork_breakpoint_ops);
10619       break;
10620     default:
10621       error (_("unsupported or unknown fork kind; cannot catch it"));
10622       break;
10623     }
10624 }
10625
10626 static void
10627 catch_exec_command_1 (char *arg, int from_tty, 
10628                       struct cmd_list_element *command)
10629 {
10630   struct exec_catchpoint *c;
10631   struct gdbarch *gdbarch = get_current_arch ();
10632   int tempflag;
10633   char *cond_string = NULL;
10634
10635   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
10636
10637   if (!arg)
10638     arg = "";
10639   arg = skip_spaces (arg);
10640
10641   /* The allowed syntax is:
10642      catch exec
10643      catch exec if <cond>
10644
10645      First, check if there's an if clause.  */
10646   cond_string = ep_parse_optional_if_clause (&arg);
10647
10648   if ((*arg != '\0') && !isspace (*arg))
10649     error (_("Junk at end of arguments."));
10650
10651   c = XNEW (struct exec_catchpoint);
10652   init_catchpoint (&c->base, gdbarch, tempflag, cond_string,
10653                    &catch_exec_breakpoint_ops);
10654   c->exec_pathname = NULL;
10655
10656   install_breakpoint (0, &c->base, 1);
10657 }
10658
10659 static enum print_stop_action
10660 print_it_exception_catchpoint (bpstat bs)
10661 {
10662   struct ui_out *uiout = current_uiout;
10663   struct breakpoint *b = bs->breakpoint_at;
10664   int bp_temp, bp_throw;
10665
10666   annotate_catchpoint (b->number);
10667
10668   bp_throw = strstr (b->addr_string, "throw") != NULL;
10669   if (b->loc->address != b->loc->requested_address)
10670     breakpoint_adjustment_warning (b->loc->requested_address,
10671                                    b->loc->address,
10672                                    b->number, 1);
10673   bp_temp = b->disposition == disp_del;
10674   ui_out_text (uiout, 
10675                bp_temp ? "Temporary catchpoint "
10676                        : "Catchpoint ");
10677   if (!ui_out_is_mi_like_p (uiout))
10678     ui_out_field_int (uiout, "bkptno", b->number);
10679   ui_out_text (uiout,
10680                bp_throw ? " (exception thrown), "
10681                         : " (exception caught), ");
10682   if (ui_out_is_mi_like_p (uiout))
10683     {
10684       ui_out_field_string (uiout, "reason", 
10685                            async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
10686       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
10687       ui_out_field_int (uiout, "bkptno", b->number);
10688     }
10689   return PRINT_SRC_AND_LOC;
10690 }
10691
10692 static void
10693 print_one_exception_catchpoint (struct breakpoint *b, 
10694                                 struct bp_location **last_loc)
10695 {
10696   struct value_print_options opts;
10697   struct ui_out *uiout = current_uiout;
10698
10699   get_user_print_options (&opts);
10700   if (opts.addressprint)
10701     {
10702       annotate_field (4);
10703       if (b->loc == NULL || b->loc->shlib_disabled)
10704         ui_out_field_string (uiout, "addr", "<PENDING>");
10705       else
10706         ui_out_field_core_addr (uiout, "addr",
10707                                 b->loc->gdbarch, b->loc->address);
10708     }
10709   annotate_field (5);
10710   if (b->loc)
10711     *last_loc = b->loc;
10712   if (strstr (b->addr_string, "throw") != NULL)
10713     ui_out_field_string (uiout, "what", "exception throw");
10714   else
10715     ui_out_field_string (uiout, "what", "exception catch");
10716 }
10717
10718 static void
10719 print_mention_exception_catchpoint (struct breakpoint *b)
10720 {
10721   struct ui_out *uiout = current_uiout;
10722   int bp_temp;
10723   int bp_throw;
10724
10725   bp_temp = b->disposition == disp_del;
10726   bp_throw = strstr (b->addr_string, "throw") != NULL;
10727   ui_out_text (uiout, bp_temp ? _("Temporary catchpoint ")
10728                               : _("Catchpoint "));
10729   ui_out_field_int (uiout, "bkptno", b->number);
10730   ui_out_text (uiout, bp_throw ? _(" (throw)")
10731                                : _(" (catch)"));
10732 }
10733
10734 /* Implement the "print_recreate" breakpoint_ops method for throw and
10735    catch catchpoints.  */
10736
10737 static void
10738 print_recreate_exception_catchpoint (struct breakpoint *b, 
10739                                      struct ui_file *fp)
10740 {
10741   int bp_temp;
10742   int bp_throw;
10743
10744   bp_temp = b->disposition == disp_del;
10745   bp_throw = strstr (b->addr_string, "throw") != NULL;
10746   fprintf_unfiltered (fp, bp_temp ? "tcatch " : "catch ");
10747   fprintf_unfiltered (fp, bp_throw ? "throw" : "catch");
10748   print_recreate_thread (b, fp);
10749 }
10750
10751 static struct breakpoint_ops gnu_v3_exception_catchpoint_ops;
10752
10753 static int
10754 handle_gnu_v3_exceptions (int tempflag, char *cond_string,
10755                           enum exception_event_kind ex_event, int from_tty)
10756 {
10757   char *trigger_func_name;
10758  
10759   if (ex_event == EX_EVENT_CATCH)
10760     trigger_func_name = "__cxa_begin_catch";
10761   else
10762     trigger_func_name = "__cxa_throw";
10763
10764   create_breakpoint (get_current_arch (),
10765                      trigger_func_name, cond_string, -1,
10766                      0 /* condition and thread are valid.  */,
10767                      tempflag, bp_breakpoint,
10768                      0,
10769                      AUTO_BOOLEAN_TRUE /* pending */,
10770                      &gnu_v3_exception_catchpoint_ops, from_tty,
10771                      1 /* enabled */,
10772                      0 /* internal */);
10773
10774   return 1;
10775 }
10776
10777 /* Deal with "catch catch" and "catch throw" commands.  */
10778
10779 static void
10780 catch_exception_command_1 (enum exception_event_kind ex_event, char *arg,
10781                            int tempflag, int from_tty)
10782 {
10783   char *cond_string = NULL;
10784
10785   if (!arg)
10786     arg = "";
10787   arg = skip_spaces (arg);
10788
10789   cond_string = ep_parse_optional_if_clause (&arg);
10790
10791   if ((*arg != '\0') && !isspace (*arg))
10792     error (_("Junk at end of arguments."));
10793
10794   if (ex_event != EX_EVENT_THROW
10795       && ex_event != EX_EVENT_CATCH)
10796     error (_("Unsupported or unknown exception event; cannot catch it"));
10797
10798   if (handle_gnu_v3_exceptions (tempflag, cond_string, ex_event, from_tty))
10799     return;
10800
10801   warning (_("Unsupported with this platform/compiler combination."));
10802 }
10803
10804 /* Implementation of "catch catch" command.  */
10805
10806 static void
10807 catch_catch_command (char *arg, int from_tty, struct cmd_list_element *command)
10808 {
10809   int tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
10810
10811   catch_exception_command_1 (EX_EVENT_CATCH, arg, tempflag, from_tty);
10812 }
10813
10814 /* Implementation of "catch throw" command.  */
10815
10816 static void
10817 catch_throw_command (char *arg, int from_tty, struct cmd_list_element *command)
10818 {
10819   int tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
10820
10821   catch_exception_command_1 (EX_EVENT_THROW, arg, tempflag, from_tty);
10822 }
10823
10824 void
10825 init_ada_exception_breakpoint (struct breakpoint *b,
10826                                struct gdbarch *gdbarch,
10827                                struct symtab_and_line sal,
10828                                char *addr_string,
10829                                const struct breakpoint_ops *ops,
10830                                int tempflag,
10831                                int from_tty)
10832 {
10833   if (from_tty)
10834     {
10835       struct gdbarch *loc_gdbarch = get_sal_arch (sal);
10836       if (!loc_gdbarch)
10837         loc_gdbarch = gdbarch;
10838
10839       describe_other_breakpoints (loc_gdbarch,
10840                                   sal.pspace, sal.pc, sal.section, -1);
10841       /* FIXME: brobecker/2006-12-28: Actually, re-implement a special
10842          version for exception catchpoints, because two catchpoints
10843          used for different exception names will use the same address.
10844          In this case, a "breakpoint ... also set at..." warning is
10845          unproductive.  Besides, the warning phrasing is also a bit
10846          inappropriate, we should use the word catchpoint, and tell
10847          the user what type of catchpoint it is.  The above is good
10848          enough for now, though.  */
10849     }
10850
10851   init_raw_breakpoint (b, gdbarch, sal, bp_breakpoint, ops);
10852
10853   b->enable_state = bp_enabled;
10854   b->disposition = tempflag ? disp_del : disp_donttouch;
10855   b->addr_string = addr_string;
10856   b->language = language_ada;
10857 }
10858
10859 /* Splits the argument using space as delimiter.  Returns an xmalloc'd
10860    filter list, or NULL if no filtering is required.  */
10861 static VEC(int) *
10862 catch_syscall_split_args (char *arg)
10863 {
10864   VEC(int) *result = NULL;
10865   struct cleanup *cleanup = make_cleanup (VEC_cleanup (int), &result);
10866
10867   while (*arg != '\0')
10868     {
10869       int i, syscall_number;
10870       char *endptr;
10871       char cur_name[128];
10872       struct syscall s;
10873
10874       /* Skip whitespace.  */
10875       while (isspace (*arg))
10876         arg++;
10877
10878       for (i = 0; i < 127 && arg[i] && !isspace (arg[i]); ++i)
10879         cur_name[i] = arg[i];
10880       cur_name[i] = '\0';
10881       arg += i;
10882
10883       /* Check if the user provided a syscall name or a number.  */
10884       syscall_number = (int) strtol (cur_name, &endptr, 0);
10885       if (*endptr == '\0')
10886         get_syscall_by_number (syscall_number, &s);
10887       else
10888         {
10889           /* We have a name.  Let's check if it's valid and convert it
10890              to a number.  */
10891           get_syscall_by_name (cur_name, &s);
10892
10893           if (s.number == UNKNOWN_SYSCALL)
10894             /* Here we have to issue an error instead of a warning,
10895                because GDB cannot do anything useful if there's no
10896                syscall number to be caught.  */
10897             error (_("Unknown syscall name '%s'."), cur_name);
10898         }
10899
10900       /* Ok, it's valid.  */
10901       VEC_safe_push (int, result, s.number);
10902     }
10903
10904   discard_cleanups (cleanup);
10905   return result;
10906 }
10907
10908 /* Implement the "catch syscall" command.  */
10909
10910 static void
10911 catch_syscall_command_1 (char *arg, int from_tty, 
10912                          struct cmd_list_element *command)
10913 {
10914   int tempflag;
10915   VEC(int) *filter;
10916   struct syscall s;
10917   struct gdbarch *gdbarch = get_current_arch ();
10918
10919   /* Checking if the feature if supported.  */
10920   if (gdbarch_get_syscall_number_p (gdbarch) == 0)
10921     error (_("The feature 'catch syscall' is not supported on \
10922 this architecture yet."));
10923
10924   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
10925
10926   arg = skip_spaces (arg);
10927
10928   /* We need to do this first "dummy" translation in order
10929      to get the syscall XML file loaded or, most important,
10930      to display a warning to the user if there's no XML file
10931      for his/her architecture.  */
10932   get_syscall_by_number (0, &s);
10933
10934   /* The allowed syntax is:
10935      catch syscall
10936      catch syscall <name | number> [<name | number> ... <name | number>]
10937
10938      Let's check if there's a syscall name.  */
10939
10940   if (arg != NULL)
10941     filter = catch_syscall_split_args (arg);
10942   else
10943     filter = NULL;
10944
10945   create_syscall_event_catchpoint (tempflag, filter,
10946                                    &catch_syscall_breakpoint_ops);
10947 }
10948
10949 static void
10950 catch_command (char *arg, int from_tty)
10951 {
10952   error (_("Catch requires an event name."));
10953 }
10954 \f
10955
10956 static void
10957 tcatch_command (char *arg, int from_tty)
10958 {
10959   error (_("Catch requires an event name."));
10960 }
10961
10962 /* A qsort comparison function that sorts breakpoints in order.  */
10963
10964 static int
10965 compare_breakpoints (const void *a, const void *b)
10966 {
10967   const breakpoint_p *ba = a;
10968   uintptr_t ua = (uintptr_t) *ba;
10969   const breakpoint_p *bb = b;
10970   uintptr_t ub = (uintptr_t) *bb;
10971
10972   if ((*ba)->number < (*bb)->number)
10973     return -1;
10974   else if ((*ba)->number > (*bb)->number)
10975     return 1;
10976
10977   /* Now sort by address, in case we see, e..g, two breakpoints with
10978      the number 0.  */
10979   if (ua < ub)
10980     return -1;
10981   return ub > ub ? 1 : 0;
10982 }
10983
10984 /* Delete breakpoints by address or line.  */
10985
10986 static void
10987 clear_command (char *arg, int from_tty)
10988 {
10989   struct breakpoint *b, *prev;
10990   VEC(breakpoint_p) *found = 0;
10991   int ix;
10992   int default_match;
10993   struct symtabs_and_lines sals;
10994   struct symtab_and_line sal;
10995   int i;
10996   struct cleanup *cleanups = make_cleanup (null_cleanup, NULL);
10997
10998   if (arg)
10999     {
11000       sals = decode_line_spec (arg, (DECODE_LINE_FUNFIRSTLINE
11001                                      | DECODE_LINE_LIST_MODE));
11002       default_match = 0;
11003     }
11004   else
11005     {
11006       sals.sals = (struct symtab_and_line *)
11007         xmalloc (sizeof (struct symtab_and_line));
11008       make_cleanup (xfree, sals.sals);
11009       init_sal (&sal);          /* Initialize to zeroes.  */
11010
11011       /* Set sal's line, symtab, pc, and pspace to the values
11012          corresponding to the last call to print_frame_info.  If the
11013          codepoint is not valid, this will set all the fields to 0.  */
11014       get_last_displayed_sal (&sal);
11015       if (sal.symtab == 0)
11016         error (_("No source file specified."));
11017
11018       sals.sals[0] = sal;
11019       sals.nelts = 1;
11020
11021       default_match = 1;
11022     }
11023
11024   /* We don't call resolve_sal_pc here.  That's not as bad as it
11025      seems, because all existing breakpoints typically have both
11026      file/line and pc set.  So, if clear is given file/line, we can
11027      match this to existing breakpoint without obtaining pc at all.
11028
11029      We only support clearing given the address explicitly 
11030      present in breakpoint table.  Say, we've set breakpoint 
11031      at file:line.  There were several PC values for that file:line,
11032      due to optimization, all in one block.
11033
11034      We've picked one PC value.  If "clear" is issued with another
11035      PC corresponding to the same file:line, the breakpoint won't
11036      be cleared.  We probably can still clear the breakpoint, but 
11037      since the other PC value is never presented to user, user
11038      can only find it by guessing, and it does not seem important
11039      to support that.  */
11040
11041   /* For each line spec given, delete bps which correspond to it.  Do
11042      it in two passes, solely to preserve the current behavior that
11043      from_tty is forced true if we delete more than one
11044      breakpoint.  */
11045
11046   found = NULL;
11047   make_cleanup (VEC_cleanup (breakpoint_p), &found);
11048   for (i = 0; i < sals.nelts; i++)
11049     {
11050       int is_abs, sal_name_len;
11051
11052       /* If exact pc given, clear bpts at that pc.
11053          If line given (pc == 0), clear all bpts on specified line.
11054          If defaulting, clear all bpts on default line
11055          or at default pc.
11056
11057          defaulting    sal.pc != 0    tests to do
11058
11059          0              1             pc
11060          1              1             pc _and_ line
11061          0              0             line
11062          1              0             <can't happen> */
11063
11064       sal = sals.sals[i];
11065       is_abs = sal.symtab == NULL ? 1 : IS_ABSOLUTE_PATH (sal.symtab->filename);
11066       sal_name_len = is_abs ? 0 : strlen (sal.symtab->filename);
11067
11068       /* Find all matching breakpoints and add them to 'found'.  */
11069       ALL_BREAKPOINTS (b)
11070         {
11071           int match = 0;
11072           /* Are we going to delete b?  */
11073           if (b->type != bp_none && !is_watchpoint (b))
11074             {
11075               struct bp_location *loc = b->loc;
11076               for (; loc; loc = loc->next)
11077                 {
11078                   /* If the user specified file:line, don't allow a PC
11079                      match.  This matches historical gdb behavior.  */
11080                   int pc_match = (!sal.explicit_line
11081                                   && sal.pc
11082                                   && (loc->pspace == sal.pspace)
11083                                   && (loc->address == sal.pc)
11084                                   && (!section_is_overlay (loc->section)
11085                                       || loc->section == sal.section));
11086                   int line_match = 0;
11087
11088                   if ((default_match || sal.explicit_line)
11089                       && loc->source_file != NULL
11090                       && sal.symtab != NULL
11091                       && sal.pspace == loc->pspace
11092                       && loc->line_number == sal.line)
11093                     {
11094                       if (filename_cmp (loc->source_file,
11095                                         sal.symtab->filename) == 0)
11096                         line_match = 1;
11097                       else if (!IS_ABSOLUTE_PATH (sal.symtab->filename)
11098                                && compare_filenames_for_search (loc->source_file,
11099                                                                 sal.symtab->filename,
11100                                                                 sal_name_len))
11101                         line_match = 1;
11102                     }
11103
11104                   if (pc_match || line_match)
11105                     {
11106                       match = 1;
11107                       break;
11108                     }
11109                 }
11110             }
11111
11112           if (match)
11113             VEC_safe_push(breakpoint_p, found, b);
11114         }
11115     }
11116
11117   /* Now go thru the 'found' chain and delete them.  */
11118   if (VEC_empty(breakpoint_p, found))
11119     {
11120       if (arg)
11121         error (_("No breakpoint at %s."), arg);
11122       else
11123         error (_("No breakpoint at this line."));
11124     }
11125
11126   /* Remove duplicates from the vec.  */
11127   qsort (VEC_address (breakpoint_p, found),
11128          VEC_length (breakpoint_p, found),
11129          sizeof (breakpoint_p),
11130          compare_breakpoints);
11131   prev = VEC_index (breakpoint_p, found, 0);
11132   for (ix = 1; VEC_iterate (breakpoint_p, found, ix, b); ++ix)
11133     {
11134       if (b == prev)
11135         {
11136           VEC_ordered_remove (breakpoint_p, found, ix);
11137           --ix;
11138         }
11139     }
11140
11141   if (VEC_length(breakpoint_p, found) > 1)
11142     from_tty = 1;       /* Always report if deleted more than one.  */
11143   if (from_tty)
11144     {
11145       if (VEC_length(breakpoint_p, found) == 1)
11146         printf_unfiltered (_("Deleted breakpoint "));
11147       else
11148         printf_unfiltered (_("Deleted breakpoints "));
11149     }
11150   breakpoints_changed ();
11151
11152   for (ix = 0; VEC_iterate(breakpoint_p, found, ix, b); ix++)
11153     {
11154       if (from_tty)
11155         printf_unfiltered ("%d ", b->number);
11156       delete_breakpoint (b);
11157     }
11158   if (from_tty)
11159     putchar_unfiltered ('\n');
11160
11161   do_cleanups (cleanups);
11162 }
11163 \f
11164 /* Delete breakpoint in BS if they are `delete' breakpoints and
11165    all breakpoints that are marked for deletion, whether hit or not.
11166    This is called after any breakpoint is hit, or after errors.  */
11167
11168 void
11169 breakpoint_auto_delete (bpstat bs)
11170 {
11171   struct breakpoint *b, *b_tmp;
11172
11173   for (; bs; bs = bs->next)
11174     if (bs->breakpoint_at
11175         && bs->breakpoint_at->disposition == disp_del
11176         && bs->stop)
11177       delete_breakpoint (bs->breakpoint_at);
11178
11179   ALL_BREAKPOINTS_SAFE (b, b_tmp)
11180   {
11181     if (b->disposition == disp_del_at_next_stop)
11182       delete_breakpoint (b);
11183   }
11184 }
11185
11186 /* A comparison function for bp_location AP and BP being interfaced to
11187    qsort.  Sort elements primarily by their ADDRESS (no matter what
11188    does breakpoint_address_is_meaningful say for its OWNER),
11189    secondarily by ordering first bp_permanent OWNERed elements and
11190    terciarily just ensuring the array is sorted stable way despite
11191    qsort being an unstable algorithm.  */
11192
11193 static int
11194 bp_location_compare (const void *ap, const void *bp)
11195 {
11196   struct bp_location *a = *(void **) ap;
11197   struct bp_location *b = *(void **) bp;
11198   /* A and B come from existing breakpoints having non-NULL OWNER.  */
11199   int a_perm = a->owner->enable_state == bp_permanent;
11200   int b_perm = b->owner->enable_state == bp_permanent;
11201
11202   if (a->address != b->address)
11203     return (a->address > b->address) - (a->address < b->address);
11204
11205   /* Sort locations at the same address by their pspace number, keeping
11206      locations of the same inferior (in a multi-inferior environment)
11207      grouped.  */
11208
11209   if (a->pspace->num != b->pspace->num)
11210     return ((a->pspace->num > b->pspace->num)
11211             - (a->pspace->num < b->pspace->num));
11212
11213   /* Sort permanent breakpoints first.  */
11214   if (a_perm != b_perm)
11215     return (a_perm < b_perm) - (a_perm > b_perm);
11216
11217   /* Make the internal GDB representation stable across GDB runs
11218      where A and B memory inside GDB can differ.  Breakpoint locations of
11219      the same type at the same address can be sorted in arbitrary order.  */
11220
11221   if (a->owner->number != b->owner->number)
11222     return ((a->owner->number > b->owner->number)
11223             - (a->owner->number < b->owner->number));
11224
11225   return (a > b) - (a < b);
11226 }
11227
11228 /* Set bp_location_placed_address_before_address_max and
11229    bp_location_shadow_len_after_address_max according to the current
11230    content of the bp_location array.  */
11231
11232 static void
11233 bp_location_target_extensions_update (void)
11234 {
11235   struct bp_location *bl, **blp_tmp;
11236
11237   bp_location_placed_address_before_address_max = 0;
11238   bp_location_shadow_len_after_address_max = 0;
11239
11240   ALL_BP_LOCATIONS (bl, blp_tmp)
11241     {
11242       CORE_ADDR start, end, addr;
11243
11244       if (!bp_location_has_shadow (bl))
11245         continue;
11246
11247       start = bl->target_info.placed_address;
11248       end = start + bl->target_info.shadow_len;
11249
11250       gdb_assert (bl->address >= start);
11251       addr = bl->address - start;
11252       if (addr > bp_location_placed_address_before_address_max)
11253         bp_location_placed_address_before_address_max = addr;
11254
11255       /* Zero SHADOW_LEN would not pass bp_location_has_shadow.  */
11256
11257       gdb_assert (bl->address < end);
11258       addr = end - bl->address;
11259       if (addr > bp_location_shadow_len_after_address_max)
11260         bp_location_shadow_len_after_address_max = addr;
11261     }
11262 }
11263
11264 /* Download tracepoint locations if they haven't been.  */
11265
11266 static void
11267 download_tracepoint_locations (void)
11268 {
11269   struct bp_location *bl, **blp_tmp;
11270   struct cleanup *old_chain;
11271
11272   if (!target_can_download_tracepoint ())
11273     return;
11274
11275   old_chain = save_current_space_and_thread ();
11276
11277   ALL_BP_LOCATIONS (bl, blp_tmp)
11278     {
11279       struct tracepoint *t;
11280
11281       if (!is_tracepoint (bl->owner))
11282         continue;
11283
11284       if ((bl->owner->type == bp_fast_tracepoint
11285            ? !may_insert_fast_tracepoints
11286            : !may_insert_tracepoints))
11287         continue;
11288
11289       /* In tracepoint, locations are _never_ duplicated, so
11290          should_be_inserted is equivalent to
11291          unduplicated_should_be_inserted.  */
11292       if (!should_be_inserted (bl) || bl->inserted)
11293         continue;
11294
11295       switch_to_program_space_and_thread (bl->pspace);
11296
11297       target_download_tracepoint (bl);
11298
11299       bl->inserted = 1;
11300       t = (struct tracepoint *) bl->owner;
11301       t->number_on_target = bl->owner->number;
11302     }
11303
11304   do_cleanups (old_chain);
11305 }
11306
11307 /* Swap the insertion/duplication state between two locations.  */
11308
11309 static void
11310 swap_insertion (struct bp_location *left, struct bp_location *right)
11311 {
11312   const int left_inserted = left->inserted;
11313   const int left_duplicate = left->duplicate;
11314   const int left_needs_update = left->needs_update;
11315   const struct bp_target_info left_target_info = left->target_info;
11316
11317   /* Locations of tracepoints can never be duplicated.  */
11318   if (is_tracepoint (left->owner))
11319     gdb_assert (!left->duplicate);
11320   if (is_tracepoint (right->owner))
11321     gdb_assert (!right->duplicate);
11322
11323   left->inserted = right->inserted;
11324   left->duplicate = right->duplicate;
11325   left->needs_update = right->needs_update;
11326   left->target_info = right->target_info;
11327   right->inserted = left_inserted;
11328   right->duplicate = left_duplicate;
11329   right->needs_update = left_needs_update;
11330   right->target_info = left_target_info;
11331 }
11332
11333 /* Force the re-insertion of the locations at ADDRESS.  This is called
11334    once a new/deleted/modified duplicate location is found and we are evaluating
11335    conditions on the target's side.  Such conditions need to be updated on
11336    the target.  */
11337
11338 static void
11339 force_breakpoint_reinsertion (struct bp_location *bl)
11340 {
11341   struct bp_location **locp = NULL, **loc2p;
11342   struct bp_location *loc;
11343   CORE_ADDR address = 0;
11344   int pspace_num;
11345
11346   address = bl->address;
11347   pspace_num = bl->pspace->num;
11348
11349   /* This is only meaningful if the target is
11350      evaluating conditions and if the user has
11351      opted for condition evaluation on the target's
11352      side.  */
11353   if (gdb_evaluates_breakpoint_condition_p ()
11354       || !target_supports_evaluation_of_breakpoint_conditions ())
11355     return;
11356
11357   /* Flag all breakpoint locations with this address and
11358      the same program space as the location
11359      as "its condition has changed".  We need to
11360      update the conditions on the target's side.  */
11361   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, address)
11362     {
11363       loc = *loc2p;
11364
11365       if (!is_breakpoint (loc->owner)
11366           || pspace_num != loc->pspace->num)
11367         continue;
11368
11369       /* Flag the location appropriately.  We use a different state to
11370          let everyone know that we already updated the set of locations
11371          with addr bl->address and program space bl->pspace.  This is so
11372          we don't have to keep calling these functions just to mark locations
11373          that have already been marked.  */
11374       loc->condition_changed = condition_updated;
11375
11376       /* Free the agent expression bytecode as well.  We will compute
11377          it later on.  */
11378       if (loc->cond_bytecode)
11379         {
11380           free_agent_expr (loc->cond_bytecode);
11381           loc->cond_bytecode = NULL;
11382         }
11383     }
11384 }
11385
11386 /* If SHOULD_INSERT is false, do not insert any breakpoint locations
11387    into the inferior, only remove already-inserted locations that no
11388    longer should be inserted.  Functions that delete a breakpoint or
11389    breakpoints should pass false, so that deleting a breakpoint
11390    doesn't have the side effect of inserting the locations of other
11391    breakpoints that are marked not-inserted, but should_be_inserted
11392    returns true on them.
11393
11394    This behaviour is useful is situations close to tear-down -- e.g.,
11395    after an exec, while the target still has execution, but breakpoint
11396    shadows of the previous executable image should *NOT* be restored
11397    to the new image; or before detaching, where the target still has
11398    execution and wants to delete breakpoints from GDB's lists, and all
11399    breakpoints had already been removed from the inferior.  */
11400
11401 static void
11402 update_global_location_list (int should_insert)
11403 {
11404   struct breakpoint *b;
11405   struct bp_location **locp, *loc;
11406   struct cleanup *cleanups;
11407   /* Last breakpoint location address that was marked for update.  */
11408   CORE_ADDR last_addr = 0;
11409   /* Last breakpoint location program space that was marked for update.  */
11410   int last_pspace_num = -1;
11411
11412   /* Used in the duplicates detection below.  When iterating over all
11413      bp_locations, points to the first bp_location of a given address.
11414      Breakpoints and watchpoints of different types are never
11415      duplicates of each other.  Keep one pointer for each type of
11416      breakpoint/watchpoint, so we only need to loop over all locations
11417      once.  */
11418   struct bp_location *bp_loc_first;  /* breakpoint */
11419   struct bp_location *wp_loc_first;  /* hardware watchpoint */
11420   struct bp_location *awp_loc_first; /* access watchpoint */
11421   struct bp_location *rwp_loc_first; /* read watchpoint */
11422
11423   /* Saved former bp_location array which we compare against the newly
11424      built bp_location from the current state of ALL_BREAKPOINTS.  */
11425   struct bp_location **old_location, **old_locp;
11426   unsigned old_location_count;
11427
11428   old_location = bp_location;
11429   old_location_count = bp_location_count;
11430   bp_location = NULL;
11431   bp_location_count = 0;
11432   cleanups = make_cleanup (xfree, old_location);
11433
11434   ALL_BREAKPOINTS (b)
11435     for (loc = b->loc; loc; loc = loc->next)
11436       bp_location_count++;
11437
11438   bp_location = xmalloc (sizeof (*bp_location) * bp_location_count);
11439   locp = bp_location;
11440   ALL_BREAKPOINTS (b)
11441     for (loc = b->loc; loc; loc = loc->next)
11442       *locp++ = loc;
11443   qsort (bp_location, bp_location_count, sizeof (*bp_location),
11444          bp_location_compare);
11445
11446   bp_location_target_extensions_update ();
11447
11448   /* Identify bp_location instances that are no longer present in the
11449      new list, and therefore should be freed.  Note that it's not
11450      necessary that those locations should be removed from inferior --
11451      if there's another location at the same address (previously
11452      marked as duplicate), we don't need to remove/insert the
11453      location.
11454      
11455      LOCP is kept in sync with OLD_LOCP, each pointing to the current
11456      and former bp_location array state respectively.  */
11457
11458   locp = bp_location;
11459   for (old_locp = old_location; old_locp < old_location + old_location_count;
11460        old_locp++)
11461     {
11462       struct bp_location *old_loc = *old_locp;
11463       struct bp_location **loc2p;
11464
11465       /* Tells if 'old_loc' is found among the new locations.  If
11466          not, we have to free it.  */
11467       int found_object = 0;
11468       /* Tells if the location should remain inserted in the target.  */
11469       int keep_in_target = 0;
11470       int removed = 0;
11471
11472       /* Skip LOCP entries which will definitely never be needed.
11473          Stop either at or being the one matching OLD_LOC.  */
11474       while (locp < bp_location + bp_location_count
11475              && (*locp)->address < old_loc->address)
11476         locp++;
11477
11478       for (loc2p = locp;
11479            (loc2p < bp_location + bp_location_count
11480             && (*loc2p)->address == old_loc->address);
11481            loc2p++)
11482         {
11483           /* Check if this is a new/duplicated location or a duplicated
11484              location that had its condition modified.  If so, we want to send
11485              its condition to the target if evaluation of conditions is taking
11486              place there.  */
11487           if ((*loc2p)->condition_changed == condition_modified
11488               && (last_addr != old_loc->address
11489                   || last_pspace_num != old_loc->pspace->num))
11490             {
11491               force_breakpoint_reinsertion (*loc2p);
11492               last_pspace_num = old_loc->pspace->num;
11493             }
11494
11495           if (*loc2p == old_loc)
11496             found_object = 1;
11497         }
11498
11499       /* We have already handled this address, update it so that we don't
11500          have to go through updates again.  */
11501       last_addr = old_loc->address;
11502
11503       /* Target-side condition evaluation: Handle deleted locations.  */
11504       if (!found_object)
11505         force_breakpoint_reinsertion (old_loc);
11506
11507       /* If this location is no longer present, and inserted, look if
11508          there's maybe a new location at the same address.  If so,
11509          mark that one inserted, and don't remove this one.  This is
11510          needed so that we don't have a time window where a breakpoint
11511          at certain location is not inserted.  */
11512
11513       if (old_loc->inserted)
11514         {
11515           /* If the location is inserted now, we might have to remove
11516              it.  */
11517
11518           if (found_object && should_be_inserted (old_loc))
11519             {
11520               /* The location is still present in the location list,
11521                  and still should be inserted.  Don't do anything.  */
11522               keep_in_target = 1;
11523             }
11524           else
11525             {
11526               /* This location still exists, but it won't be kept in the
11527                  target since it may have been disabled.  We proceed to
11528                  remove its target-side condition.  */
11529
11530               /* The location is either no longer present, or got
11531                  disabled.  See if there's another location at the
11532                  same address, in which case we don't need to remove
11533                  this one from the target.  */
11534
11535               /* OLD_LOC comes from existing struct breakpoint.  */
11536               if (breakpoint_address_is_meaningful (old_loc->owner))
11537                 {
11538                   for (loc2p = locp;
11539                        (loc2p < bp_location + bp_location_count
11540                         && (*loc2p)->address == old_loc->address);
11541                        loc2p++)
11542                     {
11543                       struct bp_location *loc2 = *loc2p;
11544
11545                       if (breakpoint_locations_match (loc2, old_loc))
11546                         {
11547                           /* Read watchpoint locations are switched to
11548                              access watchpoints, if the former are not
11549                              supported, but the latter are.  */
11550                           if (is_hardware_watchpoint (old_loc->owner))
11551                             {
11552                               gdb_assert (is_hardware_watchpoint (loc2->owner));
11553                               loc2->watchpoint_type = old_loc->watchpoint_type;
11554                             }
11555
11556                           /* loc2 is a duplicated location. We need to check
11557                              if it should be inserted in case it will be
11558                              unduplicated.  */
11559                           if (loc2 != old_loc
11560                               && unduplicated_should_be_inserted (loc2))
11561                             {
11562                               swap_insertion (old_loc, loc2);
11563                               keep_in_target = 1;
11564                               break;
11565                             }
11566                         }
11567                     }
11568                 }
11569             }
11570
11571           if (!keep_in_target)
11572             {
11573               if (remove_breakpoint (old_loc, mark_uninserted))
11574                 {
11575                   /* This is just about all we can do.  We could keep
11576                      this location on the global list, and try to
11577                      remove it next time, but there's no particular
11578                      reason why we will succeed next time.
11579                      
11580                      Note that at this point, old_loc->owner is still
11581                      valid, as delete_breakpoint frees the breakpoint
11582                      only after calling us.  */
11583                   printf_filtered (_("warning: Error removing "
11584                                      "breakpoint %d\n"), 
11585                                    old_loc->owner->number);
11586                 }
11587               removed = 1;
11588             }
11589         }
11590
11591       if (!found_object)
11592         {
11593           if (removed && non_stop
11594               && breakpoint_address_is_meaningful (old_loc->owner)
11595               && !is_hardware_watchpoint (old_loc->owner))
11596             {
11597               /* This location was removed from the target.  In
11598                  non-stop mode, a race condition is possible where
11599                  we've removed a breakpoint, but stop events for that
11600                  breakpoint are already queued and will arrive later.
11601                  We apply an heuristic to be able to distinguish such
11602                  SIGTRAPs from other random SIGTRAPs: we keep this
11603                  breakpoint location for a bit, and will retire it
11604                  after we see some number of events.  The theory here
11605                  is that reporting of events should, "on the average",
11606                  be fair, so after a while we'll see events from all
11607                  threads that have anything of interest, and no longer
11608                  need to keep this breakpoint location around.  We
11609                  don't hold locations forever so to reduce chances of
11610                  mistaking a non-breakpoint SIGTRAP for a breakpoint
11611                  SIGTRAP.
11612
11613                  The heuristic failing can be disastrous on
11614                  decr_pc_after_break targets.
11615
11616                  On decr_pc_after_break targets, like e.g., x86-linux,
11617                  if we fail to recognize a late breakpoint SIGTRAP,
11618                  because events_till_retirement has reached 0 too
11619                  soon, we'll fail to do the PC adjustment, and report
11620                  a random SIGTRAP to the user.  When the user resumes
11621                  the inferior, it will most likely immediately crash
11622                  with SIGILL/SIGBUS/SIGSEGV, or worse, get silently
11623                  corrupted, because of being resumed e.g., in the
11624                  middle of a multi-byte instruction, or skipped a
11625                  one-byte instruction.  This was actually seen happen
11626                  on native x86-linux, and should be less rare on
11627                  targets that do not support new thread events, like
11628                  remote, due to the heuristic depending on
11629                  thread_count.
11630
11631                  Mistaking a random SIGTRAP for a breakpoint trap
11632                  causes similar symptoms (PC adjustment applied when
11633                  it shouldn't), but then again, playing with SIGTRAPs
11634                  behind the debugger's back is asking for trouble.
11635
11636                  Since hardware watchpoint traps are always
11637                  distinguishable from other traps, so we don't need to
11638                  apply keep hardware watchpoint moribund locations
11639                  around.  We simply always ignore hardware watchpoint
11640                  traps we can no longer explain.  */
11641
11642               old_loc->events_till_retirement = 3 * (thread_count () + 1);
11643               old_loc->owner = NULL;
11644
11645               VEC_safe_push (bp_location_p, moribund_locations, old_loc);
11646             }
11647           else
11648             {
11649               old_loc->owner = NULL;
11650               decref_bp_location (&old_loc);
11651             }
11652         }
11653     }
11654
11655   /* Rescan breakpoints at the same address and section, marking the
11656      first one as "first" and any others as "duplicates".  This is so
11657      that the bpt instruction is only inserted once.  If we have a
11658      permanent breakpoint at the same place as BPT, make that one the
11659      official one, and the rest as duplicates.  Permanent breakpoints
11660      are sorted first for the same address.
11661
11662      Do the same for hardware watchpoints, but also considering the
11663      watchpoint's type (regular/access/read) and length.  */
11664
11665   bp_loc_first = NULL;
11666   wp_loc_first = NULL;
11667   awp_loc_first = NULL;
11668   rwp_loc_first = NULL;
11669   ALL_BP_LOCATIONS (loc, locp)
11670     {
11671       /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always
11672          non-NULL.  */
11673       struct bp_location **loc_first_p;
11674       b = loc->owner;
11675
11676       if (!should_be_inserted (loc)
11677           || !breakpoint_address_is_meaningful (b)
11678           /* Don't detect duplicate for tracepoint locations because they are
11679            never duplicated.  See the comments in field `duplicate' of
11680            `struct bp_location'.  */
11681           || is_tracepoint (b))
11682         {
11683           /* Clear the condition modification flag.  */
11684           loc->condition_changed = condition_unchanged;
11685           continue;
11686         }
11687
11688       /* Permanent breakpoint should always be inserted.  */
11689       if (b->enable_state == bp_permanent && ! loc->inserted)
11690         internal_error (__FILE__, __LINE__,
11691                         _("allegedly permanent breakpoint is not "
11692                         "actually inserted"));
11693
11694       if (b->type == bp_hardware_watchpoint)
11695         loc_first_p = &wp_loc_first;
11696       else if (b->type == bp_read_watchpoint)
11697         loc_first_p = &rwp_loc_first;
11698       else if (b->type == bp_access_watchpoint)
11699         loc_first_p = &awp_loc_first;
11700       else
11701         loc_first_p = &bp_loc_first;
11702
11703       if (*loc_first_p == NULL
11704           || (overlay_debugging && loc->section != (*loc_first_p)->section)
11705           || !breakpoint_locations_match (loc, *loc_first_p))
11706         {
11707           *loc_first_p = loc;
11708           loc->duplicate = 0;
11709
11710           if (is_breakpoint (loc->owner) && loc->condition_changed)
11711             {
11712               loc->needs_update = 1;
11713               /* Clear the condition modification flag.  */
11714               loc->condition_changed = condition_unchanged;
11715             }
11716           continue;
11717         }
11718
11719
11720       /* This and the above ensure the invariant that the first location
11721          is not duplicated, and is the inserted one.
11722          All following are marked as duplicated, and are not inserted.  */
11723       if (loc->inserted)
11724         swap_insertion (loc, *loc_first_p);
11725       loc->duplicate = 1;
11726
11727       /* Clear the condition modification flag.  */
11728       loc->condition_changed = condition_unchanged;
11729
11730       if ((*loc_first_p)->owner->enable_state == bp_permanent && loc->inserted
11731           && b->enable_state != bp_permanent)
11732         internal_error (__FILE__, __LINE__,
11733                         _("another breakpoint was inserted on top of "
11734                         "a permanent breakpoint"));
11735     }
11736
11737   if (breakpoints_always_inserted_mode ()
11738       && (have_live_inferiors ()
11739           || (gdbarch_has_global_breakpoints (target_gdbarch))))
11740     {
11741       if (should_insert)
11742         insert_breakpoint_locations ();
11743       else
11744         {
11745           /* Though should_insert is false, we may need to update conditions
11746              on the target's side if it is evaluating such conditions.  We
11747              only update conditions for locations that are marked
11748              "needs_update".  */
11749           update_inserted_breakpoint_locations ();
11750         }
11751     }
11752
11753   if (should_insert)
11754     download_tracepoint_locations ();
11755
11756   do_cleanups (cleanups);
11757 }
11758
11759 void
11760 breakpoint_retire_moribund (void)
11761 {
11762   struct bp_location *loc;
11763   int ix;
11764
11765   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
11766     if (--(loc->events_till_retirement) == 0)
11767       {
11768         decref_bp_location (&loc);
11769         VEC_unordered_remove (bp_location_p, moribund_locations, ix);
11770         --ix;
11771       }
11772 }
11773
11774 static void
11775 update_global_location_list_nothrow (int inserting)
11776 {
11777   volatile struct gdb_exception e;
11778
11779   TRY_CATCH (e, RETURN_MASK_ERROR)
11780     update_global_location_list (inserting);
11781 }
11782
11783 /* Clear BKP from a BPS.  */
11784
11785 static void
11786 bpstat_remove_bp_location (bpstat bps, struct breakpoint *bpt)
11787 {
11788   bpstat bs;
11789
11790   for (bs = bps; bs; bs = bs->next)
11791     if (bs->breakpoint_at == bpt)
11792       {
11793         bs->breakpoint_at = NULL;
11794         bs->old_val = NULL;
11795         /* bs->commands will be freed later.  */
11796       }
11797 }
11798
11799 /* Callback for iterate_over_threads.  */
11800 static int
11801 bpstat_remove_breakpoint_callback (struct thread_info *th, void *data)
11802 {
11803   struct breakpoint *bpt = data;
11804
11805   bpstat_remove_bp_location (th->control.stop_bpstat, bpt);
11806   return 0;
11807 }
11808
11809 /* Helper for breakpoint and tracepoint breakpoint_ops->mention
11810    callbacks.  */
11811
11812 static void
11813 say_where (struct breakpoint *b)
11814 {
11815   struct ui_out *uiout = current_uiout;
11816   struct value_print_options opts;
11817
11818   get_user_print_options (&opts);
11819
11820   /* i18n: cagney/2005-02-11: Below needs to be merged into a
11821      single string.  */
11822   if (b->loc == NULL)
11823     {
11824       printf_filtered (_(" (%s) pending."), b->addr_string);
11825     }
11826   else
11827     {
11828       if (opts.addressprint || b->loc->source_file == NULL)
11829         {
11830           printf_filtered (" at ");
11831           fputs_filtered (paddress (b->loc->gdbarch, b->loc->address),
11832                           gdb_stdout);
11833         }
11834       if (b->loc->source_file)
11835         {
11836           /* If there is a single location, we can print the location
11837              more nicely.  */
11838           if (b->loc->next == NULL)
11839             printf_filtered (": file %s, line %d.",
11840                              b->loc->source_file, b->loc->line_number);
11841           else
11842             /* This is not ideal, but each location may have a
11843                different file name, and this at least reflects the
11844                real situation somewhat.  */
11845             printf_filtered (": %s.", b->addr_string);
11846         }
11847
11848       if (b->loc->next)
11849         {
11850           struct bp_location *loc = b->loc;
11851           int n = 0;
11852           for (; loc; loc = loc->next)
11853             ++n;
11854           printf_filtered (" (%d locations)", n);
11855         }
11856     }
11857 }
11858
11859 /* Default bp_location_ops methods.  */
11860
11861 static void
11862 bp_location_dtor (struct bp_location *self)
11863 {
11864   xfree (self->cond);
11865   if (self->cond_bytecode)
11866     free_agent_expr (self->cond_bytecode);
11867   xfree (self->function_name);
11868   xfree (self->source_file);
11869 }
11870
11871 static const struct bp_location_ops bp_location_ops =
11872 {
11873   bp_location_dtor
11874 };
11875
11876 /* Default breakpoint_ops methods all breakpoint_ops ultimately
11877    inherit from.  */
11878
11879 static void
11880 base_breakpoint_dtor (struct breakpoint *self)
11881 {
11882   decref_counted_command_line (&self->commands);
11883   xfree (self->cond_string);
11884   xfree (self->addr_string);
11885   xfree (self->filter);
11886   xfree (self->addr_string_range_end);
11887 }
11888
11889 static struct bp_location *
11890 base_breakpoint_allocate_location (struct breakpoint *self)
11891 {
11892   struct bp_location *loc;
11893
11894   loc = XNEW (struct bp_location);
11895   init_bp_location (loc, &bp_location_ops, self);
11896   return loc;
11897 }
11898
11899 static void
11900 base_breakpoint_re_set (struct breakpoint *b)
11901 {
11902   /* Nothing to re-set. */
11903 }
11904
11905 #define internal_error_pure_virtual_called() \
11906   gdb_assert_not_reached ("pure virtual function called")
11907
11908 static int
11909 base_breakpoint_insert_location (struct bp_location *bl)
11910 {
11911   internal_error_pure_virtual_called ();
11912 }
11913
11914 static int
11915 base_breakpoint_remove_location (struct bp_location *bl)
11916 {
11917   internal_error_pure_virtual_called ();
11918 }
11919
11920 static int
11921 base_breakpoint_breakpoint_hit (const struct bp_location *bl,
11922                                 struct address_space *aspace,
11923                                 CORE_ADDR bp_addr,
11924                                 const struct target_waitstatus *ws)
11925 {
11926   internal_error_pure_virtual_called ();
11927 }
11928
11929 static void
11930 base_breakpoint_check_status (bpstat bs)
11931 {
11932   /* Always stop.   */
11933 }
11934
11935 /* A "works_in_software_mode" breakpoint_ops method that just internal
11936    errors.  */
11937
11938 static int
11939 base_breakpoint_works_in_software_mode (const struct breakpoint *b)
11940 {
11941   internal_error_pure_virtual_called ();
11942 }
11943
11944 /* A "resources_needed" breakpoint_ops method that just internal
11945    errors.  */
11946
11947 static int
11948 base_breakpoint_resources_needed (const struct bp_location *bl)
11949 {
11950   internal_error_pure_virtual_called ();
11951 }
11952
11953 static enum print_stop_action
11954 base_breakpoint_print_it (bpstat bs)
11955 {
11956   internal_error_pure_virtual_called ();
11957 }
11958
11959 static void
11960 base_breakpoint_print_one_detail (const struct breakpoint *self,
11961                                   struct ui_out *uiout)
11962 {
11963   /* nothing */
11964 }
11965
11966 static void
11967 base_breakpoint_print_mention (struct breakpoint *b)
11968 {
11969   internal_error_pure_virtual_called ();
11970 }
11971
11972 static void
11973 base_breakpoint_print_recreate (struct breakpoint *b, struct ui_file *fp)
11974 {
11975   internal_error_pure_virtual_called ();
11976 }
11977
11978 static void
11979 base_breakpoint_create_sals_from_address (char **arg,
11980                                           struct linespec_result *canonical,
11981                                           enum bptype type_wanted,
11982                                           char *addr_start,
11983                                           char **copy_arg)
11984 {
11985   internal_error_pure_virtual_called ();
11986 }
11987
11988 static void
11989 base_breakpoint_create_breakpoints_sal (struct gdbarch *gdbarch,
11990                                         struct linespec_result *c,
11991                                         struct linespec_sals *lsal,
11992                                         char *cond_string,
11993                                         enum bptype type_wanted,
11994                                         enum bpdisp disposition,
11995                                         int thread,
11996                                         int task, int ignore_count,
11997                                         const struct breakpoint_ops *o,
11998                                         int from_tty, int enabled,
11999                                         int internal)
12000 {
12001   internal_error_pure_virtual_called ();
12002 }
12003
12004 static void
12005 base_breakpoint_decode_linespec (struct breakpoint *b, char **s,
12006                                  struct symtabs_and_lines *sals)
12007 {
12008   internal_error_pure_virtual_called ();
12009 }
12010
12011 static struct breakpoint_ops base_breakpoint_ops =
12012 {
12013   base_breakpoint_dtor,
12014   base_breakpoint_allocate_location,
12015   base_breakpoint_re_set,
12016   base_breakpoint_insert_location,
12017   base_breakpoint_remove_location,
12018   base_breakpoint_breakpoint_hit,
12019   base_breakpoint_check_status,
12020   base_breakpoint_resources_needed,
12021   base_breakpoint_works_in_software_mode,
12022   base_breakpoint_print_it,
12023   NULL,
12024   base_breakpoint_print_one_detail,
12025   base_breakpoint_print_mention,
12026   base_breakpoint_print_recreate,
12027   base_breakpoint_create_sals_from_address,
12028   base_breakpoint_create_breakpoints_sal,
12029   base_breakpoint_decode_linespec,
12030 };
12031
12032 /* Default breakpoint_ops methods.  */
12033
12034 static void
12035 bkpt_re_set (struct breakpoint *b)
12036 {
12037   /* FIXME: is this still reachable?  */
12038   if (b->addr_string == NULL)
12039     {
12040       /* Anything without a string can't be re-set.  */
12041       delete_breakpoint (b);
12042       return;
12043     }
12044
12045   breakpoint_re_set_default (b);
12046 }
12047
12048 static int
12049 bkpt_insert_location (struct bp_location *bl)
12050 {
12051   if (bl->loc_type == bp_loc_hardware_breakpoint)
12052     return target_insert_hw_breakpoint (bl->gdbarch,
12053                                         &bl->target_info);
12054   else
12055     return target_insert_breakpoint (bl->gdbarch,
12056                                      &bl->target_info);
12057 }
12058
12059 static int
12060 bkpt_remove_location (struct bp_location *bl)
12061 {
12062   if (bl->loc_type == bp_loc_hardware_breakpoint)
12063     return target_remove_hw_breakpoint (bl->gdbarch, &bl->target_info);
12064   else
12065     return target_remove_breakpoint (bl->gdbarch, &bl->target_info);
12066 }
12067
12068 static int
12069 bkpt_breakpoint_hit (const struct bp_location *bl,
12070                      struct address_space *aspace, CORE_ADDR bp_addr,
12071                      const struct target_waitstatus *ws)
12072 {
12073   struct breakpoint *b = bl->owner;
12074
12075   if (ws->kind != TARGET_WAITKIND_STOPPED
12076       || ws->value.sig != TARGET_SIGNAL_TRAP)
12077     return 0;
12078
12079   if (!breakpoint_address_match (bl->pspace->aspace, bl->address,
12080                                  aspace, bp_addr))
12081     return 0;
12082
12083   if (overlay_debugging         /* unmapped overlay section */
12084       && section_is_overlay (bl->section)
12085       && !section_is_mapped (bl->section))
12086     return 0;
12087
12088   return 1;
12089 }
12090
12091 static int
12092 bkpt_resources_needed (const struct bp_location *bl)
12093 {
12094   gdb_assert (bl->owner->type == bp_hardware_breakpoint);
12095
12096   return 1;
12097 }
12098
12099 static enum print_stop_action
12100 bkpt_print_it (bpstat bs)
12101 {
12102   struct breakpoint *b;
12103   const struct bp_location *bl;
12104   int bp_temp;
12105   struct ui_out *uiout = current_uiout;
12106
12107   gdb_assert (bs->bp_location_at != NULL);
12108
12109   bl = bs->bp_location_at;
12110   b = bs->breakpoint_at;
12111
12112   bp_temp = b->disposition == disp_del;
12113   if (bl->address != bl->requested_address)
12114     breakpoint_adjustment_warning (bl->requested_address,
12115                                    bl->address,
12116                                    b->number, 1);
12117   annotate_breakpoint (b->number);
12118   if (bp_temp)
12119     ui_out_text (uiout, "\nTemporary breakpoint ");
12120   else
12121     ui_out_text (uiout, "\nBreakpoint ");
12122   if (ui_out_is_mi_like_p (uiout))
12123     {
12124       ui_out_field_string (uiout, "reason",
12125                            async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
12126       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
12127     }
12128   ui_out_field_int (uiout, "bkptno", b->number);
12129   ui_out_text (uiout, ", ");
12130
12131   return PRINT_SRC_AND_LOC;
12132 }
12133
12134 static void
12135 bkpt_print_mention (struct breakpoint *b)
12136 {
12137   if (ui_out_is_mi_like_p (current_uiout))
12138     return;
12139
12140   switch (b->type)
12141     {
12142     case bp_breakpoint:
12143     case bp_gnu_ifunc_resolver:
12144       if (b->disposition == disp_del)
12145         printf_filtered (_("Temporary breakpoint"));
12146       else
12147         printf_filtered (_("Breakpoint"));
12148       printf_filtered (_(" %d"), b->number);
12149       if (b->type == bp_gnu_ifunc_resolver)
12150         printf_filtered (_(" at gnu-indirect-function resolver"));
12151       break;
12152     case bp_hardware_breakpoint:
12153       printf_filtered (_("Hardware assisted breakpoint %d"), b->number);
12154       break;
12155     }
12156
12157   say_where (b);
12158 }
12159
12160 static void
12161 bkpt_print_recreate (struct breakpoint *tp, struct ui_file *fp)
12162 {
12163   if (tp->type == bp_breakpoint && tp->disposition == disp_del)
12164     fprintf_unfiltered (fp, "tbreak");
12165   else if (tp->type == bp_breakpoint)
12166     fprintf_unfiltered (fp, "break");
12167   else if (tp->type == bp_hardware_breakpoint
12168            && tp->disposition == disp_del)
12169     fprintf_unfiltered (fp, "thbreak");
12170   else if (tp->type == bp_hardware_breakpoint)
12171     fprintf_unfiltered (fp, "hbreak");
12172   else
12173     internal_error (__FILE__, __LINE__,
12174                     _("unhandled breakpoint type %d"), (int) tp->type);
12175
12176   fprintf_unfiltered (fp, " %s", tp->addr_string);
12177   print_recreate_thread (tp, fp);
12178 }
12179
12180 static void
12181 bkpt_create_sals_from_address (char **arg,
12182                                struct linespec_result *canonical,
12183                                enum bptype type_wanted,
12184                                char *addr_start, char **copy_arg)
12185 {
12186   create_sals_from_address_default (arg, canonical, type_wanted,
12187                                     addr_start, copy_arg);
12188 }
12189
12190 static void
12191 bkpt_create_breakpoints_sal (struct gdbarch *gdbarch,
12192                              struct linespec_result *canonical,
12193                              struct linespec_sals *lsal,
12194                              char *cond_string,
12195                              enum bptype type_wanted,
12196                              enum bpdisp disposition,
12197                              int thread,
12198                              int task, int ignore_count,
12199                              const struct breakpoint_ops *ops,
12200                              int from_tty, int enabled,
12201                              int internal)
12202 {
12203   create_breakpoints_sal_default (gdbarch, canonical, lsal,
12204                                   cond_string, type_wanted,
12205                                   disposition, thread, task,
12206                                   ignore_count, ops, from_tty,
12207                                   enabled, internal);
12208 }
12209
12210 static void
12211 bkpt_decode_linespec (struct breakpoint *b, char **s,
12212                       struct symtabs_and_lines *sals)
12213 {
12214   decode_linespec_default (b, s, sals);
12215 }
12216
12217 /* Virtual table for internal breakpoints.  */
12218
12219 static void
12220 internal_bkpt_re_set (struct breakpoint *b)
12221 {
12222   switch (b->type)
12223     {
12224       /* Delete overlay event and longjmp master breakpoints; they
12225          will be reset later by breakpoint_re_set.  */
12226     case bp_overlay_event:
12227     case bp_longjmp_master:
12228     case bp_std_terminate_master:
12229     case bp_exception_master:
12230       delete_breakpoint (b);
12231       break;
12232
12233       /* This breakpoint is special, it's set up when the inferior
12234          starts and we really don't want to touch it.  */
12235     case bp_shlib_event:
12236
12237       /* Like bp_shlib_event, this breakpoint type is special.  Once
12238          it is set up, we do not want to touch it.  */
12239     case bp_thread_event:
12240       break;
12241     }
12242 }
12243
12244 static void
12245 internal_bkpt_check_status (bpstat bs)
12246 {
12247   if (bs->breakpoint_at->type == bp_shlib_event)
12248     {
12249       /* If requested, stop when the dynamic linker notifies GDB of
12250          events.  This allows the user to get control and place
12251          breakpoints in initializer routines for dynamically loaded
12252          objects (among other things).  */
12253       bs->stop = stop_on_solib_events;
12254       bs->print = stop_on_solib_events;
12255     }
12256   else
12257     bs->stop = 0;
12258 }
12259
12260 static enum print_stop_action
12261 internal_bkpt_print_it (bpstat bs)
12262 {
12263   struct ui_out *uiout = current_uiout;
12264   struct breakpoint *b;
12265
12266   b = bs->breakpoint_at;
12267
12268   switch (b->type)
12269     {
12270     case bp_shlib_event:
12271       /* Did we stop because the user set the stop_on_solib_events
12272          variable?  (If so, we report this as a generic, "Stopped due
12273          to shlib event" message.) */
12274       print_solib_event (0);
12275       break;
12276
12277     case bp_thread_event:
12278       /* Not sure how we will get here.
12279          GDB should not stop for these breakpoints.  */
12280       printf_filtered (_("Thread Event Breakpoint: gdb should not stop!\n"));
12281       break;
12282
12283     case bp_overlay_event:
12284       /* By analogy with the thread event, GDB should not stop for these.  */
12285       printf_filtered (_("Overlay Event Breakpoint: gdb should not stop!\n"));
12286       break;
12287
12288     case bp_longjmp_master:
12289       /* These should never be enabled.  */
12290       printf_filtered (_("Longjmp Master Breakpoint: gdb should not stop!\n"));
12291       break;
12292
12293     case bp_std_terminate_master:
12294       /* These should never be enabled.  */
12295       printf_filtered (_("std::terminate Master Breakpoint: "
12296                          "gdb should not stop!\n"));
12297       break;
12298
12299     case bp_exception_master:
12300       /* These should never be enabled.  */
12301       printf_filtered (_("Exception Master Breakpoint: "
12302                          "gdb should not stop!\n"));
12303       break;
12304     }
12305
12306   return PRINT_NOTHING;
12307 }
12308
12309 static void
12310 internal_bkpt_print_mention (struct breakpoint *b)
12311 {
12312   /* Nothing to mention.  These breakpoints are internal.  */
12313 }
12314
12315 /* Virtual table for momentary breakpoints  */
12316
12317 static void
12318 momentary_bkpt_re_set (struct breakpoint *b)
12319 {
12320   /* Keep temporary breakpoints, which can be encountered when we step
12321      over a dlopen call and SOLIB_ADD is resetting the breakpoints.
12322      Otherwise these should have been blown away via the cleanup chain
12323      or by breakpoint_init_inferior when we rerun the executable.  */
12324 }
12325
12326 static void
12327 momentary_bkpt_check_status (bpstat bs)
12328 {
12329   /* Nothing.  The point of these breakpoints is causing a stop.  */
12330 }
12331
12332 static enum print_stop_action
12333 momentary_bkpt_print_it (bpstat bs)
12334 {
12335   struct ui_out *uiout = current_uiout;
12336
12337   if (ui_out_is_mi_like_p (uiout))
12338     {
12339       struct breakpoint *b = bs->breakpoint_at;
12340
12341       switch (b->type)
12342         {
12343         case bp_finish:
12344           ui_out_field_string
12345             (uiout, "reason",
12346              async_reason_lookup (EXEC_ASYNC_FUNCTION_FINISHED));
12347           break;
12348
12349         case bp_until:
12350           ui_out_field_string
12351             (uiout, "reason",
12352              async_reason_lookup (EXEC_ASYNC_LOCATION_REACHED));
12353           break;
12354         }
12355     }
12356
12357   return PRINT_UNKNOWN;
12358 }
12359
12360 static void
12361 momentary_bkpt_print_mention (struct breakpoint *b)
12362 {
12363   /* Nothing to mention.  These breakpoints are internal.  */
12364 }
12365
12366 /* The breakpoint_ops structure to be used in tracepoints.  */
12367
12368 static void
12369 tracepoint_re_set (struct breakpoint *b)
12370 {
12371   breakpoint_re_set_default (b);
12372 }
12373
12374 static int
12375 tracepoint_breakpoint_hit (const struct bp_location *bl,
12376                            struct address_space *aspace, CORE_ADDR bp_addr,
12377                            const struct target_waitstatus *ws)
12378 {
12379   /* By definition, the inferior does not report stops at
12380      tracepoints.  */
12381   return 0;
12382 }
12383
12384 static void
12385 tracepoint_print_one_detail (const struct breakpoint *self,
12386                              struct ui_out *uiout)
12387 {
12388   struct tracepoint *tp = (struct tracepoint *) self;
12389   if (tp->static_trace_marker_id)
12390     {
12391       gdb_assert (self->type == bp_static_tracepoint);
12392
12393       ui_out_text (uiout, "\tmarker id is ");
12394       ui_out_field_string (uiout, "static-tracepoint-marker-string-id",
12395                            tp->static_trace_marker_id);
12396       ui_out_text (uiout, "\n");
12397     }
12398 }
12399
12400 static void
12401 tracepoint_print_mention (struct breakpoint *b)
12402 {
12403   if (ui_out_is_mi_like_p (current_uiout))
12404     return;
12405
12406   switch (b->type)
12407     {
12408     case bp_tracepoint:
12409       printf_filtered (_("Tracepoint"));
12410       printf_filtered (_(" %d"), b->number);
12411       break;
12412     case bp_fast_tracepoint:
12413       printf_filtered (_("Fast tracepoint"));
12414       printf_filtered (_(" %d"), b->number);
12415       break;
12416     case bp_static_tracepoint:
12417       printf_filtered (_("Static tracepoint"));
12418       printf_filtered (_(" %d"), b->number);
12419       break;
12420     default:
12421       internal_error (__FILE__, __LINE__,
12422                       _("unhandled tracepoint type %d"), (int) b->type);
12423     }
12424
12425   say_where (b);
12426 }
12427
12428 static void
12429 tracepoint_print_recreate (struct breakpoint *self, struct ui_file *fp)
12430 {
12431   struct tracepoint *tp = (struct tracepoint *) self;
12432
12433   if (self->type == bp_fast_tracepoint)
12434     fprintf_unfiltered (fp, "ftrace");
12435   if (self->type == bp_static_tracepoint)
12436     fprintf_unfiltered (fp, "strace");
12437   else if (self->type == bp_tracepoint)
12438     fprintf_unfiltered (fp, "trace");
12439   else
12440     internal_error (__FILE__, __LINE__,
12441                     _("unhandled tracepoint type %d"), (int) self->type);
12442
12443   fprintf_unfiltered (fp, " %s", self->addr_string);
12444   print_recreate_thread (self, fp);
12445
12446   if (tp->pass_count)
12447     fprintf_unfiltered (fp, "  passcount %d\n", tp->pass_count);
12448 }
12449
12450 static void
12451 tracepoint_create_sals_from_address (char **arg,
12452                                      struct linespec_result *canonical,
12453                                      enum bptype type_wanted,
12454                                      char *addr_start, char **copy_arg)
12455 {
12456   create_sals_from_address_default (arg, canonical, type_wanted,
12457                                     addr_start, copy_arg);
12458 }
12459
12460 static void
12461 tracepoint_create_breakpoints_sal (struct gdbarch *gdbarch,
12462                                    struct linespec_result *canonical,
12463                                    struct linespec_sals *lsal,
12464                                    char *cond_string,
12465                                    enum bptype type_wanted,
12466                                    enum bpdisp disposition,
12467                                    int thread,
12468                                    int task, int ignore_count,
12469                                    const struct breakpoint_ops *ops,
12470                                    int from_tty, int enabled,
12471                                    int internal)
12472 {
12473   create_breakpoints_sal_default (gdbarch, canonical, lsal,
12474                                   cond_string, type_wanted,
12475                                   disposition, thread, task,
12476                                   ignore_count, ops, from_tty,
12477                                   enabled, internal);
12478 }
12479
12480 static void
12481 tracepoint_decode_linespec (struct breakpoint *b, char **s,
12482                             struct symtabs_and_lines *sals)
12483 {
12484   decode_linespec_default (b, s, sals);
12485 }
12486
12487 struct breakpoint_ops tracepoint_breakpoint_ops;
12488
12489 /* The breakpoint_ops structure to be used on static tracepoints with
12490    markers (`-m').  */
12491
12492 static void
12493 strace_marker_create_sals_from_address (char **arg,
12494                                         struct linespec_result *canonical,
12495                                         enum bptype type_wanted,
12496                                         char *addr_start, char **copy_arg)
12497 {
12498   struct linespec_sals lsal;
12499
12500   lsal.sals = decode_static_tracepoint_spec (arg);
12501
12502   *copy_arg = savestring (addr_start, *arg - addr_start);
12503
12504   canonical->addr_string = xstrdup (*copy_arg);
12505   lsal.canonical = xstrdup (*copy_arg);
12506   VEC_safe_push (linespec_sals, canonical->sals, &lsal);
12507 }
12508
12509 static void
12510 strace_marker_create_breakpoints_sal (struct gdbarch *gdbarch,
12511                                       struct linespec_result *canonical,
12512                                       struct linespec_sals *lsal,
12513                                       char *cond_string,
12514                                       enum bptype type_wanted,
12515                                       enum bpdisp disposition,
12516                                       int thread,
12517                                       int task, int ignore_count,
12518                                       const struct breakpoint_ops *ops,
12519                                       int from_tty, int enabled,
12520                                       int internal)
12521 {
12522   int i;
12523
12524   /* If the user is creating a static tracepoint by marker id
12525      (strace -m MARKER_ID), then store the sals index, so that
12526      breakpoint_re_set can try to match up which of the newly
12527      found markers corresponds to this one, and, don't try to
12528      expand multiple locations for each sal, given than SALS
12529      already should contain all sals for MARKER_ID.  */
12530
12531   for (i = 0; i < lsal->sals.nelts; ++i)
12532     {
12533       struct symtabs_and_lines expanded;
12534       struct tracepoint *tp;
12535       struct cleanup *old_chain;
12536       char *addr_string;
12537
12538       expanded.nelts = 1;
12539       expanded.sals = &lsal->sals.sals[i];
12540
12541       addr_string = xstrdup (canonical->addr_string);
12542       old_chain = make_cleanup (xfree, addr_string);
12543
12544       tp = XCNEW (struct tracepoint);
12545       init_breakpoint_sal (&tp->base, gdbarch, expanded,
12546                            addr_string, NULL,
12547                            cond_string, type_wanted, disposition,
12548                            thread, task, ignore_count, ops,
12549                            from_tty, enabled, internal,
12550                            canonical->special_display);
12551       /* Given that its possible to have multiple markers with
12552          the same string id, if the user is creating a static
12553          tracepoint by marker id ("strace -m MARKER_ID"), then
12554          store the sals index, so that breakpoint_re_set can
12555          try to match up which of the newly found markers
12556          corresponds to this one  */
12557       tp->static_trace_marker_id_idx = i;
12558
12559       install_breakpoint (internal, &tp->base, 0);
12560
12561       discard_cleanups (old_chain);
12562     }
12563 }
12564
12565 static void
12566 strace_marker_decode_linespec (struct breakpoint *b, char **s,
12567                                struct symtabs_and_lines *sals)
12568 {
12569   struct tracepoint *tp = (struct tracepoint *) b;
12570
12571   *sals = decode_static_tracepoint_spec (s);
12572   if (sals->nelts > tp->static_trace_marker_id_idx)
12573     {
12574       sals->sals[0] = sals->sals[tp->static_trace_marker_id_idx];
12575       sals->nelts = 1;
12576     }
12577   else
12578     error (_("marker %s not found"), tp->static_trace_marker_id);
12579 }
12580
12581 static struct breakpoint_ops strace_marker_breakpoint_ops;
12582
12583 static int
12584 strace_marker_p (struct breakpoint *b)
12585 {
12586   return b->ops == &strace_marker_breakpoint_ops;
12587 }
12588
12589 /* Delete a breakpoint and clean up all traces of it in the data
12590    structures.  */
12591
12592 void
12593 delete_breakpoint (struct breakpoint *bpt)
12594 {
12595   struct breakpoint *b;
12596
12597   gdb_assert (bpt != NULL);
12598
12599   /* Has this bp already been deleted?  This can happen because
12600      multiple lists can hold pointers to bp's.  bpstat lists are
12601      especial culprits.
12602
12603      One example of this happening is a watchpoint's scope bp.  When
12604      the scope bp triggers, we notice that the watchpoint is out of
12605      scope, and delete it.  We also delete its scope bp.  But the
12606      scope bp is marked "auto-deleting", and is already on a bpstat.
12607      That bpstat is then checked for auto-deleting bp's, which are
12608      deleted.
12609
12610      A real solution to this problem might involve reference counts in
12611      bp's, and/or giving them pointers back to their referencing
12612      bpstat's, and teaching delete_breakpoint to only free a bp's
12613      storage when no more references were extent.  A cheaper bandaid
12614      was chosen.  */
12615   if (bpt->type == bp_none)
12616     return;
12617
12618   /* At least avoid this stale reference until the reference counting
12619      of breakpoints gets resolved.  */
12620   if (bpt->related_breakpoint != bpt)
12621     {
12622       struct breakpoint *related;
12623       struct watchpoint *w;
12624
12625       if (bpt->type == bp_watchpoint_scope)
12626         w = (struct watchpoint *) bpt->related_breakpoint;
12627       else if (bpt->related_breakpoint->type == bp_watchpoint_scope)
12628         w = (struct watchpoint *) bpt;
12629       else
12630         w = NULL;
12631       if (w != NULL)
12632         watchpoint_del_at_next_stop (w);
12633
12634       /* Unlink bpt from the bpt->related_breakpoint ring.  */
12635       for (related = bpt; related->related_breakpoint != bpt;
12636            related = related->related_breakpoint);
12637       related->related_breakpoint = bpt->related_breakpoint;
12638       bpt->related_breakpoint = bpt;
12639     }
12640
12641   /* watch_command_1 creates a watchpoint but only sets its number if
12642      update_watchpoint succeeds in creating its bp_locations.  If there's
12643      a problem in that process, we'll be asked to delete the half-created
12644      watchpoint.  In that case, don't announce the deletion.  */
12645   if (bpt->number)
12646     observer_notify_breakpoint_deleted (bpt);
12647
12648   if (breakpoint_chain == bpt)
12649     breakpoint_chain = bpt->next;
12650
12651   ALL_BREAKPOINTS (b)
12652     if (b->next == bpt)
12653     {
12654       b->next = bpt->next;
12655       break;
12656     }
12657
12658   /* Be sure no bpstat's are pointing at the breakpoint after it's
12659      been freed.  */
12660   /* FIXME, how can we find all bpstat's?  We just check stop_bpstat
12661      in all threads for now.  Note that we cannot just remove bpstats
12662      pointing at bpt from the stop_bpstat list entirely, as breakpoint
12663      commands are associated with the bpstat; if we remove it here,
12664      then the later call to bpstat_do_actions (&stop_bpstat); in
12665      event-top.c won't do anything, and temporary breakpoints with
12666      commands won't work.  */
12667
12668   iterate_over_threads (bpstat_remove_breakpoint_callback, bpt);
12669
12670   /* Now that breakpoint is removed from breakpoint list, update the
12671      global location list.  This will remove locations that used to
12672      belong to this breakpoint.  Do this before freeing the breakpoint
12673      itself, since remove_breakpoint looks at location's owner.  It
12674      might be better design to have location completely
12675      self-contained, but it's not the case now.  */
12676   update_global_location_list (0);
12677
12678   bpt->ops->dtor (bpt);
12679   /* On the chance that someone will soon try again to delete this
12680      same bp, we mark it as deleted before freeing its storage.  */
12681   bpt->type = bp_none;
12682   xfree (bpt);
12683 }
12684
12685 static void
12686 do_delete_breakpoint_cleanup (void *b)
12687 {
12688   delete_breakpoint (b);
12689 }
12690
12691 struct cleanup *
12692 make_cleanup_delete_breakpoint (struct breakpoint *b)
12693 {
12694   return make_cleanup (do_delete_breakpoint_cleanup, b);
12695 }
12696
12697 /* Iterator function to call a user-provided callback function once
12698    for each of B and its related breakpoints.  */
12699
12700 static void
12701 iterate_over_related_breakpoints (struct breakpoint *b,
12702                                   void (*function) (struct breakpoint *,
12703                                                     void *),
12704                                   void *data)
12705 {
12706   struct breakpoint *related;
12707
12708   related = b;
12709   do
12710     {
12711       struct breakpoint *next;
12712
12713       /* FUNCTION may delete RELATED.  */
12714       next = related->related_breakpoint;
12715
12716       if (next == related)
12717         {
12718           /* RELATED is the last ring entry.  */
12719           function (related, data);
12720
12721           /* FUNCTION may have deleted it, so we'd never reach back to
12722              B.  There's nothing left to do anyway, so just break
12723              out.  */
12724           break;
12725         }
12726       else
12727         function (related, data);
12728
12729       related = next;
12730     }
12731   while (related != b);
12732 }
12733
12734 static void
12735 do_delete_breakpoint (struct breakpoint *b, void *ignore)
12736 {
12737   delete_breakpoint (b);
12738 }
12739
12740 /* A callback for map_breakpoint_numbers that calls
12741    delete_breakpoint.  */
12742
12743 static void
12744 do_map_delete_breakpoint (struct breakpoint *b, void *ignore)
12745 {
12746   iterate_over_related_breakpoints (b, do_delete_breakpoint, NULL);
12747 }
12748
12749 void
12750 delete_command (char *arg, int from_tty)
12751 {
12752   struct breakpoint *b, *b_tmp;
12753
12754   dont_repeat ();
12755
12756   if (arg == 0)
12757     {
12758       int breaks_to_delete = 0;
12759
12760       /* Delete all breakpoints if no argument.  Do not delete
12761          internal breakpoints, these have to be deleted with an
12762          explicit breakpoint number argument.  */
12763       ALL_BREAKPOINTS (b)
12764         if (user_breakpoint_p (b))
12765           {
12766             breaks_to_delete = 1;
12767             break;
12768           }
12769
12770       /* Ask user only if there are some breakpoints to delete.  */
12771       if (!from_tty
12772           || (breaks_to_delete && query (_("Delete all breakpoints? "))))
12773         {
12774           ALL_BREAKPOINTS_SAFE (b, b_tmp)
12775             if (user_breakpoint_p (b))
12776               delete_breakpoint (b);
12777         }
12778     }
12779   else
12780     map_breakpoint_numbers (arg, do_map_delete_breakpoint, NULL);
12781 }
12782
12783 static int
12784 all_locations_are_pending (struct bp_location *loc)
12785 {
12786   for (; loc; loc = loc->next)
12787     if (!loc->shlib_disabled
12788         && !loc->pspace->executing_startup)
12789       return 0;
12790   return 1;
12791 }
12792
12793 /* Subroutine of update_breakpoint_locations to simplify it.
12794    Return non-zero if multiple fns in list LOC have the same name.
12795    Null names are ignored.  */
12796
12797 static int
12798 ambiguous_names_p (struct bp_location *loc)
12799 {
12800   struct bp_location *l;
12801   htab_t htab = htab_create_alloc (13, htab_hash_string,
12802                                    (int (*) (const void *, 
12803                                              const void *)) streq,
12804                                    NULL, xcalloc, xfree);
12805
12806   for (l = loc; l != NULL; l = l->next)
12807     {
12808       const char **slot;
12809       const char *name = l->function_name;
12810
12811       /* Allow for some names to be NULL, ignore them.  */
12812       if (name == NULL)
12813         continue;
12814
12815       slot = (const char **) htab_find_slot (htab, (const void *) name,
12816                                              INSERT);
12817       /* NOTE: We can assume slot != NULL here because xcalloc never
12818          returns NULL.  */
12819       if (*slot != NULL)
12820         {
12821           htab_delete (htab);
12822           return 1;
12823         }
12824       *slot = name;
12825     }
12826
12827   htab_delete (htab);
12828   return 0;
12829 }
12830
12831 /* When symbols change, it probably means the sources changed as well,
12832    and it might mean the static tracepoint markers are no longer at
12833    the same address or line numbers they used to be at last we
12834    checked.  Losing your static tracepoints whenever you rebuild is
12835    undesirable.  This function tries to resync/rematch gdb static
12836    tracepoints with the markers on the target, for static tracepoints
12837    that have not been set by marker id.  Static tracepoint that have
12838    been set by marker id are reset by marker id in breakpoint_re_set.
12839    The heuristic is:
12840
12841    1) For a tracepoint set at a specific address, look for a marker at
12842    the old PC.  If one is found there, assume to be the same marker.
12843    If the name / string id of the marker found is different from the
12844    previous known name, assume that means the user renamed the marker
12845    in the sources, and output a warning.
12846
12847    2) For a tracepoint set at a given line number, look for a marker
12848    at the new address of the old line number.  If one is found there,
12849    assume to be the same marker.  If the name / string id of the
12850    marker found is different from the previous known name, assume that
12851    means the user renamed the marker in the sources, and output a
12852    warning.
12853
12854    3) If a marker is no longer found at the same address or line, it
12855    may mean the marker no longer exists.  But it may also just mean
12856    the code changed a bit.  Maybe the user added a few lines of code
12857    that made the marker move up or down (in line number terms).  Ask
12858    the target for info about the marker with the string id as we knew
12859    it.  If found, update line number and address in the matching
12860    static tracepoint.  This will get confused if there's more than one
12861    marker with the same ID (possible in UST, although unadvised
12862    precisely because it confuses tools).  */
12863
12864 static struct symtab_and_line
12865 update_static_tracepoint (struct breakpoint *b, struct symtab_and_line sal)
12866 {
12867   struct tracepoint *tp = (struct tracepoint *) b;
12868   struct static_tracepoint_marker marker;
12869   CORE_ADDR pc;
12870   int i;
12871
12872   pc = sal.pc;
12873   if (sal.line)
12874     find_line_pc (sal.symtab, sal.line, &pc);
12875
12876   if (target_static_tracepoint_marker_at (pc, &marker))
12877     {
12878       if (strcmp (tp->static_trace_marker_id, marker.str_id) != 0)
12879         warning (_("static tracepoint %d changed probed marker from %s to %s"),
12880                  b->number,
12881                  tp->static_trace_marker_id, marker.str_id);
12882
12883       xfree (tp->static_trace_marker_id);
12884       tp->static_trace_marker_id = xstrdup (marker.str_id);
12885       release_static_tracepoint_marker (&marker);
12886
12887       return sal;
12888     }
12889
12890   /* Old marker wasn't found on target at lineno.  Try looking it up
12891      by string ID.  */
12892   if (!sal.explicit_pc
12893       && sal.line != 0
12894       && sal.symtab != NULL
12895       && tp->static_trace_marker_id != NULL)
12896     {
12897       VEC(static_tracepoint_marker_p) *markers;
12898
12899       markers
12900         = target_static_tracepoint_markers_by_strid (tp->static_trace_marker_id);
12901
12902       if (!VEC_empty(static_tracepoint_marker_p, markers))
12903         {
12904           struct symtab_and_line sal2;
12905           struct symbol *sym;
12906           struct static_tracepoint_marker *tpmarker;
12907           struct ui_out *uiout = current_uiout;
12908
12909           tpmarker = VEC_index (static_tracepoint_marker_p, markers, 0);
12910
12911           xfree (tp->static_trace_marker_id);
12912           tp->static_trace_marker_id = xstrdup (tpmarker->str_id);
12913
12914           warning (_("marker for static tracepoint %d (%s) not "
12915                      "found at previous line number"),
12916                    b->number, tp->static_trace_marker_id);
12917
12918           init_sal (&sal2);
12919
12920           sal2.pc = tpmarker->address;
12921
12922           sal2 = find_pc_line (tpmarker->address, 0);
12923           sym = find_pc_sect_function (tpmarker->address, NULL);
12924           ui_out_text (uiout, "Now in ");
12925           if (sym)
12926             {
12927               ui_out_field_string (uiout, "func",
12928                                    SYMBOL_PRINT_NAME (sym));
12929               ui_out_text (uiout, " at ");
12930             }
12931           ui_out_field_string (uiout, "file", sal2.symtab->filename);
12932           ui_out_text (uiout, ":");
12933
12934           if (ui_out_is_mi_like_p (uiout))
12935             {
12936               char *fullname = symtab_to_fullname (sal2.symtab);
12937
12938               if (fullname)
12939                 ui_out_field_string (uiout, "fullname", fullname);
12940             }
12941
12942           ui_out_field_int (uiout, "line", sal2.line);
12943           ui_out_text (uiout, "\n");
12944
12945           b->loc->line_number = sal2.line;
12946
12947           xfree (b->loc->source_file);
12948           if (sym)
12949             b->loc->source_file = xstrdup (sal2.symtab->filename);
12950           else
12951             b->loc->source_file = NULL;
12952
12953           xfree (b->addr_string);
12954           b->addr_string = xstrprintf ("%s:%d",
12955                                        sal2.symtab->filename,
12956                                        b->loc->line_number);
12957
12958           /* Might be nice to check if function changed, and warn if
12959              so.  */
12960
12961           release_static_tracepoint_marker (tpmarker);
12962         }
12963     }
12964   return sal;
12965 }
12966
12967 /* Returns 1 iff locations A and B are sufficiently same that
12968    we don't need to report breakpoint as changed.  */
12969
12970 static int
12971 locations_are_equal (struct bp_location *a, struct bp_location *b)
12972 {
12973   while (a && b)
12974     {
12975       if (a->address != b->address)
12976         return 0;
12977
12978       if (a->shlib_disabled != b->shlib_disabled)
12979         return 0;
12980
12981       if (a->enabled != b->enabled)
12982         return 0;
12983
12984       a = a->next;
12985       b = b->next;
12986     }
12987
12988   if ((a == NULL) != (b == NULL))
12989     return 0;
12990
12991   return 1;
12992 }
12993
12994 /* Create new breakpoint locations for B (a hardware or software breakpoint)
12995    based on SALS and SALS_END.  If SALS_END.NELTS is not zero, then B is
12996    a ranged breakpoint.  */
12997
12998 void
12999 update_breakpoint_locations (struct breakpoint *b,
13000                              struct symtabs_and_lines sals,
13001                              struct symtabs_and_lines sals_end)
13002 {
13003   int i;
13004   struct bp_location *existing_locations = b->loc;
13005
13006   if (sals_end.nelts != 0 && (sals.nelts != 1 || sals_end.nelts != 1))
13007     {
13008       /* Ranged breakpoints have only one start location and one end
13009          location.  */
13010       b->enable_state = bp_disabled;
13011       update_global_location_list (1);
13012       printf_unfiltered (_("Could not reset ranged breakpoint %d: "
13013                            "multiple locations found\n"),
13014                          b->number);
13015       return;
13016     }
13017
13018   /* If there's no new locations, and all existing locations are
13019      pending, don't do anything.  This optimizes the common case where
13020      all locations are in the same shared library, that was unloaded.
13021      We'd like to retain the location, so that when the library is
13022      loaded again, we don't loose the enabled/disabled status of the
13023      individual locations.  */
13024   if (all_locations_are_pending (existing_locations) && sals.nelts == 0)
13025     return;
13026
13027   b->loc = NULL;
13028
13029   for (i = 0; i < sals.nelts; ++i)
13030     {
13031       struct bp_location *new_loc;
13032
13033       switch_to_program_space_and_thread (sals.sals[i].pspace);
13034
13035       new_loc = add_location_to_breakpoint (b, &(sals.sals[i]));
13036
13037       /* Reparse conditions, they might contain references to the
13038          old symtab.  */
13039       if (b->cond_string != NULL)
13040         {
13041           char *s;
13042           volatile struct gdb_exception e;
13043
13044           s = b->cond_string;
13045           TRY_CATCH (e, RETURN_MASK_ERROR)
13046             {
13047               new_loc->cond = parse_exp_1 (&s, block_for_pc (sals.sals[i].pc), 
13048                                            0);
13049             }
13050           if (e.reason < 0)
13051             {
13052               warning (_("failed to reevaluate condition "
13053                          "for breakpoint %d: %s"), 
13054                        b->number, e.message);
13055               new_loc->enabled = 0;
13056             }
13057         }
13058
13059       if (sals_end.nelts)
13060         {
13061           CORE_ADDR end = find_breakpoint_range_end (sals_end.sals[0]);
13062
13063           new_loc->length = end - sals.sals[0].pc + 1;
13064         }
13065     }
13066
13067   /* Update locations of permanent breakpoints.  */
13068   if (b->enable_state == bp_permanent)
13069     make_breakpoint_permanent (b);
13070
13071   /* If possible, carry over 'disable' status from existing
13072      breakpoints.  */
13073   {
13074     struct bp_location *e = existing_locations;
13075     /* If there are multiple breakpoints with the same function name,
13076        e.g. for inline functions, comparing function names won't work.
13077        Instead compare pc addresses; this is just a heuristic as things
13078        may have moved, but in practice it gives the correct answer
13079        often enough until a better solution is found.  */
13080     int have_ambiguous_names = ambiguous_names_p (b->loc);
13081
13082     for (; e; e = e->next)
13083       {
13084         if (!e->enabled && e->function_name)
13085           {
13086             struct bp_location *l = b->loc;
13087             if (have_ambiguous_names)
13088               {
13089                 for (; l; l = l->next)
13090                   if (breakpoint_locations_match (e, l))
13091                     {
13092                       l->enabled = 0;
13093                       break;
13094                     }
13095               }
13096             else
13097               {
13098                 for (; l; l = l->next)
13099                   if (l->function_name
13100                       && strcmp (e->function_name, l->function_name) == 0)
13101                     {
13102                       l->enabled = 0;
13103                       break;
13104                     }
13105               }
13106           }
13107       }
13108   }
13109
13110   if (!locations_are_equal (existing_locations, b->loc))
13111     observer_notify_breakpoint_modified (b);
13112
13113   update_global_location_list (1);
13114 }
13115
13116 /* Find the SaL locations corresponding to the given ADDR_STRING.
13117    On return, FOUND will be 1 if any SaL was found, zero otherwise.  */
13118
13119 static struct symtabs_and_lines
13120 addr_string_to_sals (struct breakpoint *b, char *addr_string, int *found)
13121 {
13122   char *s;
13123   struct symtabs_and_lines sals = {0};
13124   volatile struct gdb_exception e;
13125
13126   gdb_assert (b->ops != NULL);
13127   s = addr_string;
13128
13129   TRY_CATCH (e, RETURN_MASK_ERROR)
13130     {
13131       b->ops->decode_linespec (b, &s, &sals);
13132     }
13133   if (e.reason < 0)
13134     {
13135       int not_found_and_ok = 0;
13136       /* For pending breakpoints, it's expected that parsing will
13137          fail until the right shared library is loaded.  User has
13138          already told to create pending breakpoints and don't need
13139          extra messages.  If breakpoint is in bp_shlib_disabled
13140          state, then user already saw the message about that
13141          breakpoint being disabled, and don't want to see more
13142          errors.  */
13143       if (e.error == NOT_FOUND_ERROR
13144           && (b->condition_not_parsed 
13145               || (b->loc && b->loc->shlib_disabled)
13146               || (b->loc && b->loc->pspace->executing_startup)
13147               || b->enable_state == bp_disabled))
13148         not_found_and_ok = 1;
13149
13150       if (!not_found_and_ok)
13151         {
13152           /* We surely don't want to warn about the same breakpoint
13153              10 times.  One solution, implemented here, is disable
13154              the breakpoint on error.  Another solution would be to
13155              have separate 'warning emitted' flag.  Since this
13156              happens only when a binary has changed, I don't know
13157              which approach is better.  */
13158           b->enable_state = bp_disabled;
13159           throw_exception (e);
13160         }
13161     }
13162
13163   if (e.reason == 0 || e.error != NOT_FOUND_ERROR)
13164     {
13165       int i;
13166
13167       for (i = 0; i < sals.nelts; ++i)
13168         resolve_sal_pc (&sals.sals[i]);
13169       if (b->condition_not_parsed && s && s[0])
13170         {
13171           char *cond_string = 0;
13172           int thread = -1;
13173           int task = 0;
13174
13175           find_condition_and_thread (s, sals.sals[0].pc,
13176                                      &cond_string, &thread, &task);
13177           if (cond_string)
13178             b->cond_string = cond_string;
13179           b->thread = thread;
13180           b->task = task;
13181           b->condition_not_parsed = 0;
13182         }
13183
13184       if (b->type == bp_static_tracepoint && !strace_marker_p (b))
13185         sals.sals[0] = update_static_tracepoint (b, sals.sals[0]);
13186
13187       *found = 1;
13188     }
13189   else
13190     *found = 0;
13191
13192   return sals;
13193 }
13194
13195 /* The default re_set method, for typical hardware or software
13196    breakpoints.  Reevaluate the breakpoint and recreate its
13197    locations.  */
13198
13199 static void
13200 breakpoint_re_set_default (struct breakpoint *b)
13201 {
13202   int found;
13203   struct symtabs_and_lines sals, sals_end;
13204   struct symtabs_and_lines expanded = {0};
13205   struct symtabs_and_lines expanded_end = {0};
13206
13207   sals = addr_string_to_sals (b, b->addr_string, &found);
13208   if (found)
13209     {
13210       make_cleanup (xfree, sals.sals);
13211       expanded = sals;
13212     }
13213
13214   if (b->addr_string_range_end)
13215     {
13216       sals_end = addr_string_to_sals (b, b->addr_string_range_end, &found);
13217       if (found)
13218         {
13219           make_cleanup (xfree, sals_end.sals);
13220           expanded_end = sals_end;
13221         }
13222     }
13223
13224   update_breakpoint_locations (b, expanded, expanded_end);
13225 }
13226
13227 /* Default method for creating SALs from an address string.  It basically
13228    calls parse_breakpoint_sals.  Return 1 for success, zero for failure.  */
13229
13230 static void
13231 create_sals_from_address_default (char **arg,
13232                                   struct linespec_result *canonical,
13233                                   enum bptype type_wanted,
13234                                   char *addr_start, char **copy_arg)
13235 {
13236   parse_breakpoint_sals (arg, canonical);
13237 }
13238
13239 /* Call create_breakpoints_sal for the given arguments.  This is the default
13240    function for the `create_breakpoints_sal' method of
13241    breakpoint_ops.  */
13242
13243 static void
13244 create_breakpoints_sal_default (struct gdbarch *gdbarch,
13245                                 struct linespec_result *canonical,
13246                                 struct linespec_sals *lsal,
13247                                 char *cond_string,
13248                                 enum bptype type_wanted,
13249                                 enum bpdisp disposition,
13250                                 int thread,
13251                                 int task, int ignore_count,
13252                                 const struct breakpoint_ops *ops,
13253                                 int from_tty, int enabled,
13254                                 int internal)
13255 {
13256   create_breakpoints_sal (gdbarch, canonical, cond_string,
13257                           type_wanted, disposition,
13258                           thread, task, ignore_count, ops, from_tty,
13259                           enabled, internal);
13260 }
13261
13262 /* Decode the line represented by S by calling decode_line_full.  This is the
13263    default function for the `decode_linespec' method of breakpoint_ops.  */
13264
13265 static void
13266 decode_linespec_default (struct breakpoint *b, char **s,
13267                          struct symtabs_and_lines *sals)
13268 {
13269   struct linespec_result canonical;
13270
13271   init_linespec_result (&canonical);
13272   decode_line_full (s, DECODE_LINE_FUNFIRSTLINE,
13273                     (struct symtab *) NULL, 0,
13274                     &canonical, multiple_symbols_all,
13275                     b->filter);
13276
13277   /* We should get 0 or 1 resulting SALs.  */
13278   gdb_assert (VEC_length (linespec_sals, canonical.sals) < 2);
13279
13280   if (VEC_length (linespec_sals, canonical.sals) > 0)
13281     {
13282       struct linespec_sals *lsal;
13283
13284       lsal = VEC_index (linespec_sals, canonical.sals, 0);
13285       *sals = lsal->sals;
13286       /* Arrange it so the destructor does not free the
13287          contents.  */
13288       lsal->sals.sals = NULL;
13289     }
13290
13291   destroy_linespec_result (&canonical);
13292 }
13293
13294 /* Prepare the global context for a re-set of breakpoint B.  */
13295
13296 static struct cleanup *
13297 prepare_re_set_context (struct breakpoint *b)
13298 {
13299   struct cleanup *cleanups;
13300
13301   input_radix = b->input_radix;
13302   cleanups = save_current_space_and_thread ();
13303   if (b->pspace != NULL)
13304     switch_to_program_space_and_thread (b->pspace);
13305   set_language (b->language);
13306
13307   return cleanups;
13308 }
13309
13310 /* Reset a breakpoint given it's struct breakpoint * BINT.
13311    The value we return ends up being the return value from catch_errors.
13312    Unused in this case.  */
13313
13314 static int
13315 breakpoint_re_set_one (void *bint)
13316 {
13317   /* Get past catch_errs.  */
13318   struct breakpoint *b = (struct breakpoint *) bint;
13319   struct cleanup *cleanups;
13320
13321   cleanups = prepare_re_set_context (b);
13322   b->ops->re_set (b);
13323   do_cleanups (cleanups);
13324   return 0;
13325 }
13326
13327 /* Re-set all breakpoints after symbols have been re-loaded.  */
13328 void
13329 breakpoint_re_set (void)
13330 {
13331   struct breakpoint *b, *b_tmp;
13332   enum language save_language;
13333   int save_input_radix;
13334   struct cleanup *old_chain;
13335
13336   save_language = current_language->la_language;
13337   save_input_radix = input_radix;
13338   old_chain = save_current_program_space ();
13339
13340   ALL_BREAKPOINTS_SAFE (b, b_tmp)
13341   {
13342     /* Format possible error msg.  */
13343     char *message = xstrprintf ("Error in re-setting breakpoint %d: ",
13344                                 b->number);
13345     struct cleanup *cleanups = make_cleanup (xfree, message);
13346     catch_errors (breakpoint_re_set_one, b, message, RETURN_MASK_ALL);
13347     do_cleanups (cleanups);
13348   }
13349   set_language (save_language);
13350   input_radix = save_input_radix;
13351
13352   jit_breakpoint_re_set ();
13353
13354   do_cleanups (old_chain);
13355
13356   create_overlay_event_breakpoint ();
13357   create_longjmp_master_breakpoint ();
13358   create_std_terminate_master_breakpoint ();
13359   create_exception_master_breakpoint ();
13360
13361   /* While we're at it, reset the skip list too.  */
13362   skip_re_set ();
13363 }
13364 \f
13365 /* Reset the thread number of this breakpoint:
13366
13367    - If the breakpoint is for all threads, leave it as-is.
13368    - Else, reset it to the current thread for inferior_ptid.  */
13369 void
13370 breakpoint_re_set_thread (struct breakpoint *b)
13371 {
13372   if (b->thread != -1)
13373     {
13374       if (in_thread_list (inferior_ptid))
13375         b->thread = pid_to_thread_id (inferior_ptid);
13376
13377       /* We're being called after following a fork.  The new fork is
13378          selected as current, and unless this was a vfork will have a
13379          different program space from the original thread.  Reset that
13380          as well.  */
13381       b->loc->pspace = current_program_space;
13382     }
13383 }
13384
13385 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
13386    If from_tty is nonzero, it prints a message to that effect,
13387    which ends with a period (no newline).  */
13388
13389 void
13390 set_ignore_count (int bptnum, int count, int from_tty)
13391 {
13392   struct breakpoint *b;
13393
13394   if (count < 0)
13395     count = 0;
13396
13397   ALL_BREAKPOINTS (b)
13398     if (b->number == bptnum)
13399     {
13400       if (is_tracepoint (b))
13401         {
13402           if (from_tty && count != 0)
13403             printf_filtered (_("Ignore count ignored for tracepoint %d."),
13404                              bptnum);
13405           return;
13406         }
13407       
13408       b->ignore_count = count;
13409       if (from_tty)
13410         {
13411           if (count == 0)
13412             printf_filtered (_("Will stop next time "
13413                                "breakpoint %d is reached."),
13414                              bptnum);
13415           else if (count == 1)
13416             printf_filtered (_("Will ignore next crossing of breakpoint %d."),
13417                              bptnum);
13418           else
13419             printf_filtered (_("Will ignore next %d "
13420                                "crossings of breakpoint %d."),
13421                              count, bptnum);
13422         }
13423       breakpoints_changed ();
13424       observer_notify_breakpoint_modified (b);
13425       return;
13426     }
13427
13428   error (_("No breakpoint number %d."), bptnum);
13429 }
13430
13431 /* Command to set ignore-count of breakpoint N to COUNT.  */
13432
13433 static void
13434 ignore_command (char *args, int from_tty)
13435 {
13436   char *p = args;
13437   int num;
13438
13439   if (p == 0)
13440     error_no_arg (_("a breakpoint number"));
13441
13442   num = get_number (&p);
13443   if (num == 0)
13444     error (_("bad breakpoint number: '%s'"), args);
13445   if (*p == 0)
13446     error (_("Second argument (specified ignore-count) is missing."));
13447
13448   set_ignore_count (num,
13449                     longest_to_int (value_as_long (parse_and_eval (p))),
13450                     from_tty);
13451   if (from_tty)
13452     printf_filtered ("\n");
13453 }
13454 \f
13455 /* Call FUNCTION on each of the breakpoints
13456    whose numbers are given in ARGS.  */
13457
13458 static void
13459 map_breakpoint_numbers (char *args, void (*function) (struct breakpoint *,
13460                                                       void *),
13461                         void *data)
13462 {
13463   int num;
13464   struct breakpoint *b, *tmp;
13465   int match;
13466   struct get_number_or_range_state state;
13467
13468   if (args == 0)
13469     error_no_arg (_("one or more breakpoint numbers"));
13470
13471   init_number_or_range (&state, args);
13472
13473   while (!state.finished)
13474     {
13475       char *p = state.string;
13476
13477       match = 0;
13478
13479       num = get_number_or_range (&state);
13480       if (num == 0)
13481         {
13482           warning (_("bad breakpoint number at or near '%s'"), p);
13483         }
13484       else
13485         {
13486           ALL_BREAKPOINTS_SAFE (b, tmp)
13487             if (b->number == num)
13488               {
13489                 match = 1;
13490                 function (b, data);
13491                 break;
13492               }
13493           if (match == 0)
13494             printf_unfiltered (_("No breakpoint number %d.\n"), num);
13495         }
13496     }
13497 }
13498
13499 static struct bp_location *
13500 find_location_by_number (char *number)
13501 {
13502   char *dot = strchr (number, '.');
13503   char *p1;
13504   int bp_num;
13505   int loc_num;
13506   struct breakpoint *b;
13507   struct bp_location *loc;  
13508
13509   *dot = '\0';
13510
13511   p1 = number;
13512   bp_num = get_number (&p1);
13513   if (bp_num == 0)
13514     error (_("Bad breakpoint number '%s'"), number);
13515
13516   ALL_BREAKPOINTS (b)
13517     if (b->number == bp_num)
13518       {
13519         break;
13520       }
13521
13522   if (!b || b->number != bp_num)
13523     error (_("Bad breakpoint number '%s'"), number);
13524   
13525   p1 = dot+1;
13526   loc_num = get_number (&p1);
13527   if (loc_num == 0)
13528     error (_("Bad breakpoint location number '%s'"), number);
13529
13530   --loc_num;
13531   loc = b->loc;
13532   for (;loc_num && loc; --loc_num, loc = loc->next)
13533     ;
13534   if (!loc)
13535     error (_("Bad breakpoint location number '%s'"), dot+1);
13536     
13537   return loc;  
13538 }
13539
13540
13541 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
13542    If from_tty is nonzero, it prints a message to that effect,
13543    which ends with a period (no newline).  */
13544
13545 void
13546 disable_breakpoint (struct breakpoint *bpt)
13547 {
13548   /* Never disable a watchpoint scope breakpoint; we want to
13549      hit them when we leave scope so we can delete both the
13550      watchpoint and its scope breakpoint at that time.  */
13551   if (bpt->type == bp_watchpoint_scope)
13552     return;
13553
13554   /* You can't disable permanent breakpoints.  */
13555   if (bpt->enable_state == bp_permanent)
13556     return;
13557
13558   bpt->enable_state = bp_disabled;
13559
13560   /* Mark breakpoint locations modified.  */
13561   mark_breakpoint_modified (bpt);
13562
13563   if (target_supports_enable_disable_tracepoint ()
13564       && current_trace_status ()->running && is_tracepoint (bpt))
13565     {
13566       struct bp_location *location;
13567      
13568       for (location = bpt->loc; location; location = location->next)
13569         target_disable_tracepoint (location);
13570     }
13571
13572   update_global_location_list (0);
13573
13574   observer_notify_breakpoint_modified (bpt);
13575 }
13576
13577 /* A callback for iterate_over_related_breakpoints.  */
13578
13579 static void
13580 do_disable_breakpoint (struct breakpoint *b, void *ignore)
13581 {
13582   disable_breakpoint (b);
13583 }
13584
13585 /* A callback for map_breakpoint_numbers that calls
13586    disable_breakpoint.  */
13587
13588 static void
13589 do_map_disable_breakpoint (struct breakpoint *b, void *ignore)
13590 {
13591   iterate_over_related_breakpoints (b, do_disable_breakpoint, NULL);
13592 }
13593
13594 static void
13595 disable_command (char *args, int from_tty)
13596 {
13597   if (args == 0)
13598     {
13599       struct breakpoint *bpt;
13600
13601       ALL_BREAKPOINTS (bpt)
13602         if (user_breakpoint_p (bpt))
13603           disable_breakpoint (bpt);
13604     }
13605   else if (strchr (args, '.'))
13606     {
13607       struct bp_location *loc = find_location_by_number (args);
13608       if (loc)
13609         {
13610           if (loc->enabled)
13611             {
13612               loc->enabled = 0;
13613               mark_breakpoint_location_modified (loc);
13614             }
13615           if (target_supports_enable_disable_tracepoint ()
13616               && current_trace_status ()->running && loc->owner
13617               && is_tracepoint (loc->owner))
13618             target_disable_tracepoint (loc);
13619         }
13620       update_global_location_list (0);
13621     }
13622   else
13623     map_breakpoint_numbers (args, do_map_disable_breakpoint, NULL);
13624 }
13625
13626 static void
13627 enable_breakpoint_disp (struct breakpoint *bpt, enum bpdisp disposition,
13628                         int count)
13629 {
13630   int target_resources_ok;
13631
13632   if (bpt->type == bp_hardware_breakpoint)
13633     {
13634       int i;
13635       i = hw_breakpoint_used_count ();
13636       target_resources_ok = 
13637         target_can_use_hardware_watchpoint (bp_hardware_breakpoint, 
13638                                             i + 1, 0);
13639       if (target_resources_ok == 0)
13640         error (_("No hardware breakpoint support in the target."));
13641       else if (target_resources_ok < 0)
13642         error (_("Hardware breakpoints used exceeds limit."));
13643     }
13644
13645   if (is_watchpoint (bpt))
13646     {
13647       /* Initialize it just to avoid a GCC false warning.  */
13648       enum enable_state orig_enable_state = 0;
13649       volatile struct gdb_exception e;
13650
13651       TRY_CATCH (e, RETURN_MASK_ALL)
13652         {
13653           struct watchpoint *w = (struct watchpoint *) bpt;
13654
13655           orig_enable_state = bpt->enable_state;
13656           bpt->enable_state = bp_enabled;
13657           update_watchpoint (w, 1 /* reparse */);
13658         }
13659       if (e.reason < 0)
13660         {
13661           bpt->enable_state = orig_enable_state;
13662           exception_fprintf (gdb_stderr, e, _("Cannot enable watchpoint %d: "),
13663                              bpt->number);
13664           return;
13665         }
13666     }
13667
13668   if (bpt->enable_state != bp_permanent)
13669     bpt->enable_state = bp_enabled;
13670
13671   bpt->enable_state = bp_enabled;
13672
13673   /* Mark breakpoint locations modified.  */
13674   mark_breakpoint_modified (bpt);
13675
13676   if (target_supports_enable_disable_tracepoint ()
13677       && current_trace_status ()->running && is_tracepoint (bpt))
13678     {
13679       struct bp_location *location;
13680
13681       for (location = bpt->loc; location; location = location->next)
13682         target_enable_tracepoint (location);
13683     }
13684
13685   bpt->disposition = disposition;
13686   bpt->enable_count = count;
13687   update_global_location_list (1);
13688   breakpoints_changed ();
13689   
13690   observer_notify_breakpoint_modified (bpt);
13691 }
13692
13693
13694 void
13695 enable_breakpoint (struct breakpoint *bpt)
13696 {
13697   enable_breakpoint_disp (bpt, bpt->disposition, 0);
13698 }
13699
13700 static void
13701 do_enable_breakpoint (struct breakpoint *bpt, void *arg)
13702 {
13703   enable_breakpoint (bpt);
13704 }
13705
13706 /* A callback for map_breakpoint_numbers that calls
13707    enable_breakpoint.  */
13708
13709 static void
13710 do_map_enable_breakpoint (struct breakpoint *b, void *ignore)
13711 {
13712   iterate_over_related_breakpoints (b, do_enable_breakpoint, NULL);
13713 }
13714
13715 /* The enable command enables the specified breakpoints (or all defined
13716    breakpoints) so they once again become (or continue to be) effective
13717    in stopping the inferior.  */
13718
13719 static void
13720 enable_command (char *args, int from_tty)
13721 {
13722   if (args == 0)
13723     {
13724       struct breakpoint *bpt;
13725
13726       ALL_BREAKPOINTS (bpt)
13727         if (user_breakpoint_p (bpt))
13728           enable_breakpoint (bpt);
13729     }
13730   else if (strchr (args, '.'))
13731     {
13732       struct bp_location *loc = find_location_by_number (args);
13733       if (loc)
13734         {
13735           if (!loc->enabled)
13736             {
13737               loc->enabled = 1;
13738               mark_breakpoint_location_modified (loc);
13739             }
13740           if (target_supports_enable_disable_tracepoint ()
13741               && current_trace_status ()->running && loc->owner
13742               && is_tracepoint (loc->owner))
13743             target_enable_tracepoint (loc);
13744         }
13745       update_global_location_list (1);
13746     }
13747   else
13748     map_breakpoint_numbers (args, do_map_enable_breakpoint, NULL);
13749 }
13750
13751 /* This struct packages up disposition data for application to multiple
13752    breakpoints.  */
13753
13754 struct disp_data
13755 {
13756   enum bpdisp disp;
13757   int count;
13758 };
13759
13760 static void
13761 do_enable_breakpoint_disp (struct breakpoint *bpt, void *arg)
13762 {
13763   struct disp_data disp_data = *(struct disp_data *) arg;
13764
13765   enable_breakpoint_disp (bpt, disp_data.disp, disp_data.count);
13766 }
13767
13768 static void
13769 do_map_enable_once_breakpoint (struct breakpoint *bpt, void *ignore)
13770 {
13771   struct disp_data disp = { disp_disable, 1 };
13772
13773   iterate_over_related_breakpoints (bpt, do_enable_breakpoint_disp, &disp);
13774 }
13775
13776 static void
13777 enable_once_command (char *args, int from_tty)
13778 {
13779   map_breakpoint_numbers (args, do_map_enable_once_breakpoint, NULL);
13780 }
13781
13782 static void
13783 do_map_enable_count_breakpoint (struct breakpoint *bpt, void *countptr)
13784 {
13785   struct disp_data disp = { disp_disable, *(int *) countptr };
13786
13787   iterate_over_related_breakpoints (bpt, do_enable_breakpoint_disp, &disp);
13788 }
13789
13790 static void
13791 enable_count_command (char *args, int from_tty)
13792 {
13793   int count = get_number (&args);
13794
13795   map_breakpoint_numbers (args, do_map_enable_count_breakpoint, &count);
13796 }
13797
13798 static void
13799 do_map_enable_delete_breakpoint (struct breakpoint *bpt, void *ignore)
13800 {
13801   struct disp_data disp = { disp_del, 1 };
13802
13803   iterate_over_related_breakpoints (bpt, do_enable_breakpoint_disp, &disp);
13804 }
13805
13806 static void
13807 enable_delete_command (char *args, int from_tty)
13808 {
13809   map_breakpoint_numbers (args, do_map_enable_delete_breakpoint, NULL);
13810 }
13811 \f
13812 static void
13813 set_breakpoint_cmd (char *args, int from_tty)
13814 {
13815 }
13816
13817 static void
13818 show_breakpoint_cmd (char *args, int from_tty)
13819 {
13820 }
13821
13822 /* Invalidate last known value of any hardware watchpoint if
13823    the memory which that value represents has been written to by
13824    GDB itself.  */
13825
13826 static void
13827 invalidate_bp_value_on_memory_change (CORE_ADDR addr, int len,
13828                                       const bfd_byte *data)
13829 {
13830   struct breakpoint *bp;
13831
13832   ALL_BREAKPOINTS (bp)
13833     if (bp->enable_state == bp_enabled
13834         && bp->type == bp_hardware_watchpoint)
13835       {
13836         struct watchpoint *wp = (struct watchpoint *) bp;
13837
13838         if (wp->val_valid && wp->val)
13839           {
13840             struct bp_location *loc;
13841
13842             for (loc = bp->loc; loc != NULL; loc = loc->next)
13843               if (loc->loc_type == bp_loc_hardware_watchpoint
13844                   && loc->address + loc->length > addr
13845                   && addr + len > loc->address)
13846                 {
13847                   value_free (wp->val);
13848                   wp->val = NULL;
13849                   wp->val_valid = 0;
13850                 }
13851           }
13852       }
13853 }
13854
13855 /* Use the last displayed codepoint's values, or nothing
13856    if they aren't valid.  */
13857
13858 struct symtabs_and_lines
13859 decode_line_spec_1 (char *string, int flags)
13860 {
13861   struct symtabs_and_lines sals;
13862
13863   if (string == 0)
13864     error (_("Empty line specification."));
13865   if (last_displayed_sal_is_valid ())
13866     sals = decode_line_1 (&string, flags,
13867                           get_last_displayed_symtab (),
13868                           get_last_displayed_line ());
13869   else
13870     sals = decode_line_1 (&string, flags, (struct symtab *) NULL, 0);
13871   if (*string)
13872     error (_("Junk at end of line specification: %s"), string);
13873   return sals;
13874 }
13875
13876 /* Create and insert a raw software breakpoint at PC.  Return an
13877    identifier, which should be used to remove the breakpoint later.
13878    In general, places which call this should be using something on the
13879    breakpoint chain instead; this function should be eliminated
13880    someday.  */
13881
13882 void *
13883 deprecated_insert_raw_breakpoint (struct gdbarch *gdbarch,
13884                                   struct address_space *aspace, CORE_ADDR pc)
13885 {
13886   struct bp_target_info *bp_tgt;
13887
13888   bp_tgt = XZALLOC (struct bp_target_info);
13889
13890   bp_tgt->placed_address_space = aspace;
13891   bp_tgt->placed_address = pc;
13892
13893   if (target_insert_breakpoint (gdbarch, bp_tgt) != 0)
13894     {
13895       /* Could not insert the breakpoint.  */
13896       xfree (bp_tgt);
13897       return NULL;
13898     }
13899
13900   return bp_tgt;
13901 }
13902
13903 /* Remove a breakpoint BP inserted by
13904    deprecated_insert_raw_breakpoint.  */
13905
13906 int
13907 deprecated_remove_raw_breakpoint (struct gdbarch *gdbarch, void *bp)
13908 {
13909   struct bp_target_info *bp_tgt = bp;
13910   int ret;
13911
13912   ret = target_remove_breakpoint (gdbarch, bp_tgt);
13913   xfree (bp_tgt);
13914
13915   return ret;
13916 }
13917
13918 /* One (or perhaps two) breakpoints used for software single
13919    stepping.  */
13920
13921 static void *single_step_breakpoints[2];
13922 static struct gdbarch *single_step_gdbarch[2];
13923
13924 /* Create and insert a breakpoint for software single step.  */
13925
13926 void
13927 insert_single_step_breakpoint (struct gdbarch *gdbarch,
13928                                struct address_space *aspace, 
13929                                CORE_ADDR next_pc)
13930 {
13931   void **bpt_p;
13932
13933   if (single_step_breakpoints[0] == NULL)
13934     {
13935       bpt_p = &single_step_breakpoints[0];
13936       single_step_gdbarch[0] = gdbarch;
13937     }
13938   else
13939     {
13940       gdb_assert (single_step_breakpoints[1] == NULL);
13941       bpt_p = &single_step_breakpoints[1];
13942       single_step_gdbarch[1] = gdbarch;
13943     }
13944
13945   /* NOTE drow/2006-04-11: A future improvement to this function would
13946      be to only create the breakpoints once, and actually put them on
13947      the breakpoint chain.  That would let us use set_raw_breakpoint.
13948      We could adjust the addresses each time they were needed.  Doing
13949      this requires corresponding changes elsewhere where single step
13950      breakpoints are handled, however.  So, for now, we use this.  */
13951
13952   *bpt_p = deprecated_insert_raw_breakpoint (gdbarch, aspace, next_pc);
13953   if (*bpt_p == NULL)
13954     error (_("Could not insert single-step breakpoint at %s"),
13955              paddress (gdbarch, next_pc));
13956 }
13957
13958 /* Check if the breakpoints used for software single stepping
13959    were inserted or not.  */
13960
13961 int
13962 single_step_breakpoints_inserted (void)
13963 {
13964   return (single_step_breakpoints[0] != NULL
13965           || single_step_breakpoints[1] != NULL);
13966 }
13967
13968 /* Remove and delete any breakpoints used for software single step.  */
13969
13970 void
13971 remove_single_step_breakpoints (void)
13972 {
13973   gdb_assert (single_step_breakpoints[0] != NULL);
13974
13975   /* See insert_single_step_breakpoint for more about this deprecated
13976      call.  */
13977   deprecated_remove_raw_breakpoint (single_step_gdbarch[0],
13978                                     single_step_breakpoints[0]);
13979   single_step_gdbarch[0] = NULL;
13980   single_step_breakpoints[0] = NULL;
13981
13982   if (single_step_breakpoints[1] != NULL)
13983     {
13984       deprecated_remove_raw_breakpoint (single_step_gdbarch[1],
13985                                         single_step_breakpoints[1]);
13986       single_step_gdbarch[1] = NULL;
13987       single_step_breakpoints[1] = NULL;
13988     }
13989 }
13990
13991 /* Delete software single step breakpoints without removing them from
13992    the inferior.  This is intended to be used if the inferior's address
13993    space where they were inserted is already gone, e.g. after exit or
13994    exec.  */
13995
13996 void
13997 cancel_single_step_breakpoints (void)
13998 {
13999   int i;
14000
14001   for (i = 0; i < 2; i++)
14002     if (single_step_breakpoints[i])
14003       {
14004         xfree (single_step_breakpoints[i]);
14005         single_step_breakpoints[i] = NULL;
14006         single_step_gdbarch[i] = NULL;
14007       }
14008 }
14009
14010 /* Detach software single-step breakpoints from INFERIOR_PTID without
14011    removing them.  */
14012
14013 static void
14014 detach_single_step_breakpoints (void)
14015 {
14016   int i;
14017
14018   for (i = 0; i < 2; i++)
14019     if (single_step_breakpoints[i])
14020       target_remove_breakpoint (single_step_gdbarch[i],
14021                                 single_step_breakpoints[i]);
14022 }
14023
14024 /* Check whether a software single-step breakpoint is inserted at
14025    PC.  */
14026
14027 static int
14028 single_step_breakpoint_inserted_here_p (struct address_space *aspace, 
14029                                         CORE_ADDR pc)
14030 {
14031   int i;
14032
14033   for (i = 0; i < 2; i++)
14034     {
14035       struct bp_target_info *bp_tgt = single_step_breakpoints[i];
14036       if (bp_tgt
14037           && breakpoint_address_match (bp_tgt->placed_address_space,
14038                                        bp_tgt->placed_address,
14039                                        aspace, pc))
14040         return 1;
14041     }
14042
14043   return 0;
14044 }
14045
14046 /* Returns 0 if 'bp' is NOT a syscall catchpoint,
14047    non-zero otherwise.  */
14048 static int
14049 is_syscall_catchpoint_enabled (struct breakpoint *bp)
14050 {
14051   if (syscall_catchpoint_p (bp)
14052       && bp->enable_state != bp_disabled
14053       && bp->enable_state != bp_call_disabled)
14054     return 1;
14055   else
14056     return 0;
14057 }
14058
14059 int
14060 catch_syscall_enabled (void)
14061 {
14062   struct inferior *inf = current_inferior ();
14063
14064   return inf->total_syscalls_count != 0;
14065 }
14066
14067 int
14068 catching_syscall_number (int syscall_number)
14069 {
14070   struct breakpoint *bp;
14071
14072   ALL_BREAKPOINTS (bp)
14073     if (is_syscall_catchpoint_enabled (bp))
14074       {
14075         struct syscall_catchpoint *c = (struct syscall_catchpoint *) bp;
14076
14077         if (c->syscalls_to_be_caught)
14078           {
14079             int i, iter;
14080             for (i = 0;
14081                  VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
14082                  i++)
14083               if (syscall_number == iter)
14084                 return 1;
14085           }
14086         else
14087           return 1;
14088       }
14089
14090   return 0;
14091 }
14092
14093 /* Complete syscall names.  Used by "catch syscall".  */
14094 static char **
14095 catch_syscall_completer (struct cmd_list_element *cmd,
14096                          char *text, char *word)
14097 {
14098   const char **list = get_syscall_names ();
14099   char **retlist
14100     = (list == NULL) ? NULL : complete_on_enum (list, text, word);
14101
14102   xfree (list);
14103   return retlist;
14104 }
14105
14106 /* Tracepoint-specific operations.  */
14107
14108 /* Set tracepoint count to NUM.  */
14109 static void
14110 set_tracepoint_count (int num)
14111 {
14112   tracepoint_count = num;
14113   set_internalvar_integer (lookup_internalvar ("tpnum"), num);
14114 }
14115
14116 static void
14117 trace_command (char *arg, int from_tty)
14118 {
14119   if (create_breakpoint (get_current_arch (),
14120                          arg,
14121                          NULL, 0, 1 /* parse arg */,
14122                          0 /* tempflag */,
14123                          bp_tracepoint /* type_wanted */,
14124                          0 /* Ignore count */,
14125                          pending_break_support,
14126                          &tracepoint_breakpoint_ops,
14127                          from_tty,
14128                          1 /* enabled */,
14129                          0 /* internal */))
14130     set_tracepoint_count (breakpoint_count);
14131 }
14132
14133 static void
14134 ftrace_command (char *arg, int from_tty)
14135 {
14136   if (create_breakpoint (get_current_arch (),
14137                          arg,
14138                          NULL, 0, 1 /* parse arg */,
14139                          0 /* tempflag */,
14140                          bp_fast_tracepoint /* type_wanted */,
14141                          0 /* Ignore count */,
14142                          pending_break_support,
14143                          &tracepoint_breakpoint_ops,
14144                          from_tty,
14145                          1 /* enabled */,
14146                          0 /* internal */))
14147     set_tracepoint_count (breakpoint_count);
14148 }
14149
14150 /* strace command implementation.  Creates a static tracepoint.  */
14151
14152 static void
14153 strace_command (char *arg, int from_tty)
14154 {
14155   struct breakpoint_ops *ops;
14156
14157   /* Decide if we are dealing with a static tracepoint marker (`-m'),
14158      or with a normal static tracepoint.  */
14159   if (arg && strncmp (arg, "-m", 2) == 0 && isspace (arg[2]))
14160     ops = &strace_marker_breakpoint_ops;
14161   else
14162     ops = &tracepoint_breakpoint_ops;
14163
14164   if (create_breakpoint (get_current_arch (),
14165                          arg,
14166                          NULL, 0, 1 /* parse arg */,
14167                          0 /* tempflag */,
14168                          bp_static_tracepoint /* type_wanted */,
14169                          0 /* Ignore count */,
14170                          pending_break_support,
14171                          ops,
14172                          from_tty,
14173                          1 /* enabled */,
14174                          0 /* internal */))
14175     set_tracepoint_count (breakpoint_count);
14176 }
14177
14178 /* Set up a fake reader function that gets command lines from a linked
14179    list that was acquired during tracepoint uploading.  */
14180
14181 static struct uploaded_tp *this_utp;
14182 static int next_cmd;
14183
14184 static char *
14185 read_uploaded_action (void)
14186 {
14187   char *rslt;
14188
14189   VEC_iterate (char_ptr, this_utp->cmd_strings, next_cmd, rslt);
14190
14191   next_cmd++;
14192
14193   return rslt;
14194 }
14195
14196 /* Given information about a tracepoint as recorded on a target (which
14197    can be either a live system or a trace file), attempt to create an
14198    equivalent GDB tracepoint.  This is not a reliable process, since
14199    the target does not necessarily have all the information used when
14200    the tracepoint was originally defined.  */
14201   
14202 struct tracepoint *
14203 create_tracepoint_from_upload (struct uploaded_tp *utp)
14204 {
14205   char *addr_str, small_buf[100];
14206   struct tracepoint *tp;
14207
14208   if (utp->at_string)
14209     addr_str = utp->at_string;
14210   else
14211     {
14212       /* In the absence of a source location, fall back to raw
14213          address.  Since there is no way to confirm that the address
14214          means the same thing as when the trace was started, warn the
14215          user.  */
14216       warning (_("Uploaded tracepoint %d has no "
14217                  "source location, using raw address"),
14218                utp->number);
14219       sprintf (small_buf, "*%s", hex_string (utp->addr));
14220       addr_str = small_buf;
14221     }
14222
14223   /* There's not much we can do with a sequence of bytecodes.  */
14224   if (utp->cond && !utp->cond_string)
14225     warning (_("Uploaded tracepoint %d condition "
14226                "has no source form, ignoring it"),
14227              utp->number);
14228
14229   if (!create_breakpoint (get_current_arch (),
14230                           addr_str,
14231                           utp->cond_string, -1, 0 /* parse cond/thread */,
14232                           0 /* tempflag */,
14233                           utp->type /* type_wanted */,
14234                           0 /* Ignore count */,
14235                           pending_break_support,
14236                           &tracepoint_breakpoint_ops,
14237                           0 /* from_tty */,
14238                           utp->enabled /* enabled */,
14239                           0 /* internal */))
14240     return NULL;
14241
14242   set_tracepoint_count (breakpoint_count);
14243   
14244   /* Get the tracepoint we just created.  */
14245   tp = get_tracepoint (tracepoint_count);
14246   gdb_assert (tp != NULL);
14247
14248   if (utp->pass > 0)
14249     {
14250       sprintf (small_buf, "%d %d", utp->pass, tp->base.number);
14251
14252       trace_pass_command (small_buf, 0);
14253     }
14254
14255   /* If we have uploaded versions of the original commands, set up a
14256      special-purpose "reader" function and call the usual command line
14257      reader, then pass the result to the breakpoint command-setting
14258      function.  */
14259   if (!VEC_empty (char_ptr, utp->cmd_strings))
14260     {
14261       struct command_line *cmd_list;
14262
14263       this_utp = utp;
14264       next_cmd = 0;
14265
14266       cmd_list = read_command_lines_1 (read_uploaded_action, 1, NULL, NULL);
14267
14268       breakpoint_set_commands (&tp->base, cmd_list);
14269     }
14270   else if (!VEC_empty (char_ptr, utp->actions)
14271            || !VEC_empty (char_ptr, utp->step_actions))
14272     warning (_("Uploaded tracepoint %d actions "
14273                "have no source form, ignoring them"),
14274              utp->number);
14275
14276   /* Copy any status information that might be available.  */
14277   tp->base.hit_count = utp->hit_count;
14278   tp->traceframe_usage = utp->traceframe_usage;
14279
14280   return tp;
14281 }
14282   
14283 /* Print information on tracepoint number TPNUM_EXP, or all if
14284    omitted.  */
14285
14286 static void
14287 tracepoints_info (char *args, int from_tty)
14288 {
14289   struct ui_out *uiout = current_uiout;
14290   int num_printed;
14291
14292   num_printed = breakpoint_1 (args, 0, is_tracepoint);
14293
14294   if (num_printed == 0)
14295     {
14296       if (args == NULL || *args == '\0')
14297         ui_out_message (uiout, 0, "No tracepoints.\n");
14298       else
14299         ui_out_message (uiout, 0, "No tracepoint matching '%s'.\n", args);
14300     }
14301
14302   default_collect_info ();
14303 }
14304
14305 /* The 'enable trace' command enables tracepoints.
14306    Not supported by all targets.  */
14307 static void
14308 enable_trace_command (char *args, int from_tty)
14309 {
14310   enable_command (args, from_tty);
14311 }
14312
14313 /* The 'disable trace' command disables tracepoints.
14314    Not supported by all targets.  */
14315 static void
14316 disable_trace_command (char *args, int from_tty)
14317 {
14318   disable_command (args, from_tty);
14319 }
14320
14321 /* Remove a tracepoint (or all if no argument).  */
14322 static void
14323 delete_trace_command (char *arg, int from_tty)
14324 {
14325   struct breakpoint *b, *b_tmp;
14326
14327   dont_repeat ();
14328
14329   if (arg == 0)
14330     {
14331       int breaks_to_delete = 0;
14332
14333       /* Delete all breakpoints if no argument.
14334          Do not delete internal or call-dummy breakpoints, these
14335          have to be deleted with an explicit breakpoint number 
14336          argument.  */
14337       ALL_TRACEPOINTS (b)
14338         if (is_tracepoint (b) && user_breakpoint_p (b))
14339           {
14340             breaks_to_delete = 1;
14341             break;
14342           }
14343
14344       /* Ask user only if there are some breakpoints to delete.  */
14345       if (!from_tty
14346           || (breaks_to_delete && query (_("Delete all tracepoints? "))))
14347         {
14348           ALL_BREAKPOINTS_SAFE (b, b_tmp)
14349             if (is_tracepoint (b) && user_breakpoint_p (b))
14350               delete_breakpoint (b);
14351         }
14352     }
14353   else
14354     map_breakpoint_numbers (arg, do_map_delete_breakpoint, NULL);
14355 }
14356
14357 /* Helper function for trace_pass_command.  */
14358
14359 static void
14360 trace_pass_set_count (struct tracepoint *tp, int count, int from_tty)
14361 {
14362   tp->pass_count = count;
14363   observer_notify_tracepoint_modified (tp->base.number);
14364   if (from_tty)
14365     printf_filtered (_("Setting tracepoint %d's passcount to %d\n"),
14366                      tp->base.number, count);
14367 }
14368
14369 /* Set passcount for tracepoint.
14370
14371    First command argument is passcount, second is tracepoint number.
14372    If tracepoint number omitted, apply to most recently defined.
14373    Also accepts special argument "all".  */
14374
14375 static void
14376 trace_pass_command (char *args, int from_tty)
14377 {
14378   struct tracepoint *t1;
14379   unsigned int count;
14380
14381   if (args == 0 || *args == 0)
14382     error (_("passcount command requires an "
14383              "argument (count + optional TP num)"));
14384
14385   count = strtoul (args, &args, 10);    /* Count comes first, then TP num.  */
14386
14387   while (*args && isspace ((int) *args))
14388     args++;
14389
14390   if (*args && strncasecmp (args, "all", 3) == 0)
14391     {
14392       struct breakpoint *b;
14393
14394       args += 3;                        /* Skip special argument "all".  */
14395       if (*args)
14396         error (_("Junk at end of arguments."));
14397
14398       ALL_TRACEPOINTS (b)
14399       {
14400         t1 = (struct tracepoint *) b;
14401         trace_pass_set_count (t1, count, from_tty);
14402       }
14403     }
14404   else if (*args == '\0')
14405     {
14406       t1 = get_tracepoint_by_number (&args, NULL, 1);
14407       if (t1)
14408         trace_pass_set_count (t1, count, from_tty);
14409     }
14410   else
14411     {
14412       struct get_number_or_range_state state;
14413
14414       init_number_or_range (&state, args);
14415       while (!state.finished)
14416         {
14417           t1 = get_tracepoint_by_number (&args, &state, 1);
14418           if (t1)
14419             trace_pass_set_count (t1, count, from_tty);
14420         }
14421     }
14422 }
14423
14424 struct tracepoint *
14425 get_tracepoint (int num)
14426 {
14427   struct breakpoint *t;
14428
14429   ALL_TRACEPOINTS (t)
14430     if (t->number == num)
14431       return (struct tracepoint *) t;
14432
14433   return NULL;
14434 }
14435
14436 /* Find the tracepoint with the given target-side number (which may be
14437    different from the tracepoint number after disconnecting and
14438    reconnecting).  */
14439
14440 struct tracepoint *
14441 get_tracepoint_by_number_on_target (int num)
14442 {
14443   struct breakpoint *b;
14444
14445   ALL_TRACEPOINTS (b)
14446     {
14447       struct tracepoint *t = (struct tracepoint *) b;
14448
14449       if (t->number_on_target == num)
14450         return t;
14451     }
14452
14453   return NULL;
14454 }
14455
14456 /* Utility: parse a tracepoint number and look it up in the list.
14457    If STATE is not NULL, use, get_number_or_range_state and ignore ARG.
14458    If OPTIONAL_P is true, then if the argument is missing, the most
14459    recent tracepoint (tracepoint_count) is returned.  */
14460 struct tracepoint *
14461 get_tracepoint_by_number (char **arg,
14462                           struct get_number_or_range_state *state,
14463                           int optional_p)
14464 {
14465   extern int tracepoint_count;
14466   struct breakpoint *t;
14467   int tpnum;
14468   char *instring = arg == NULL ? NULL : *arg;
14469
14470   if (state)
14471     {
14472       gdb_assert (!state->finished);
14473       tpnum = get_number_or_range (state);
14474     }
14475   else if (arg == NULL || *arg == NULL || ! **arg)
14476     {
14477       if (optional_p)
14478         tpnum = tracepoint_count;
14479       else
14480         error_no_arg (_("tracepoint number"));
14481     }
14482   else
14483     tpnum = get_number (arg);
14484
14485   if (tpnum <= 0)
14486     {
14487       if (instring && *instring)
14488         printf_filtered (_("bad tracepoint number at or near '%s'\n"), 
14489                          instring);
14490       else
14491         printf_filtered (_("Tracepoint argument missing "
14492                            "and no previous tracepoint\n"));
14493       return NULL;
14494     }
14495
14496   ALL_TRACEPOINTS (t)
14497     if (t->number == tpnum)
14498     {
14499       return (struct tracepoint *) t;
14500     }
14501
14502   printf_unfiltered ("No tracepoint number %d.\n", tpnum);
14503   return NULL;
14504 }
14505
14506 void
14507 print_recreate_thread (struct breakpoint *b, struct ui_file *fp)
14508 {
14509   if (b->thread != -1)
14510     fprintf_unfiltered (fp, " thread %d", b->thread);
14511
14512   if (b->task != 0)
14513     fprintf_unfiltered (fp, " task %d", b->task);
14514
14515   fprintf_unfiltered (fp, "\n");
14516 }
14517
14518 /* Save information on user settable breakpoints (watchpoints, etc) to
14519    a new script file named FILENAME.  If FILTER is non-NULL, call it
14520    on each breakpoint and only include the ones for which it returns
14521    non-zero.  */
14522
14523 static void
14524 save_breakpoints (char *filename, int from_tty,
14525                   int (*filter) (const struct breakpoint *))
14526 {
14527   struct breakpoint *tp;
14528   int any = 0;
14529   char *pathname;
14530   struct cleanup *cleanup;
14531   struct ui_file *fp;
14532   int extra_trace_bits = 0;
14533
14534   if (filename == 0 || *filename == 0)
14535     error (_("Argument required (file name in which to save)"));
14536
14537   /* See if we have anything to save.  */
14538   ALL_BREAKPOINTS (tp)
14539   {
14540     /* Skip internal and momentary breakpoints.  */
14541     if (!user_breakpoint_p (tp))
14542       continue;
14543
14544     /* If we have a filter, only save the breakpoints it accepts.  */
14545     if (filter && !filter (tp))
14546       continue;
14547
14548     any = 1;
14549
14550     if (is_tracepoint (tp))
14551       {
14552         extra_trace_bits = 1;
14553
14554         /* We can stop searching.  */
14555         break;
14556       }
14557   }
14558
14559   if (!any)
14560     {
14561       warning (_("Nothing to save."));
14562       return;
14563     }
14564
14565   pathname = tilde_expand (filename);
14566   cleanup = make_cleanup (xfree, pathname);
14567   fp = gdb_fopen (pathname, "w");
14568   if (!fp)
14569     error (_("Unable to open file '%s' for saving (%s)"),
14570            filename, safe_strerror (errno));
14571   make_cleanup_ui_file_delete (fp);
14572
14573   if (extra_trace_bits)
14574     save_trace_state_variables (fp);
14575
14576   ALL_BREAKPOINTS (tp)
14577   {
14578     /* Skip internal and momentary breakpoints.  */
14579     if (!user_breakpoint_p (tp))
14580       continue;
14581
14582     /* If we have a filter, only save the breakpoints it accepts.  */
14583     if (filter && !filter (tp))
14584       continue;
14585
14586     tp->ops->print_recreate (tp, fp);
14587
14588     /* Note, we can't rely on tp->number for anything, as we can't
14589        assume the recreated breakpoint numbers will match.  Use $bpnum
14590        instead.  */
14591
14592     if (tp->cond_string)
14593       fprintf_unfiltered (fp, "  condition $bpnum %s\n", tp->cond_string);
14594
14595     if (tp->ignore_count)
14596       fprintf_unfiltered (fp, "  ignore $bpnum %d\n", tp->ignore_count);
14597
14598     if (tp->commands)
14599       {
14600         volatile struct gdb_exception ex;       
14601
14602         fprintf_unfiltered (fp, "  commands\n");
14603         
14604         ui_out_redirect (current_uiout, fp);
14605         TRY_CATCH (ex, RETURN_MASK_ALL)
14606           {
14607             print_command_lines (current_uiout, tp->commands->commands, 2);
14608           }
14609         ui_out_redirect (current_uiout, NULL);
14610
14611         if (ex.reason < 0)
14612           throw_exception (ex);
14613
14614         fprintf_unfiltered (fp, "  end\n");
14615       }
14616
14617     if (tp->enable_state == bp_disabled)
14618       fprintf_unfiltered (fp, "disable\n");
14619
14620     /* If this is a multi-location breakpoint, check if the locations
14621        should be individually disabled.  Watchpoint locations are
14622        special, and not user visible.  */
14623     if (!is_watchpoint (tp) && tp->loc && tp->loc->next)
14624       {
14625         struct bp_location *loc;
14626         int n = 1;
14627
14628         for (loc = tp->loc; loc != NULL; loc = loc->next, n++)
14629           if (!loc->enabled)
14630             fprintf_unfiltered (fp, "disable $bpnum.%d\n", n);
14631       }
14632   }
14633
14634   if (extra_trace_bits && *default_collect)
14635     fprintf_unfiltered (fp, "set default-collect %s\n", default_collect);
14636
14637   do_cleanups (cleanup);
14638   if (from_tty)
14639     printf_filtered (_("Saved to file '%s'.\n"), filename);
14640 }
14641
14642 /* The `save breakpoints' command.  */
14643
14644 static void
14645 save_breakpoints_command (char *args, int from_tty)
14646 {
14647   save_breakpoints (args, from_tty, NULL);
14648 }
14649
14650 /* The `save tracepoints' command.  */
14651
14652 static void
14653 save_tracepoints_command (char *args, int from_tty)
14654 {
14655   save_breakpoints (args, from_tty, is_tracepoint);
14656 }
14657
14658 /* Create a vector of all tracepoints.  */
14659
14660 VEC(breakpoint_p) *
14661 all_tracepoints (void)
14662 {
14663   VEC(breakpoint_p) *tp_vec = 0;
14664   struct breakpoint *tp;
14665
14666   ALL_TRACEPOINTS (tp)
14667   {
14668     VEC_safe_push (breakpoint_p, tp_vec, tp);
14669   }
14670
14671   return tp_vec;
14672 }
14673
14674 \f
14675 /* This help string is used for the break, hbreak, tbreak and thbreak
14676    commands.  It is defined as a macro to prevent duplication.
14677    COMMAND should be a string constant containing the name of the
14678    command.  */
14679 #define BREAK_ARGS_HELP(command) \
14680 command" [LOCATION] [thread THREADNUM] [if CONDITION]\n\
14681 LOCATION may be a line number, function name, or \"*\" and an address.\n\
14682 If a line number is specified, break at start of code for that line.\n\
14683 If a function is specified, break at start of code for that function.\n\
14684 If an address is specified, break at that exact address.\n\
14685 With no LOCATION, uses current execution address of the selected\n\
14686 stack frame.  This is useful for breaking on return to a stack frame.\n\
14687 \n\
14688 THREADNUM is the number from \"info threads\".\n\
14689 CONDITION is a boolean expression.\n\
14690 \n\
14691 Multiple breakpoints at one place are permitted, and useful if their\n\
14692 conditions are different.\n\
14693 \n\
14694 Do \"help breakpoints\" for info on other commands dealing with breakpoints."
14695
14696 /* List of subcommands for "catch".  */
14697 static struct cmd_list_element *catch_cmdlist;
14698
14699 /* List of subcommands for "tcatch".  */
14700 static struct cmd_list_element *tcatch_cmdlist;
14701
14702 void
14703 add_catch_command (char *name, char *docstring,
14704                    void (*sfunc) (char *args, int from_tty,
14705                                   struct cmd_list_element *command),
14706                    char **(*completer) (struct cmd_list_element *cmd,
14707                                          char *text, char *word),
14708                    void *user_data_catch,
14709                    void *user_data_tcatch)
14710 {
14711   struct cmd_list_element *command;
14712
14713   command = add_cmd (name, class_breakpoint, NULL, docstring,
14714                      &catch_cmdlist);
14715   set_cmd_sfunc (command, sfunc);
14716   set_cmd_context (command, user_data_catch);
14717   set_cmd_completer (command, completer);
14718
14719   command = add_cmd (name, class_breakpoint, NULL, docstring,
14720                      &tcatch_cmdlist);
14721   set_cmd_sfunc (command, sfunc);
14722   set_cmd_context (command, user_data_tcatch);
14723   set_cmd_completer (command, completer);
14724 }
14725
14726 static void
14727 clear_syscall_counts (struct inferior *inf)
14728 {
14729   inf->total_syscalls_count = 0;
14730   inf->any_syscall_count = 0;
14731   VEC_free (int, inf->syscalls_counts);
14732 }
14733
14734 static void
14735 save_command (char *arg, int from_tty)
14736 {
14737   printf_unfiltered (_("\"save\" must be followed by "
14738                        "the name of a save subcommand.\n"));
14739   help_list (save_cmdlist, "save ", -1, gdb_stdout);
14740 }
14741
14742 struct breakpoint *
14743 iterate_over_breakpoints (int (*callback) (struct breakpoint *, void *),
14744                           void *data)
14745 {
14746   struct breakpoint *b, *b_tmp;
14747
14748   ALL_BREAKPOINTS_SAFE (b, b_tmp)
14749     {
14750       if ((*callback) (b, data))
14751         return b;
14752     }
14753
14754   return NULL;
14755 }
14756
14757 /* Zero if any of the breakpoint's locations could be a location where
14758    functions have been inlined, nonzero otherwise.  */
14759
14760 static int
14761 is_non_inline_function (struct breakpoint *b)
14762 {
14763   /* The shared library event breakpoint is set on the address of a
14764      non-inline function.  */
14765   if (b->type == bp_shlib_event)
14766     return 1;
14767
14768   return 0;
14769 }
14770
14771 /* Nonzero if the specified PC cannot be a location where functions
14772    have been inlined.  */
14773
14774 int
14775 pc_at_non_inline_function (struct address_space *aspace, CORE_ADDR pc,
14776                            const struct target_waitstatus *ws)
14777 {
14778   struct breakpoint *b;
14779   struct bp_location *bl;
14780
14781   ALL_BREAKPOINTS (b)
14782     {
14783       if (!is_non_inline_function (b))
14784         continue;
14785
14786       for (bl = b->loc; bl != NULL; bl = bl->next)
14787         {
14788           if (!bl->shlib_disabled
14789               && bpstat_check_location (bl, aspace, pc, ws))
14790             return 1;
14791         }
14792     }
14793
14794   return 0;
14795 }
14796
14797 void
14798 initialize_breakpoint_ops (void)
14799 {
14800   static int initialized = 0;
14801
14802   struct breakpoint_ops *ops;
14803
14804   if (initialized)
14805     return;
14806   initialized = 1;
14807
14808   /* The breakpoint_ops structure to be inherit by all kinds of
14809      breakpoints (real breakpoints, i.e., user "break" breakpoints,
14810      internal and momentary breakpoints, etc.).  */
14811   ops = &bkpt_base_breakpoint_ops;
14812   *ops = base_breakpoint_ops;
14813   ops->re_set = bkpt_re_set;
14814   ops->insert_location = bkpt_insert_location;
14815   ops->remove_location = bkpt_remove_location;
14816   ops->breakpoint_hit = bkpt_breakpoint_hit;
14817   ops->create_sals_from_address = bkpt_create_sals_from_address;
14818   ops->create_breakpoints_sal = bkpt_create_breakpoints_sal;
14819   ops->decode_linespec = bkpt_decode_linespec;
14820
14821   /* The breakpoint_ops structure to be used in regular breakpoints.  */
14822   ops = &bkpt_breakpoint_ops;
14823   *ops = bkpt_base_breakpoint_ops;
14824   ops->re_set = bkpt_re_set;
14825   ops->resources_needed = bkpt_resources_needed;
14826   ops->print_it = bkpt_print_it;
14827   ops->print_mention = bkpt_print_mention;
14828   ops->print_recreate = bkpt_print_recreate;
14829
14830   /* Ranged breakpoints.  */
14831   ops = &ranged_breakpoint_ops;
14832   *ops = bkpt_breakpoint_ops;
14833   ops->breakpoint_hit = breakpoint_hit_ranged_breakpoint;
14834   ops->resources_needed = resources_needed_ranged_breakpoint;
14835   ops->print_it = print_it_ranged_breakpoint;
14836   ops->print_one = print_one_ranged_breakpoint;
14837   ops->print_one_detail = print_one_detail_ranged_breakpoint;
14838   ops->print_mention = print_mention_ranged_breakpoint;
14839   ops->print_recreate = print_recreate_ranged_breakpoint;
14840
14841   /* Internal breakpoints.  */
14842   ops = &internal_breakpoint_ops;
14843   *ops = bkpt_base_breakpoint_ops;
14844   ops->re_set = internal_bkpt_re_set;
14845   ops->check_status = internal_bkpt_check_status;
14846   ops->print_it = internal_bkpt_print_it;
14847   ops->print_mention = internal_bkpt_print_mention;
14848
14849   /* Momentary breakpoints.  */
14850   ops = &momentary_breakpoint_ops;
14851   *ops = bkpt_base_breakpoint_ops;
14852   ops->re_set = momentary_bkpt_re_set;
14853   ops->check_status = momentary_bkpt_check_status;
14854   ops->print_it = momentary_bkpt_print_it;
14855   ops->print_mention = momentary_bkpt_print_mention;
14856
14857   /* GNU v3 exception catchpoints.  */
14858   ops = &gnu_v3_exception_catchpoint_ops;
14859   *ops = bkpt_breakpoint_ops;
14860   ops->print_it = print_it_exception_catchpoint;
14861   ops->print_one = print_one_exception_catchpoint;
14862   ops->print_mention = print_mention_exception_catchpoint;
14863   ops->print_recreate = print_recreate_exception_catchpoint;
14864
14865   /* Watchpoints.  */
14866   ops = &watchpoint_breakpoint_ops;
14867   *ops = base_breakpoint_ops;
14868   ops->dtor = dtor_watchpoint;
14869   ops->re_set = re_set_watchpoint;
14870   ops->insert_location = insert_watchpoint;
14871   ops->remove_location = remove_watchpoint;
14872   ops->breakpoint_hit = breakpoint_hit_watchpoint;
14873   ops->check_status = check_status_watchpoint;
14874   ops->resources_needed = resources_needed_watchpoint;
14875   ops->works_in_software_mode = works_in_software_mode_watchpoint;
14876   ops->print_it = print_it_watchpoint;
14877   ops->print_mention = print_mention_watchpoint;
14878   ops->print_recreate = print_recreate_watchpoint;
14879
14880   /* Masked watchpoints.  */
14881   ops = &masked_watchpoint_breakpoint_ops;
14882   *ops = watchpoint_breakpoint_ops;
14883   ops->insert_location = insert_masked_watchpoint;
14884   ops->remove_location = remove_masked_watchpoint;
14885   ops->resources_needed = resources_needed_masked_watchpoint;
14886   ops->works_in_software_mode = works_in_software_mode_masked_watchpoint;
14887   ops->print_it = print_it_masked_watchpoint;
14888   ops->print_one_detail = print_one_detail_masked_watchpoint;
14889   ops->print_mention = print_mention_masked_watchpoint;
14890   ops->print_recreate = print_recreate_masked_watchpoint;
14891
14892   /* Tracepoints.  */
14893   ops = &tracepoint_breakpoint_ops;
14894   *ops = base_breakpoint_ops;
14895   ops->re_set = tracepoint_re_set;
14896   ops->breakpoint_hit = tracepoint_breakpoint_hit;
14897   ops->print_one_detail = tracepoint_print_one_detail;
14898   ops->print_mention = tracepoint_print_mention;
14899   ops->print_recreate = tracepoint_print_recreate;
14900   ops->create_sals_from_address = tracepoint_create_sals_from_address;
14901   ops->create_breakpoints_sal = tracepoint_create_breakpoints_sal;
14902   ops->decode_linespec = tracepoint_decode_linespec;
14903
14904   /* Static tracepoints with marker (`-m').  */
14905   ops = &strace_marker_breakpoint_ops;
14906   *ops = tracepoint_breakpoint_ops;
14907   ops->create_sals_from_address = strace_marker_create_sals_from_address;
14908   ops->create_breakpoints_sal = strace_marker_create_breakpoints_sal;
14909   ops->decode_linespec = strace_marker_decode_linespec;
14910
14911   /* Fork catchpoints.  */
14912   ops = &catch_fork_breakpoint_ops;
14913   *ops = base_breakpoint_ops;
14914   ops->insert_location = insert_catch_fork;
14915   ops->remove_location = remove_catch_fork;
14916   ops->breakpoint_hit = breakpoint_hit_catch_fork;
14917   ops->print_it = print_it_catch_fork;
14918   ops->print_one = print_one_catch_fork;
14919   ops->print_mention = print_mention_catch_fork;
14920   ops->print_recreate = print_recreate_catch_fork;
14921
14922   /* Vfork catchpoints.  */
14923   ops = &catch_vfork_breakpoint_ops;
14924   *ops = base_breakpoint_ops;
14925   ops->insert_location = insert_catch_vfork;
14926   ops->remove_location = remove_catch_vfork;
14927   ops->breakpoint_hit = breakpoint_hit_catch_vfork;
14928   ops->print_it = print_it_catch_vfork;
14929   ops->print_one = print_one_catch_vfork;
14930   ops->print_mention = print_mention_catch_vfork;
14931   ops->print_recreate = print_recreate_catch_vfork;
14932
14933   /* Exec catchpoints.  */
14934   ops = &catch_exec_breakpoint_ops;
14935   *ops = base_breakpoint_ops;
14936   ops->dtor = dtor_catch_exec;
14937   ops->insert_location = insert_catch_exec;
14938   ops->remove_location = remove_catch_exec;
14939   ops->breakpoint_hit = breakpoint_hit_catch_exec;
14940   ops->print_it = print_it_catch_exec;
14941   ops->print_one = print_one_catch_exec;
14942   ops->print_mention = print_mention_catch_exec;
14943   ops->print_recreate = print_recreate_catch_exec;
14944
14945   /* Syscall catchpoints.  */
14946   ops = &catch_syscall_breakpoint_ops;
14947   *ops = base_breakpoint_ops;
14948   ops->dtor = dtor_catch_syscall;
14949   ops->insert_location = insert_catch_syscall;
14950   ops->remove_location = remove_catch_syscall;
14951   ops->breakpoint_hit = breakpoint_hit_catch_syscall;
14952   ops->print_it = print_it_catch_syscall;
14953   ops->print_one = print_one_catch_syscall;
14954   ops->print_mention = print_mention_catch_syscall;
14955   ops->print_recreate = print_recreate_catch_syscall;
14956
14957   /* Solib-related catchpoints.  */
14958   ops = &catch_solib_breakpoint_ops;
14959   *ops = base_breakpoint_ops;
14960   ops->dtor = dtor_catch_solib;
14961   ops->insert_location = insert_catch_solib;
14962   ops->remove_location = remove_catch_solib;
14963   ops->breakpoint_hit = breakpoint_hit_catch_solib;
14964   ops->check_status = check_status_catch_solib;
14965   ops->print_it = print_it_catch_solib;
14966   ops->print_one = print_one_catch_solib;
14967   ops->print_mention = print_mention_catch_solib;
14968   ops->print_recreate = print_recreate_catch_solib;
14969 }
14970
14971 void
14972 _initialize_breakpoint (void)
14973 {
14974   struct cmd_list_element *c;
14975
14976   initialize_breakpoint_ops ();
14977
14978   observer_attach_solib_unloaded (disable_breakpoints_in_unloaded_shlib);
14979   observer_attach_inferior_exit (clear_syscall_counts);
14980   observer_attach_memory_changed (invalidate_bp_value_on_memory_change);
14981
14982   breakpoint_objfile_key = register_objfile_data ();
14983
14984   breakpoint_chain = 0;
14985   /* Don't bother to call set_breakpoint_count.  $bpnum isn't useful
14986      before a breakpoint is set.  */
14987   breakpoint_count = 0;
14988
14989   tracepoint_count = 0;
14990
14991   add_com ("ignore", class_breakpoint, ignore_command, _("\
14992 Set ignore-count of breakpoint number N to COUNT.\n\
14993 Usage is `ignore N COUNT'."));
14994   if (xdb_commands)
14995     add_com_alias ("bc", "ignore", class_breakpoint, 1);
14996
14997   add_com ("commands", class_breakpoint, commands_command, _("\
14998 Set commands to be executed when a breakpoint is hit.\n\
14999 Give breakpoint number as argument after \"commands\".\n\
15000 With no argument, the targeted breakpoint is the last one set.\n\
15001 The commands themselves follow starting on the next line.\n\
15002 Type a line containing \"end\" to indicate the end of them.\n\
15003 Give \"silent\" as the first line to make the breakpoint silent;\n\
15004 then no output is printed when it is hit, except what the commands print."));
15005
15006   add_com ("condition", class_breakpoint, condition_command, _("\
15007 Specify breakpoint number N to break only if COND is true.\n\
15008 Usage is `condition N COND', where N is an integer and COND is an\n\
15009 expression to be evaluated whenever breakpoint N is reached."));
15010
15011   c = add_com ("tbreak", class_breakpoint, tbreak_command, _("\
15012 Set a temporary breakpoint.\n\
15013 Like \"break\" except the breakpoint is only temporary,\n\
15014 so it will be deleted when hit.  Equivalent to \"break\" followed\n\
15015 by using \"enable delete\" on the breakpoint number.\n\
15016 \n"
15017 BREAK_ARGS_HELP ("tbreak")));
15018   set_cmd_completer (c, location_completer);
15019
15020   c = add_com ("hbreak", class_breakpoint, hbreak_command, _("\
15021 Set a hardware assisted breakpoint.\n\
15022 Like \"break\" except the breakpoint requires hardware support,\n\
15023 some target hardware may not have this support.\n\
15024 \n"
15025 BREAK_ARGS_HELP ("hbreak")));
15026   set_cmd_completer (c, location_completer);
15027
15028   c = add_com ("thbreak", class_breakpoint, thbreak_command, _("\
15029 Set a temporary hardware assisted breakpoint.\n\
15030 Like \"hbreak\" except the breakpoint is only temporary,\n\
15031 so it will be deleted when hit.\n\
15032 \n"
15033 BREAK_ARGS_HELP ("thbreak")));
15034   set_cmd_completer (c, location_completer);
15035
15036   add_prefix_cmd ("enable", class_breakpoint, enable_command, _("\
15037 Enable some breakpoints.\n\
15038 Give breakpoint numbers (separated by spaces) as arguments.\n\
15039 With no subcommand, breakpoints are enabled until you command otherwise.\n\
15040 This is used to cancel the effect of the \"disable\" command.\n\
15041 With a subcommand you can enable temporarily."),
15042                   &enablelist, "enable ", 1, &cmdlist);
15043   if (xdb_commands)
15044     add_com ("ab", class_breakpoint, enable_command, _("\
15045 Enable some breakpoints.\n\
15046 Give breakpoint numbers (separated by spaces) as arguments.\n\
15047 With no subcommand, breakpoints are enabled until you command otherwise.\n\
15048 This is used to cancel the effect of the \"disable\" command.\n\
15049 With a subcommand you can enable temporarily."));
15050
15051   add_com_alias ("en", "enable", class_breakpoint, 1);
15052
15053   add_prefix_cmd ("breakpoints", class_breakpoint, enable_command, _("\
15054 Enable some breakpoints.\n\
15055 Give breakpoint numbers (separated by spaces) as arguments.\n\
15056 This is used to cancel the effect of the \"disable\" command.\n\
15057 May be abbreviated to simply \"enable\".\n"),
15058                    &enablebreaklist, "enable breakpoints ", 1, &enablelist);
15059
15060   add_cmd ("once", no_class, enable_once_command, _("\
15061 Enable breakpoints for one hit.  Give breakpoint numbers.\n\
15062 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
15063            &enablebreaklist);
15064
15065   add_cmd ("delete", no_class, enable_delete_command, _("\
15066 Enable breakpoints and delete when hit.  Give breakpoint numbers.\n\
15067 If a breakpoint is hit while enabled in this fashion, it is deleted."),
15068            &enablebreaklist);
15069
15070   add_cmd ("count", no_class, enable_count_command, _("\
15071 Enable breakpoints for COUNT hits.  Give count and then breakpoint numbers.\n\
15072 If a breakpoint is hit while enabled in this fashion,\n\
15073 the count is decremented; when it reaches zero, the breakpoint is disabled."),
15074            &enablebreaklist);
15075
15076   add_cmd ("delete", no_class, enable_delete_command, _("\
15077 Enable breakpoints and delete when hit.  Give breakpoint numbers.\n\
15078 If a breakpoint is hit while enabled in this fashion, it is deleted."),
15079            &enablelist);
15080
15081   add_cmd ("once", no_class, enable_once_command, _("\
15082 Enable breakpoints for one hit.  Give breakpoint numbers.\n\
15083 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
15084            &enablelist);
15085
15086   add_cmd ("count", no_class, enable_count_command, _("\
15087 Enable breakpoints for COUNT hits.  Give count and then breakpoint numbers.\n\
15088 If a breakpoint is hit while enabled in this fashion,\n\
15089 the count is decremented; when it reaches zero, the breakpoint is disabled."),
15090            &enablelist);
15091
15092   add_prefix_cmd ("disable", class_breakpoint, disable_command, _("\
15093 Disable some breakpoints.\n\
15094 Arguments are breakpoint numbers with spaces in between.\n\
15095 To disable all breakpoints, give no argument.\n\
15096 A disabled breakpoint is not forgotten, but has no effect until re-enabled."),
15097                   &disablelist, "disable ", 1, &cmdlist);
15098   add_com_alias ("dis", "disable", class_breakpoint, 1);
15099   add_com_alias ("disa", "disable", class_breakpoint, 1);
15100   if (xdb_commands)
15101     add_com ("sb", class_breakpoint, disable_command, _("\
15102 Disable some breakpoints.\n\
15103 Arguments are breakpoint numbers with spaces in between.\n\
15104 To disable all breakpoints, give no argument.\n\
15105 A disabled breakpoint is not forgotten, but has no effect until re-enabled."));
15106
15107   add_cmd ("breakpoints", class_alias, disable_command, _("\
15108 Disable some breakpoints.\n\
15109 Arguments are breakpoint numbers with spaces in between.\n\
15110 To disable all breakpoints, give no argument.\n\
15111 A disabled breakpoint is not forgotten, but has no effect until re-enabled.\n\
15112 This command may be abbreviated \"disable\"."),
15113            &disablelist);
15114
15115   add_prefix_cmd ("delete", class_breakpoint, delete_command, _("\
15116 Delete some breakpoints or auto-display expressions.\n\
15117 Arguments are breakpoint numbers with spaces in between.\n\
15118 To delete all breakpoints, give no argument.\n\
15119 \n\
15120 Also a prefix command for deletion of other GDB objects.\n\
15121 The \"unset\" command is also an alias for \"delete\"."),
15122                   &deletelist, "delete ", 1, &cmdlist);
15123   add_com_alias ("d", "delete", class_breakpoint, 1);
15124   add_com_alias ("del", "delete", class_breakpoint, 1);
15125   if (xdb_commands)
15126     add_com ("db", class_breakpoint, delete_command, _("\
15127 Delete some breakpoints.\n\
15128 Arguments are breakpoint numbers with spaces in between.\n\
15129 To delete all breakpoints, give no argument.\n"));
15130
15131   add_cmd ("breakpoints", class_alias, delete_command, _("\
15132 Delete some breakpoints or auto-display expressions.\n\
15133 Arguments are breakpoint numbers with spaces in between.\n\
15134 To delete all breakpoints, give no argument.\n\
15135 This command may be abbreviated \"delete\"."),
15136            &deletelist);
15137
15138   add_com ("clear", class_breakpoint, clear_command, _("\
15139 Clear breakpoint at specified line or function.\n\
15140 Argument may be line number, function name, or \"*\" and an address.\n\
15141 If line number is specified, all breakpoints in that line are cleared.\n\
15142 If function is specified, breakpoints at beginning of function are cleared.\n\
15143 If an address is specified, breakpoints at that address are cleared.\n\
15144 \n\
15145 With no argument, clears all breakpoints in the line that the selected frame\n\
15146 is executing in.\n\
15147 \n\
15148 See also the \"delete\" command which clears breakpoints by number."));
15149   add_com_alias ("cl", "clear", class_breakpoint, 1);
15150
15151   c = add_com ("break", class_breakpoint, break_command, _("\
15152 Set breakpoint at specified line or function.\n"
15153 BREAK_ARGS_HELP ("break")));
15154   set_cmd_completer (c, location_completer);
15155
15156   add_com_alias ("b", "break", class_run, 1);
15157   add_com_alias ("br", "break", class_run, 1);
15158   add_com_alias ("bre", "break", class_run, 1);
15159   add_com_alias ("brea", "break", class_run, 1);
15160
15161   if (xdb_commands)
15162    add_com_alias ("ba", "break", class_breakpoint, 1);
15163
15164   if (dbx_commands)
15165     {
15166       add_abbrev_prefix_cmd ("stop", class_breakpoint, stop_command, _("\
15167 Break in function/address or break at a line in the current file."),
15168                              &stoplist, "stop ", 1, &cmdlist);
15169       add_cmd ("in", class_breakpoint, stopin_command,
15170                _("Break in function or address."), &stoplist);
15171       add_cmd ("at", class_breakpoint, stopat_command,
15172                _("Break at a line in the current file."), &stoplist);
15173       add_com ("status", class_info, breakpoints_info, _("\
15174 Status of user-settable breakpoints, or breakpoint number NUMBER.\n\
15175 The \"Type\" column indicates one of:\n\
15176 \tbreakpoint     - normal breakpoint\n\
15177 \twatchpoint     - watchpoint\n\
15178 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
15179 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
15180 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
15181 address and file/line number respectively.\n\
15182 \n\
15183 Convenience variable \"$_\" and default examine address for \"x\"\n\
15184 are set to the address of the last breakpoint listed unless the command\n\
15185 is prefixed with \"server \".\n\n\
15186 Convenience variable \"$bpnum\" contains the number of the last\n\
15187 breakpoint set."));
15188     }
15189
15190   add_info ("breakpoints", breakpoints_info, _("\
15191 Status of specified breakpoints (all user-settable breakpoints if no argument).\n\
15192 The \"Type\" column indicates one of:\n\
15193 \tbreakpoint     - normal breakpoint\n\
15194 \twatchpoint     - watchpoint\n\
15195 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
15196 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
15197 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
15198 address and file/line number respectively.\n\
15199 \n\
15200 Convenience variable \"$_\" and default examine address for \"x\"\n\
15201 are set to the address of the last breakpoint listed unless the command\n\
15202 is prefixed with \"server \".\n\n\
15203 Convenience variable \"$bpnum\" contains the number of the last\n\
15204 breakpoint set."));
15205
15206   add_info_alias ("b", "breakpoints", 1);
15207
15208   if (xdb_commands)
15209     add_com ("lb", class_breakpoint, breakpoints_info, _("\
15210 Status of user-settable breakpoints, or breakpoint number NUMBER.\n\
15211 The \"Type\" column indicates one of:\n\
15212 \tbreakpoint     - normal breakpoint\n\
15213 \twatchpoint     - watchpoint\n\
15214 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
15215 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
15216 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
15217 address and file/line number respectively.\n\
15218 \n\
15219 Convenience variable \"$_\" and default examine address for \"x\"\n\
15220 are set to the address of the last breakpoint listed unless the command\n\
15221 is prefixed with \"server \".\n\n\
15222 Convenience variable \"$bpnum\" contains the number of the last\n\
15223 breakpoint set."));
15224
15225   add_cmd ("breakpoints", class_maintenance, maintenance_info_breakpoints, _("\
15226 Status of all breakpoints, or breakpoint number NUMBER.\n\
15227 The \"Type\" column indicates one of:\n\
15228 \tbreakpoint     - normal breakpoint\n\
15229 \twatchpoint     - watchpoint\n\
15230 \tlongjmp        - internal breakpoint used to step through longjmp()\n\
15231 \tlongjmp resume - internal breakpoint at the target of longjmp()\n\
15232 \tuntil          - internal breakpoint used by the \"until\" command\n\
15233 \tfinish         - internal breakpoint used by the \"finish\" command\n\
15234 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
15235 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
15236 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
15237 address and file/line number respectively.\n\
15238 \n\
15239 Convenience variable \"$_\" and default examine address for \"x\"\n\
15240 are set to the address of the last breakpoint listed unless the command\n\
15241 is prefixed with \"server \".\n\n\
15242 Convenience variable \"$bpnum\" contains the number of the last\n\
15243 breakpoint set."),
15244            &maintenanceinfolist);
15245
15246   add_prefix_cmd ("catch", class_breakpoint, catch_command, _("\
15247 Set catchpoints to catch events."),
15248                   &catch_cmdlist, "catch ",
15249                   0/*allow-unknown*/, &cmdlist);
15250
15251   add_prefix_cmd ("tcatch", class_breakpoint, tcatch_command, _("\
15252 Set temporary catchpoints to catch events."),
15253                   &tcatch_cmdlist, "tcatch ",
15254                   0/*allow-unknown*/, &cmdlist);
15255
15256   /* Add catch and tcatch sub-commands.  */
15257   add_catch_command ("catch", _("\
15258 Catch an exception, when caught."),
15259                      catch_catch_command,
15260                      NULL,
15261                      CATCH_PERMANENT,
15262                      CATCH_TEMPORARY);
15263   add_catch_command ("throw", _("\
15264 Catch an exception, when thrown."),
15265                      catch_throw_command,
15266                      NULL,
15267                      CATCH_PERMANENT,
15268                      CATCH_TEMPORARY);
15269   add_catch_command ("fork", _("Catch calls to fork."),
15270                      catch_fork_command_1,
15271                      NULL,
15272                      (void *) (uintptr_t) catch_fork_permanent,
15273                      (void *) (uintptr_t) catch_fork_temporary);
15274   add_catch_command ("vfork", _("Catch calls to vfork."),
15275                      catch_fork_command_1,
15276                      NULL,
15277                      (void *) (uintptr_t) catch_vfork_permanent,
15278                      (void *) (uintptr_t) catch_vfork_temporary);
15279   add_catch_command ("exec", _("Catch calls to exec."),
15280                      catch_exec_command_1,
15281                      NULL,
15282                      CATCH_PERMANENT,
15283                      CATCH_TEMPORARY);
15284   add_catch_command ("load", _("Catch loads of shared libraries.\n\
15285 Usage: catch load [REGEX]\n\
15286 If REGEX is given, only stop for libraries matching the regular expression."),
15287                      catch_load_command_1,
15288                      NULL,
15289                      CATCH_PERMANENT,
15290                      CATCH_TEMPORARY);
15291   add_catch_command ("unload", _("Catch unloads of shared libraries.\n\
15292 Usage: catch unload [REGEX]\n\
15293 If REGEX is given, only stop for libraries matching the regular expression."),
15294                      catch_unload_command_1,
15295                      NULL,
15296                      CATCH_PERMANENT,
15297                      CATCH_TEMPORARY);
15298   add_catch_command ("syscall", _("\
15299 Catch system calls by their names and/or numbers.\n\
15300 Arguments say which system calls to catch.  If no arguments\n\
15301 are given, every system call will be caught.\n\
15302 Arguments, if given, should be one or more system call names\n\
15303 (if your system supports that), or system call numbers."),
15304                      catch_syscall_command_1,
15305                      catch_syscall_completer,
15306                      CATCH_PERMANENT,
15307                      CATCH_TEMPORARY);
15308
15309   c = add_com ("watch", class_breakpoint, watch_command, _("\
15310 Set a watchpoint for an expression.\n\
15311 Usage: watch [-l|-location] EXPRESSION\n\
15312 A watchpoint stops execution of your program whenever the value of\n\
15313 an expression changes.\n\
15314 If -l or -location is given, this evaluates EXPRESSION and watches\n\
15315 the memory to which it refers."));
15316   set_cmd_completer (c, expression_completer);
15317
15318   c = add_com ("rwatch", class_breakpoint, rwatch_command, _("\
15319 Set a read watchpoint for an expression.\n\
15320 Usage: rwatch [-l|-location] EXPRESSION\n\
15321 A watchpoint stops execution of your program whenever the value of\n\
15322 an expression is read.\n\
15323 If -l or -location is given, this evaluates EXPRESSION and watches\n\
15324 the memory to which it refers."));
15325   set_cmd_completer (c, expression_completer);
15326
15327   c = add_com ("awatch", class_breakpoint, awatch_command, _("\
15328 Set a watchpoint for an expression.\n\
15329 Usage: awatch [-l|-location] EXPRESSION\n\
15330 A watchpoint stops execution of your program whenever the value of\n\
15331 an expression is either read or written.\n\
15332 If -l or -location is given, this evaluates EXPRESSION and watches\n\
15333 the memory to which it refers."));
15334   set_cmd_completer (c, expression_completer);
15335
15336   add_info ("watchpoints", watchpoints_info, _("\
15337 Status of specified watchpoints (all watchpoints if no argument)."));
15338
15339   /* XXX: cagney/2005-02-23: This should be a boolean, and should
15340      respond to changes - contrary to the description.  */
15341   add_setshow_zinteger_cmd ("can-use-hw-watchpoints", class_support,
15342                             &can_use_hw_watchpoints, _("\
15343 Set debugger's willingness to use watchpoint hardware."), _("\
15344 Show debugger's willingness to use watchpoint hardware."), _("\
15345 If zero, gdb will not use hardware for new watchpoints, even if\n\
15346 such is available.  (However, any hardware watchpoints that were\n\
15347 created before setting this to nonzero, will continue to use watchpoint\n\
15348 hardware.)"),
15349                             NULL,
15350                             show_can_use_hw_watchpoints,
15351                             &setlist, &showlist);
15352
15353   can_use_hw_watchpoints = 1;
15354
15355   /* Tracepoint manipulation commands.  */
15356
15357   c = add_com ("trace", class_breakpoint, trace_command, _("\
15358 Set a tracepoint at specified line or function.\n\
15359 \n"
15360 BREAK_ARGS_HELP ("trace") "\n\
15361 Do \"help tracepoints\" for info on other tracepoint commands."));
15362   set_cmd_completer (c, location_completer);
15363
15364   add_com_alias ("tp", "trace", class_alias, 0);
15365   add_com_alias ("tr", "trace", class_alias, 1);
15366   add_com_alias ("tra", "trace", class_alias, 1);
15367   add_com_alias ("trac", "trace", class_alias, 1);
15368
15369   c = add_com ("ftrace", class_breakpoint, ftrace_command, _("\
15370 Set a fast tracepoint at specified line or function.\n\
15371 \n"
15372 BREAK_ARGS_HELP ("ftrace") "\n\
15373 Do \"help tracepoints\" for info on other tracepoint commands."));
15374   set_cmd_completer (c, location_completer);
15375
15376   c = add_com ("strace", class_breakpoint, strace_command, _("\
15377 Set a static tracepoint at specified line, function or marker.\n\
15378 \n\
15379 strace [LOCATION] [if CONDITION]\n\
15380 LOCATION may be a line number, function name, \"*\" and an address,\n\
15381 or -m MARKER_ID.\n\
15382 If a line number is specified, probe the marker at start of code\n\
15383 for that line.  If a function is specified, probe the marker at start\n\
15384 of code for that function.  If an address is specified, probe the marker\n\
15385 at that exact address.  If a marker id is specified, probe the marker\n\
15386 with that name.  With no LOCATION, uses current execution address of\n\
15387 the selected stack frame.\n\
15388 Static tracepoints accept an extra collect action -- ``collect $_sdata''.\n\
15389 This collects arbitrary user data passed in the probe point call to the\n\
15390 tracing library.  You can inspect it when analyzing the trace buffer,\n\
15391 by printing the $_sdata variable like any other convenience variable.\n\
15392 \n\
15393 CONDITION is a boolean expression.\n\
15394 \n\
15395 Multiple tracepoints at one place are permitted, and useful if their\n\
15396 conditions are different.\n\
15397 \n\
15398 Do \"help breakpoints\" for info on other commands dealing with breakpoints.\n\
15399 Do \"help tracepoints\" for info on other tracepoint commands."));
15400   set_cmd_completer (c, location_completer);
15401
15402   add_info ("tracepoints", tracepoints_info, _("\
15403 Status of specified tracepoints (all tracepoints if no argument).\n\
15404 Convenience variable \"$tpnum\" contains the number of the\n\
15405 last tracepoint set."));
15406
15407   add_info_alias ("tp", "tracepoints", 1);
15408
15409   add_cmd ("tracepoints", class_trace, delete_trace_command, _("\
15410 Delete specified tracepoints.\n\
15411 Arguments are tracepoint numbers, separated by spaces.\n\
15412 No argument means delete all tracepoints."),
15413            &deletelist);
15414
15415   c = add_cmd ("tracepoints", class_trace, disable_trace_command, _("\
15416 Disable specified tracepoints.\n\
15417 Arguments are tracepoint numbers, separated by spaces.\n\
15418 No argument means disable all tracepoints."),
15419            &disablelist);
15420   deprecate_cmd (c, "disable");
15421
15422   c = add_cmd ("tracepoints", class_trace, enable_trace_command, _("\
15423 Enable specified tracepoints.\n\
15424 Arguments are tracepoint numbers, separated by spaces.\n\
15425 No argument means enable all tracepoints."),
15426            &enablelist);
15427   deprecate_cmd (c, "enable");
15428
15429   add_com ("passcount", class_trace, trace_pass_command, _("\
15430 Set the passcount for a tracepoint.\n\
15431 The trace will end when the tracepoint has been passed 'count' times.\n\
15432 Usage: passcount COUNT TPNUM, where TPNUM may also be \"all\";\n\
15433 if TPNUM is omitted, passcount refers to the last tracepoint defined."));
15434
15435   add_prefix_cmd ("save", class_breakpoint, save_command,
15436                   _("Save breakpoint definitions as a script."),
15437                   &save_cmdlist, "save ",
15438                   0/*allow-unknown*/, &cmdlist);
15439
15440   c = add_cmd ("breakpoints", class_breakpoint, save_breakpoints_command, _("\
15441 Save current breakpoint definitions as a script.\n\
15442 This includes all types of breakpoints (breakpoints, watchpoints,\n\
15443 catchpoints, tracepoints).  Use the 'source' command in another debug\n\
15444 session to restore them."),
15445                &save_cmdlist);
15446   set_cmd_completer (c, filename_completer);
15447
15448   c = add_cmd ("tracepoints", class_trace, save_tracepoints_command, _("\
15449 Save current tracepoint definitions as a script.\n\
15450 Use the 'source' command in another debug session to restore them."),
15451                &save_cmdlist);
15452   set_cmd_completer (c, filename_completer);
15453
15454   c = add_com_alias ("save-tracepoints", "save tracepoints", class_trace, 0);
15455   deprecate_cmd (c, "save tracepoints");
15456
15457   add_prefix_cmd ("breakpoint", class_maintenance, set_breakpoint_cmd, _("\
15458 Breakpoint specific settings\n\
15459 Configure various breakpoint-specific variables such as\n\
15460 pending breakpoint behavior"),
15461                   &breakpoint_set_cmdlist, "set breakpoint ",
15462                   0/*allow-unknown*/, &setlist);
15463   add_prefix_cmd ("breakpoint", class_maintenance, show_breakpoint_cmd, _("\
15464 Breakpoint specific settings\n\
15465 Configure various breakpoint-specific variables such as\n\
15466 pending breakpoint behavior"),
15467                   &breakpoint_show_cmdlist, "show breakpoint ",
15468                   0/*allow-unknown*/, &showlist);
15469
15470   add_setshow_auto_boolean_cmd ("pending", no_class,
15471                                 &pending_break_support, _("\
15472 Set debugger's behavior regarding pending breakpoints."), _("\
15473 Show debugger's behavior regarding pending breakpoints."), _("\
15474 If on, an unrecognized breakpoint location will cause gdb to create a\n\
15475 pending breakpoint.  If off, an unrecognized breakpoint location results in\n\
15476 an error.  If auto, an unrecognized breakpoint location results in a\n\
15477 user-query to see if a pending breakpoint should be created."),
15478                                 NULL,
15479                                 show_pending_break_support,
15480                                 &breakpoint_set_cmdlist,
15481                                 &breakpoint_show_cmdlist);
15482
15483   pending_break_support = AUTO_BOOLEAN_AUTO;
15484
15485   add_setshow_boolean_cmd ("auto-hw", no_class,
15486                            &automatic_hardware_breakpoints, _("\
15487 Set automatic usage of hardware breakpoints."), _("\
15488 Show automatic usage of hardware breakpoints."), _("\
15489 If set, the debugger will automatically use hardware breakpoints for\n\
15490 breakpoints set with \"break\" but falling in read-only memory.  If not set,\n\
15491 a warning will be emitted for such breakpoints."),
15492                            NULL,
15493                            show_automatic_hardware_breakpoints,
15494                            &breakpoint_set_cmdlist,
15495                            &breakpoint_show_cmdlist);
15496
15497   add_setshow_enum_cmd ("always-inserted", class_support,
15498                         always_inserted_enums, &always_inserted_mode, _("\
15499 Set mode for inserting breakpoints."), _("\
15500 Show mode for inserting breakpoints."), _("\
15501 When this mode is off, breakpoints are inserted in inferior when it is\n\
15502 resumed, and removed when execution stops.  When this mode is on,\n\
15503 breakpoints are inserted immediately and removed only when the user\n\
15504 deletes the breakpoint.  When this mode is auto (which is the default),\n\
15505 the behaviour depends on the non-stop setting (see help set non-stop).\n\
15506 In this case, if gdb is controlling the inferior in non-stop mode, gdb\n\
15507 behaves as if always-inserted mode is on; if gdb is controlling the\n\
15508 inferior in all-stop mode, gdb behaves as if always-inserted mode is off."),
15509                            NULL,
15510                            &show_always_inserted_mode,
15511                            &breakpoint_set_cmdlist,
15512                            &breakpoint_show_cmdlist);
15513
15514   add_setshow_enum_cmd ("condition-evaluation", class_breakpoint,
15515                         condition_evaluation_enums,
15516                         &condition_evaluation_mode_1, _("\
15517 Set mode of breakpoint condition evaluation."), _("\
15518 Show mode of breakpoint condition evaluation."), _("\
15519 When this is set to \"gdb\", breakpoint conditions will be\n\
15520 evaluated on the host's side by GDB.  When it is set to \"target\",\n\
15521 breakpoint conditions will be downloaded to the target (if the target\n\
15522 supports such feature) and conditions will be evaluated on the target's side.\n\
15523 If this is set to \"auto\" (default), this will be automatically set to\n\
15524 \"target\" if it supports condition evaluation, otherwise it will\n\
15525 be set to \"gdb\""),
15526                            &set_condition_evaluation_mode,
15527                            &show_condition_evaluation_mode,
15528                            &breakpoint_set_cmdlist,
15529                            &breakpoint_show_cmdlist);
15530
15531   add_com ("break-range", class_breakpoint, break_range_command, _("\
15532 Set a breakpoint for an address range.\n\
15533 break-range START-LOCATION, END-LOCATION\n\
15534 where START-LOCATION and END-LOCATION can be one of the following:\n\
15535   LINENUM, for that line in the current file,\n\
15536   FILE:LINENUM, for that line in that file,\n\
15537   +OFFSET, for that number of lines after the current line\n\
15538            or the start of the range\n\
15539   FUNCTION, for the first line in that function,\n\
15540   FILE:FUNCTION, to distinguish among like-named static functions.\n\
15541   *ADDRESS, for the instruction at that address.\n\
15542 \n\
15543 The breakpoint will stop execution of the inferior whenever it executes\n\
15544 an instruction at any address within the [START-LOCATION, END-LOCATION]\n\
15545 range (including START-LOCATION and END-LOCATION)."));
15546
15547   automatic_hardware_breakpoints = 1;
15548
15549   observer_attach_about_to_proceed (breakpoint_about_to_proceed);
15550 }