gdb:
[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   /* Flip the switch.  Flip it even if OLD_MODE == NEW_MODE as one of the
765      settings was "auto".  */
766   condition_evaluation_mode = condition_evaluation_mode_1;
767
768   /* Only update the mode if the user picked a different one.  */
769   if (new_mode != old_mode)
770     {
771       struct bp_location *loc, **loc_tmp;
772       /* If the user switched to a different evaluation mode, we
773          need to synch the changes with the target as follows:
774
775          "host" -> "target": Send all (valid) conditions to the target.
776          "target" -> "host": Remove all the conditions from the target.
777       */
778
779       if (new_mode == condition_evaluation_target)
780         {
781           /* Mark everything modified and synch conditions with the
782              target.  */
783           ALL_BP_LOCATIONS (loc, loc_tmp)
784             mark_breakpoint_location_modified (loc);
785         }
786       else
787         {
788           /* Manually mark non-duplicate locations to synch conditions
789              with the target.  We do this to remove all the conditions the
790              target knows about.  */
791           ALL_BP_LOCATIONS (loc, loc_tmp)
792             if (is_breakpoint (loc->owner) && loc->inserted)
793               loc->needs_update = 1;
794         }
795
796       /* Do the update.  */
797       update_global_location_list (1);
798     }
799
800   return;
801 }
802
803 /* Shows the current mode of breakpoint condition evaluation.  Explicitly shows
804    what "auto" is translating to.  */
805
806 static void
807 show_condition_evaluation_mode (struct ui_file *file, int from_tty,
808                                 struct cmd_list_element *c, const char *value)
809 {
810   if (condition_evaluation_mode == condition_evaluation_auto)
811     fprintf_filtered (file,
812                       _("Breakpoint condition evaluation "
813                         "mode is %s (currently %s).\n"),
814                       value,
815                       breakpoint_condition_evaluation_mode ());
816   else
817     fprintf_filtered (file, _("Breakpoint condition evaluation mode is %s.\n"),
818                       value);
819 }
820
821 /* A comparison function for bp_location AP and BP that is used by
822    bsearch.  This comparison function only cares about addresses, unlike
823    the more general bp_location_compare function.  */
824
825 static int
826 bp_location_compare_addrs (const void *ap, const void *bp)
827 {
828   struct bp_location *a = *(void **) ap;
829   struct bp_location *b = *(void **) bp;
830
831   if (a->address == b->address)
832     return 0;
833   else
834     return ((a->address > b->address) - (a->address < b->address));
835 }
836
837 /* Helper function to skip all bp_locations with addresses
838    less than ADDRESS.  It returns the first bp_location that
839    is greater than or equal to ADDRESS.  If none is found, just
840    return NULL.  */
841
842 static struct bp_location **
843 get_first_locp_gte_addr (CORE_ADDR address)
844 {
845   struct bp_location dummy_loc;
846   struct bp_location *dummy_locp = &dummy_loc;
847   struct bp_location **locp_found = NULL;
848
849   /* Initialize the dummy location's address field.  */
850   memset (&dummy_loc, 0, sizeof (struct bp_location));
851   dummy_loc.address = address;
852
853   /* Find a close match to the first location at ADDRESS.  */
854   locp_found = bsearch (&dummy_locp, bp_location, bp_location_count,
855                         sizeof (struct bp_location **),
856                         bp_location_compare_addrs);
857
858   /* Nothing was found, nothing left to do.  */
859   if (locp_found == NULL)
860     return NULL;
861
862   /* We may have found a location that is at ADDRESS but is not the first in the
863      location's list.  Go backwards (if possible) and locate the first one.  */
864   while ((locp_found - 1) >= bp_location
865          && (*(locp_found - 1))->address == address)
866     locp_found--;
867
868   return locp_found;
869 }
870
871 void
872 set_breakpoint_condition (struct breakpoint *b, char *exp,
873                           int from_tty)
874 {
875   xfree (b->cond_string);
876   b->cond_string = NULL;
877
878   if (is_watchpoint (b))
879     {
880       struct watchpoint *w = (struct watchpoint *) b;
881
882       xfree (w->cond_exp);
883       w->cond_exp = NULL;
884     }
885   else
886     {
887       struct bp_location *loc;
888
889       for (loc = b->loc; loc; loc = loc->next)
890         {
891           xfree (loc->cond);
892           loc->cond = NULL;
893
894           /* No need to free the condition agent expression
895              bytecode (if we have one).  We will handle this
896              when we go through update_global_location_list.  */
897         }
898     }
899
900   if (*exp == 0)
901     {
902       if (from_tty)
903         printf_filtered (_("Breakpoint %d now unconditional.\n"), b->number);
904     }
905   else
906     {
907       char *arg = exp;
908
909       /* I don't know if it matters whether this is the string the user
910          typed in or the decompiled expression.  */
911       b->cond_string = xstrdup (arg);
912       b->condition_not_parsed = 0;
913
914       if (is_watchpoint (b))
915         {
916           struct watchpoint *w = (struct watchpoint *) b;
917
918           innermost_block = NULL;
919           arg = exp;
920           w->cond_exp = parse_exp_1 (&arg, 0, 0);
921           if (*arg)
922             error (_("Junk at end of expression"));
923           w->cond_exp_valid_block = innermost_block;
924         }
925       else
926         {
927           struct bp_location *loc;
928
929           for (loc = b->loc; loc; loc = loc->next)
930             {
931               arg = exp;
932               loc->cond =
933                 parse_exp_1 (&arg, block_for_pc (loc->address), 0);
934               if (*arg)
935                 error (_("Junk at end of expression"));
936             }
937         }
938     }
939   mark_breakpoint_modified (b);
940
941   breakpoints_changed ();
942   observer_notify_breakpoint_modified (b);
943 }
944
945 /* condition N EXP -- set break condition of breakpoint N to EXP.  */
946
947 static void
948 condition_command (char *arg, int from_tty)
949 {
950   struct breakpoint *b;
951   char *p;
952   int bnum;
953
954   if (arg == 0)
955     error_no_arg (_("breakpoint number"));
956
957   p = arg;
958   bnum = get_number (&p);
959   if (bnum == 0)
960     error (_("Bad breakpoint argument: '%s'"), arg);
961
962   ALL_BREAKPOINTS (b)
963     if (b->number == bnum)
964       {
965         /* Check if this breakpoint has a Python object assigned to
966            it, and if it has a definition of the "stop"
967            method.  This method and conditions entered into GDB from
968            the CLI are mutually exclusive.  */
969         if (b->py_bp_object
970             && gdbpy_breakpoint_has_py_cond (b->py_bp_object))
971           error (_("Cannot set a condition where a Python 'stop' "
972                    "method has been defined in the breakpoint."));
973         set_breakpoint_condition (b, p, from_tty);
974
975         if (is_breakpoint (b))
976           update_global_location_list (1);
977
978         return;
979       }
980
981   error (_("No breakpoint number %d."), bnum);
982 }
983
984 /* Check that COMMAND do not contain commands that are suitable
985    only for tracepoints and not suitable for ordinary breakpoints.
986    Throw if any such commands is found.  */
987
988 static void
989 check_no_tracepoint_commands (struct command_line *commands)
990 {
991   struct command_line *c;
992
993   for (c = commands; c; c = c->next)
994     {
995       int i;
996
997       if (c->control_type == while_stepping_control)
998         error (_("The 'while-stepping' command can "
999                  "only be used for tracepoints"));
1000
1001       for (i = 0; i < c->body_count; ++i)
1002         check_no_tracepoint_commands ((c->body_list)[i]);
1003
1004       /* Not that command parsing removes leading whitespace and comment
1005          lines and also empty lines.  So, we only need to check for
1006          command directly.  */
1007       if (strstr (c->line, "collect ") == c->line)
1008         error (_("The 'collect' command can only be used for tracepoints"));
1009
1010       if (strstr (c->line, "teval ") == c->line)
1011         error (_("The 'teval' command can only be used for tracepoints"));
1012     }
1013 }
1014
1015 /* Encapsulate tests for different types of tracepoints.  */
1016
1017 static int
1018 is_tracepoint_type (enum bptype type)
1019 {
1020   return (type == bp_tracepoint
1021           || type == bp_fast_tracepoint
1022           || type == bp_static_tracepoint);
1023 }
1024
1025 int
1026 is_tracepoint (const struct breakpoint *b)
1027 {
1028   return is_tracepoint_type (b->type);
1029 }
1030
1031 /* A helper function that validates that COMMANDS are valid for a
1032    breakpoint.  This function will throw an exception if a problem is
1033    found.  */
1034
1035 static void
1036 validate_commands_for_breakpoint (struct breakpoint *b,
1037                                   struct command_line *commands)
1038 {
1039   if (is_tracepoint (b))
1040     {
1041       /* We need to verify that each top-level element of commands is
1042          valid for tracepoints, that there's at most one
1043          while-stepping element, and that while-stepping's body has
1044          valid tracing commands excluding nested while-stepping.  */
1045       struct command_line *c;
1046       struct command_line *while_stepping = 0;
1047       for (c = commands; c; c = c->next)
1048         {
1049           if (c->control_type == while_stepping_control)
1050             {
1051               if (b->type == bp_fast_tracepoint)
1052                 error (_("The 'while-stepping' command "
1053                          "cannot be used for fast tracepoint"));
1054               else if (b->type == bp_static_tracepoint)
1055                 error (_("The 'while-stepping' command "
1056                          "cannot be used for static tracepoint"));
1057
1058               if (while_stepping)
1059                 error (_("The 'while-stepping' command "
1060                          "can be used only once"));
1061               else
1062                 while_stepping = c;
1063             }
1064         }
1065       if (while_stepping)
1066         {
1067           struct command_line *c2;
1068
1069           gdb_assert (while_stepping->body_count == 1);
1070           c2 = while_stepping->body_list[0];
1071           for (; c2; c2 = c2->next)
1072             {
1073               if (c2->control_type == while_stepping_control)
1074                 error (_("The 'while-stepping' command cannot be nested"));
1075             }
1076         }
1077     }
1078   else
1079     {
1080       check_no_tracepoint_commands (commands);
1081     }
1082 }
1083
1084 /* Return a vector of all the static tracepoints set at ADDR.  The
1085    caller is responsible for releasing the vector.  */
1086
1087 VEC(breakpoint_p) *
1088 static_tracepoints_here (CORE_ADDR addr)
1089 {
1090   struct breakpoint *b;
1091   VEC(breakpoint_p) *found = 0;
1092   struct bp_location *loc;
1093
1094   ALL_BREAKPOINTS (b)
1095     if (b->type == bp_static_tracepoint)
1096       {
1097         for (loc = b->loc; loc; loc = loc->next)
1098           if (loc->address == addr)
1099             VEC_safe_push(breakpoint_p, found, b);
1100       }
1101
1102   return found;
1103 }
1104
1105 /* Set the command list of B to COMMANDS.  If breakpoint is tracepoint,
1106    validate that only allowed commands are included.  */
1107
1108 void
1109 breakpoint_set_commands (struct breakpoint *b, 
1110                          struct command_line *commands)
1111 {
1112   validate_commands_for_breakpoint (b, commands);
1113
1114   decref_counted_command_line (&b->commands);
1115   b->commands = alloc_counted_command_line (commands);
1116   breakpoints_changed ();
1117   observer_notify_breakpoint_modified (b);
1118 }
1119
1120 /* Set the internal `silent' flag on the breakpoint.  Note that this
1121    is not the same as the "silent" that may appear in the breakpoint's
1122    commands.  */
1123
1124 void
1125 breakpoint_set_silent (struct breakpoint *b, int silent)
1126 {
1127   int old_silent = b->silent;
1128
1129   b->silent = silent;
1130   if (old_silent != silent)
1131     observer_notify_breakpoint_modified (b);
1132 }
1133
1134 /* Set the thread for this breakpoint.  If THREAD is -1, make the
1135    breakpoint work for any thread.  */
1136
1137 void
1138 breakpoint_set_thread (struct breakpoint *b, int thread)
1139 {
1140   int old_thread = b->thread;
1141
1142   b->thread = thread;
1143   if (old_thread != thread)
1144     observer_notify_breakpoint_modified (b);
1145 }
1146
1147 /* Set the task for this breakpoint.  If TASK is 0, make the
1148    breakpoint work for any task.  */
1149
1150 void
1151 breakpoint_set_task (struct breakpoint *b, int task)
1152 {
1153   int old_task = b->task;
1154
1155   b->task = task;
1156   if (old_task != task)
1157     observer_notify_breakpoint_modified (b);
1158 }
1159
1160 void
1161 check_tracepoint_command (char *line, void *closure)
1162 {
1163   struct breakpoint *b = closure;
1164
1165   validate_actionline (&line, b);
1166 }
1167
1168 /* A structure used to pass information through
1169    map_breakpoint_numbers.  */
1170
1171 struct commands_info
1172 {
1173   /* True if the command was typed at a tty.  */
1174   int from_tty;
1175
1176   /* The breakpoint range spec.  */
1177   char *arg;
1178
1179   /* Non-NULL if the body of the commands are being read from this
1180      already-parsed command.  */
1181   struct command_line *control;
1182
1183   /* The command lines read from the user, or NULL if they have not
1184      yet been read.  */
1185   struct counted_command_line *cmd;
1186 };
1187
1188 /* A callback for map_breakpoint_numbers that sets the commands for
1189    commands_command.  */
1190
1191 static void
1192 do_map_commands_command (struct breakpoint *b, void *data)
1193 {
1194   struct commands_info *info = data;
1195
1196   if (info->cmd == NULL)
1197     {
1198       struct command_line *l;
1199
1200       if (info->control != NULL)
1201         l = copy_command_lines (info->control->body_list[0]);
1202       else
1203         {
1204           struct cleanup *old_chain;
1205           char *str;
1206
1207           str = xstrprintf (_("Type commands for breakpoint(s) "
1208                               "%s, one per line."),
1209                             info->arg);
1210
1211           old_chain = make_cleanup (xfree, str);
1212
1213           l = read_command_lines (str,
1214                                   info->from_tty, 1,
1215                                   (is_tracepoint (b)
1216                                    ? check_tracepoint_command : 0),
1217                                   b);
1218
1219           do_cleanups (old_chain);
1220         }
1221
1222       info->cmd = alloc_counted_command_line (l);
1223     }
1224
1225   /* If a breakpoint was on the list more than once, we don't need to
1226      do anything.  */
1227   if (b->commands != info->cmd)
1228     {
1229       validate_commands_for_breakpoint (b, info->cmd->commands);
1230       incref_counted_command_line (info->cmd);
1231       decref_counted_command_line (&b->commands);
1232       b->commands = info->cmd;
1233       breakpoints_changed ();
1234       observer_notify_breakpoint_modified (b);
1235     }
1236 }
1237
1238 static void
1239 commands_command_1 (char *arg, int from_tty, 
1240                     struct command_line *control)
1241 {
1242   struct cleanup *cleanups;
1243   struct commands_info info;
1244
1245   info.from_tty = from_tty;
1246   info.control = control;
1247   info.cmd = NULL;
1248   /* If we read command lines from the user, then `info' will hold an
1249      extra reference to the commands that we must clean up.  */
1250   cleanups = make_cleanup_decref_counted_command_line (&info.cmd);
1251
1252   if (arg == NULL || !*arg)
1253     {
1254       if (breakpoint_count - prev_breakpoint_count > 1)
1255         arg = xstrprintf ("%d-%d", prev_breakpoint_count + 1, 
1256                           breakpoint_count);
1257       else if (breakpoint_count > 0)
1258         arg = xstrprintf ("%d", breakpoint_count);
1259       else
1260         {
1261           /* So that we don't try to free the incoming non-NULL
1262              argument in the cleanup below.  Mapping breakpoint
1263              numbers will fail in this case.  */
1264           arg = NULL;
1265         }
1266     }
1267   else
1268     /* The command loop has some static state, so we need to preserve
1269        our argument.  */
1270     arg = xstrdup (arg);
1271
1272   if (arg != NULL)
1273     make_cleanup (xfree, arg);
1274
1275   info.arg = arg;
1276
1277   map_breakpoint_numbers (arg, do_map_commands_command, &info);
1278
1279   if (info.cmd == NULL)
1280     error (_("No breakpoints specified."));
1281
1282   do_cleanups (cleanups);
1283 }
1284
1285 static void
1286 commands_command (char *arg, int from_tty)
1287 {
1288   commands_command_1 (arg, from_tty, NULL);
1289 }
1290
1291 /* Like commands_command, but instead of reading the commands from
1292    input stream, takes them from an already parsed command structure.
1293
1294    This is used by cli-script.c to DTRT with breakpoint commands
1295    that are part of if and while bodies.  */
1296 enum command_control_type
1297 commands_from_control_command (char *arg, struct command_line *cmd)
1298 {
1299   commands_command_1 (arg, 0, cmd);
1300   return simple_control;
1301 }
1302
1303 /* Return non-zero if BL->TARGET_INFO contains valid information.  */
1304
1305 static int
1306 bp_location_has_shadow (struct bp_location *bl)
1307 {
1308   if (bl->loc_type != bp_loc_software_breakpoint)
1309     return 0;
1310   if (!bl->inserted)
1311     return 0;
1312   if (bl->target_info.shadow_len == 0)
1313     /* BL isn't valid, or doesn't shadow memory.  */
1314     return 0;
1315   return 1;
1316 }
1317
1318 /* Update BUF, which is LEN bytes read from the target address MEMADDR,
1319    by replacing any memory breakpoints with their shadowed contents.
1320
1321    The range of shadowed area by each bp_location is:
1322      bl->address - bp_location_placed_address_before_address_max
1323      up to bl->address + bp_location_shadow_len_after_address_max
1324    The range we were requested to resolve shadows for is:
1325      memaddr ... memaddr + len
1326    Thus the safe cutoff boundaries for performance optimization are
1327      memaddr + len <= (bl->address
1328                        - bp_location_placed_address_before_address_max)
1329    and:
1330      bl->address + bp_location_shadow_len_after_address_max <= memaddr  */
1331
1332 void
1333 breakpoint_xfer_memory (gdb_byte *readbuf, gdb_byte *writebuf,
1334                         const gdb_byte *writebuf_org,
1335                         ULONGEST memaddr, LONGEST len)
1336 {
1337   /* Left boundary, right boundary and median element of our binary
1338      search.  */
1339   unsigned bc_l, bc_r, bc;
1340
1341   /* Find BC_L which is a leftmost element which may affect BUF
1342      content.  It is safe to report lower value but a failure to
1343      report higher one.  */
1344
1345   bc_l = 0;
1346   bc_r = bp_location_count;
1347   while (bc_l + 1 < bc_r)
1348     {
1349       struct bp_location *bl;
1350
1351       bc = (bc_l + bc_r) / 2;
1352       bl = bp_location[bc];
1353
1354       /* Check first BL->ADDRESS will not overflow due to the added
1355          constant.  Then advance the left boundary only if we are sure
1356          the BC element can in no way affect the BUF content (MEMADDR
1357          to MEMADDR + LEN range).
1358
1359          Use the BP_LOCATION_SHADOW_LEN_AFTER_ADDRESS_MAX safety
1360          offset so that we cannot miss a breakpoint with its shadow
1361          range tail still reaching MEMADDR.  */
1362
1363       if ((bl->address + bp_location_shadow_len_after_address_max
1364            >= bl->address)
1365           && (bl->address + bp_location_shadow_len_after_address_max
1366               <= memaddr))
1367         bc_l = bc;
1368       else
1369         bc_r = bc;
1370     }
1371
1372   /* Due to the binary search above, we need to make sure we pick the
1373      first location that's at BC_L's address.  E.g., if there are
1374      multiple locations at the same address, BC_L may end up pointing
1375      at a duplicate location, and miss the "master"/"inserted"
1376      location.  Say, given locations L1, L2 and L3 at addresses A and
1377      B:
1378
1379       L1@A, L2@A, L3@B, ...
1380
1381      BC_L could end up pointing at location L2, while the "master"
1382      location could be L1.  Since the `loc->inserted' flag is only set
1383      on "master" locations, we'd forget to restore the shadow of L1
1384      and L2.  */
1385   while (bc_l > 0
1386          && bp_location[bc_l]->address == bp_location[bc_l - 1]->address)
1387     bc_l--;
1388
1389   /* Now do full processing of the found relevant range of elements.  */
1390
1391   for (bc = bc_l; bc < bp_location_count; bc++)
1392   {
1393     struct bp_location *bl = bp_location[bc];
1394     CORE_ADDR bp_addr = 0;
1395     int bp_size = 0;
1396     int bptoffset = 0;
1397
1398     /* bp_location array has BL->OWNER always non-NULL.  */
1399     if (bl->owner->type == bp_none)
1400       warning (_("reading through apparently deleted breakpoint #%d?"),
1401                bl->owner->number);
1402
1403     /* Performance optimization: any further element can no longer affect BUF
1404        content.  */
1405
1406     if (bl->address >= bp_location_placed_address_before_address_max
1407         && memaddr + len <= (bl->address
1408                              - bp_location_placed_address_before_address_max))
1409       break;
1410
1411     if (!bp_location_has_shadow (bl))
1412       continue;
1413     if (!breakpoint_address_match (bl->target_info.placed_address_space, 0,
1414                                    current_program_space->aspace, 0))
1415       continue;
1416
1417     /* Addresses and length of the part of the breakpoint that
1418        we need to copy.  */
1419     bp_addr = bl->target_info.placed_address;
1420     bp_size = bl->target_info.shadow_len;
1421
1422     if (bp_addr + bp_size <= memaddr)
1423       /* The breakpoint is entirely before the chunk of memory we
1424          are reading.  */
1425       continue;
1426
1427     if (bp_addr >= memaddr + len)
1428       /* The breakpoint is entirely after the chunk of memory we are
1429          reading.  */
1430       continue;
1431
1432     /* Offset within shadow_contents.  */
1433     if (bp_addr < memaddr)
1434       {
1435         /* Only copy the second part of the breakpoint.  */
1436         bp_size -= memaddr - bp_addr;
1437         bptoffset = memaddr - bp_addr;
1438         bp_addr = memaddr;
1439       }
1440
1441     if (bp_addr + bp_size > memaddr + len)
1442       {
1443         /* Only copy the first part of the breakpoint.  */
1444         bp_size -= (bp_addr + bp_size) - (memaddr + len);
1445       }
1446
1447     if (readbuf != NULL)
1448       {
1449         /* Update the read buffer with this inserted breakpoint's
1450            shadow.  */
1451         memcpy (readbuf + bp_addr - memaddr,
1452                 bl->target_info.shadow_contents + bptoffset, bp_size);
1453       }
1454     else
1455       {
1456         struct gdbarch *gdbarch = bl->gdbarch;
1457         const unsigned char *bp;
1458         CORE_ADDR placed_address = bl->target_info.placed_address;
1459         unsigned placed_size = bl->target_info.placed_size;
1460
1461         /* Update the shadow with what we want to write to memory.  */
1462         memcpy (bl->target_info.shadow_contents + bptoffset,
1463                 writebuf_org + bp_addr - memaddr, bp_size);
1464
1465         /* Determine appropriate breakpoint contents and size for this
1466            address.  */
1467         bp = gdbarch_breakpoint_from_pc (gdbarch, &placed_address, &placed_size);
1468
1469         /* Update the final write buffer with this inserted
1470            breakpoint's INSN.  */
1471         memcpy (writebuf + bp_addr - memaddr, bp + bptoffset, bp_size);
1472       }
1473   }
1474 }
1475 \f
1476
1477 /* Return true if BPT is either a software breakpoint or a hardware
1478    breakpoint.  */
1479
1480 int
1481 is_breakpoint (const struct breakpoint *bpt)
1482 {
1483   return (bpt->type == bp_breakpoint
1484           || bpt->type == bp_hardware_breakpoint);
1485 }
1486
1487 /* Return true if BPT is of any hardware watchpoint kind.  */
1488
1489 static int
1490 is_hardware_watchpoint (const struct breakpoint *bpt)
1491 {
1492   return (bpt->type == bp_hardware_watchpoint
1493           || bpt->type == bp_read_watchpoint
1494           || bpt->type == bp_access_watchpoint);
1495 }
1496
1497 /* Return true if BPT is of any watchpoint kind, hardware or
1498    software.  */
1499
1500 int
1501 is_watchpoint (const struct breakpoint *bpt)
1502 {
1503   return (is_hardware_watchpoint (bpt)
1504           || bpt->type == bp_watchpoint);
1505 }
1506
1507 /* Returns true if the current thread and its running state are safe
1508    to evaluate or update watchpoint B.  Watchpoints on local
1509    expressions need to be evaluated in the context of the thread that
1510    was current when the watchpoint was created, and, that thread needs
1511    to be stopped to be able to select the correct frame context.
1512    Watchpoints on global expressions can be evaluated on any thread,
1513    and in any state.  It is presently left to the target allowing
1514    memory accesses when threads are running.  */
1515
1516 static int
1517 watchpoint_in_thread_scope (struct watchpoint *b)
1518 {
1519   return (b->base.pspace == current_program_space
1520           && (ptid_equal (b->watchpoint_thread, null_ptid)
1521               || (ptid_equal (inferior_ptid, b->watchpoint_thread)
1522                   && !is_executing (inferior_ptid))));
1523 }
1524
1525 /* Set watchpoint B to disp_del_at_next_stop, even including its possible
1526    associated bp_watchpoint_scope breakpoint.  */
1527
1528 static void
1529 watchpoint_del_at_next_stop (struct watchpoint *w)
1530 {
1531   struct breakpoint *b = &w->base;
1532
1533   if (b->related_breakpoint != b)
1534     {
1535       gdb_assert (b->related_breakpoint->type == bp_watchpoint_scope);
1536       gdb_assert (b->related_breakpoint->related_breakpoint == b);
1537       b->related_breakpoint->disposition = disp_del_at_next_stop;
1538       b->related_breakpoint->related_breakpoint = b->related_breakpoint;
1539       b->related_breakpoint = b;
1540     }
1541   b->disposition = disp_del_at_next_stop;
1542 }
1543
1544 /* Assuming that B is a watchpoint:
1545    - Reparse watchpoint expression, if REPARSE is non-zero
1546    - Evaluate expression and store the result in B->val
1547    - Evaluate the condition if there is one, and store the result
1548      in b->loc->cond.
1549    - Update the list of values that must be watched in B->loc.
1550
1551    If the watchpoint disposition is disp_del_at_next_stop, then do
1552    nothing.  If this is local watchpoint that is out of scope, delete
1553    it.
1554
1555    Even with `set breakpoint always-inserted on' the watchpoints are
1556    removed + inserted on each stop here.  Normal breakpoints must
1557    never be removed because they might be missed by a running thread
1558    when debugging in non-stop mode.  On the other hand, hardware
1559    watchpoints (is_hardware_watchpoint; processed here) are specific
1560    to each LWP since they are stored in each LWP's hardware debug
1561    registers.  Therefore, such LWP must be stopped first in order to
1562    be able to modify its hardware watchpoints.
1563
1564    Hardware watchpoints must be reset exactly once after being
1565    presented to the user.  It cannot be done sooner, because it would
1566    reset the data used to present the watchpoint hit to the user.  And
1567    it must not be done later because it could display the same single
1568    watchpoint hit during multiple GDB stops.  Note that the latter is
1569    relevant only to the hardware watchpoint types bp_read_watchpoint
1570    and bp_access_watchpoint.  False hit by bp_hardware_watchpoint is
1571    not user-visible - its hit is suppressed if the memory content has
1572    not changed.
1573
1574    The following constraints influence the location where we can reset
1575    hardware watchpoints:
1576
1577    * target_stopped_by_watchpoint and target_stopped_data_address are
1578      called several times when GDB stops.
1579
1580    [linux] 
1581    * Multiple hardware watchpoints can be hit at the same time,
1582      causing GDB to stop.  GDB only presents one hardware watchpoint
1583      hit at a time as the reason for stopping, and all the other hits
1584      are presented later, one after the other, each time the user
1585      requests the execution to be resumed.  Execution is not resumed
1586      for the threads still having pending hit event stored in
1587      LWP_INFO->STATUS.  While the watchpoint is already removed from
1588      the inferior on the first stop the thread hit event is kept being
1589      reported from its cached value by linux_nat_stopped_data_address
1590      until the real thread resume happens after the watchpoint gets
1591      presented and thus its LWP_INFO->STATUS gets reset.
1592
1593    Therefore the hardware watchpoint hit can get safely reset on the
1594    watchpoint removal from inferior.  */
1595
1596 static void
1597 update_watchpoint (struct watchpoint *b, int reparse)
1598 {
1599   int within_current_scope;
1600   struct frame_id saved_frame_id;
1601   int frame_saved;
1602
1603   /* If this is a local watchpoint, we only want to check if the
1604      watchpoint frame is in scope if the current thread is the thread
1605      that was used to create the watchpoint.  */
1606   if (!watchpoint_in_thread_scope (b))
1607     return;
1608
1609   if (b->base.disposition == disp_del_at_next_stop)
1610     return;
1611  
1612   frame_saved = 0;
1613
1614   /* Determine if the watchpoint is within scope.  */
1615   if (b->exp_valid_block == NULL)
1616     within_current_scope = 1;
1617   else
1618     {
1619       struct frame_info *fi = get_current_frame ();
1620       struct gdbarch *frame_arch = get_frame_arch (fi);
1621       CORE_ADDR frame_pc = get_frame_pc (fi);
1622
1623       /* If we're in a function epilogue, unwinding may not work
1624          properly, so do not attempt to recreate locations at this
1625          point.  See similar comments in watchpoint_check.  */
1626       if (gdbarch_in_function_epilogue_p (frame_arch, frame_pc))
1627         return;
1628
1629       /* Save the current frame's ID so we can restore it after
1630          evaluating the watchpoint expression on its own frame.  */
1631       /* FIXME drow/2003-09-09: It would be nice if evaluate_expression
1632          took a frame parameter, so that we didn't have to change the
1633          selected frame.  */
1634       frame_saved = 1;
1635       saved_frame_id = get_frame_id (get_selected_frame (NULL));
1636
1637       fi = frame_find_by_id (b->watchpoint_frame);
1638       within_current_scope = (fi != NULL);
1639       if (within_current_scope)
1640         select_frame (fi);
1641     }
1642
1643   /* We don't free locations.  They are stored in the bp_location array
1644      and update_global_location_list will eventually delete them and
1645      remove breakpoints if needed.  */
1646   b->base.loc = NULL;
1647
1648   if (within_current_scope && reparse)
1649     {
1650       char *s;
1651
1652       if (b->exp)
1653         {
1654           xfree (b->exp);
1655           b->exp = NULL;
1656         }
1657       s = b->exp_string_reparse ? b->exp_string_reparse : b->exp_string;
1658       b->exp = parse_exp_1 (&s, b->exp_valid_block, 0);
1659       /* If the meaning of expression itself changed, the old value is
1660          no longer relevant.  We don't want to report a watchpoint hit
1661          to the user when the old value and the new value may actually
1662          be completely different objects.  */
1663       value_free (b->val);
1664       b->val = NULL;
1665       b->val_valid = 0;
1666
1667       /* Note that unlike with breakpoints, the watchpoint's condition
1668          expression is stored in the breakpoint object, not in the
1669          locations (re)created below.  */
1670       if (b->base.cond_string != NULL)
1671         {
1672           if (b->cond_exp != NULL)
1673             {
1674               xfree (b->cond_exp);
1675               b->cond_exp = NULL;
1676             }
1677
1678           s = b->base.cond_string;
1679           b->cond_exp = parse_exp_1 (&s, b->cond_exp_valid_block, 0);
1680         }
1681     }
1682
1683   /* If we failed to parse the expression, for example because
1684      it refers to a global variable in a not-yet-loaded shared library,
1685      don't try to insert watchpoint.  We don't automatically delete
1686      such watchpoint, though, since failure to parse expression
1687      is different from out-of-scope watchpoint.  */
1688   if ( !target_has_execution)
1689     {
1690       /* Without execution, memory can't change.  No use to try and
1691          set watchpoint locations.  The watchpoint will be reset when
1692          the target gains execution, through breakpoint_re_set.  */
1693     }
1694   else if (within_current_scope && b->exp)
1695     {
1696       int pc = 0;
1697       struct value *val_chain, *v, *result, *next;
1698       struct program_space *frame_pspace;
1699
1700       fetch_subexp_value (b->exp, &pc, &v, &result, &val_chain);
1701
1702       /* Avoid setting b->val if it's already set.  The meaning of
1703          b->val is 'the last value' user saw, and we should update
1704          it only if we reported that last value to user.  As it
1705          happens, the code that reports it updates b->val directly.
1706          We don't keep track of the memory value for masked
1707          watchpoints.  */
1708       if (!b->val_valid && !is_masked_watchpoint (&b->base))
1709         {
1710           b->val = v;
1711           b->val_valid = 1;
1712         }
1713
1714       frame_pspace = get_frame_program_space (get_selected_frame (NULL));
1715
1716       /* Look at each value on the value chain.  */
1717       for (v = val_chain; v; v = value_next (v))
1718         {
1719           /* If it's a memory location, and GDB actually needed
1720              its contents to evaluate the expression, then we
1721              must watch it.  If the first value returned is
1722              still lazy, that means an error occurred reading it;
1723              watch it anyway in case it becomes readable.  */
1724           if (VALUE_LVAL (v) == lval_memory
1725               && (v == val_chain || ! value_lazy (v)))
1726             {
1727               struct type *vtype = check_typedef (value_type (v));
1728
1729               /* We only watch structs and arrays if user asked
1730                  for it explicitly, never if they just happen to
1731                  appear in the middle of some value chain.  */
1732               if (v == result
1733                   || (TYPE_CODE (vtype) != TYPE_CODE_STRUCT
1734                       && TYPE_CODE (vtype) != TYPE_CODE_ARRAY))
1735                 {
1736                   CORE_ADDR addr;
1737                   int len, type;
1738                   struct bp_location *loc, **tmp;
1739
1740                   addr = value_address (v);
1741                   len = TYPE_LENGTH (value_type (v));
1742                   type = hw_write;
1743                   if (b->base.type == bp_read_watchpoint)
1744                     type = hw_read;
1745                   else if (b->base.type == bp_access_watchpoint)
1746                     type = hw_access;
1747
1748                   loc = allocate_bp_location (&b->base);
1749                   for (tmp = &(b->base.loc); *tmp != NULL; tmp = &((*tmp)->next))
1750                     ;
1751                   *tmp = loc;
1752                   loc->gdbarch = get_type_arch (value_type (v));
1753
1754                   loc->pspace = frame_pspace;
1755                   loc->address = addr;
1756                   loc->length = len;
1757                   loc->watchpoint_type = type;
1758                 }
1759             }
1760         }
1761
1762       /* Change the type of breakpoint between hardware assisted or
1763          an ordinary watchpoint depending on the hardware support
1764          and free hardware slots.  REPARSE is set when the inferior
1765          is started.  */
1766       if (reparse)
1767         {
1768           int reg_cnt;
1769           enum bp_loc_type loc_type;
1770           struct bp_location *bl;
1771
1772           reg_cnt = can_use_hardware_watchpoint (val_chain);
1773
1774           if (reg_cnt)
1775             {
1776               int i, target_resources_ok, other_type_used;
1777               enum bptype type;
1778
1779               /* Use an exact watchpoint when there's only one memory region to be
1780                  watched, and only one debug register is needed to watch it.  */
1781               b->exact = target_exact_watchpoints && reg_cnt == 1;
1782
1783               /* We need to determine how many resources are already
1784                  used for all other hardware watchpoints plus this one
1785                  to see if we still have enough resources to also fit
1786                  this watchpoint in as well.  */
1787
1788               /* If this is a software watchpoint, we try to turn it
1789                  to a hardware one -- count resources as if B was of
1790                  hardware watchpoint type.  */
1791               type = b->base.type;
1792               if (type == bp_watchpoint)
1793                 type = bp_hardware_watchpoint;
1794
1795               /* This watchpoint may or may not have been placed on
1796                  the list yet at this point (it won't be in the list
1797                  if we're trying to create it for the first time,
1798                  through watch_command), so always account for it
1799                  manually.  */
1800
1801               /* Count resources used by all watchpoints except B.  */
1802               i = hw_watchpoint_used_count_others (&b->base, type, &other_type_used);
1803
1804               /* Add in the resources needed for B.  */
1805               i += hw_watchpoint_use_count (&b->base);
1806
1807               target_resources_ok
1808                 = target_can_use_hardware_watchpoint (type, i, other_type_used);
1809               if (target_resources_ok <= 0)
1810                 {
1811                   int sw_mode = b->base.ops->works_in_software_mode (&b->base);
1812
1813                   if (target_resources_ok == 0 && !sw_mode)
1814                     error (_("Target does not support this type of "
1815                              "hardware watchpoint."));
1816                   else if (target_resources_ok < 0 && !sw_mode)
1817                     error (_("There are not enough available hardware "
1818                              "resources for this watchpoint."));
1819
1820                   /* Downgrade to software watchpoint.  */
1821                   b->base.type = bp_watchpoint;
1822                 }
1823               else
1824                 {
1825                   /* If this was a software watchpoint, we've just
1826                      found we have enough resources to turn it to a
1827                      hardware watchpoint.  Otherwise, this is a
1828                      nop.  */
1829                   b->base.type = type;
1830                 }
1831             }
1832           else if (!b->base.ops->works_in_software_mode (&b->base))
1833             error (_("Expression cannot be implemented with "
1834                      "read/access watchpoint."));
1835           else
1836             b->base.type = bp_watchpoint;
1837
1838           loc_type = (b->base.type == bp_watchpoint? bp_loc_other
1839                       : bp_loc_hardware_watchpoint);
1840           for (bl = b->base.loc; bl; bl = bl->next)
1841             bl->loc_type = loc_type;
1842         }
1843
1844       for (v = val_chain; v; v = next)
1845         {
1846           next = value_next (v);
1847           if (v != b->val)
1848             value_free (v);
1849         }
1850
1851       /* If a software watchpoint is not watching any memory, then the
1852          above left it without any location set up.  But,
1853          bpstat_stop_status requires a location to be able to report
1854          stops, so make sure there's at least a dummy one.  */
1855       if (b->base.type == bp_watchpoint && b->base.loc == NULL)
1856         {
1857           struct breakpoint *base = &b->base;
1858           base->loc = allocate_bp_location (base);
1859           base->loc->pspace = frame_pspace;
1860           base->loc->address = -1;
1861           base->loc->length = -1;
1862           base->loc->watchpoint_type = -1;
1863         }
1864     }
1865   else if (!within_current_scope)
1866     {
1867       printf_filtered (_("\
1868 Watchpoint %d deleted because the program has left the block\n\
1869 in which its expression is valid.\n"),
1870                        b->base.number);
1871       watchpoint_del_at_next_stop (b);
1872     }
1873
1874   /* Restore the selected frame.  */
1875   if (frame_saved)
1876     select_frame (frame_find_by_id (saved_frame_id));
1877 }
1878
1879
1880 /* Returns 1 iff breakpoint location should be
1881    inserted in the inferior.  We don't differentiate the type of BL's owner
1882    (breakpoint vs. tracepoint), although insert_location in tracepoint's
1883    breakpoint_ops is not defined, because in insert_bp_location,
1884    tracepoint's insert_location will not be called.  */
1885 static int
1886 should_be_inserted (struct bp_location *bl)
1887 {
1888   if (bl->owner == NULL || !breakpoint_enabled (bl->owner))
1889     return 0;
1890
1891   if (bl->owner->disposition == disp_del_at_next_stop)
1892     return 0;
1893
1894   if (!bl->enabled || bl->shlib_disabled || bl->duplicate)
1895     return 0;
1896
1897   if (user_breakpoint_p (bl->owner) && bl->pspace->executing_startup)
1898     return 0;
1899
1900   /* This is set for example, when we're attached to the parent of a
1901      vfork, and have detached from the child.  The child is running
1902      free, and we expect it to do an exec or exit, at which point the
1903      OS makes the parent schedulable again (and the target reports
1904      that the vfork is done).  Until the child is done with the shared
1905      memory region, do not insert breakpoints in the parent, otherwise
1906      the child could still trip on the parent's breakpoints.  Since
1907      the parent is blocked anyway, it won't miss any breakpoint.  */
1908   if (bl->pspace->breakpoints_not_allowed)
1909     return 0;
1910
1911   return 1;
1912 }
1913
1914 /* Same as should_be_inserted but does the check assuming
1915    that the location is not duplicated.  */
1916
1917 static int
1918 unduplicated_should_be_inserted (struct bp_location *bl)
1919 {
1920   int result;
1921   const int save_duplicate = bl->duplicate;
1922
1923   bl->duplicate = 0;
1924   result = should_be_inserted (bl);
1925   bl->duplicate = save_duplicate;
1926   return result;
1927 }
1928
1929 /* Parses a conditional described by an expression COND into an
1930    agent expression bytecode suitable for evaluation
1931    by the bytecode interpreter.  Return NULL if there was
1932    any error during parsing.  */
1933
1934 static struct agent_expr *
1935 parse_cond_to_aexpr (CORE_ADDR scope, struct expression *cond)
1936 {
1937   struct agent_expr *aexpr = NULL;
1938   struct cleanup *old_chain = NULL;
1939   volatile struct gdb_exception ex;
1940
1941   if (!cond)
1942     return NULL;
1943
1944   /* We don't want to stop processing, so catch any errors
1945      that may show up.  */
1946   TRY_CATCH (ex, RETURN_MASK_ERROR)
1947     {
1948       aexpr = gen_eval_for_expr (scope, cond);
1949     }
1950
1951   if (ex.reason < 0)
1952     {
1953       /* If we got here, it means the condition could not be parsed to a valid
1954          bytecode expression and thus can't be evaluated on the target's side.
1955          It's no use iterating through the conditions.  */
1956       return NULL;
1957     }
1958
1959   /* We have a valid agent expression.  */
1960   return aexpr;
1961 }
1962
1963 /* Based on location BL, create a list of breakpoint conditions to be
1964    passed on to the target.  If we have duplicated locations with different
1965    conditions, we will add such conditions to the list.  The idea is that the
1966    target will evaluate the list of conditions and will only notify GDB when
1967    one of them is true.  */
1968
1969 static void
1970 build_target_condition_list (struct bp_location *bl)
1971 {
1972   struct bp_location **locp = NULL, **loc2p;
1973   int null_condition_or_parse_error = 0;
1974   int modified = bl->needs_update;
1975   struct bp_location *loc;
1976
1977   /* This is only meaningful if the target is
1978      evaluating conditions and if the user has
1979      opted for condition evaluation on the target's
1980      side.  */
1981   if (gdb_evaluates_breakpoint_condition_p ()
1982       || !target_supports_evaluation_of_breakpoint_conditions ())
1983     return;
1984
1985   /* Do a first pass to check for locations with no assigned
1986      conditions or conditions that fail to parse to a valid agent expression
1987      bytecode.  If any of these happen, then it's no use to send conditions
1988      to the target since this location will always trigger and generate a
1989      response back to GDB.  */
1990   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
1991     {
1992       loc = (*loc2p);
1993       if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
1994         {
1995           if (modified)
1996             {
1997               struct agent_expr *aexpr;
1998
1999               /* Re-parse the conditions since something changed.  In that
2000                  case we already freed the condition bytecodes (see
2001                  force_breakpoint_reinsertion).  We just
2002                  need to parse the condition to bytecodes again.  */
2003               aexpr = parse_cond_to_aexpr (bl->address, loc->cond);
2004               loc->cond_bytecode = aexpr;
2005
2006               /* Check if we managed to parse the conditional expression
2007                  correctly.  If not, we will not send this condition
2008                  to the target.  */
2009               if (aexpr)
2010                 continue;
2011             }
2012
2013           /* If we have a NULL bytecode expression, it means something
2014              went wrong or we have a null condition expression.  */
2015           if (!loc->cond_bytecode)
2016             {
2017               null_condition_or_parse_error = 1;
2018               break;
2019             }
2020         }
2021     }
2022
2023   /* If any of these happened, it means we will have to evaluate the conditions
2024      for the location's address on gdb's side.  It is no use keeping bytecodes
2025      for all the other duplicate locations, thus we free all of them here.
2026
2027      This is so we have a finer control over which locations' conditions are
2028      being evaluated by GDB or the remote stub.  */
2029   if (null_condition_or_parse_error)
2030     {
2031       ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2032         {
2033           loc = (*loc2p);
2034           if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2035             {
2036               /* Only go as far as the first NULL bytecode is
2037                  located.  */
2038               if (!loc->cond_bytecode)
2039                 return;
2040
2041               free_agent_expr (loc->cond_bytecode);
2042               loc->cond_bytecode = NULL;
2043             }
2044         }
2045     }
2046
2047   /* No NULL conditions or failed bytecode generation.  Build a condition list
2048      for this location's address.  */
2049   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2050     {
2051       loc = (*loc2p);
2052       if (loc->cond
2053           && is_breakpoint (loc->owner)
2054           && loc->pspace->num == bl->pspace->num
2055           && loc->owner->enable_state == bp_enabled
2056           && loc->enabled)
2057         /* Add the condition to the vector.  This will be used later to send the
2058            conditions to the target.  */
2059         VEC_safe_push (agent_expr_p, bl->target_info.conditions,
2060                        loc->cond_bytecode);
2061     }
2062
2063   return;
2064 }
2065
2066 /* Insert a low-level "breakpoint" of some type.  BL is the breakpoint
2067    location.  Any error messages are printed to TMP_ERROR_STREAM; and
2068    DISABLED_BREAKS, and HW_BREAKPOINT_ERROR are used to report problems.
2069    Returns 0 for success, 1 if the bp_location type is not supported or
2070    -1 for failure.
2071
2072    NOTE drow/2003-09-09: This routine could be broken down to an
2073    object-style method for each breakpoint or catchpoint type.  */
2074 static int
2075 insert_bp_location (struct bp_location *bl,
2076                     struct ui_file *tmp_error_stream,
2077                     int *disabled_breaks,
2078                     int *hw_breakpoint_error)
2079 {
2080   int val = 0;
2081
2082   if (!should_be_inserted (bl) || (bl->inserted && !bl->needs_update))
2083     return 0;
2084
2085   /* Initialize the target-specific information.  */
2086   memset (&bl->target_info, 0, sizeof (bl->target_info));
2087   bl->target_info.placed_address = bl->address;
2088   bl->target_info.placed_address_space = bl->pspace->aspace;
2089   bl->target_info.length = bl->length;
2090
2091   /* When working with target-side conditions, we must pass all the conditions
2092      for the same breakpoint address down to the target since GDB will not
2093      insert those locations.  With a list of breakpoint conditions, the target
2094      can decide when to stop and notify GDB.  */
2095
2096   if (is_breakpoint (bl->owner))
2097     {
2098       build_target_condition_list (bl);
2099       /* Reset the condition modification marker.  */
2100       bl->needs_update = 0;
2101     }
2102
2103   if (bl->loc_type == bp_loc_software_breakpoint
2104       || bl->loc_type == bp_loc_hardware_breakpoint)
2105     {
2106       if (bl->owner->type != bp_hardware_breakpoint)
2107         {
2108           /* If the explicitly specified breakpoint type
2109              is not hardware breakpoint, check the memory map to see
2110              if the breakpoint address is in read only memory or not.
2111
2112              Two important cases are:
2113              - location type is not hardware breakpoint, memory
2114              is readonly.  We change the type of the location to
2115              hardware breakpoint.
2116              - location type is hardware breakpoint, memory is
2117              read-write.  This means we've previously made the
2118              location hardware one, but then the memory map changed,
2119              so we undo.
2120              
2121              When breakpoints are removed, remove_breakpoints will use
2122              location types we've just set here, the only possible
2123              problem is that memory map has changed during running
2124              program, but it's not going to work anyway with current
2125              gdb.  */
2126           struct mem_region *mr 
2127             = lookup_mem_region (bl->target_info.placed_address);
2128           
2129           if (mr)
2130             {
2131               if (automatic_hardware_breakpoints)
2132                 {
2133                   enum bp_loc_type new_type;
2134                   
2135                   if (mr->attrib.mode != MEM_RW)
2136                     new_type = bp_loc_hardware_breakpoint;
2137                   else 
2138                     new_type = bp_loc_software_breakpoint;
2139                   
2140                   if (new_type != bl->loc_type)
2141                     {
2142                       static int said = 0;
2143
2144                       bl->loc_type = new_type;
2145                       if (!said)
2146                         {
2147                           fprintf_filtered (gdb_stdout,
2148                                             _("Note: automatically using "
2149                                               "hardware breakpoints for "
2150                                               "read-only addresses.\n"));
2151                           said = 1;
2152                         }
2153                     }
2154                 }
2155               else if (bl->loc_type == bp_loc_software_breakpoint
2156                        && mr->attrib.mode != MEM_RW)        
2157                 warning (_("cannot set software breakpoint "
2158                            "at readonly address %s"),
2159                          paddress (bl->gdbarch, bl->address));
2160             }
2161         }
2162         
2163       /* First check to see if we have to handle an overlay.  */
2164       if (overlay_debugging == ovly_off
2165           || bl->section == NULL
2166           || !(section_is_overlay (bl->section)))
2167         {
2168           /* No overlay handling: just set the breakpoint.  */
2169
2170           val = bl->owner->ops->insert_location (bl);
2171         }
2172       else
2173         {
2174           /* This breakpoint is in an overlay section.
2175              Shall we set a breakpoint at the LMA?  */
2176           if (!overlay_events_enabled)
2177             {
2178               /* Yes -- overlay event support is not active, 
2179                  so we must try to set a breakpoint at the LMA.
2180                  This will not work for a hardware breakpoint.  */
2181               if (bl->loc_type == bp_loc_hardware_breakpoint)
2182                 warning (_("hardware breakpoint %d not supported in overlay!"),
2183                          bl->owner->number);
2184               else
2185                 {
2186                   CORE_ADDR addr = overlay_unmapped_address (bl->address,
2187                                                              bl->section);
2188                   /* Set a software (trap) breakpoint at the LMA.  */
2189                   bl->overlay_target_info = bl->target_info;
2190                   bl->overlay_target_info.placed_address = addr;
2191                   val = target_insert_breakpoint (bl->gdbarch,
2192                                                   &bl->overlay_target_info);
2193                   if (val != 0)
2194                     fprintf_unfiltered (tmp_error_stream,
2195                                         "Overlay breakpoint %d "
2196                                         "failed: in ROM?\n",
2197                                         bl->owner->number);
2198                 }
2199             }
2200           /* Shall we set a breakpoint at the VMA? */
2201           if (section_is_mapped (bl->section))
2202             {
2203               /* Yes.  This overlay section is mapped into memory.  */
2204               val = bl->owner->ops->insert_location (bl);
2205             }
2206           else
2207             {
2208               /* No.  This breakpoint will not be inserted.  
2209                  No error, but do not mark the bp as 'inserted'.  */
2210               return 0;
2211             }
2212         }
2213
2214       if (val)
2215         {
2216           /* Can't set the breakpoint.  */
2217           if (solib_name_from_address (bl->pspace, bl->address))
2218             {
2219               /* See also: disable_breakpoints_in_shlibs.  */
2220               val = 0;
2221               bl->shlib_disabled = 1;
2222               observer_notify_breakpoint_modified (bl->owner);
2223               if (!*disabled_breaks)
2224                 {
2225                   fprintf_unfiltered (tmp_error_stream, 
2226                                       "Cannot insert breakpoint %d.\n", 
2227                                       bl->owner->number);
2228                   fprintf_unfiltered (tmp_error_stream, 
2229                                       "Temporarily disabling shared "
2230                                       "library breakpoints:\n");
2231                 }
2232               *disabled_breaks = 1;
2233               fprintf_unfiltered (tmp_error_stream,
2234                                   "breakpoint #%d\n", bl->owner->number);
2235             }
2236           else
2237             {
2238               if (bl->loc_type == bp_loc_hardware_breakpoint)
2239                 {
2240                   *hw_breakpoint_error = 1;
2241                   fprintf_unfiltered (tmp_error_stream,
2242                                       "Cannot insert hardware "
2243                                       "breakpoint %d.\n",
2244                                       bl->owner->number);
2245                 }
2246               else
2247                 {
2248                   fprintf_unfiltered (tmp_error_stream, 
2249                                       "Cannot insert breakpoint %d.\n", 
2250                                       bl->owner->number);
2251                   fprintf_filtered (tmp_error_stream, 
2252                                     "Error accessing memory address ");
2253                   fputs_filtered (paddress (bl->gdbarch, bl->address),
2254                                   tmp_error_stream);
2255                   fprintf_filtered (tmp_error_stream, ": %s.\n",
2256                                     safe_strerror (val));
2257                 }
2258
2259             }
2260         }
2261       else
2262         bl->inserted = 1;
2263
2264       return val;
2265     }
2266
2267   else if (bl->loc_type == bp_loc_hardware_watchpoint
2268            /* NOTE drow/2003-09-08: This state only exists for removing
2269               watchpoints.  It's not clear that it's necessary...  */
2270            && bl->owner->disposition != disp_del_at_next_stop)
2271     {
2272       gdb_assert (bl->owner->ops != NULL
2273                   && bl->owner->ops->insert_location != NULL);
2274
2275       val = bl->owner->ops->insert_location (bl);
2276
2277       /* If trying to set a read-watchpoint, and it turns out it's not
2278          supported, try emulating one with an access watchpoint.  */
2279       if (val == 1 && bl->watchpoint_type == hw_read)
2280         {
2281           struct bp_location *loc, **loc_temp;
2282
2283           /* But don't try to insert it, if there's already another
2284              hw_access location that would be considered a duplicate
2285              of this one.  */
2286           ALL_BP_LOCATIONS (loc, loc_temp)
2287             if (loc != bl
2288                 && loc->watchpoint_type == hw_access
2289                 && watchpoint_locations_match (bl, loc))
2290               {
2291                 bl->duplicate = 1;
2292                 bl->inserted = 1;
2293                 bl->target_info = loc->target_info;
2294                 bl->watchpoint_type = hw_access;
2295                 val = 0;
2296                 break;
2297               }
2298
2299           if (val == 1)
2300             {
2301               bl->watchpoint_type = hw_access;
2302               val = bl->owner->ops->insert_location (bl);
2303
2304               if (val)
2305                 /* Back to the original value.  */
2306                 bl->watchpoint_type = hw_read;
2307             }
2308         }
2309
2310       bl->inserted = (val == 0);
2311     }
2312
2313   else if (bl->owner->type == bp_catchpoint)
2314     {
2315       gdb_assert (bl->owner->ops != NULL
2316                   && bl->owner->ops->insert_location != NULL);
2317
2318       val = bl->owner->ops->insert_location (bl);
2319       if (val)
2320         {
2321           bl->owner->enable_state = bp_disabled;
2322
2323           if (val == 1)
2324             warning (_("\
2325 Error inserting catchpoint %d: Your system does not support this type\n\
2326 of catchpoint."), bl->owner->number);
2327           else
2328             warning (_("Error inserting catchpoint %d."), bl->owner->number);
2329         }
2330
2331       bl->inserted = (val == 0);
2332
2333       /* We've already printed an error message if there was a problem
2334          inserting this catchpoint, and we've disabled the catchpoint,
2335          so just return success.  */
2336       return 0;
2337     }
2338
2339   return 0;
2340 }
2341
2342 /* This function is called when program space PSPACE is about to be
2343    deleted.  It takes care of updating breakpoints to not reference
2344    PSPACE anymore.  */
2345
2346 void
2347 breakpoint_program_space_exit (struct program_space *pspace)
2348 {
2349   struct breakpoint *b, *b_temp;
2350   struct bp_location *loc, **loc_temp;
2351
2352   /* Remove any breakpoint that was set through this program space.  */
2353   ALL_BREAKPOINTS_SAFE (b, b_temp)
2354     {
2355       if (b->pspace == pspace)
2356         delete_breakpoint (b);
2357     }
2358
2359   /* Breakpoints set through other program spaces could have locations
2360      bound to PSPACE as well.  Remove those.  */
2361   ALL_BP_LOCATIONS (loc, loc_temp)
2362     {
2363       struct bp_location *tmp;
2364
2365       if (loc->pspace == pspace)
2366         {
2367           /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
2368           if (loc->owner->loc == loc)
2369             loc->owner->loc = loc->next;
2370           else
2371             for (tmp = loc->owner->loc; tmp->next != NULL; tmp = tmp->next)
2372               if (tmp->next == loc)
2373                 {
2374                   tmp->next = loc->next;
2375                   break;
2376                 }
2377         }
2378     }
2379
2380   /* Now update the global location list to permanently delete the
2381      removed locations above.  */
2382   update_global_location_list (0);
2383 }
2384
2385 /* Make sure all breakpoints are inserted in inferior.
2386    Throws exception on any error.
2387    A breakpoint that is already inserted won't be inserted
2388    again, so calling this function twice is safe.  */
2389 void
2390 insert_breakpoints (void)
2391 {
2392   struct breakpoint *bpt;
2393
2394   ALL_BREAKPOINTS (bpt)
2395     if (is_hardware_watchpoint (bpt))
2396       {
2397         struct watchpoint *w = (struct watchpoint *) bpt;
2398
2399         update_watchpoint (w, 0 /* don't reparse.  */);
2400       }
2401
2402   update_global_location_list (1);
2403
2404   /* update_global_location_list does not insert breakpoints when
2405      always_inserted_mode is not enabled.  Explicitly insert them
2406      now.  */
2407   if (!breakpoints_always_inserted_mode ())
2408     insert_breakpoint_locations ();
2409 }
2410
2411 /* This is used when we need to synch breakpoint conditions between GDB and the
2412    target.  It is the case with deleting and disabling of breakpoints when using
2413    always-inserted mode.  */
2414
2415 static void
2416 update_inserted_breakpoint_locations (void)
2417 {
2418   struct bp_location *bl, **blp_tmp;
2419   int error_flag = 0;
2420   int val = 0;
2421   int disabled_breaks = 0;
2422   int hw_breakpoint_error = 0;
2423
2424   struct ui_file *tmp_error_stream = mem_fileopen ();
2425   struct cleanup *cleanups = make_cleanup_ui_file_delete (tmp_error_stream);
2426
2427   /* Explicitly mark the warning -- this will only be printed if
2428      there was an error.  */
2429   fprintf_unfiltered (tmp_error_stream, "Warning:\n");
2430
2431   save_current_space_and_thread ();
2432
2433   ALL_BP_LOCATIONS (bl, blp_tmp)
2434     {
2435       /* We only want to update software breakpoints and hardware
2436          breakpoints.  */
2437       if (!is_breakpoint (bl->owner))
2438         continue;
2439
2440       /* We only want to update locations that are already inserted
2441          and need updating.  This is to avoid unwanted insertion during
2442          deletion of breakpoints.  */
2443       if (!bl->inserted || (bl->inserted && !bl->needs_update))
2444         continue;
2445
2446       switch_to_program_space_and_thread (bl->pspace);
2447
2448       /* For targets that support global breakpoints, there's no need
2449          to select an inferior to insert breakpoint to.  In fact, even
2450          if we aren't attached to any process yet, we should still
2451          insert breakpoints.  */
2452       if (!gdbarch_has_global_breakpoints (target_gdbarch)
2453           && ptid_equal (inferior_ptid, null_ptid))
2454         continue;
2455
2456       val = insert_bp_location (bl, tmp_error_stream, &disabled_breaks,
2457                                     &hw_breakpoint_error);
2458       if (val)
2459         error_flag = val;
2460     }
2461
2462   if (error_flag)
2463     {
2464       target_terminal_ours_for_output ();
2465       error_stream (tmp_error_stream);
2466     }
2467
2468   do_cleanups (cleanups);
2469 }
2470
2471 /* Used when starting or continuing the program.  */
2472
2473 static void
2474 insert_breakpoint_locations (void)
2475 {
2476   struct breakpoint *bpt;
2477   struct bp_location *bl, **blp_tmp;
2478   int error_flag = 0;
2479   int val = 0;
2480   int disabled_breaks = 0;
2481   int hw_breakpoint_error = 0;
2482
2483   struct ui_file *tmp_error_stream = mem_fileopen ();
2484   struct cleanup *cleanups = make_cleanup_ui_file_delete (tmp_error_stream);
2485   
2486   /* Explicitly mark the warning -- this will only be printed if
2487      there was an error.  */
2488   fprintf_unfiltered (tmp_error_stream, "Warning:\n");
2489
2490   save_current_space_and_thread ();
2491
2492   ALL_BP_LOCATIONS (bl, blp_tmp)
2493     {
2494       if (!should_be_inserted (bl) || (bl->inserted && !bl->needs_update))
2495         continue;
2496
2497       /* There is no point inserting thread-specific breakpoints if
2498          the thread no longer exists.  ALL_BP_LOCATIONS bp_location
2499          has BL->OWNER always non-NULL.  */
2500       if (bl->owner->thread != -1
2501           && !valid_thread_id (bl->owner->thread))
2502         continue;
2503
2504       switch_to_program_space_and_thread (bl->pspace);
2505
2506       /* For targets that support global breakpoints, there's no need
2507          to select an inferior to insert breakpoint to.  In fact, even
2508          if we aren't attached to any process yet, we should still
2509          insert breakpoints.  */
2510       if (!gdbarch_has_global_breakpoints (target_gdbarch)
2511           && ptid_equal (inferior_ptid, null_ptid))
2512         continue;
2513
2514       val = insert_bp_location (bl, tmp_error_stream, &disabled_breaks,
2515                                     &hw_breakpoint_error);
2516       if (val)
2517         error_flag = val;
2518     }
2519
2520   /* If we failed to insert all locations of a watchpoint, remove
2521      them, as half-inserted watchpoint is of limited use.  */
2522   ALL_BREAKPOINTS (bpt)  
2523     {
2524       int some_failed = 0;
2525       struct bp_location *loc;
2526
2527       if (!is_hardware_watchpoint (bpt))
2528         continue;
2529
2530       if (!breakpoint_enabled (bpt))
2531         continue;
2532
2533       if (bpt->disposition == disp_del_at_next_stop)
2534         continue;
2535       
2536       for (loc = bpt->loc; loc; loc = loc->next)
2537         if (!loc->inserted && should_be_inserted (loc))
2538           {
2539             some_failed = 1;
2540             break;
2541           }
2542       if (some_failed)
2543         {
2544           for (loc = bpt->loc; loc; loc = loc->next)
2545             if (loc->inserted)
2546               remove_breakpoint (loc, mark_uninserted);
2547
2548           hw_breakpoint_error = 1;
2549           fprintf_unfiltered (tmp_error_stream,
2550                               "Could not insert hardware watchpoint %d.\n", 
2551                               bpt->number);
2552           error_flag = -1;
2553         }
2554     }
2555
2556   if (error_flag)
2557     {
2558       /* If a hardware breakpoint or watchpoint was inserted, add a
2559          message about possibly exhausted resources.  */
2560       if (hw_breakpoint_error)
2561         {
2562           fprintf_unfiltered (tmp_error_stream, 
2563                               "Could not insert hardware breakpoints:\n\
2564 You may have requested too many hardware breakpoints/watchpoints.\n");
2565         }
2566       target_terminal_ours_for_output ();
2567       error_stream (tmp_error_stream);
2568     }
2569
2570   do_cleanups (cleanups);
2571 }
2572
2573 /* Used when the program stops.
2574    Returns zero if successful, or non-zero if there was a problem
2575    removing a breakpoint location.  */
2576
2577 int
2578 remove_breakpoints (void)
2579 {
2580   struct bp_location *bl, **blp_tmp;
2581   int val = 0;
2582
2583   ALL_BP_LOCATIONS (bl, blp_tmp)
2584   {
2585     if (bl->inserted && !is_tracepoint (bl->owner))
2586       val |= remove_breakpoint (bl, mark_uninserted);
2587   }
2588   return val;
2589 }
2590
2591 /* Remove breakpoints of process PID.  */
2592
2593 int
2594 remove_breakpoints_pid (int pid)
2595 {
2596   struct bp_location *bl, **blp_tmp;
2597   int val;
2598   struct inferior *inf = find_inferior_pid (pid);
2599
2600   ALL_BP_LOCATIONS (bl, blp_tmp)
2601   {
2602     if (bl->pspace != inf->pspace)
2603       continue;
2604
2605     if (bl->inserted)
2606       {
2607         val = remove_breakpoint (bl, mark_uninserted);
2608         if (val != 0)
2609           return val;
2610       }
2611   }
2612   return 0;
2613 }
2614
2615 int
2616 reattach_breakpoints (int pid)
2617 {
2618   struct cleanup *old_chain;
2619   struct bp_location *bl, **blp_tmp;
2620   int val;
2621   struct ui_file *tmp_error_stream;
2622   int dummy1 = 0, dummy2 = 0;
2623   struct inferior *inf;
2624   struct thread_info *tp;
2625
2626   tp = any_live_thread_of_process (pid);
2627   if (tp == NULL)
2628     return 1;
2629
2630   inf = find_inferior_pid (pid);
2631   old_chain = save_inferior_ptid ();
2632
2633   inferior_ptid = tp->ptid;
2634
2635   tmp_error_stream = mem_fileopen ();
2636   make_cleanup_ui_file_delete (tmp_error_stream);
2637
2638   ALL_BP_LOCATIONS (bl, blp_tmp)
2639   {
2640     if (bl->pspace != inf->pspace)
2641       continue;
2642
2643     if (bl->inserted)
2644       {
2645         bl->inserted = 0;
2646         val = insert_bp_location (bl, tmp_error_stream, &dummy1, &dummy2);
2647         if (val != 0)
2648           {
2649             do_cleanups (old_chain);
2650             return val;
2651           }
2652       }
2653   }
2654   do_cleanups (old_chain);
2655   return 0;
2656 }
2657
2658 static int internal_breakpoint_number = -1;
2659
2660 /* Set the breakpoint number of B, depending on the value of INTERNAL.
2661    If INTERNAL is non-zero, the breakpoint number will be populated
2662    from internal_breakpoint_number and that variable decremented.
2663    Otherwise the breakpoint number will be populated from
2664    breakpoint_count and that value incremented.  Internal breakpoints
2665    do not set the internal var bpnum.  */
2666 static void
2667 set_breakpoint_number (int internal, struct breakpoint *b)
2668 {
2669   if (internal)
2670     b->number = internal_breakpoint_number--;
2671   else
2672     {
2673       set_breakpoint_count (breakpoint_count + 1);
2674       b->number = breakpoint_count;
2675     }
2676 }
2677
2678 static struct breakpoint *
2679 create_internal_breakpoint (struct gdbarch *gdbarch,
2680                             CORE_ADDR address, enum bptype type,
2681                             const struct breakpoint_ops *ops)
2682 {
2683   struct symtab_and_line sal;
2684   struct breakpoint *b;
2685
2686   init_sal (&sal);              /* Initialize to zeroes.  */
2687
2688   sal.pc = address;
2689   sal.section = find_pc_overlay (sal.pc);
2690   sal.pspace = current_program_space;
2691
2692   b = set_raw_breakpoint (gdbarch, sal, type, ops);
2693   b->number = internal_breakpoint_number--;
2694   b->disposition = disp_donttouch;
2695
2696   return b;
2697 }
2698
2699 static const char *const longjmp_names[] =
2700   {
2701     "longjmp", "_longjmp", "siglongjmp", "_siglongjmp"
2702   };
2703 #define NUM_LONGJMP_NAMES ARRAY_SIZE(longjmp_names)
2704
2705 /* Per-objfile data private to breakpoint.c.  */
2706 struct breakpoint_objfile_data
2707 {
2708   /* Minimal symbol for "_ovly_debug_event" (if any).  */
2709   struct minimal_symbol *overlay_msym;
2710
2711   /* Minimal symbol(s) for "longjmp", "siglongjmp", etc. (if any).  */
2712   struct minimal_symbol *longjmp_msym[NUM_LONGJMP_NAMES];
2713
2714   /* Minimal symbol for "std::terminate()" (if any).  */
2715   struct minimal_symbol *terminate_msym;
2716
2717   /* Minimal symbol for "_Unwind_DebugHook" (if any).  */
2718   struct minimal_symbol *exception_msym;
2719 };
2720
2721 static const struct objfile_data *breakpoint_objfile_key;
2722
2723 /* Minimal symbol not found sentinel.  */
2724 static struct minimal_symbol msym_not_found;
2725
2726 /* Returns TRUE if MSYM point to the "not found" sentinel.  */
2727
2728 static int
2729 msym_not_found_p (const struct minimal_symbol *msym)
2730 {
2731   return msym == &msym_not_found;
2732 }
2733
2734 /* Return per-objfile data needed by breakpoint.c.
2735    Allocate the data if necessary.  */
2736
2737 static struct breakpoint_objfile_data *
2738 get_breakpoint_objfile_data (struct objfile *objfile)
2739 {
2740   struct breakpoint_objfile_data *bp_objfile_data;
2741
2742   bp_objfile_data = objfile_data (objfile, breakpoint_objfile_key);
2743   if (bp_objfile_data == NULL)
2744     {
2745       bp_objfile_data = obstack_alloc (&objfile->objfile_obstack,
2746                                        sizeof (*bp_objfile_data));
2747
2748       memset (bp_objfile_data, 0, sizeof (*bp_objfile_data));
2749       set_objfile_data (objfile, breakpoint_objfile_key, bp_objfile_data);
2750     }
2751   return bp_objfile_data;
2752 }
2753
2754 static void
2755 create_overlay_event_breakpoint (void)
2756 {
2757   struct objfile *objfile;
2758   const char *const func_name = "_ovly_debug_event";
2759
2760   ALL_OBJFILES (objfile)
2761     {
2762       struct breakpoint *b;
2763       struct breakpoint_objfile_data *bp_objfile_data;
2764       CORE_ADDR addr;
2765
2766       bp_objfile_data = get_breakpoint_objfile_data (objfile);
2767
2768       if (msym_not_found_p (bp_objfile_data->overlay_msym))
2769         continue;
2770
2771       if (bp_objfile_data->overlay_msym == NULL)
2772         {
2773           struct minimal_symbol *m;
2774
2775           m = lookup_minimal_symbol_text (func_name, objfile);
2776           if (m == NULL)
2777             {
2778               /* Avoid future lookups in this objfile.  */
2779               bp_objfile_data->overlay_msym = &msym_not_found;
2780               continue;
2781             }
2782           bp_objfile_data->overlay_msym = m;
2783         }
2784
2785       addr = SYMBOL_VALUE_ADDRESS (bp_objfile_data->overlay_msym);
2786       b = create_internal_breakpoint (get_objfile_arch (objfile), addr,
2787                                       bp_overlay_event,
2788                                       &internal_breakpoint_ops);
2789       b->addr_string = xstrdup (func_name);
2790
2791       if (overlay_debugging == ovly_auto)
2792         {
2793           b->enable_state = bp_enabled;
2794           overlay_events_enabled = 1;
2795         }
2796       else
2797        {
2798          b->enable_state = bp_disabled;
2799          overlay_events_enabled = 0;
2800        }
2801     }
2802   update_global_location_list (1);
2803 }
2804
2805 static void
2806 create_longjmp_master_breakpoint (void)
2807 {
2808   struct program_space *pspace;
2809   struct cleanup *old_chain;
2810
2811   old_chain = save_current_program_space ();
2812
2813   ALL_PSPACES (pspace)
2814   {
2815     struct objfile *objfile;
2816
2817     set_current_program_space (pspace);
2818
2819     ALL_OBJFILES (objfile)
2820     {
2821       int i;
2822       struct gdbarch *gdbarch;
2823       struct breakpoint_objfile_data *bp_objfile_data;
2824
2825       gdbarch = get_objfile_arch (objfile);
2826       if (!gdbarch_get_longjmp_target_p (gdbarch))
2827         continue;
2828
2829       bp_objfile_data = get_breakpoint_objfile_data (objfile);
2830
2831       for (i = 0; i < NUM_LONGJMP_NAMES; i++)
2832         {
2833           struct breakpoint *b;
2834           const char *func_name;
2835           CORE_ADDR addr;
2836
2837           if (msym_not_found_p (bp_objfile_data->longjmp_msym[i]))
2838             continue;
2839
2840           func_name = longjmp_names[i];
2841           if (bp_objfile_data->longjmp_msym[i] == NULL)
2842             {
2843               struct minimal_symbol *m;
2844
2845               m = lookup_minimal_symbol_text (func_name, objfile);
2846               if (m == NULL)
2847                 {
2848                   /* Prevent future lookups in this objfile.  */
2849                   bp_objfile_data->longjmp_msym[i] = &msym_not_found;
2850                   continue;
2851                 }
2852               bp_objfile_data->longjmp_msym[i] = m;
2853             }
2854
2855           addr = SYMBOL_VALUE_ADDRESS (bp_objfile_data->longjmp_msym[i]);
2856           b = create_internal_breakpoint (gdbarch, addr, bp_longjmp_master,
2857                                           &internal_breakpoint_ops);
2858           b->addr_string = xstrdup (func_name);
2859           b->enable_state = bp_disabled;
2860         }
2861     }
2862   }
2863   update_global_location_list (1);
2864
2865   do_cleanups (old_chain);
2866 }
2867
2868 /* Create a master std::terminate breakpoint.  */
2869 static void
2870 create_std_terminate_master_breakpoint (void)
2871 {
2872   struct program_space *pspace;
2873   struct cleanup *old_chain;
2874   const char *const func_name = "std::terminate()";
2875
2876   old_chain = save_current_program_space ();
2877
2878   ALL_PSPACES (pspace)
2879   {
2880     struct objfile *objfile;
2881     CORE_ADDR addr;
2882
2883     set_current_program_space (pspace);
2884
2885     ALL_OBJFILES (objfile)
2886     {
2887       struct breakpoint *b;
2888       struct breakpoint_objfile_data *bp_objfile_data;
2889
2890       bp_objfile_data = get_breakpoint_objfile_data (objfile);
2891
2892       if (msym_not_found_p (bp_objfile_data->terminate_msym))
2893         continue;
2894
2895       if (bp_objfile_data->terminate_msym == NULL)
2896         {
2897           struct minimal_symbol *m;
2898
2899           m = lookup_minimal_symbol (func_name, NULL, objfile);
2900           if (m == NULL || (MSYMBOL_TYPE (m) != mst_text
2901                             && MSYMBOL_TYPE (m) != mst_file_text))
2902             {
2903               /* Prevent future lookups in this objfile.  */
2904               bp_objfile_data->terminate_msym = &msym_not_found;
2905               continue;
2906             }
2907           bp_objfile_data->terminate_msym = m;
2908         }
2909
2910       addr = SYMBOL_VALUE_ADDRESS (bp_objfile_data->terminate_msym);
2911       b = create_internal_breakpoint (get_objfile_arch (objfile), addr,
2912                                       bp_std_terminate_master,
2913                                       &internal_breakpoint_ops);
2914       b->addr_string = xstrdup (func_name);
2915       b->enable_state = bp_disabled;
2916     }
2917   }
2918
2919   update_global_location_list (1);
2920
2921   do_cleanups (old_chain);
2922 }
2923
2924 /* Install a master breakpoint on the unwinder's debug hook.  */
2925
2926 static void
2927 create_exception_master_breakpoint (void)
2928 {
2929   struct objfile *objfile;
2930   const char *const func_name = "_Unwind_DebugHook";
2931
2932   ALL_OBJFILES (objfile)
2933     {
2934       struct breakpoint *b;
2935       struct gdbarch *gdbarch;
2936       struct breakpoint_objfile_data *bp_objfile_data;
2937       CORE_ADDR addr;
2938
2939       bp_objfile_data = get_breakpoint_objfile_data (objfile);
2940
2941       if (msym_not_found_p (bp_objfile_data->exception_msym))
2942         continue;
2943
2944       gdbarch = get_objfile_arch (objfile);
2945
2946       if (bp_objfile_data->exception_msym == NULL)
2947         {
2948           struct minimal_symbol *debug_hook;
2949
2950           debug_hook = lookup_minimal_symbol (func_name, NULL, objfile);
2951           if (debug_hook == NULL)
2952             {
2953               bp_objfile_data->exception_msym = &msym_not_found;
2954               continue;
2955             }
2956
2957           bp_objfile_data->exception_msym = debug_hook;
2958         }
2959
2960       addr = SYMBOL_VALUE_ADDRESS (bp_objfile_data->exception_msym);
2961       addr = gdbarch_convert_from_func_ptr_addr (gdbarch, addr,
2962                                                  &current_target);
2963       b = create_internal_breakpoint (gdbarch, addr, bp_exception_master,
2964                                       &internal_breakpoint_ops);
2965       b->addr_string = xstrdup (func_name);
2966       b->enable_state = bp_disabled;
2967     }
2968
2969   update_global_location_list (1);
2970 }
2971
2972 void
2973 update_breakpoints_after_exec (void)
2974 {
2975   struct breakpoint *b, *b_tmp;
2976   struct bp_location *bploc, **bplocp_tmp;
2977
2978   /* We're about to delete breakpoints from GDB's lists.  If the
2979      INSERTED flag is true, GDB will try to lift the breakpoints by
2980      writing the breakpoints' "shadow contents" back into memory.  The
2981      "shadow contents" are NOT valid after an exec, so GDB should not
2982      do that.  Instead, the target is responsible from marking
2983      breakpoints out as soon as it detects an exec.  We don't do that
2984      here instead, because there may be other attempts to delete
2985      breakpoints after detecting an exec and before reaching here.  */
2986   ALL_BP_LOCATIONS (bploc, bplocp_tmp)
2987     if (bploc->pspace == current_program_space)
2988       gdb_assert (!bploc->inserted);
2989
2990   ALL_BREAKPOINTS_SAFE (b, b_tmp)
2991   {
2992     if (b->pspace != current_program_space)
2993       continue;
2994
2995     /* Solib breakpoints must be explicitly reset after an exec().  */
2996     if (b->type == bp_shlib_event)
2997       {
2998         delete_breakpoint (b);
2999         continue;
3000       }
3001
3002     /* JIT breakpoints must be explicitly reset after an exec().  */
3003     if (b->type == bp_jit_event)
3004       {
3005         delete_breakpoint (b);
3006         continue;
3007       }
3008
3009     /* Thread event breakpoints must be set anew after an exec(),
3010        as must overlay event and longjmp master breakpoints.  */
3011     if (b->type == bp_thread_event || b->type == bp_overlay_event
3012         || b->type == bp_longjmp_master || b->type == bp_std_terminate_master
3013         || b->type == bp_exception_master)
3014       {
3015         delete_breakpoint (b);
3016         continue;
3017       }
3018
3019     /* Step-resume breakpoints are meaningless after an exec().  */
3020     if (b->type == bp_step_resume || b->type == bp_hp_step_resume)
3021       {
3022         delete_breakpoint (b);
3023         continue;
3024       }
3025
3026     /* Longjmp and longjmp-resume breakpoints are also meaningless
3027        after an exec.  */
3028     if (b->type == bp_longjmp || b->type == bp_longjmp_resume
3029         || b->type == bp_exception || b->type == bp_exception_resume)
3030       {
3031         delete_breakpoint (b);
3032         continue;
3033       }
3034
3035     if (b->type == bp_catchpoint)
3036       {
3037         /* For now, none of the bp_catchpoint breakpoints need to
3038            do anything at this point.  In the future, if some of
3039            the catchpoints need to something, we will need to add
3040            a new method, and call this method from here.  */
3041         continue;
3042       }
3043
3044     /* bp_finish is a special case.  The only way we ought to be able
3045        to see one of these when an exec() has happened, is if the user
3046        caught a vfork, and then said "finish".  Ordinarily a finish just
3047        carries them to the call-site of the current callee, by setting
3048        a temporary bp there and resuming.  But in this case, the finish
3049        will carry them entirely through the vfork & exec.
3050
3051        We don't want to allow a bp_finish to remain inserted now.  But
3052        we can't safely delete it, 'cause finish_command has a handle to
3053        the bp on a bpstat, and will later want to delete it.  There's a
3054        chance (and I've seen it happen) that if we delete the bp_finish
3055        here, that its storage will get reused by the time finish_command
3056        gets 'round to deleting the "use to be a bp_finish" breakpoint.
3057        We really must allow finish_command to delete a bp_finish.
3058
3059        In the absence of a general solution for the "how do we know
3060        it's safe to delete something others may have handles to?"
3061        problem, what we'll do here is just uninsert the bp_finish, and
3062        let finish_command delete it.
3063
3064        (We know the bp_finish is "doomed" in the sense that it's
3065        momentary, and will be deleted as soon as finish_command sees
3066        the inferior stopped.  So it doesn't matter that the bp's
3067        address is probably bogus in the new a.out, unlike e.g., the
3068        solib breakpoints.)  */
3069
3070     if (b->type == bp_finish)
3071       {
3072         continue;
3073       }
3074
3075     /* Without a symbolic address, we have little hope of the
3076        pre-exec() address meaning the same thing in the post-exec()
3077        a.out.  */
3078     if (b->addr_string == NULL)
3079       {
3080         delete_breakpoint (b);
3081         continue;
3082       }
3083   }
3084   /* FIXME what about longjmp breakpoints?  Re-create them here?  */
3085   create_overlay_event_breakpoint ();
3086   create_longjmp_master_breakpoint ();
3087   create_std_terminate_master_breakpoint ();
3088   create_exception_master_breakpoint ();
3089 }
3090
3091 int
3092 detach_breakpoints (int pid)
3093 {
3094   struct bp_location *bl, **blp_tmp;
3095   int val = 0;
3096   struct cleanup *old_chain = save_inferior_ptid ();
3097   struct inferior *inf = current_inferior ();
3098
3099   if (pid == PIDGET (inferior_ptid))
3100     error (_("Cannot detach breakpoints of inferior_ptid"));
3101
3102   /* Set inferior_ptid; remove_breakpoint_1 uses this global.  */
3103   inferior_ptid = pid_to_ptid (pid);
3104   ALL_BP_LOCATIONS (bl, blp_tmp)
3105   {
3106     if (bl->pspace != inf->pspace)
3107       continue;
3108
3109     if (bl->inserted)
3110       val |= remove_breakpoint_1 (bl, mark_inserted);
3111   }
3112
3113   /* Detach single-step breakpoints as well.  */
3114   detach_single_step_breakpoints ();
3115
3116   do_cleanups (old_chain);
3117   return val;
3118 }
3119
3120 /* Remove the breakpoint location BL from the current address space.
3121    Note that this is used to detach breakpoints from a child fork.
3122    When we get here, the child isn't in the inferior list, and neither
3123    do we have objects to represent its address space --- we should
3124    *not* look at bl->pspace->aspace here.  */
3125
3126 static int
3127 remove_breakpoint_1 (struct bp_location *bl, insertion_state_t is)
3128 {
3129   int val;
3130
3131   /* BL is never in moribund_locations by our callers.  */
3132   gdb_assert (bl->owner != NULL);
3133
3134   if (bl->owner->enable_state == bp_permanent)
3135     /* Permanent breakpoints cannot be inserted or removed.  */
3136     return 0;
3137
3138   /* The type of none suggests that owner is actually deleted.
3139      This should not ever happen.  */
3140   gdb_assert (bl->owner->type != bp_none);
3141
3142   if (bl->loc_type == bp_loc_software_breakpoint
3143       || bl->loc_type == bp_loc_hardware_breakpoint)
3144     {
3145       /* "Normal" instruction breakpoint: either the standard
3146          trap-instruction bp (bp_breakpoint), or a
3147          bp_hardware_breakpoint.  */
3148
3149       /* First check to see if we have to handle an overlay.  */
3150       if (overlay_debugging == ovly_off
3151           || bl->section == NULL
3152           || !(section_is_overlay (bl->section)))
3153         {
3154           /* No overlay handling: just remove the breakpoint.  */
3155           val = bl->owner->ops->remove_location (bl);
3156         }
3157       else
3158         {
3159           /* This breakpoint is in an overlay section.
3160              Did we set a breakpoint at the LMA?  */
3161           if (!overlay_events_enabled)
3162               {
3163                 /* Yes -- overlay event support is not active, so we
3164                    should have set a breakpoint at the LMA.  Remove it.  
3165                 */
3166                 /* Ignore any failures: if the LMA is in ROM, we will
3167                    have already warned when we failed to insert it.  */
3168                 if (bl->loc_type == bp_loc_hardware_breakpoint)
3169                   target_remove_hw_breakpoint (bl->gdbarch,
3170                                                &bl->overlay_target_info);
3171                 else
3172                   target_remove_breakpoint (bl->gdbarch,
3173                                             &bl->overlay_target_info);
3174               }
3175           /* Did we set a breakpoint at the VMA? 
3176              If so, we will have marked the breakpoint 'inserted'.  */
3177           if (bl->inserted)
3178             {
3179               /* Yes -- remove it.  Previously we did not bother to
3180                  remove the breakpoint if the section had been
3181                  unmapped, but let's not rely on that being safe.  We
3182                  don't know what the overlay manager might do.  */
3183
3184               /* However, we should remove *software* breakpoints only
3185                  if the section is still mapped, or else we overwrite
3186                  wrong code with the saved shadow contents.  */
3187               if (bl->loc_type == bp_loc_hardware_breakpoint
3188                   || section_is_mapped (bl->section))
3189                 val = bl->owner->ops->remove_location (bl);
3190               else
3191                 val = 0;
3192             }
3193           else
3194             {
3195               /* No -- not inserted, so no need to remove.  No error.  */
3196               val = 0;
3197             }
3198         }
3199
3200       /* In some cases, we might not be able to remove a breakpoint
3201          in a shared library that has already been removed, but we
3202          have not yet processed the shlib unload event.  */
3203       if (val && solib_name_from_address (bl->pspace, bl->address))
3204         val = 0;
3205
3206       if (val)
3207         return val;
3208       bl->inserted = (is == mark_inserted);
3209     }
3210   else if (bl->loc_type == bp_loc_hardware_watchpoint)
3211     {
3212       gdb_assert (bl->owner->ops != NULL
3213                   && bl->owner->ops->remove_location != NULL);
3214
3215       bl->inserted = (is == mark_inserted);
3216       bl->owner->ops->remove_location (bl);
3217
3218       /* Failure to remove any of the hardware watchpoints comes here.  */
3219       if ((is == mark_uninserted) && (bl->inserted))
3220         warning (_("Could not remove hardware watchpoint %d."),
3221                  bl->owner->number);
3222     }
3223   else if (bl->owner->type == bp_catchpoint
3224            && breakpoint_enabled (bl->owner)
3225            && !bl->duplicate)
3226     {
3227       gdb_assert (bl->owner->ops != NULL
3228                   && bl->owner->ops->remove_location != NULL);
3229
3230       val = bl->owner->ops->remove_location (bl);
3231       if (val)
3232         return val;
3233
3234       bl->inserted = (is == mark_inserted);
3235     }
3236
3237   return 0;
3238 }
3239
3240 static int
3241 remove_breakpoint (struct bp_location *bl, insertion_state_t is)
3242 {
3243   int ret;
3244   struct cleanup *old_chain;
3245
3246   /* BL is never in moribund_locations by our callers.  */
3247   gdb_assert (bl->owner != NULL);
3248
3249   if (bl->owner->enable_state == bp_permanent)
3250     /* Permanent breakpoints cannot be inserted or removed.  */
3251     return 0;
3252
3253   /* The type of none suggests that owner is actually deleted.
3254      This should not ever happen.  */
3255   gdb_assert (bl->owner->type != bp_none);
3256
3257   old_chain = save_current_space_and_thread ();
3258
3259   switch_to_program_space_and_thread (bl->pspace);
3260
3261   ret = remove_breakpoint_1 (bl, is);
3262
3263   do_cleanups (old_chain);
3264   return ret;
3265 }
3266
3267 /* Clear the "inserted" flag in all breakpoints.  */
3268
3269 void
3270 mark_breakpoints_out (void)
3271 {
3272   struct bp_location *bl, **blp_tmp;
3273
3274   ALL_BP_LOCATIONS (bl, blp_tmp)
3275     if (bl->pspace == current_program_space)
3276       bl->inserted = 0;
3277 }
3278
3279 /* Clear the "inserted" flag in all breakpoints and delete any
3280    breakpoints which should go away between runs of the program.
3281
3282    Plus other such housekeeping that has to be done for breakpoints
3283    between runs.
3284
3285    Note: this function gets called at the end of a run (by
3286    generic_mourn_inferior) and when a run begins (by
3287    init_wait_for_inferior).  */
3288
3289
3290
3291 void
3292 breakpoint_init_inferior (enum inf_context context)
3293 {
3294   struct breakpoint *b, *b_tmp;
3295   struct bp_location *bl, **blp_tmp;
3296   int ix;
3297   struct program_space *pspace = current_program_space;
3298
3299   /* If breakpoint locations are shared across processes, then there's
3300      nothing to do.  */
3301   if (gdbarch_has_global_breakpoints (target_gdbarch))
3302     return;
3303
3304   ALL_BP_LOCATIONS (bl, blp_tmp)
3305   {
3306     /* ALL_BP_LOCATIONS bp_location has BL->OWNER always non-NULL.  */
3307     if (bl->pspace == pspace
3308         && bl->owner->enable_state != bp_permanent)
3309       bl->inserted = 0;
3310   }
3311
3312   ALL_BREAKPOINTS_SAFE (b, b_tmp)
3313   {
3314     if (b->loc && b->loc->pspace != pspace)
3315       continue;
3316
3317     switch (b->type)
3318       {
3319       case bp_call_dummy:
3320
3321         /* If the call dummy breakpoint is at the entry point it will
3322            cause problems when the inferior is rerun, so we better get
3323            rid of it.  */
3324
3325       case bp_watchpoint_scope:
3326
3327         /* Also get rid of scope breakpoints.  */
3328
3329       case bp_shlib_event:
3330
3331         /* Also remove solib event breakpoints.  Their addresses may
3332            have changed since the last time we ran the program.
3333            Actually we may now be debugging against different target;
3334            and so the solib backend that installed this breakpoint may
3335            not be used in by the target.  E.g.,
3336
3337            (gdb) file prog-linux
3338            (gdb) run               # native linux target
3339            ...
3340            (gdb) kill
3341            (gdb) file prog-win.exe
3342            (gdb) tar rem :9999     # remote Windows gdbserver.
3343         */
3344
3345       case bp_step_resume:
3346
3347         /* Also remove step-resume breakpoints.  */
3348
3349         delete_breakpoint (b);
3350         break;
3351
3352       case bp_watchpoint:
3353       case bp_hardware_watchpoint:
3354       case bp_read_watchpoint:
3355       case bp_access_watchpoint:
3356         {
3357           struct watchpoint *w = (struct watchpoint *) b;
3358
3359           /* Likewise for watchpoints on local expressions.  */
3360           if (w->exp_valid_block != NULL)
3361             delete_breakpoint (b);
3362           else if (context == inf_starting)
3363             {
3364               /* Reset val field to force reread of starting value in
3365                  insert_breakpoints.  */
3366               if (w->val)
3367                 value_free (w->val);
3368               w->val = NULL;
3369               w->val_valid = 0;
3370           }
3371         }
3372         break;
3373       default:
3374         break;
3375       }
3376   }
3377
3378   /* Get rid of the moribund locations.  */
3379   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, bl); ++ix)
3380     decref_bp_location (&bl);
3381   VEC_free (bp_location_p, moribund_locations);
3382 }
3383
3384 /* These functions concern about actual breakpoints inserted in the
3385    target --- to e.g. check if we need to do decr_pc adjustment or if
3386    we need to hop over the bkpt --- so we check for address space
3387    match, not program space.  */
3388
3389 /* breakpoint_here_p (PC) returns non-zero if an enabled breakpoint
3390    exists at PC.  It returns ordinary_breakpoint_here if it's an
3391    ordinary breakpoint, or permanent_breakpoint_here if it's a
3392    permanent breakpoint.
3393    - When continuing from a location with an ordinary breakpoint, we
3394      actually single step once before calling insert_breakpoints.
3395    - When continuing from a location with a permanent breakpoint, we
3396      need to use the `SKIP_PERMANENT_BREAKPOINT' macro, provided by
3397      the target, to advance the PC past the breakpoint.  */
3398
3399 enum breakpoint_here
3400 breakpoint_here_p (struct address_space *aspace, CORE_ADDR pc)
3401 {
3402   struct bp_location *bl, **blp_tmp;
3403   int any_breakpoint_here = 0;
3404
3405   ALL_BP_LOCATIONS (bl, blp_tmp)
3406     {
3407       if (bl->loc_type != bp_loc_software_breakpoint
3408           && bl->loc_type != bp_loc_hardware_breakpoint)
3409         continue;
3410
3411       /* ALL_BP_LOCATIONS bp_location has BL->OWNER always non-NULL.  */
3412       if ((breakpoint_enabled (bl->owner)
3413            || bl->owner->enable_state == bp_permanent)
3414           && breakpoint_location_address_match (bl, aspace, pc))
3415         {
3416           if (overlay_debugging 
3417               && section_is_overlay (bl->section)
3418               && !section_is_mapped (bl->section))
3419             continue;           /* unmapped overlay -- can't be a match */
3420           else if (bl->owner->enable_state == bp_permanent)
3421             return permanent_breakpoint_here;
3422           else
3423             any_breakpoint_here = 1;
3424         }
3425     }
3426
3427   return any_breakpoint_here ? ordinary_breakpoint_here : 0;
3428 }
3429
3430 /* Return true if there's a moribund breakpoint at PC.  */
3431
3432 int
3433 moribund_breakpoint_here_p (struct address_space *aspace, CORE_ADDR pc)
3434 {
3435   struct bp_location *loc;
3436   int ix;
3437
3438   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
3439     if (breakpoint_location_address_match (loc, aspace, pc))
3440       return 1;
3441
3442   return 0;
3443 }
3444
3445 /* Returns non-zero if there's a breakpoint inserted at PC, which is
3446    inserted using regular breakpoint_chain / bp_location array
3447    mechanism.  This does not check for single-step breakpoints, which
3448    are inserted and removed using direct target manipulation.  */
3449
3450 int
3451 regular_breakpoint_inserted_here_p (struct address_space *aspace, 
3452                                     CORE_ADDR pc)
3453 {
3454   struct bp_location *bl, **blp_tmp;
3455
3456   ALL_BP_LOCATIONS (bl, blp_tmp)
3457     {
3458       if (bl->loc_type != bp_loc_software_breakpoint
3459           && bl->loc_type != bp_loc_hardware_breakpoint)
3460         continue;
3461
3462       if (bl->inserted
3463           && breakpoint_location_address_match (bl, aspace, pc))
3464         {
3465           if (overlay_debugging 
3466               && section_is_overlay (bl->section)
3467               && !section_is_mapped (bl->section))
3468             continue;           /* unmapped overlay -- can't be a match */
3469           else
3470             return 1;
3471         }
3472     }
3473   return 0;
3474 }
3475
3476 /* Returns non-zero iff there's either regular breakpoint
3477    or a single step breakpoint inserted at PC.  */
3478
3479 int
3480 breakpoint_inserted_here_p (struct address_space *aspace, CORE_ADDR pc)
3481 {
3482   if (regular_breakpoint_inserted_here_p (aspace, pc))
3483     return 1;
3484
3485   if (single_step_breakpoint_inserted_here_p (aspace, pc))
3486     return 1;
3487
3488   return 0;
3489 }
3490
3491 /* This function returns non-zero iff there is a software breakpoint
3492    inserted at PC.  */
3493
3494 int
3495 software_breakpoint_inserted_here_p (struct address_space *aspace,
3496                                      CORE_ADDR pc)
3497 {
3498   struct bp_location *bl, **blp_tmp;
3499
3500   ALL_BP_LOCATIONS (bl, blp_tmp)
3501     {
3502       if (bl->loc_type != bp_loc_software_breakpoint)
3503         continue;
3504
3505       if (bl->inserted
3506           && breakpoint_address_match (bl->pspace->aspace, bl->address,
3507                                        aspace, pc))
3508         {
3509           if (overlay_debugging 
3510               && section_is_overlay (bl->section)
3511               && !section_is_mapped (bl->section))
3512             continue;           /* unmapped overlay -- can't be a match */
3513           else
3514             return 1;
3515         }
3516     }
3517
3518   /* Also check for software single-step breakpoints.  */
3519   if (single_step_breakpoint_inserted_here_p (aspace, pc))
3520     return 1;
3521
3522   return 0;
3523 }
3524
3525 int
3526 hardware_watchpoint_inserted_in_range (struct address_space *aspace,
3527                                        CORE_ADDR addr, ULONGEST len)
3528 {
3529   struct breakpoint *bpt;
3530
3531   ALL_BREAKPOINTS (bpt)
3532     {
3533       struct bp_location *loc;
3534
3535       if (bpt->type != bp_hardware_watchpoint
3536           && bpt->type != bp_access_watchpoint)
3537         continue;
3538
3539       if (!breakpoint_enabled (bpt))
3540         continue;
3541
3542       for (loc = bpt->loc; loc; loc = loc->next)
3543         if (loc->pspace->aspace == aspace && loc->inserted)
3544           {
3545             CORE_ADDR l, h;
3546
3547             /* Check for intersection.  */
3548             l = max (loc->address, addr);
3549             h = min (loc->address + loc->length, addr + len);
3550             if (l < h)
3551               return 1;
3552           }
3553     }
3554   return 0;
3555 }
3556
3557 /* breakpoint_thread_match (PC, PTID) returns true if the breakpoint at
3558    PC is valid for process/thread PTID.  */
3559
3560 int
3561 breakpoint_thread_match (struct address_space *aspace, CORE_ADDR pc,
3562                          ptid_t ptid)
3563 {
3564   struct bp_location *bl, **blp_tmp;
3565   /* The thread and task IDs associated to PTID, computed lazily.  */
3566   int thread = -1;
3567   int task = 0;
3568   
3569   ALL_BP_LOCATIONS (bl, blp_tmp)
3570     {
3571       if (bl->loc_type != bp_loc_software_breakpoint
3572           && bl->loc_type != bp_loc_hardware_breakpoint)
3573         continue;
3574
3575       /* ALL_BP_LOCATIONS bp_location has bl->OWNER always non-NULL.  */
3576       if (!breakpoint_enabled (bl->owner)
3577           && bl->owner->enable_state != bp_permanent)
3578         continue;
3579
3580       if (!breakpoint_location_address_match (bl, aspace, pc))
3581         continue;
3582
3583       if (bl->owner->thread != -1)
3584         {
3585           /* This is a thread-specific breakpoint.  Check that ptid
3586              matches that thread.  If thread hasn't been computed yet,
3587              it is now time to do so.  */
3588           if (thread == -1)
3589             thread = pid_to_thread_id (ptid);
3590           if (bl->owner->thread != thread)
3591             continue;
3592         }
3593
3594       if (bl->owner->task != 0)
3595         {
3596           /* This is a task-specific breakpoint.  Check that ptid
3597              matches that task.  If task hasn't been computed yet,
3598              it is now time to do so.  */
3599           if (task == 0)
3600             task = ada_get_task_number (ptid);
3601           if (bl->owner->task != task)
3602             continue;
3603         }
3604
3605       if (overlay_debugging 
3606           && section_is_overlay (bl->section)
3607           && !section_is_mapped (bl->section))
3608         continue;           /* unmapped overlay -- can't be a match */
3609
3610       return 1;
3611     }
3612
3613   return 0;
3614 }
3615 \f
3616
3617 /* bpstat stuff.  External routines' interfaces are documented
3618    in breakpoint.h.  */
3619
3620 int
3621 ep_is_catchpoint (struct breakpoint *ep)
3622 {
3623   return (ep->type == bp_catchpoint);
3624 }
3625
3626 /* Frees any storage that is part of a bpstat.  Does not walk the
3627    'next' chain.  */
3628
3629 static void
3630 bpstat_free (bpstat bs)
3631 {
3632   if (bs->old_val != NULL)
3633     value_free (bs->old_val);
3634   decref_counted_command_line (&bs->commands);
3635   decref_bp_location (&bs->bp_location_at);
3636   xfree (bs);
3637 }
3638
3639 /* Clear a bpstat so that it says we are not at any breakpoint.
3640    Also free any storage that is part of a bpstat.  */
3641
3642 void
3643 bpstat_clear (bpstat *bsp)
3644 {
3645   bpstat p;
3646   bpstat q;
3647
3648   if (bsp == 0)
3649     return;
3650   p = *bsp;
3651   while (p != NULL)
3652     {
3653       q = p->next;
3654       bpstat_free (p);
3655       p = q;
3656     }
3657   *bsp = NULL;
3658 }
3659
3660 /* Return a copy of a bpstat.  Like "bs1 = bs2" but all storage that
3661    is part of the bpstat is copied as well.  */
3662
3663 bpstat
3664 bpstat_copy (bpstat bs)
3665 {
3666   bpstat p = NULL;
3667   bpstat tmp;
3668   bpstat retval = NULL;
3669
3670   if (bs == NULL)
3671     return bs;
3672
3673   for (; bs != NULL; bs = bs->next)
3674     {
3675       tmp = (bpstat) xmalloc (sizeof (*tmp));
3676       memcpy (tmp, bs, sizeof (*tmp));
3677       incref_counted_command_line (tmp->commands);
3678       incref_bp_location (tmp->bp_location_at);
3679       if (bs->old_val != NULL)
3680         {
3681           tmp->old_val = value_copy (bs->old_val);
3682           release_value (tmp->old_val);
3683         }
3684
3685       if (p == NULL)
3686         /* This is the first thing in the chain.  */
3687         retval = tmp;
3688       else
3689         p->next = tmp;
3690       p = tmp;
3691     }
3692   p->next = NULL;
3693   return retval;
3694 }
3695
3696 /* Find the bpstat associated with this breakpoint.  */
3697
3698 bpstat
3699 bpstat_find_breakpoint (bpstat bsp, struct breakpoint *breakpoint)
3700 {
3701   if (bsp == NULL)
3702     return NULL;
3703
3704   for (; bsp != NULL; bsp = bsp->next)
3705     {
3706       if (bsp->breakpoint_at == breakpoint)
3707         return bsp;
3708     }
3709   return NULL;
3710 }
3711
3712 /* Put in *NUM the breakpoint number of the first breakpoint we are
3713    stopped at.  *BSP upon return is a bpstat which points to the
3714    remaining breakpoints stopped at (but which is not guaranteed to be
3715    good for anything but further calls to bpstat_num).
3716
3717    Return 0 if passed a bpstat which does not indicate any breakpoints.
3718    Return -1 if stopped at a breakpoint that has been deleted since
3719    we set it.
3720    Return 1 otherwise.  */
3721
3722 int
3723 bpstat_num (bpstat *bsp, int *num)
3724 {
3725   struct breakpoint *b;
3726
3727   if ((*bsp) == NULL)
3728     return 0;                   /* No more breakpoint values */
3729
3730   /* We assume we'll never have several bpstats that correspond to a
3731      single breakpoint -- otherwise, this function might return the
3732      same number more than once and this will look ugly.  */
3733   b = (*bsp)->breakpoint_at;
3734   *bsp = (*bsp)->next;
3735   if (b == NULL)
3736     return -1;                  /* breakpoint that's been deleted since */
3737
3738   *num = b->number;             /* We have its number */
3739   return 1;
3740 }
3741
3742 /* See breakpoint.h.  */
3743
3744 void
3745 bpstat_clear_actions (void)
3746 {
3747   struct thread_info *tp;
3748   bpstat bs;
3749
3750   if (ptid_equal (inferior_ptid, null_ptid))
3751     return;
3752
3753   tp = find_thread_ptid (inferior_ptid);
3754   if (tp == NULL)
3755     return;
3756
3757   for (bs = tp->control.stop_bpstat; bs != NULL; bs = bs->next)
3758     {
3759       decref_counted_command_line (&bs->commands);
3760
3761       if (bs->old_val != NULL)
3762         {
3763           value_free (bs->old_val);
3764           bs->old_val = NULL;
3765         }
3766     }
3767 }
3768
3769 /* Called when a command is about to proceed the inferior.  */
3770
3771 static void
3772 breakpoint_about_to_proceed (void)
3773 {
3774   if (!ptid_equal (inferior_ptid, null_ptid))
3775     {
3776       struct thread_info *tp = inferior_thread ();
3777
3778       /* Allow inferior function calls in breakpoint commands to not
3779          interrupt the command list.  When the call finishes
3780          successfully, the inferior will be standing at the same
3781          breakpoint as if nothing happened.  */
3782       if (tp->control.in_infcall)
3783         return;
3784     }
3785
3786   breakpoint_proceeded = 1;
3787 }
3788
3789 /* Stub for cleaning up our state if we error-out of a breakpoint
3790    command.  */
3791 static void
3792 cleanup_executing_breakpoints (void *ignore)
3793 {
3794   executing_breakpoint_commands = 0;
3795 }
3796
3797 /* Return non-zero iff CMD as the first line of a command sequence is `silent'
3798    or its equivalent.  */
3799
3800 static int
3801 command_line_is_silent (struct command_line *cmd)
3802 {
3803   return cmd && (strcmp ("silent", cmd->line) == 0
3804                  || (xdb_commands && strcmp ("Q", cmd->line) == 0));
3805 }
3806
3807 /* Execute all the commands associated with all the breakpoints at
3808    this location.  Any of these commands could cause the process to
3809    proceed beyond this point, etc.  We look out for such changes by
3810    checking the global "breakpoint_proceeded" after each command.
3811
3812    Returns true if a breakpoint command resumed the inferior.  In that
3813    case, it is the caller's responsibility to recall it again with the
3814    bpstat of the current thread.  */
3815
3816 static int
3817 bpstat_do_actions_1 (bpstat *bsp)
3818 {
3819   bpstat bs;
3820   struct cleanup *old_chain;
3821   int again = 0;
3822
3823   /* Avoid endless recursion if a `source' command is contained
3824      in bs->commands.  */
3825   if (executing_breakpoint_commands)
3826     return 0;
3827
3828   executing_breakpoint_commands = 1;
3829   old_chain = make_cleanup (cleanup_executing_breakpoints, 0);
3830
3831   prevent_dont_repeat ();
3832
3833   /* This pointer will iterate over the list of bpstat's.  */
3834   bs = *bsp;
3835
3836   breakpoint_proceeded = 0;
3837   for (; bs != NULL; bs = bs->next)
3838     {
3839       struct counted_command_line *ccmd;
3840       struct command_line *cmd;
3841       struct cleanup *this_cmd_tree_chain;
3842
3843       /* Take ownership of the BSP's command tree, if it has one.
3844
3845          The command tree could legitimately contain commands like
3846          'step' and 'next', which call clear_proceed_status, which
3847          frees stop_bpstat's command tree.  To make sure this doesn't
3848          free the tree we're executing out from under us, we need to
3849          take ownership of the tree ourselves.  Since a given bpstat's
3850          commands are only executed once, we don't need to copy it; we
3851          can clear the pointer in the bpstat, and make sure we free
3852          the tree when we're done.  */
3853       ccmd = bs->commands;
3854       bs->commands = NULL;
3855       this_cmd_tree_chain = make_cleanup_decref_counted_command_line (&ccmd);
3856       cmd = ccmd ? ccmd->commands : NULL;
3857       if (command_line_is_silent (cmd))
3858         {
3859           /* The action has been already done by bpstat_stop_status.  */
3860           cmd = cmd->next;
3861         }
3862
3863       while (cmd != NULL)
3864         {
3865           execute_control_command (cmd);
3866
3867           if (breakpoint_proceeded)
3868             break;
3869           else
3870             cmd = cmd->next;
3871         }
3872
3873       /* We can free this command tree now.  */
3874       do_cleanups (this_cmd_tree_chain);
3875
3876       if (breakpoint_proceeded)
3877         {
3878           if (target_can_async_p ())
3879             /* If we are in async mode, then the target might be still
3880                running, not stopped at any breakpoint, so nothing for
3881                us to do here -- just return to the event loop.  */
3882             ;
3883           else
3884             /* In sync mode, when execute_control_command returns
3885                we're already standing on the next breakpoint.
3886                Breakpoint commands for that stop were not run, since
3887                execute_command does not run breakpoint commands --
3888                only command_line_handler does, but that one is not
3889                involved in execution of breakpoint commands.  So, we
3890                can now execute breakpoint commands.  It should be
3891                noted that making execute_command do bpstat actions is
3892                not an option -- in this case we'll have recursive
3893                invocation of bpstat for each breakpoint with a
3894                command, and can easily blow up GDB stack.  Instead, we
3895                return true, which will trigger the caller to recall us
3896                with the new stop_bpstat.  */
3897             again = 1;
3898           break;
3899         }
3900     }
3901   do_cleanups (old_chain);
3902   return again;
3903 }
3904
3905 void
3906 bpstat_do_actions (void)
3907 {
3908   struct cleanup *cleanup_if_error = make_bpstat_clear_actions_cleanup ();
3909
3910   /* Do any commands attached to breakpoint we are stopped at.  */
3911   while (!ptid_equal (inferior_ptid, null_ptid)
3912          && target_has_execution
3913          && !is_exited (inferior_ptid)
3914          && !is_executing (inferior_ptid))
3915     /* Since in sync mode, bpstat_do_actions may resume the inferior,
3916        and only return when it is stopped at the next breakpoint, we
3917        keep doing breakpoint actions until it returns false to
3918        indicate the inferior was not resumed.  */
3919     if (!bpstat_do_actions_1 (&inferior_thread ()->control.stop_bpstat))
3920       break;
3921
3922   discard_cleanups (cleanup_if_error);
3923 }
3924
3925 /* Print out the (old or new) value associated with a watchpoint.  */
3926
3927 static void
3928 watchpoint_value_print (struct value *val, struct ui_file *stream)
3929 {
3930   if (val == NULL)
3931     fprintf_unfiltered (stream, _("<unreadable>"));
3932   else
3933     {
3934       struct value_print_options opts;
3935       get_user_print_options (&opts);
3936       value_print (val, stream, &opts);
3937     }
3938 }
3939
3940 /* Generic routine for printing messages indicating why we
3941    stopped.  The behavior of this function depends on the value
3942    'print_it' in the bpstat structure.  Under some circumstances we
3943    may decide not to print anything here and delegate the task to
3944    normal_stop().  */
3945
3946 static enum print_stop_action
3947 print_bp_stop_message (bpstat bs)
3948 {
3949   switch (bs->print_it)
3950     {
3951     case print_it_noop:
3952       /* Nothing should be printed for this bpstat entry.  */
3953       return PRINT_UNKNOWN;
3954       break;
3955
3956     case print_it_done:
3957       /* We still want to print the frame, but we already printed the
3958          relevant messages.  */
3959       return PRINT_SRC_AND_LOC;
3960       break;
3961
3962     case print_it_normal:
3963       {
3964         struct breakpoint *b = bs->breakpoint_at;
3965
3966         /* bs->breakpoint_at can be NULL if it was a momentary breakpoint
3967            which has since been deleted.  */
3968         if (b == NULL)
3969           return PRINT_UNKNOWN;
3970
3971         /* Normal case.  Call the breakpoint's print_it method.  */
3972         return b->ops->print_it (bs);
3973       }
3974       break;
3975
3976     default:
3977       internal_error (__FILE__, __LINE__,
3978                       _("print_bp_stop_message: unrecognized enum value"));
3979       break;
3980     }
3981 }
3982
3983 /* A helper function that prints a shared library stopped event.  */
3984
3985 static void
3986 print_solib_event (int is_catchpoint)
3987 {
3988   int any_deleted
3989     = !VEC_empty (char_ptr, current_program_space->deleted_solibs);
3990   int any_added
3991     = !VEC_empty (so_list_ptr, current_program_space->added_solibs);
3992
3993   if (!is_catchpoint)
3994     {
3995       if (any_added || any_deleted)
3996         ui_out_text (current_uiout,
3997                      _("Stopped due to shared library event:\n"));
3998       else
3999         ui_out_text (current_uiout,
4000                      _("Stopped due to shared library event (no "
4001                        "libraries added or removed)\n"));
4002     }
4003
4004   if (ui_out_is_mi_like_p (current_uiout))
4005     ui_out_field_string (current_uiout, "reason",
4006                          async_reason_lookup (EXEC_ASYNC_SOLIB_EVENT));
4007
4008   if (any_deleted)
4009     {
4010       struct cleanup *cleanup;
4011       char *name;
4012       int ix;
4013
4014       ui_out_text (current_uiout, _("  Inferior unloaded "));
4015       cleanup = make_cleanup_ui_out_list_begin_end (current_uiout,
4016                                                     "removed");
4017       for (ix = 0;
4018            VEC_iterate (char_ptr, current_program_space->deleted_solibs,
4019                         ix, name);
4020            ++ix)
4021         {
4022           if (ix > 0)
4023             ui_out_text (current_uiout, "    ");
4024           ui_out_field_string (current_uiout, "library", name);
4025           ui_out_text (current_uiout, "\n");
4026         }
4027
4028       do_cleanups (cleanup);
4029     }
4030
4031   if (any_added)
4032     {
4033       struct so_list *iter;
4034       int ix;
4035       struct cleanup *cleanup;
4036
4037       ui_out_text (current_uiout, _("  Inferior loaded "));
4038       cleanup = make_cleanup_ui_out_list_begin_end (current_uiout,
4039                                                     "added");
4040       for (ix = 0;
4041            VEC_iterate (so_list_ptr, current_program_space->added_solibs,
4042                         ix, iter);
4043            ++ix)
4044         {
4045           if (ix > 0)
4046             ui_out_text (current_uiout, "    ");
4047           ui_out_field_string (current_uiout, "library", iter->so_name);
4048           ui_out_text (current_uiout, "\n");
4049         }
4050
4051       do_cleanups (cleanup);
4052     }
4053 }
4054
4055 /* Print a message indicating what happened.  This is called from
4056    normal_stop().  The input to this routine is the head of the bpstat
4057    list - a list of the eventpoints that caused this stop.  KIND is
4058    the target_waitkind for the stopping event.  This
4059    routine calls the generic print routine for printing a message
4060    about reasons for stopping.  This will print (for example) the
4061    "Breakpoint n," part of the output.  The return value of this
4062    routine is one of:
4063
4064    PRINT_UNKNOWN: Means we printed nothing.
4065    PRINT_SRC_AND_LOC: Means we printed something, and expect subsequent
4066    code to print the location.  An example is 
4067    "Breakpoint 1, " which should be followed by
4068    the location.
4069    PRINT_SRC_ONLY: Means we printed something, but there is no need
4070    to also print the location part of the message.
4071    An example is the catch/throw messages, which
4072    don't require a location appended to the end.
4073    PRINT_NOTHING: We have done some printing and we don't need any 
4074    further info to be printed.  */
4075
4076 enum print_stop_action
4077 bpstat_print (bpstat bs, int kind)
4078 {
4079   int val;
4080
4081   /* Maybe another breakpoint in the chain caused us to stop.
4082      (Currently all watchpoints go on the bpstat whether hit or not.
4083      That probably could (should) be changed, provided care is taken
4084      with respect to bpstat_explains_signal).  */
4085   for (; bs; bs = bs->next)
4086     {
4087       val = print_bp_stop_message (bs);
4088       if (val == PRINT_SRC_ONLY 
4089           || val == PRINT_SRC_AND_LOC 
4090           || val == PRINT_NOTHING)
4091         return val;
4092     }
4093
4094   /* If we had hit a shared library event breakpoint,
4095      print_bp_stop_message would print out this message.  If we hit an
4096      OS-level shared library event, do the same thing.  */
4097   if (kind == TARGET_WAITKIND_LOADED)
4098     {
4099       print_solib_event (0);
4100       return PRINT_NOTHING;
4101     }
4102
4103   /* We reached the end of the chain, or we got a null BS to start
4104      with and nothing was printed.  */
4105   return PRINT_UNKNOWN;
4106 }
4107
4108 /* Evaluate the expression EXP and return 1 if value is zero.  This is
4109    used inside a catch_errors to evaluate the breakpoint condition.
4110    The argument is a "struct expression *" that has been cast to a
4111    "char *" to make it pass through catch_errors.  */
4112
4113 static int
4114 breakpoint_cond_eval (void *exp)
4115 {
4116   struct value *mark = value_mark ();
4117   int i = !value_true (evaluate_expression ((struct expression *) exp));
4118
4119   value_free_to_mark (mark);
4120   return i;
4121 }
4122
4123 /* Allocate a new bpstat.  Link it to the FIFO list by BS_LINK_POINTER.  */
4124
4125 static bpstat
4126 bpstat_alloc (struct bp_location *bl, bpstat **bs_link_pointer)
4127 {
4128   bpstat bs;
4129
4130   bs = (bpstat) xmalloc (sizeof (*bs));
4131   bs->next = NULL;
4132   **bs_link_pointer = bs;
4133   *bs_link_pointer = &bs->next;
4134   bs->breakpoint_at = bl->owner;
4135   bs->bp_location_at = bl;
4136   incref_bp_location (bl);
4137   /* If the condition is false, etc., don't do the commands.  */
4138   bs->commands = NULL;
4139   bs->old_val = NULL;
4140   bs->print_it = print_it_normal;
4141   return bs;
4142 }
4143 \f
4144 /* The target has stopped with waitstatus WS.  Check if any hardware
4145    watchpoints have triggered, according to the target.  */
4146
4147 int
4148 watchpoints_triggered (struct target_waitstatus *ws)
4149 {
4150   int stopped_by_watchpoint = target_stopped_by_watchpoint ();
4151   CORE_ADDR addr;
4152   struct breakpoint *b;
4153
4154   if (!stopped_by_watchpoint)
4155     {
4156       /* We were not stopped by a watchpoint.  Mark all watchpoints
4157          as not triggered.  */
4158       ALL_BREAKPOINTS (b)
4159         if (is_hardware_watchpoint (b))
4160           {
4161             struct watchpoint *w = (struct watchpoint *) b;
4162
4163             w->watchpoint_triggered = watch_triggered_no;
4164           }
4165
4166       return 0;
4167     }
4168
4169   if (!target_stopped_data_address (&current_target, &addr))
4170     {
4171       /* We were stopped by a watchpoint, but we don't know where.
4172          Mark all watchpoints as unknown.  */
4173       ALL_BREAKPOINTS (b)
4174         if (is_hardware_watchpoint (b))
4175           {
4176             struct watchpoint *w = (struct watchpoint *) b;
4177
4178             w->watchpoint_triggered = watch_triggered_unknown;
4179           }
4180
4181       return stopped_by_watchpoint;
4182     }
4183
4184   /* The target could report the data address.  Mark watchpoints
4185      affected by this data address as triggered, and all others as not
4186      triggered.  */
4187
4188   ALL_BREAKPOINTS (b)
4189     if (is_hardware_watchpoint (b))
4190       {
4191         struct watchpoint *w = (struct watchpoint *) b;
4192         struct bp_location *loc;
4193
4194         w->watchpoint_triggered = watch_triggered_no;
4195         for (loc = b->loc; loc; loc = loc->next)
4196           {
4197             if (is_masked_watchpoint (b))
4198               {
4199                 CORE_ADDR newaddr = addr & w->hw_wp_mask;
4200                 CORE_ADDR start = loc->address & w->hw_wp_mask;
4201
4202                 if (newaddr == start)
4203                   {
4204                     w->watchpoint_triggered = watch_triggered_yes;
4205                     break;
4206                   }
4207               }
4208             /* Exact match not required.  Within range is sufficient.  */
4209             else if (target_watchpoint_addr_within_range (&current_target,
4210                                                          addr, loc->address,
4211                                                          loc->length))
4212               {
4213                 w->watchpoint_triggered = watch_triggered_yes;
4214                 break;
4215               }
4216           }
4217       }
4218
4219   return 1;
4220 }
4221
4222 /* Possible return values for watchpoint_check (this can't be an enum
4223    because of check_errors).  */
4224 /* The watchpoint has been deleted.  */
4225 #define WP_DELETED 1
4226 /* The value has changed.  */
4227 #define WP_VALUE_CHANGED 2
4228 /* The value has not changed.  */
4229 #define WP_VALUE_NOT_CHANGED 3
4230 /* Ignore this watchpoint, no matter if the value changed or not.  */
4231 #define WP_IGNORE 4
4232
4233 #define BP_TEMPFLAG 1
4234 #define BP_HARDWAREFLAG 2
4235
4236 /* Evaluate watchpoint condition expression and check if its value
4237    changed.
4238
4239    P should be a pointer to struct bpstat, but is defined as a void *
4240    in order for this function to be usable with catch_errors.  */
4241
4242 static int
4243 watchpoint_check (void *p)
4244 {
4245   bpstat bs = (bpstat) p;
4246   struct watchpoint *b;
4247   struct frame_info *fr;
4248   int within_current_scope;
4249
4250   /* BS is built from an existing struct breakpoint.  */
4251   gdb_assert (bs->breakpoint_at != NULL);
4252   b = (struct watchpoint *) bs->breakpoint_at;
4253
4254   /* If this is a local watchpoint, we only want to check if the
4255      watchpoint frame is in scope if the current thread is the thread
4256      that was used to create the watchpoint.  */
4257   if (!watchpoint_in_thread_scope (b))
4258     return WP_IGNORE;
4259
4260   if (b->exp_valid_block == NULL)
4261     within_current_scope = 1;
4262   else
4263     {
4264       struct frame_info *frame = get_current_frame ();
4265       struct gdbarch *frame_arch = get_frame_arch (frame);
4266       CORE_ADDR frame_pc = get_frame_pc (frame);
4267
4268       /* in_function_epilogue_p() returns a non-zero value if we're
4269          still in the function but the stack frame has already been
4270          invalidated.  Since we can't rely on the values of local
4271          variables after the stack has been destroyed, we are treating
4272          the watchpoint in that state as `not changed' without further
4273          checking.  Don't mark watchpoints as changed if the current
4274          frame is in an epilogue - even if they are in some other
4275          frame, our view of the stack is likely to be wrong and
4276          frame_find_by_id could error out.  */
4277       if (gdbarch_in_function_epilogue_p (frame_arch, frame_pc))
4278         return WP_IGNORE;
4279
4280       fr = frame_find_by_id (b->watchpoint_frame);
4281       within_current_scope = (fr != NULL);
4282
4283       /* If we've gotten confused in the unwinder, we might have
4284          returned a frame that can't describe this variable.  */
4285       if (within_current_scope)
4286         {
4287           struct symbol *function;
4288
4289           function = get_frame_function (fr);
4290           if (function == NULL
4291               || !contained_in (b->exp_valid_block,
4292                                 SYMBOL_BLOCK_VALUE (function)))
4293             within_current_scope = 0;
4294         }
4295
4296       if (within_current_scope)
4297         /* If we end up stopping, the current frame will get selected
4298            in normal_stop.  So this call to select_frame won't affect
4299            the user.  */
4300         select_frame (fr);
4301     }
4302
4303   if (within_current_scope)
4304     {
4305       /* We use value_{,free_to_}mark because it could be a *long*
4306          time before we return to the command level and call
4307          free_all_values.  We can't call free_all_values because we
4308          might be in the middle of evaluating a function call.  */
4309
4310       int pc = 0;
4311       struct value *mark;
4312       struct value *new_val;
4313
4314       if (is_masked_watchpoint (&b->base))
4315         /* Since we don't know the exact trigger address (from
4316            stopped_data_address), just tell the user we've triggered
4317            a mask watchpoint.  */
4318         return WP_VALUE_CHANGED;
4319
4320       mark = value_mark ();
4321       fetch_subexp_value (b->exp, &pc, &new_val, NULL, NULL);
4322
4323       /* We use value_equal_contents instead of value_equal because
4324          the latter coerces an array to a pointer, thus comparing just
4325          the address of the array instead of its contents.  This is
4326          not what we want.  */
4327       if ((b->val != NULL) != (new_val != NULL)
4328           || (b->val != NULL && !value_equal_contents (b->val, new_val)))
4329         {
4330           if (new_val != NULL)
4331             {
4332               release_value (new_val);
4333               value_free_to_mark (mark);
4334             }
4335           bs->old_val = b->val;
4336           b->val = new_val;
4337           b->val_valid = 1;
4338           return WP_VALUE_CHANGED;
4339         }
4340       else
4341         {
4342           /* Nothing changed.  */
4343           value_free_to_mark (mark);
4344           return WP_VALUE_NOT_CHANGED;
4345         }
4346     }
4347   else
4348     {
4349       struct ui_out *uiout = current_uiout;
4350
4351       /* This seems like the only logical thing to do because
4352          if we temporarily ignored the watchpoint, then when
4353          we reenter the block in which it is valid it contains
4354          garbage (in the case of a function, it may have two
4355          garbage values, one before and one after the prologue).
4356          So we can't even detect the first assignment to it and
4357          watch after that (since the garbage may or may not equal
4358          the first value assigned).  */
4359       /* We print all the stop information in
4360          breakpoint_ops->print_it, but in this case, by the time we
4361          call breakpoint_ops->print_it this bp will be deleted
4362          already.  So we have no choice but print the information
4363          here.  */
4364       if (ui_out_is_mi_like_p (uiout))
4365         ui_out_field_string
4366           (uiout, "reason", async_reason_lookup (EXEC_ASYNC_WATCHPOINT_SCOPE));
4367       ui_out_text (uiout, "\nWatchpoint ");
4368       ui_out_field_int (uiout, "wpnum", b->base.number);
4369       ui_out_text (uiout,
4370                    " deleted because the program has left the block in\n\
4371 which its expression is valid.\n");     
4372
4373       /* Make sure the watchpoint's commands aren't executed.  */
4374       decref_counted_command_line (&b->base.commands);
4375       watchpoint_del_at_next_stop (b);
4376
4377       return WP_DELETED;
4378     }
4379 }
4380
4381 /* Return true if it looks like target has stopped due to hitting
4382    breakpoint location BL.  This function does not check if we should
4383    stop, only if BL explains the stop.  */
4384
4385 static int
4386 bpstat_check_location (const struct bp_location *bl,
4387                        struct address_space *aspace, CORE_ADDR bp_addr,
4388                        const struct target_waitstatus *ws)
4389 {
4390   struct breakpoint *b = bl->owner;
4391
4392   /* BL is from an existing breakpoint.  */
4393   gdb_assert (b != NULL);
4394
4395   return b->ops->breakpoint_hit (bl, aspace, bp_addr, ws);
4396 }
4397
4398 /* Determine if the watched values have actually changed, and we
4399    should stop.  If not, set BS->stop to 0.  */
4400
4401 static void
4402 bpstat_check_watchpoint (bpstat bs)
4403 {
4404   const struct bp_location *bl;
4405   struct watchpoint *b;
4406
4407   /* BS is built for existing struct breakpoint.  */
4408   bl = bs->bp_location_at;
4409   gdb_assert (bl != NULL);
4410   b = (struct watchpoint *) bs->breakpoint_at;
4411   gdb_assert (b != NULL);
4412
4413     {
4414       int must_check_value = 0;
4415       
4416       if (b->base.type == bp_watchpoint)
4417         /* For a software watchpoint, we must always check the
4418            watched value.  */
4419         must_check_value = 1;
4420       else if (b->watchpoint_triggered == watch_triggered_yes)
4421         /* We have a hardware watchpoint (read, write, or access)
4422            and the target earlier reported an address watched by
4423            this watchpoint.  */
4424         must_check_value = 1;
4425       else if (b->watchpoint_triggered == watch_triggered_unknown
4426                && b->base.type == bp_hardware_watchpoint)
4427         /* We were stopped by a hardware watchpoint, but the target could
4428            not report the data address.  We must check the watchpoint's
4429            value.  Access and read watchpoints are out of luck; without
4430            a data address, we can't figure it out.  */
4431         must_check_value = 1;
4432
4433       if (must_check_value)
4434         {
4435           char *message
4436             = xstrprintf ("Error evaluating expression for watchpoint %d\n",
4437                           b->base.number);
4438           struct cleanup *cleanups = make_cleanup (xfree, message);
4439           int e = catch_errors (watchpoint_check, bs, message,
4440                                 RETURN_MASK_ALL);
4441           do_cleanups (cleanups);
4442           switch (e)
4443             {
4444             case WP_DELETED:
4445               /* We've already printed what needs to be printed.  */
4446               bs->print_it = print_it_done;
4447               /* Stop.  */
4448               break;
4449             case WP_IGNORE:
4450               bs->print_it = print_it_noop;
4451               bs->stop = 0;
4452               break;
4453             case WP_VALUE_CHANGED:
4454               if (b->base.type == bp_read_watchpoint)
4455                 {
4456                   /* There are two cases to consider here:
4457
4458                      1. We're watching the triggered memory for reads.
4459                      In that case, trust the target, and always report
4460                      the watchpoint hit to the user.  Even though
4461                      reads don't cause value changes, the value may
4462                      have changed since the last time it was read, and
4463                      since we're not trapping writes, we will not see
4464                      those, and as such we should ignore our notion of
4465                      old value.
4466
4467                      2. We're watching the triggered memory for both
4468                      reads and writes.  There are two ways this may
4469                      happen:
4470
4471                      2.1. This is a target that can't break on data
4472                      reads only, but can break on accesses (reads or
4473                      writes), such as e.g., x86.  We detect this case
4474                      at the time we try to insert read watchpoints.
4475
4476                      2.2. Otherwise, the target supports read
4477                      watchpoints, but, the user set an access or write
4478                      watchpoint watching the same memory as this read
4479                      watchpoint.
4480
4481                      If we're watching memory writes as well as reads,
4482                      ignore watchpoint hits when we find that the
4483                      value hasn't changed, as reads don't cause
4484                      changes.  This still gives false positives when
4485                      the program writes the same value to memory as
4486                      what there was already in memory (we will confuse
4487                      it for a read), but it's much better than
4488                      nothing.  */
4489
4490                   int other_write_watchpoint = 0;
4491
4492                   if (bl->watchpoint_type == hw_read)
4493                     {
4494                       struct breakpoint *other_b;
4495
4496                       ALL_BREAKPOINTS (other_b)
4497                         if (other_b->type == bp_hardware_watchpoint
4498                             || other_b->type == bp_access_watchpoint)
4499                           {
4500                             struct watchpoint *other_w =
4501                               (struct watchpoint *) other_b;
4502
4503                             if (other_w->watchpoint_triggered
4504                                 == watch_triggered_yes)
4505                               {
4506                                 other_write_watchpoint = 1;
4507                                 break;
4508                               }
4509                           }
4510                     }
4511
4512                   if (other_write_watchpoint
4513                       || bl->watchpoint_type == hw_access)
4514                     {
4515                       /* We're watching the same memory for writes,
4516                          and the value changed since the last time we
4517                          updated it, so this trap must be for a write.
4518                          Ignore it.  */
4519                       bs->print_it = print_it_noop;
4520                       bs->stop = 0;
4521                     }
4522                 }
4523               break;
4524             case WP_VALUE_NOT_CHANGED:
4525               if (b->base.type == bp_hardware_watchpoint
4526                   || b->base.type == bp_watchpoint)
4527                 {
4528                   /* Don't stop: write watchpoints shouldn't fire if
4529                      the value hasn't changed.  */
4530                   bs->print_it = print_it_noop;
4531                   bs->stop = 0;
4532                 }
4533               /* Stop.  */
4534               break;
4535             default:
4536               /* Can't happen.  */
4537             case 0:
4538               /* Error from catch_errors.  */
4539               printf_filtered (_("Watchpoint %d deleted.\n"), b->base.number);
4540               watchpoint_del_at_next_stop (b);
4541               /* We've already printed what needs to be printed.  */
4542               bs->print_it = print_it_done;
4543               break;
4544             }
4545         }
4546       else      /* must_check_value == 0 */
4547         {
4548           /* This is a case where some watchpoint(s) triggered, but
4549              not at the address of this watchpoint, or else no
4550              watchpoint triggered after all.  So don't print
4551              anything for this watchpoint.  */
4552           bs->print_it = print_it_noop;
4553           bs->stop = 0;
4554         }
4555     }
4556 }
4557
4558
4559 /* Check conditions (condition proper, frame, thread and ignore count)
4560    of breakpoint referred to by BS.  If we should not stop for this
4561    breakpoint, set BS->stop to 0.  */
4562
4563 static void
4564 bpstat_check_breakpoint_conditions (bpstat bs, ptid_t ptid)
4565 {
4566   int thread_id = pid_to_thread_id (ptid);
4567   const struct bp_location *bl;
4568   struct breakpoint *b;
4569
4570   /* BS is built for existing struct breakpoint.  */
4571   bl = bs->bp_location_at;
4572   gdb_assert (bl != NULL);
4573   b = bs->breakpoint_at;
4574   gdb_assert (b != NULL);
4575
4576   /* Even if the target evaluated the condition on its end and notified GDB, we
4577      need to do so again since GDB does not know if we stopped due to a
4578      breakpoint or a single step breakpoint.  */
4579
4580   if (frame_id_p (b->frame_id)
4581       && !frame_id_eq (b->frame_id, get_stack_frame_id (get_current_frame ())))
4582     bs->stop = 0;
4583   else if (bs->stop)
4584     {
4585       int value_is_zero = 0;
4586       struct expression *cond;
4587
4588       /* Evaluate Python breakpoints that have a "stop"
4589          method implemented.  */
4590       if (b->py_bp_object)
4591         bs->stop = gdbpy_should_stop (b->py_bp_object);
4592
4593       if (is_watchpoint (b))
4594         {
4595           struct watchpoint *w = (struct watchpoint *) b;
4596
4597           cond = w->cond_exp;
4598         }
4599       else
4600         cond = bl->cond;
4601
4602       if (cond && b->disposition != disp_del_at_next_stop)
4603         {
4604           int within_current_scope = 1;
4605           struct watchpoint * w;
4606
4607           /* We use value_mark and value_free_to_mark because it could
4608              be a long time before we return to the command level and
4609              call free_all_values.  We can't call free_all_values
4610              because we might be in the middle of evaluating a
4611              function call.  */
4612           struct value *mark = value_mark ();
4613
4614           if (is_watchpoint (b))
4615             w = (struct watchpoint *) b;
4616           else
4617             w = NULL;
4618
4619           /* Need to select the frame, with all that implies so that
4620              the conditions will have the right context.  Because we
4621              use the frame, we will not see an inlined function's
4622              variables when we arrive at a breakpoint at the start
4623              of the inlined function; the current frame will be the
4624              call site.  */
4625           if (w == NULL || w->cond_exp_valid_block == NULL)
4626             select_frame (get_current_frame ());
4627           else
4628             {
4629               struct frame_info *frame;
4630
4631               /* For local watchpoint expressions, which particular
4632                  instance of a local is being watched matters, so we
4633                  keep track of the frame to evaluate the expression
4634                  in.  To evaluate the condition however, it doesn't
4635                  really matter which instantiation of the function
4636                  where the condition makes sense triggers the
4637                  watchpoint.  This allows an expression like "watch
4638                  global if q > 10" set in `func', catch writes to
4639                  global on all threads that call `func', or catch
4640                  writes on all recursive calls of `func' by a single
4641                  thread.  We simply always evaluate the condition in
4642                  the innermost frame that's executing where it makes
4643                  sense to evaluate the condition.  It seems
4644                  intuitive.  */
4645               frame = block_innermost_frame (w->cond_exp_valid_block);
4646               if (frame != NULL)
4647                 select_frame (frame);
4648               else
4649                 within_current_scope = 0;
4650             }
4651           if (within_current_scope)
4652             value_is_zero
4653               = catch_errors (breakpoint_cond_eval, cond,
4654                               "Error in testing breakpoint condition:\n",
4655                               RETURN_MASK_ALL);
4656           else
4657             {
4658               warning (_("Watchpoint condition cannot be tested "
4659                          "in the current scope"));
4660               /* If we failed to set the right context for this
4661                  watchpoint, unconditionally report it.  */
4662               value_is_zero = 0;
4663             }
4664           /* FIXME-someday, should give breakpoint #.  */
4665           value_free_to_mark (mark);
4666         }
4667
4668       if (cond && value_is_zero)
4669         {
4670           bs->stop = 0;
4671         }
4672       else if (b->thread != -1 && b->thread != thread_id)
4673         {
4674           bs->stop = 0;
4675         }
4676       else if (b->ignore_count > 0)
4677         {
4678           b->ignore_count--;
4679           annotate_ignore_count_change ();
4680           bs->stop = 0;
4681           /* Increase the hit count even though we don't stop.  */
4682           ++(b->hit_count);
4683           observer_notify_breakpoint_modified (b);
4684         }       
4685     }
4686 }
4687
4688
4689 /* Get a bpstat associated with having just stopped at address
4690    BP_ADDR in thread PTID.
4691
4692    Determine whether we stopped at a breakpoint, etc, or whether we
4693    don't understand this stop.  Result is a chain of bpstat's such
4694    that:
4695
4696    if we don't understand the stop, the result is a null pointer.
4697
4698    if we understand why we stopped, the result is not null.
4699
4700    Each element of the chain refers to a particular breakpoint or
4701    watchpoint at which we have stopped.  (We may have stopped for
4702    several reasons concurrently.)
4703
4704    Each element of the chain has valid next, breakpoint_at,
4705    commands, FIXME??? fields.  */
4706
4707 bpstat
4708 bpstat_stop_status (struct address_space *aspace,
4709                     CORE_ADDR bp_addr, ptid_t ptid,
4710                     const struct target_waitstatus *ws)
4711 {
4712   struct breakpoint *b = NULL;
4713   struct bp_location *bl;
4714   struct bp_location *loc;
4715   /* First item of allocated bpstat's.  */
4716   bpstat bs_head = NULL, *bs_link = &bs_head;
4717   /* Pointer to the last thing in the chain currently.  */
4718   bpstat bs;
4719   int ix;
4720   int need_remove_insert;
4721   int removed_any;
4722
4723   /* First, build the bpstat chain with locations that explain a
4724      target stop, while being careful to not set the target running,
4725      as that may invalidate locations (in particular watchpoint
4726      locations are recreated).  Resuming will happen here with
4727      breakpoint conditions or watchpoint expressions that include
4728      inferior function calls.  */
4729
4730   ALL_BREAKPOINTS (b)
4731     {
4732       if (!breakpoint_enabled (b) && b->enable_state != bp_permanent)
4733         continue;
4734
4735       for (bl = b->loc; bl != NULL; bl = bl->next)
4736         {
4737           /* For hardware watchpoints, we look only at the first
4738              location.  The watchpoint_check function will work on the
4739              entire expression, not the individual locations.  For
4740              read watchpoints, the watchpoints_triggered function has
4741              checked all locations already.  */
4742           if (b->type == bp_hardware_watchpoint && bl != b->loc)
4743             break;
4744
4745           if (bl->shlib_disabled)
4746             continue;
4747
4748           if (!bpstat_check_location (bl, aspace, bp_addr, ws))
4749             continue;
4750
4751           /* Come here if it's a watchpoint, or if the break address
4752              matches.  */
4753
4754           bs = bpstat_alloc (bl, &bs_link);     /* Alloc a bpstat to
4755                                                    explain stop.  */
4756
4757           /* Assume we stop.  Should we find a watchpoint that is not
4758              actually triggered, or if the condition of the breakpoint
4759              evaluates as false, we'll reset 'stop' to 0.  */
4760           bs->stop = 1;
4761           bs->print = 1;
4762
4763           /* If this is a scope breakpoint, mark the associated
4764              watchpoint as triggered so that we will handle the
4765              out-of-scope event.  We'll get to the watchpoint next
4766              iteration.  */
4767           if (b->type == bp_watchpoint_scope && b->related_breakpoint != b)
4768             {
4769               struct watchpoint *w = (struct watchpoint *) b->related_breakpoint;
4770
4771               w->watchpoint_triggered = watch_triggered_yes;
4772             }
4773         }
4774     }
4775
4776   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
4777     {
4778       if (breakpoint_location_address_match (loc, aspace, bp_addr))
4779         {
4780           bs = bpstat_alloc (loc, &bs_link);
4781           /* For hits of moribund locations, we should just proceed.  */
4782           bs->stop = 0;
4783           bs->print = 0;
4784           bs->print_it = print_it_noop;
4785         }
4786     }
4787
4788   /* A bit of special processing for shlib breakpoints.  We need to
4789      process solib loading here, so that the lists of loaded and
4790      unloaded libraries are correct before we handle "catch load" and
4791      "catch unload".  */
4792   for (bs = bs_head; bs != NULL; bs = bs->next)
4793     {
4794       if (bs->breakpoint_at && bs->breakpoint_at->type == bp_shlib_event)
4795         {
4796           handle_solib_event ();
4797           break;
4798         }
4799     }
4800
4801   /* Now go through the locations that caused the target to stop, and
4802      check whether we're interested in reporting this stop to higher
4803      layers, or whether we should resume the target transparently.  */
4804
4805   removed_any = 0;
4806
4807   for (bs = bs_head; bs != NULL; bs = bs->next)
4808     {
4809       if (!bs->stop)
4810         continue;
4811
4812       b = bs->breakpoint_at;
4813       b->ops->check_status (bs);
4814       if (bs->stop)
4815         {
4816           bpstat_check_breakpoint_conditions (bs, ptid);
4817
4818           if (bs->stop)
4819             {
4820               ++(b->hit_count);
4821               observer_notify_breakpoint_modified (b);
4822
4823               /* We will stop here.  */
4824               if (b->disposition == disp_disable)
4825                 {
4826                   --(b->enable_count);
4827                   if (b->enable_count <= 0
4828                       && b->enable_state != bp_permanent)
4829                     b->enable_state = bp_disabled;
4830                   removed_any = 1;
4831                 }
4832               if (b->silent)
4833                 bs->print = 0;
4834               bs->commands = b->commands;
4835               incref_counted_command_line (bs->commands);
4836               if (command_line_is_silent (bs->commands
4837                                           ? bs->commands->commands : NULL))
4838                 bs->print = 0;
4839             }
4840
4841         }
4842
4843       /* Print nothing for this entry if we don't stop or don't
4844          print.  */
4845       if (!bs->stop || !bs->print)
4846         bs->print_it = print_it_noop;
4847     }
4848
4849   /* If we aren't stopping, the value of some hardware watchpoint may
4850      not have changed, but the intermediate memory locations we are
4851      watching may have.  Don't bother if we're stopping; this will get
4852      done later.  */
4853   need_remove_insert = 0;
4854   if (! bpstat_causes_stop (bs_head))
4855     for (bs = bs_head; bs != NULL; bs = bs->next)
4856       if (!bs->stop
4857           && bs->breakpoint_at
4858           && is_hardware_watchpoint (bs->breakpoint_at))
4859         {
4860           struct watchpoint *w = (struct watchpoint *) bs->breakpoint_at;
4861
4862           update_watchpoint (w, 0 /* don't reparse.  */);
4863           need_remove_insert = 1;
4864         }
4865
4866   if (need_remove_insert)
4867     update_global_location_list (1);
4868   else if (removed_any)
4869     update_global_location_list (0);
4870
4871   return bs_head;
4872 }
4873
4874 static void
4875 handle_jit_event (void)
4876 {
4877   struct frame_info *frame;
4878   struct gdbarch *gdbarch;
4879
4880   /* Switch terminal for any messages produced by
4881      breakpoint_re_set.  */
4882   target_terminal_ours_for_output ();
4883
4884   frame = get_current_frame ();
4885   gdbarch = get_frame_arch (frame);
4886
4887   jit_event_handler (gdbarch);
4888
4889   target_terminal_inferior ();
4890 }
4891
4892 /* Handle an solib event by calling solib_add.  */
4893
4894 void
4895 handle_solib_event (void)
4896 {
4897   clear_program_space_solib_cache (current_inferior ()->pspace);
4898
4899   /* Check for any newly added shared libraries if we're supposed to
4900      be adding them automatically.  Switch terminal for any messages
4901      produced by breakpoint_re_set.  */
4902   target_terminal_ours_for_output ();
4903 #ifdef SOLIB_ADD
4904   SOLIB_ADD (NULL, 0, &current_target, auto_solib_add);
4905 #else
4906   solib_add (NULL, 0, &current_target, auto_solib_add);
4907 #endif
4908   target_terminal_inferior ();
4909 }
4910
4911 /* Prepare WHAT final decision for infrun.  */
4912
4913 /* Decide what infrun needs to do with this bpstat.  */
4914
4915 struct bpstat_what
4916 bpstat_what (bpstat bs_head)
4917 {
4918   struct bpstat_what retval;
4919   int jit_event = 0;
4920   bpstat bs;
4921
4922   retval.main_action = BPSTAT_WHAT_KEEP_CHECKING;
4923   retval.call_dummy = STOP_NONE;
4924   retval.is_longjmp = 0;
4925
4926   for (bs = bs_head; bs != NULL; bs = bs->next)
4927     {
4928       /* Extract this BS's action.  After processing each BS, we check
4929          if its action overrides all we've seem so far.  */
4930       enum bpstat_what_main_action this_action = BPSTAT_WHAT_KEEP_CHECKING;
4931       enum bptype bptype;
4932
4933       if (bs->breakpoint_at == NULL)
4934         {
4935           /* I suspect this can happen if it was a momentary
4936              breakpoint which has since been deleted.  */
4937           bptype = bp_none;
4938         }
4939       else
4940         bptype = bs->breakpoint_at->type;
4941
4942       switch (bptype)
4943         {
4944         case bp_none:
4945           break;
4946         case bp_breakpoint:
4947         case bp_hardware_breakpoint:
4948         case bp_until:
4949         case bp_finish:
4950         case bp_shlib_event:
4951           if (bs->stop)
4952             {
4953               if (bs->print)
4954                 this_action = BPSTAT_WHAT_STOP_NOISY;
4955               else
4956                 this_action = BPSTAT_WHAT_STOP_SILENT;
4957             }
4958           else
4959             this_action = BPSTAT_WHAT_SINGLE;
4960           break;
4961         case bp_watchpoint:
4962         case bp_hardware_watchpoint:
4963         case bp_read_watchpoint:
4964         case bp_access_watchpoint:
4965           if (bs->stop)
4966             {
4967               if (bs->print)
4968                 this_action = BPSTAT_WHAT_STOP_NOISY;
4969               else
4970                 this_action = BPSTAT_WHAT_STOP_SILENT;
4971             }
4972           else
4973             {
4974               /* There was a watchpoint, but we're not stopping.
4975                  This requires no further action.  */
4976             }
4977           break;
4978         case bp_longjmp:
4979         case bp_exception:
4980           this_action = BPSTAT_WHAT_SET_LONGJMP_RESUME;
4981           retval.is_longjmp = bptype == bp_longjmp;
4982           break;
4983         case bp_longjmp_resume:
4984         case bp_exception_resume:
4985           this_action = BPSTAT_WHAT_CLEAR_LONGJMP_RESUME;
4986           retval.is_longjmp = bptype == bp_longjmp_resume;
4987           break;
4988         case bp_step_resume:
4989           if (bs->stop)
4990             this_action = BPSTAT_WHAT_STEP_RESUME;
4991           else
4992             {
4993               /* It is for the wrong frame.  */
4994               this_action = BPSTAT_WHAT_SINGLE;
4995             }
4996           break;
4997         case bp_hp_step_resume:
4998           if (bs->stop)
4999             this_action = BPSTAT_WHAT_HP_STEP_RESUME;
5000           else
5001             {
5002               /* It is for the wrong frame.  */
5003               this_action = BPSTAT_WHAT_SINGLE;
5004             }
5005           break;
5006         case bp_watchpoint_scope:
5007         case bp_thread_event:
5008         case bp_overlay_event:
5009         case bp_longjmp_master:
5010         case bp_std_terminate_master:
5011         case bp_exception_master:
5012           this_action = BPSTAT_WHAT_SINGLE;
5013           break;
5014         case bp_catchpoint:
5015           if (bs->stop)
5016             {
5017               if (bs->print)
5018                 this_action = BPSTAT_WHAT_STOP_NOISY;
5019               else
5020                 this_action = BPSTAT_WHAT_STOP_SILENT;
5021             }
5022           else
5023             {
5024               /* There was a catchpoint, but we're not stopping.
5025                  This requires no further action.  */
5026             }
5027           break;
5028         case bp_jit_event:
5029           jit_event = 1;
5030           this_action = BPSTAT_WHAT_SINGLE;
5031           break;
5032         case bp_call_dummy:
5033           /* Make sure the action is stop (silent or noisy),
5034              so infrun.c pops the dummy frame.  */
5035           retval.call_dummy = STOP_STACK_DUMMY;
5036           this_action = BPSTAT_WHAT_STOP_SILENT;
5037           break;
5038         case bp_std_terminate:
5039           /* Make sure the action is stop (silent or noisy),
5040              so infrun.c pops the dummy frame.  */
5041           retval.call_dummy = STOP_STD_TERMINATE;
5042           this_action = BPSTAT_WHAT_STOP_SILENT;
5043           break;
5044         case bp_tracepoint:
5045         case bp_fast_tracepoint:
5046         case bp_static_tracepoint:
5047           /* Tracepoint hits should not be reported back to GDB, and
5048              if one got through somehow, it should have been filtered
5049              out already.  */
5050           internal_error (__FILE__, __LINE__,
5051                           _("bpstat_what: tracepoint encountered"));
5052           break;
5053         case bp_gnu_ifunc_resolver:
5054           /* Step over it (and insert bp_gnu_ifunc_resolver_return).  */
5055           this_action = BPSTAT_WHAT_SINGLE;
5056           break;
5057         case bp_gnu_ifunc_resolver_return:
5058           /* The breakpoint will be removed, execution will restart from the
5059              PC of the former breakpoint.  */
5060           this_action = BPSTAT_WHAT_KEEP_CHECKING;
5061           break;
5062         default:
5063           internal_error (__FILE__, __LINE__,
5064                           _("bpstat_what: unhandled bptype %d"), (int) bptype);
5065         }
5066
5067       retval.main_action = max (retval.main_action, this_action);
5068     }
5069
5070   /* These operations may affect the bs->breakpoint_at state so they are
5071      delayed after MAIN_ACTION is decided above.  */
5072
5073   if (jit_event)
5074     {
5075       if (debug_infrun)
5076         fprintf_unfiltered (gdb_stdlog, "bpstat_what: bp_jit_event\n");
5077
5078       handle_jit_event ();
5079     }
5080
5081   for (bs = bs_head; bs != NULL; bs = bs->next)
5082     {
5083       struct breakpoint *b = bs->breakpoint_at;
5084
5085       if (b == NULL)
5086         continue;
5087       switch (b->type)
5088         {
5089         case bp_gnu_ifunc_resolver:
5090           gnu_ifunc_resolver_stop (b);
5091           break;
5092         case bp_gnu_ifunc_resolver_return:
5093           gnu_ifunc_resolver_return_stop (b);
5094           break;
5095         }
5096     }
5097
5098   return retval;
5099 }
5100
5101 /* Nonzero if we should step constantly (e.g. watchpoints on machines
5102    without hardware support).  This isn't related to a specific bpstat,
5103    just to things like whether watchpoints are set.  */
5104
5105 int
5106 bpstat_should_step (void)
5107 {
5108   struct breakpoint *b;
5109
5110   ALL_BREAKPOINTS (b)
5111     if (breakpoint_enabled (b) && b->type == bp_watchpoint && b->loc != NULL)
5112       return 1;
5113   return 0;
5114 }
5115
5116 int
5117 bpstat_causes_stop (bpstat bs)
5118 {
5119   for (; bs != NULL; bs = bs->next)
5120     if (bs->stop)
5121       return 1;
5122
5123   return 0;
5124 }
5125
5126 \f
5127
5128 /* Compute a string of spaces suitable to indent the next line
5129    so it starts at the position corresponding to the table column
5130    named COL_NAME in the currently active table of UIOUT.  */
5131
5132 static char *
5133 wrap_indent_at_field (struct ui_out *uiout, const char *col_name)
5134 {
5135   static char wrap_indent[80];
5136   int i, total_width, width, align;
5137   char *text;
5138
5139   total_width = 0;
5140   for (i = 1; ui_out_query_field (uiout, i, &width, &align, &text); i++)
5141     {
5142       if (strcmp (text, col_name) == 0)
5143         {
5144           gdb_assert (total_width < sizeof wrap_indent);
5145           memset (wrap_indent, ' ', total_width);
5146           wrap_indent[total_width] = 0;
5147
5148           return wrap_indent;
5149         }
5150
5151       total_width += width + 1;
5152     }
5153
5154   return NULL;
5155 }
5156
5157 /* Determine if the locations of this breakpoint will have their conditions
5158    evaluated by the target, host or a mix of both.  Returns the following:
5159
5160     "host": Host evals condition.
5161     "host or target": Host or Target evals condition.
5162     "target": Target evals condition.
5163 */
5164
5165 static const char *
5166 bp_condition_evaluator (struct breakpoint *b)
5167 {
5168   struct bp_location *bl;
5169   char host_evals = 0;
5170   char target_evals = 0;
5171
5172   if (!b)
5173     return NULL;
5174
5175   if (!is_breakpoint (b))
5176     return NULL;
5177
5178   if (gdb_evaluates_breakpoint_condition_p ()
5179       || !target_supports_evaluation_of_breakpoint_conditions ())
5180     return condition_evaluation_host;
5181
5182   for (bl = b->loc; bl; bl = bl->next)
5183     {
5184       if (bl->cond_bytecode)
5185         target_evals++;
5186       else
5187         host_evals++;
5188     }
5189
5190   if (host_evals && target_evals)
5191     return condition_evaluation_both;
5192   else if (target_evals)
5193     return condition_evaluation_target;
5194   else
5195     return condition_evaluation_host;
5196 }
5197
5198 /* Determine the breakpoint location's condition evaluator.  This is
5199    similar to bp_condition_evaluator, but for locations.  */
5200
5201 static const char *
5202 bp_location_condition_evaluator (struct bp_location *bl)
5203 {
5204   if (bl && !is_breakpoint (bl->owner))
5205     return NULL;
5206
5207   if (gdb_evaluates_breakpoint_condition_p ()
5208       || !target_supports_evaluation_of_breakpoint_conditions ())
5209     return condition_evaluation_host;
5210
5211   if (bl && bl->cond_bytecode)
5212     return condition_evaluation_target;
5213   else
5214     return condition_evaluation_host;
5215 }
5216
5217 /* Print the LOC location out of the list of B->LOC locations.  */
5218
5219 static void
5220 print_breakpoint_location (struct breakpoint *b,
5221                            struct bp_location *loc)
5222 {
5223   struct ui_out *uiout = current_uiout;
5224   struct cleanup *old_chain = save_current_program_space ();
5225
5226   if (loc != NULL && loc->shlib_disabled)
5227     loc = NULL;
5228
5229   if (loc != NULL)
5230     set_current_program_space (loc->pspace);
5231
5232   if (b->display_canonical)
5233     ui_out_field_string (uiout, "what", b->addr_string);
5234   else if (loc && loc->source_file)
5235     {
5236       struct symbol *sym 
5237         = find_pc_sect_function (loc->address, loc->section);
5238       if (sym)
5239         {
5240           ui_out_text (uiout, "in ");
5241           ui_out_field_string (uiout, "func",
5242                                SYMBOL_PRINT_NAME (sym));
5243           ui_out_text (uiout, " ");
5244           ui_out_wrap_hint (uiout, wrap_indent_at_field (uiout, "what"));
5245           ui_out_text (uiout, "at ");
5246         }
5247       ui_out_field_string (uiout, "file", loc->source_file);
5248       ui_out_text (uiout, ":");
5249       
5250       if (ui_out_is_mi_like_p (uiout))
5251         {
5252           struct symtab_and_line sal = find_pc_line (loc->address, 0);
5253           char *fullname = symtab_to_fullname (sal.symtab);
5254           
5255           if (fullname)
5256             ui_out_field_string (uiout, "fullname", fullname);
5257         }
5258       
5259       ui_out_field_int (uiout, "line", loc->line_number);
5260     }
5261   else if (loc)
5262     {
5263       struct ui_stream *stb = ui_out_stream_new (uiout);
5264       struct cleanup *stb_chain = make_cleanup_ui_out_stream_delete (stb);
5265
5266       print_address_symbolic (loc->gdbarch, loc->address, stb->stream,
5267                               demangle, "");
5268       ui_out_field_stream (uiout, "at", stb);
5269
5270       do_cleanups (stb_chain);
5271     }
5272   else
5273     ui_out_field_string (uiout, "pending", b->addr_string);
5274
5275   if (loc && is_breakpoint (b)
5276       && breakpoint_condition_evaluation_mode () == condition_evaluation_target
5277       && bp_condition_evaluator (b) == condition_evaluation_both)
5278     {
5279       ui_out_text (uiout, " (");
5280       ui_out_field_string (uiout, "evaluated-by",
5281                            bp_location_condition_evaluator (loc));
5282       ui_out_text (uiout, ")");
5283     }
5284
5285   do_cleanups (old_chain);
5286 }
5287
5288 static const char *
5289 bptype_string (enum bptype type)
5290 {
5291   struct ep_type_description
5292     {
5293       enum bptype type;
5294       char *description;
5295     };
5296   static struct ep_type_description bptypes[] =
5297   {
5298     {bp_none, "?deleted?"},
5299     {bp_breakpoint, "breakpoint"},
5300     {bp_hardware_breakpoint, "hw breakpoint"},
5301     {bp_until, "until"},
5302     {bp_finish, "finish"},
5303     {bp_watchpoint, "watchpoint"},
5304     {bp_hardware_watchpoint, "hw watchpoint"},
5305     {bp_read_watchpoint, "read watchpoint"},
5306     {bp_access_watchpoint, "acc watchpoint"},
5307     {bp_longjmp, "longjmp"},
5308     {bp_longjmp_resume, "longjmp resume"},
5309     {bp_exception, "exception"},
5310     {bp_exception_resume, "exception resume"},
5311     {bp_step_resume, "step resume"},
5312     {bp_hp_step_resume, "high-priority step resume"},
5313     {bp_watchpoint_scope, "watchpoint scope"},
5314     {bp_call_dummy, "call dummy"},
5315     {bp_std_terminate, "std::terminate"},
5316     {bp_shlib_event, "shlib events"},
5317     {bp_thread_event, "thread events"},
5318     {bp_overlay_event, "overlay events"},
5319     {bp_longjmp_master, "longjmp master"},
5320     {bp_std_terminate_master, "std::terminate master"},
5321     {bp_exception_master, "exception master"},
5322     {bp_catchpoint, "catchpoint"},
5323     {bp_tracepoint, "tracepoint"},
5324     {bp_fast_tracepoint, "fast tracepoint"},
5325     {bp_static_tracepoint, "static tracepoint"},
5326     {bp_jit_event, "jit events"},
5327     {bp_gnu_ifunc_resolver, "STT_GNU_IFUNC resolver"},
5328     {bp_gnu_ifunc_resolver_return, "STT_GNU_IFUNC resolver return"},
5329   };
5330
5331   if (((int) type >= (sizeof (bptypes) / sizeof (bptypes[0])))
5332       || ((int) type != bptypes[(int) type].type))
5333     internal_error (__FILE__, __LINE__,
5334                     _("bptypes table does not describe type #%d."),
5335                     (int) type);
5336
5337   return bptypes[(int) type].description;
5338 }
5339
5340 /* Print B to gdb_stdout.  */
5341
5342 static void
5343 print_one_breakpoint_location (struct breakpoint *b,
5344                                struct bp_location *loc,
5345                                int loc_number,
5346                                struct bp_location **last_loc,
5347                                int allflag)
5348 {
5349   struct command_line *l;
5350   static char bpenables[] = "nynny";
5351
5352   struct ui_out *uiout = current_uiout;
5353   int header_of_multiple = 0;
5354   int part_of_multiple = (loc != NULL);
5355   struct value_print_options opts;
5356
5357   get_user_print_options (&opts);
5358
5359   gdb_assert (!loc || loc_number != 0);
5360   /* See comment in print_one_breakpoint concerning treatment of
5361      breakpoints with single disabled location.  */
5362   if (loc == NULL 
5363       && (b->loc != NULL 
5364           && (b->loc->next != NULL || !b->loc->enabled)))
5365     header_of_multiple = 1;
5366   if (loc == NULL)
5367     loc = b->loc;
5368
5369   annotate_record ();
5370
5371   /* 1 */
5372   annotate_field (0);
5373   if (part_of_multiple)
5374     {
5375       char *formatted;
5376       formatted = xstrprintf ("%d.%d", b->number, loc_number);
5377       ui_out_field_string (uiout, "number", formatted);
5378       xfree (formatted);
5379     }
5380   else
5381     {
5382       ui_out_field_int (uiout, "number", b->number);
5383     }
5384
5385   /* 2 */
5386   annotate_field (1);
5387   if (part_of_multiple)
5388     ui_out_field_skip (uiout, "type");
5389   else
5390     ui_out_field_string (uiout, "type", bptype_string (b->type));
5391
5392   /* 3 */
5393   annotate_field (2);
5394   if (part_of_multiple)
5395     ui_out_field_skip (uiout, "disp");
5396   else
5397     ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
5398
5399
5400   /* 4 */
5401   annotate_field (3);
5402   if (part_of_multiple)
5403     ui_out_field_string (uiout, "enabled", loc->enabled ? "y" : "n");
5404   else
5405     ui_out_field_fmt (uiout, "enabled", "%c", 
5406                       bpenables[(int) b->enable_state]);
5407   ui_out_spaces (uiout, 2);
5408
5409   
5410   /* 5 and 6 */
5411   if (b->ops != NULL && b->ops->print_one != NULL)
5412     {
5413       /* Although the print_one can possibly print all locations,
5414          calling it here is not likely to get any nice result.  So,
5415          make sure there's just one location.  */
5416       gdb_assert (b->loc == NULL || b->loc->next == NULL);
5417       b->ops->print_one (b, last_loc);
5418     }
5419   else
5420     switch (b->type)
5421       {
5422       case bp_none:
5423         internal_error (__FILE__, __LINE__,
5424                         _("print_one_breakpoint: bp_none encountered\n"));
5425         break;
5426
5427       case bp_watchpoint:
5428       case bp_hardware_watchpoint:
5429       case bp_read_watchpoint:
5430       case bp_access_watchpoint:
5431         {
5432           struct watchpoint *w = (struct watchpoint *) b;
5433
5434           /* Field 4, the address, is omitted (which makes the columns
5435              not line up too nicely with the headers, but the effect
5436              is relatively readable).  */
5437           if (opts.addressprint)
5438             ui_out_field_skip (uiout, "addr");
5439           annotate_field (5);
5440           ui_out_field_string (uiout, "what", w->exp_string);
5441         }
5442         break;
5443
5444       case bp_breakpoint:
5445       case bp_hardware_breakpoint:
5446       case bp_until:
5447       case bp_finish:
5448       case bp_longjmp:
5449       case bp_longjmp_resume:
5450       case bp_exception:
5451       case bp_exception_resume:
5452       case bp_step_resume:
5453       case bp_hp_step_resume:
5454       case bp_watchpoint_scope:
5455       case bp_call_dummy:
5456       case bp_std_terminate:
5457       case bp_shlib_event:
5458       case bp_thread_event:
5459       case bp_overlay_event:
5460       case bp_longjmp_master:
5461       case bp_std_terminate_master:
5462       case bp_exception_master:
5463       case bp_tracepoint:
5464       case bp_fast_tracepoint:
5465       case bp_static_tracepoint:
5466       case bp_jit_event:
5467       case bp_gnu_ifunc_resolver:
5468       case bp_gnu_ifunc_resolver_return:
5469         if (opts.addressprint)
5470           {
5471             annotate_field (4);
5472             if (header_of_multiple)
5473               ui_out_field_string (uiout, "addr", "<MULTIPLE>");
5474             else if (b->loc == NULL || loc->shlib_disabled)
5475               ui_out_field_string (uiout, "addr", "<PENDING>");
5476             else
5477               ui_out_field_core_addr (uiout, "addr",
5478                                       loc->gdbarch, loc->address);
5479           }
5480         annotate_field (5);
5481         if (!header_of_multiple)
5482           print_breakpoint_location (b, loc);
5483         if (b->loc)
5484           *last_loc = b->loc;
5485         break;
5486       }
5487
5488
5489   /* For backward compatibility, don't display inferiors unless there
5490      are several.  */
5491   if (loc != NULL
5492       && !header_of_multiple
5493       && (allflag
5494           || (!gdbarch_has_global_breakpoints (target_gdbarch)
5495               && (number_of_program_spaces () > 1
5496                   || number_of_inferiors () > 1)
5497               /* LOC is for existing B, it cannot be in
5498                  moribund_locations and thus having NULL OWNER.  */
5499               && loc->owner->type != bp_catchpoint)))
5500     {
5501       struct inferior *inf;
5502       int first = 1;
5503
5504       for (inf = inferior_list; inf != NULL; inf = inf->next)
5505         {
5506           if (inf->pspace == loc->pspace)
5507             {
5508               if (first)
5509                 {
5510                   first = 0;
5511                   ui_out_text (uiout, " inf ");
5512                 }
5513               else
5514                 ui_out_text (uiout, ", ");
5515               ui_out_text (uiout, plongest (inf->num));
5516             }
5517         }
5518     }
5519
5520   if (!part_of_multiple)
5521     {
5522       if (b->thread != -1)
5523         {
5524           /* FIXME: This seems to be redundant and lost here; see the
5525              "stop only in" line a little further down.  */
5526           ui_out_text (uiout, " thread ");
5527           ui_out_field_int (uiout, "thread", b->thread);
5528         }
5529       else if (b->task != 0)
5530         {
5531           ui_out_text (uiout, " task ");
5532           ui_out_field_int (uiout, "task", b->task);
5533         }
5534     }
5535
5536   ui_out_text (uiout, "\n");
5537
5538   if (!part_of_multiple)
5539     b->ops->print_one_detail (b, uiout);
5540
5541   if (part_of_multiple && frame_id_p (b->frame_id))
5542     {
5543       annotate_field (6);
5544       ui_out_text (uiout, "\tstop only in stack frame at ");
5545       /* FIXME: cagney/2002-12-01: Shouldn't be poking around inside
5546          the frame ID.  */
5547       ui_out_field_core_addr (uiout, "frame",
5548                               b->gdbarch, b->frame_id.stack_addr);
5549       ui_out_text (uiout, "\n");
5550     }
5551   
5552   if (!part_of_multiple && b->cond_string)
5553     {
5554       annotate_field (7);
5555       if (is_tracepoint (b))
5556         ui_out_text (uiout, "\ttrace only if ");
5557       else
5558         ui_out_text (uiout, "\tstop only if ");
5559       ui_out_field_string (uiout, "cond", b->cond_string);
5560
5561       /* Print whether the target is doing the breakpoint's condition
5562          evaluation.  If GDB is doing the evaluation, don't print anything.  */
5563       if (is_breakpoint (b)
5564           && breakpoint_condition_evaluation_mode ()
5565           == condition_evaluation_target)
5566         {
5567           ui_out_text (uiout, " (");
5568           ui_out_field_string (uiout, "evaluated-by",
5569                                bp_condition_evaluator (b));
5570           ui_out_text (uiout, " evals)");
5571         }
5572       ui_out_text (uiout, "\n");
5573     }
5574
5575   if (!part_of_multiple && b->thread != -1)
5576     {
5577       /* FIXME should make an annotation for this.  */
5578       ui_out_text (uiout, "\tstop only in thread ");
5579       ui_out_field_int (uiout, "thread", b->thread);
5580       ui_out_text (uiout, "\n");
5581     }
5582   
5583   if (!part_of_multiple && b->hit_count)
5584     {
5585       /* FIXME should make an annotation for this.  */
5586       if (ep_is_catchpoint (b))
5587         ui_out_text (uiout, "\tcatchpoint");
5588       else if (is_tracepoint (b))
5589         ui_out_text (uiout, "\ttracepoint");
5590       else
5591         ui_out_text (uiout, "\tbreakpoint");
5592       ui_out_text (uiout, " already hit ");
5593       ui_out_field_int (uiout, "times", b->hit_count);
5594       if (b->hit_count == 1)
5595         ui_out_text (uiout, " time\n");
5596       else
5597         ui_out_text (uiout, " times\n");
5598     }
5599   
5600   /* Output the count also if it is zero, but only if this is mi.
5601      FIXME: Should have a better test for this.  */
5602   if (ui_out_is_mi_like_p (uiout))
5603     if (!part_of_multiple && b->hit_count == 0)
5604       ui_out_field_int (uiout, "times", b->hit_count);
5605
5606   if (!part_of_multiple && b->ignore_count)
5607     {
5608       annotate_field (8);
5609       ui_out_text (uiout, "\tignore next ");
5610       ui_out_field_int (uiout, "ignore", b->ignore_count);
5611       ui_out_text (uiout, " hits\n");
5612     }
5613
5614   /* Note that an enable count of 1 corresponds to "enable once"
5615      behavior, which is reported by the combination of enablement and
5616      disposition, so we don't need to mention it here.  */
5617   if (!part_of_multiple && b->enable_count > 1)
5618     {
5619       annotate_field (8);
5620       ui_out_text (uiout, "\tdisable after ");
5621       /* Tweak the wording to clarify that ignore and enable counts
5622          are distinct, and have additive effect.  */
5623       if (b->ignore_count)
5624         ui_out_text (uiout, "additional ");
5625       else
5626         ui_out_text (uiout, "next ");
5627       ui_out_field_int (uiout, "enable", b->enable_count);
5628       ui_out_text (uiout, " hits\n");
5629     }
5630
5631   if (!part_of_multiple && is_tracepoint (b))
5632     {
5633       struct tracepoint *tp = (struct tracepoint *) b;
5634
5635       if (tp->traceframe_usage)
5636         {
5637           ui_out_text (uiout, "\ttrace buffer usage ");
5638           ui_out_field_int (uiout, "traceframe-usage", tp->traceframe_usage);
5639           ui_out_text (uiout, " bytes\n");
5640         }
5641     }
5642   
5643   l = b->commands ? b->commands->commands : NULL;
5644   if (!part_of_multiple && l)
5645     {
5646       struct cleanup *script_chain;
5647
5648       annotate_field (9);
5649       script_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "script");
5650       print_command_lines (uiout, l, 4);
5651       do_cleanups (script_chain);
5652     }
5653
5654   if (is_tracepoint (b))
5655     {
5656       struct tracepoint *t = (struct tracepoint *) b;
5657
5658       if (!part_of_multiple && t->pass_count)
5659         {
5660           annotate_field (10);
5661           ui_out_text (uiout, "\tpass count ");
5662           ui_out_field_int (uiout, "pass", t->pass_count);
5663           ui_out_text (uiout, " \n");
5664         }
5665     }
5666
5667   if (ui_out_is_mi_like_p (uiout) && !part_of_multiple)
5668     {
5669       if (is_watchpoint (b))
5670         {
5671           struct watchpoint *w = (struct watchpoint *) b;
5672
5673           ui_out_field_string (uiout, "original-location", w->exp_string);
5674         }
5675       else if (b->addr_string)
5676         ui_out_field_string (uiout, "original-location", b->addr_string);
5677     }
5678 }
5679
5680 static void
5681 print_one_breakpoint (struct breakpoint *b,
5682                       struct bp_location **last_loc, 
5683                       int allflag)
5684 {
5685   struct cleanup *bkpt_chain;
5686   struct ui_out *uiout = current_uiout;
5687
5688   bkpt_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "bkpt");
5689
5690   print_one_breakpoint_location (b, NULL, 0, last_loc, allflag);
5691   do_cleanups (bkpt_chain);
5692
5693   /* If this breakpoint has custom print function,
5694      it's already printed.  Otherwise, print individual
5695      locations, if any.  */
5696   if (b->ops == NULL || b->ops->print_one == NULL)
5697     {
5698       /* If breakpoint has a single location that is disabled, we
5699          print it as if it had several locations, since otherwise it's
5700          hard to represent "breakpoint enabled, location disabled"
5701          situation.
5702
5703          Note that while hardware watchpoints have several locations
5704          internally, that's not a property exposed to user.  */
5705       if (b->loc 
5706           && !is_hardware_watchpoint (b)
5707           && (b->loc->next || !b->loc->enabled))
5708         {
5709           struct bp_location *loc;
5710           int n = 1;
5711
5712           for (loc = b->loc; loc; loc = loc->next, ++n)
5713             {
5714               struct cleanup *inner2 =
5715                 make_cleanup_ui_out_tuple_begin_end (uiout, NULL);
5716               print_one_breakpoint_location (b, loc, n, last_loc, allflag);
5717               do_cleanups (inner2);
5718             }
5719         }
5720     }
5721 }
5722
5723 static int
5724 breakpoint_address_bits (struct breakpoint *b)
5725 {
5726   int print_address_bits = 0;
5727   struct bp_location *loc;
5728
5729   for (loc = b->loc; loc; loc = loc->next)
5730     {
5731       int addr_bit;
5732
5733       /* Software watchpoints that aren't watching memory don't have
5734          an address to print.  */
5735       if (b->type == bp_watchpoint && loc->watchpoint_type == -1)
5736         continue;
5737
5738       addr_bit = gdbarch_addr_bit (loc->gdbarch);
5739       if (addr_bit > print_address_bits)
5740         print_address_bits = addr_bit;
5741     }
5742
5743   return print_address_bits;
5744 }
5745
5746 struct captured_breakpoint_query_args
5747   {
5748     int bnum;
5749   };
5750
5751 static int
5752 do_captured_breakpoint_query (struct ui_out *uiout, void *data)
5753 {
5754   struct captured_breakpoint_query_args *args = data;
5755   struct breakpoint *b;
5756   struct bp_location *dummy_loc = NULL;
5757
5758   ALL_BREAKPOINTS (b)
5759     {
5760       if (args->bnum == b->number)
5761         {
5762           print_one_breakpoint (b, &dummy_loc, 0);
5763           return GDB_RC_OK;
5764         }
5765     }
5766   return GDB_RC_NONE;
5767 }
5768
5769 enum gdb_rc
5770 gdb_breakpoint_query (struct ui_out *uiout, int bnum, 
5771                       char **error_message)
5772 {
5773   struct captured_breakpoint_query_args args;
5774
5775   args.bnum = bnum;
5776   /* For the moment we don't trust print_one_breakpoint() to not throw
5777      an error.  */
5778   if (catch_exceptions_with_msg (uiout, do_captured_breakpoint_query, &args,
5779                                  error_message, RETURN_MASK_ALL) < 0)
5780     return GDB_RC_FAIL;
5781   else
5782     return GDB_RC_OK;
5783 }
5784
5785 /* Return true if this breakpoint was set by the user, false if it is
5786    internal or momentary.  */
5787
5788 int
5789 user_breakpoint_p (struct breakpoint *b)
5790 {
5791   return b->number > 0;
5792 }
5793
5794 /* Print information on user settable breakpoint (watchpoint, etc)
5795    number BNUM.  If BNUM is -1 print all user-settable breakpoints.
5796    If ALLFLAG is non-zero, include non-user-settable breakpoints.  If
5797    FILTER is non-NULL, call it on each breakpoint and only include the
5798    ones for which it returns non-zero.  Return the total number of
5799    breakpoints listed.  */
5800
5801 static int
5802 breakpoint_1 (char *args, int allflag, 
5803               int (*filter) (const struct breakpoint *))
5804 {
5805   struct breakpoint *b;
5806   struct bp_location *last_loc = NULL;
5807   int nr_printable_breakpoints;
5808   struct cleanup *bkpttbl_chain;
5809   struct value_print_options opts;
5810   int print_address_bits = 0;
5811   int print_type_col_width = 14;
5812   struct ui_out *uiout = current_uiout;
5813
5814   get_user_print_options (&opts);
5815
5816   /* Compute the number of rows in the table, as well as the size
5817      required for address fields.  */
5818   nr_printable_breakpoints = 0;
5819   ALL_BREAKPOINTS (b)
5820     {
5821       /* If we have a filter, only list the breakpoints it accepts.  */
5822       if (filter && !filter (b))
5823         continue;
5824
5825       /* If we have an "args" string, it is a list of breakpoints to 
5826          accept.  Skip the others.  */
5827       if (args != NULL && *args != '\0')
5828         {
5829           if (allflag && parse_and_eval_long (args) != b->number)
5830             continue;
5831           if (!allflag && !number_is_in_list (args, b->number))
5832             continue;
5833         }
5834
5835       if (allflag || user_breakpoint_p (b))
5836         {
5837           int addr_bit, type_len;
5838
5839           addr_bit = breakpoint_address_bits (b);
5840           if (addr_bit > print_address_bits)
5841             print_address_bits = addr_bit;
5842
5843           type_len = strlen (bptype_string (b->type));
5844           if (type_len > print_type_col_width)
5845             print_type_col_width = type_len;
5846
5847           nr_printable_breakpoints++;
5848         }
5849     }
5850
5851   if (opts.addressprint)
5852     bkpttbl_chain 
5853       = make_cleanup_ui_out_table_begin_end (uiout, 6,
5854                                              nr_printable_breakpoints,
5855                                              "BreakpointTable");
5856   else
5857     bkpttbl_chain 
5858       = make_cleanup_ui_out_table_begin_end (uiout, 5,
5859                                              nr_printable_breakpoints,
5860                                              "BreakpointTable");
5861
5862   if (nr_printable_breakpoints > 0)
5863     annotate_breakpoints_headers ();
5864   if (nr_printable_breakpoints > 0)
5865     annotate_field (0);
5866   ui_out_table_header (uiout, 7, ui_left, "number", "Num");     /* 1 */
5867   if (nr_printable_breakpoints > 0)
5868     annotate_field (1);
5869   ui_out_table_header (uiout, print_type_col_width, ui_left,
5870                        "type", "Type");                         /* 2 */
5871   if (nr_printable_breakpoints > 0)
5872     annotate_field (2);
5873   ui_out_table_header (uiout, 4, ui_left, "disp", "Disp");      /* 3 */
5874   if (nr_printable_breakpoints > 0)
5875     annotate_field (3);
5876   ui_out_table_header (uiout, 3, ui_left, "enabled", "Enb");    /* 4 */
5877   if (opts.addressprint)
5878     {
5879       if (nr_printable_breakpoints > 0)
5880         annotate_field (4);
5881       if (print_address_bits <= 32)
5882         ui_out_table_header (uiout, 10, ui_left, 
5883                              "addr", "Address");                /* 5 */
5884       else
5885         ui_out_table_header (uiout, 18, ui_left, 
5886                              "addr", "Address");                /* 5 */
5887     }
5888   if (nr_printable_breakpoints > 0)
5889     annotate_field (5);
5890   ui_out_table_header (uiout, 40, ui_noalign, "what", "What");  /* 6 */
5891   ui_out_table_body (uiout);
5892   if (nr_printable_breakpoints > 0)
5893     annotate_breakpoints_table ();
5894
5895   ALL_BREAKPOINTS (b)
5896     {
5897       QUIT;
5898       /* If we have a filter, only list the breakpoints it accepts.  */
5899       if (filter && !filter (b))
5900         continue;
5901
5902       /* If we have an "args" string, it is a list of breakpoints to 
5903          accept.  Skip the others.  */
5904
5905       if (args != NULL && *args != '\0')
5906         {
5907           if (allflag)  /* maintenance info breakpoint */
5908             {
5909               if (parse_and_eval_long (args) != b->number)
5910                 continue;
5911             }
5912           else          /* all others */
5913             {
5914               if (!number_is_in_list (args, b->number))
5915                 continue;
5916             }
5917         }
5918       /* We only print out user settable breakpoints unless the
5919          allflag is set.  */
5920       if (allflag || user_breakpoint_p (b))
5921         print_one_breakpoint (b, &last_loc, allflag);
5922     }
5923
5924   do_cleanups (bkpttbl_chain);
5925
5926   if (nr_printable_breakpoints == 0)
5927     {
5928       /* If there's a filter, let the caller decide how to report
5929          empty list.  */
5930       if (!filter)
5931         {
5932           if (args == NULL || *args == '\0')
5933             ui_out_message (uiout, 0, "No breakpoints or watchpoints.\n");
5934           else
5935             ui_out_message (uiout, 0, 
5936                             "No breakpoint or watchpoint matching '%s'.\n",
5937                             args);
5938         }
5939     }
5940   else
5941     {
5942       if (last_loc && !server_command)
5943         set_next_address (last_loc->gdbarch, last_loc->address);
5944     }
5945
5946   /* FIXME?  Should this be moved up so that it is only called when
5947      there have been breakpoints? */
5948   annotate_breakpoints_table_end ();
5949
5950   return nr_printable_breakpoints;
5951 }
5952
5953 /* Display the value of default-collect in a way that is generally
5954    compatible with the breakpoint list.  */
5955
5956 static void
5957 default_collect_info (void)
5958 {
5959   struct ui_out *uiout = current_uiout;
5960
5961   /* If it has no value (which is frequently the case), say nothing; a
5962      message like "No default-collect." gets in user's face when it's
5963      not wanted.  */
5964   if (!*default_collect)
5965     return;
5966
5967   /* The following phrase lines up nicely with per-tracepoint collect
5968      actions.  */
5969   ui_out_text (uiout, "default collect ");
5970   ui_out_field_string (uiout, "default-collect", default_collect);
5971   ui_out_text (uiout, " \n");
5972 }
5973   
5974 static void
5975 breakpoints_info (char *args, int from_tty)
5976 {
5977   breakpoint_1 (args, 0, NULL);
5978
5979   default_collect_info ();
5980 }
5981
5982 static void
5983 watchpoints_info (char *args, int from_tty)
5984 {
5985   int num_printed = breakpoint_1 (args, 0, is_watchpoint);
5986   struct ui_out *uiout = current_uiout;
5987
5988   if (num_printed == 0)
5989     {
5990       if (args == NULL || *args == '\0')
5991         ui_out_message (uiout, 0, "No watchpoints.\n");
5992       else
5993         ui_out_message (uiout, 0, "No watchpoint matching '%s'.\n", args);
5994     }
5995 }
5996
5997 static void
5998 maintenance_info_breakpoints (char *args, int from_tty)
5999 {
6000   breakpoint_1 (args, 1, NULL);
6001
6002   default_collect_info ();
6003 }
6004
6005 static int
6006 breakpoint_has_pc (struct breakpoint *b,
6007                    struct program_space *pspace,
6008                    CORE_ADDR pc, struct obj_section *section)
6009 {
6010   struct bp_location *bl = b->loc;
6011
6012   for (; bl; bl = bl->next)
6013     {
6014       if (bl->pspace == pspace
6015           && bl->address == pc
6016           && (!overlay_debugging || bl->section == section))
6017         return 1;         
6018     }
6019   return 0;
6020 }
6021
6022 /* Print a message describing any user-breakpoints set at PC.  This
6023    concerns with logical breakpoints, so we match program spaces, not
6024    address spaces.  */
6025
6026 static void
6027 describe_other_breakpoints (struct gdbarch *gdbarch,
6028                             struct program_space *pspace, CORE_ADDR pc,
6029                             struct obj_section *section, int thread)
6030 {
6031   int others = 0;
6032   struct breakpoint *b;
6033
6034   ALL_BREAKPOINTS (b)
6035     others += (user_breakpoint_p (b)
6036                && breakpoint_has_pc (b, pspace, pc, section));
6037   if (others > 0)
6038     {
6039       if (others == 1)
6040         printf_filtered (_("Note: breakpoint "));
6041       else /* if (others == ???) */
6042         printf_filtered (_("Note: breakpoints "));
6043       ALL_BREAKPOINTS (b)
6044         if (user_breakpoint_p (b) && breakpoint_has_pc (b, pspace, pc, section))
6045           {
6046             others--;
6047             printf_filtered ("%d", b->number);
6048             if (b->thread == -1 && thread != -1)
6049               printf_filtered (" (all threads)");
6050             else if (b->thread != -1)
6051               printf_filtered (" (thread %d)", b->thread);
6052             printf_filtered ("%s%s ",
6053                              ((b->enable_state == bp_disabled
6054                                || b->enable_state == bp_call_disabled)
6055                               ? " (disabled)"
6056                               : b->enable_state == bp_permanent 
6057                               ? " (permanent)"
6058                               : ""),
6059                              (others > 1) ? "," 
6060                              : ((others == 1) ? " and" : ""));
6061           }
6062       printf_filtered (_("also set at pc "));
6063       fputs_filtered (paddress (gdbarch, pc), gdb_stdout);
6064       printf_filtered (".\n");
6065     }
6066 }
6067 \f
6068
6069 /* Return true iff it is meaningful to use the address member of
6070    BPT.  For some breakpoint types, the address member is irrelevant
6071    and it makes no sense to attempt to compare it to other addresses
6072    (or use it for any other purpose either).
6073
6074    More specifically, each of the following breakpoint types will
6075    always have a zero valued address and we don't want to mark
6076    breakpoints of any of these types to be a duplicate of an actual
6077    breakpoint at address zero:
6078
6079       bp_watchpoint
6080       bp_catchpoint
6081
6082 */
6083
6084 static int
6085 breakpoint_address_is_meaningful (struct breakpoint *bpt)
6086 {
6087   enum bptype type = bpt->type;
6088
6089   return (type != bp_watchpoint && type != bp_catchpoint);
6090 }
6091
6092 /* Assuming LOC1 and LOC2's owners are hardware watchpoints, returns
6093    true if LOC1 and LOC2 represent the same watchpoint location.  */
6094
6095 static int
6096 watchpoint_locations_match (struct bp_location *loc1, 
6097                             struct bp_location *loc2)
6098 {
6099   struct watchpoint *w1 = (struct watchpoint *) loc1->owner;
6100   struct watchpoint *w2 = (struct watchpoint *) loc2->owner;
6101
6102   /* Both of them must exist.  */
6103   gdb_assert (w1 != NULL);
6104   gdb_assert (w2 != NULL);
6105
6106   /* If the target can evaluate the condition expression in hardware,
6107      then we we need to insert both watchpoints even if they are at
6108      the same place.  Otherwise the watchpoint will only trigger when
6109      the condition of whichever watchpoint was inserted evaluates to
6110      true, not giving a chance for GDB to check the condition of the
6111      other watchpoint.  */
6112   if ((w1->cond_exp
6113        && target_can_accel_watchpoint_condition (loc1->address, 
6114                                                  loc1->length,
6115                                                  loc1->watchpoint_type,
6116                                                  w1->cond_exp))
6117       || (w2->cond_exp
6118           && target_can_accel_watchpoint_condition (loc2->address, 
6119                                                     loc2->length,
6120                                                     loc2->watchpoint_type,
6121                                                     w2->cond_exp)))
6122     return 0;
6123
6124   /* Note that this checks the owner's type, not the location's.  In
6125      case the target does not support read watchpoints, but does
6126      support access watchpoints, we'll have bp_read_watchpoint
6127      watchpoints with hw_access locations.  Those should be considered
6128      duplicates of hw_read locations.  The hw_read locations will
6129      become hw_access locations later.  */
6130   return (loc1->owner->type == loc2->owner->type
6131           && loc1->pspace->aspace == loc2->pspace->aspace
6132           && loc1->address == loc2->address
6133           && loc1->length == loc2->length);
6134 }
6135
6136 /* Returns true if {ASPACE1,ADDR1} and {ASPACE2,ADDR2} represent the
6137    same breakpoint location.  In most targets, this can only be true
6138    if ASPACE1 matches ASPACE2.  On targets that have global
6139    breakpoints, the address space doesn't really matter.  */
6140
6141 static int
6142 breakpoint_address_match (struct address_space *aspace1, CORE_ADDR addr1,
6143                           struct address_space *aspace2, CORE_ADDR addr2)
6144 {
6145   return ((gdbarch_has_global_breakpoints (target_gdbarch)
6146            || aspace1 == aspace2)
6147           && addr1 == addr2);
6148 }
6149
6150 /* Returns true if {ASPACE2,ADDR2} falls within the range determined by
6151    {ASPACE1,ADDR1,LEN1}.  In most targets, this can only be true if ASPACE1
6152    matches ASPACE2.  On targets that have global breakpoints, the address
6153    space doesn't really matter.  */
6154
6155 static int
6156 breakpoint_address_match_range (struct address_space *aspace1, CORE_ADDR addr1,
6157                                 int len1, struct address_space *aspace2,
6158                                 CORE_ADDR addr2)
6159 {
6160   return ((gdbarch_has_global_breakpoints (target_gdbarch)
6161            || aspace1 == aspace2)
6162           && addr2 >= addr1 && addr2 < addr1 + len1);
6163 }
6164
6165 /* Returns true if {ASPACE,ADDR} matches the breakpoint BL.  BL may be
6166    a ranged breakpoint.  In most targets, a match happens only if ASPACE
6167    matches the breakpoint's address space.  On targets that have global
6168    breakpoints, the address space doesn't really matter.  */
6169
6170 static int
6171 breakpoint_location_address_match (struct bp_location *bl,
6172                                    struct address_space *aspace,
6173                                    CORE_ADDR addr)
6174 {
6175   return (breakpoint_address_match (bl->pspace->aspace, bl->address,
6176                                     aspace, addr)
6177           || (bl->length
6178               && breakpoint_address_match_range (bl->pspace->aspace,
6179                                                  bl->address, bl->length,
6180                                                  aspace, addr)));
6181 }
6182
6183 /* If LOC1 and LOC2's owners are not tracepoints, returns false directly.
6184    Then, if LOC1 and LOC2 represent the same tracepoint location, returns
6185    true, otherwise returns false.  */
6186
6187 static int
6188 tracepoint_locations_match (struct bp_location *loc1,
6189                             struct bp_location *loc2)
6190 {
6191   if (is_tracepoint (loc1->owner) && is_tracepoint (loc2->owner))
6192     /* Since tracepoint locations are never duplicated with others', tracepoint
6193        locations at the same address of different tracepoints are regarded as
6194        different locations.  */
6195     return (loc1->address == loc2->address && loc1->owner == loc2->owner);
6196   else
6197     return 0;
6198 }
6199
6200 /* Assuming LOC1 and LOC2's types' have meaningful target addresses
6201    (breakpoint_address_is_meaningful), returns true if LOC1 and LOC2
6202    represent the same location.  */
6203
6204 static int
6205 breakpoint_locations_match (struct bp_location *loc1, 
6206                             struct bp_location *loc2)
6207 {
6208   int hw_point1, hw_point2;
6209
6210   /* Both of them must not be in moribund_locations.  */
6211   gdb_assert (loc1->owner != NULL);
6212   gdb_assert (loc2->owner != NULL);
6213
6214   hw_point1 = is_hardware_watchpoint (loc1->owner);
6215   hw_point2 = is_hardware_watchpoint (loc2->owner);
6216
6217   if (hw_point1 != hw_point2)
6218     return 0;
6219   else if (hw_point1)
6220     return watchpoint_locations_match (loc1, loc2);
6221   else if (is_tracepoint (loc1->owner) || is_tracepoint (loc2->owner))
6222     return tracepoint_locations_match (loc1, loc2);
6223   else
6224     /* We compare bp_location.length in order to cover ranged breakpoints.  */
6225     return (breakpoint_address_match (loc1->pspace->aspace, loc1->address,
6226                                      loc2->pspace->aspace, loc2->address)
6227             && loc1->length == loc2->length);
6228 }
6229
6230 static void
6231 breakpoint_adjustment_warning (CORE_ADDR from_addr, CORE_ADDR to_addr,
6232                                int bnum, int have_bnum)
6233 {
6234   /* The longest string possibly returned by hex_string_custom
6235      is 50 chars.  These must be at least that big for safety.  */
6236   char astr1[64];
6237   char astr2[64];
6238
6239   strcpy (astr1, hex_string_custom ((unsigned long) from_addr, 8));
6240   strcpy (astr2, hex_string_custom ((unsigned long) to_addr, 8));
6241   if (have_bnum)
6242     warning (_("Breakpoint %d address previously adjusted from %s to %s."),
6243              bnum, astr1, astr2);
6244   else
6245     warning (_("Breakpoint address adjusted from %s to %s."), astr1, astr2);
6246 }
6247
6248 /* Adjust a breakpoint's address to account for architectural
6249    constraints on breakpoint placement.  Return the adjusted address.
6250    Note: Very few targets require this kind of adjustment.  For most
6251    targets, this function is simply the identity function.  */
6252
6253 static CORE_ADDR
6254 adjust_breakpoint_address (struct gdbarch *gdbarch,
6255                            CORE_ADDR bpaddr, enum bptype bptype)
6256 {
6257   if (!gdbarch_adjust_breakpoint_address_p (gdbarch))
6258     {
6259       /* Very few targets need any kind of breakpoint adjustment.  */
6260       return bpaddr;
6261     }
6262   else if (bptype == bp_watchpoint
6263            || bptype == bp_hardware_watchpoint
6264            || bptype == bp_read_watchpoint
6265            || bptype == bp_access_watchpoint
6266            || bptype == bp_catchpoint)
6267     {
6268       /* Watchpoints and the various bp_catch_* eventpoints should not
6269          have their addresses modified.  */
6270       return bpaddr;
6271     }
6272   else
6273     {
6274       CORE_ADDR adjusted_bpaddr;
6275
6276       /* Some targets have architectural constraints on the placement
6277          of breakpoint instructions.  Obtain the adjusted address.  */
6278       adjusted_bpaddr = gdbarch_adjust_breakpoint_address (gdbarch, bpaddr);
6279
6280       /* An adjusted breakpoint address can significantly alter
6281          a user's expectations.  Print a warning if an adjustment
6282          is required.  */
6283       if (adjusted_bpaddr != bpaddr)
6284         breakpoint_adjustment_warning (bpaddr, adjusted_bpaddr, 0, 0);
6285
6286       return adjusted_bpaddr;
6287     }
6288 }
6289
6290 void
6291 init_bp_location (struct bp_location *loc, const struct bp_location_ops *ops,
6292                   struct breakpoint *owner)
6293 {
6294   memset (loc, 0, sizeof (*loc));
6295
6296   gdb_assert (ops != NULL);
6297
6298   loc->ops = ops;
6299   loc->owner = owner;
6300   loc->cond = NULL;
6301   loc->cond_bytecode = NULL;
6302   loc->shlib_disabled = 0;
6303   loc->enabled = 1;
6304
6305   switch (owner->type)
6306     {
6307     case bp_breakpoint:
6308     case bp_until:
6309     case bp_finish:
6310     case bp_longjmp:
6311     case bp_longjmp_resume:
6312     case bp_exception:
6313     case bp_exception_resume:
6314     case bp_step_resume:
6315     case bp_hp_step_resume:
6316     case bp_watchpoint_scope:
6317     case bp_call_dummy:
6318     case bp_std_terminate:
6319     case bp_shlib_event:
6320     case bp_thread_event:
6321     case bp_overlay_event:
6322     case bp_jit_event:
6323     case bp_longjmp_master:
6324     case bp_std_terminate_master:
6325     case bp_exception_master:
6326     case bp_gnu_ifunc_resolver:
6327     case bp_gnu_ifunc_resolver_return:
6328       loc->loc_type = bp_loc_software_breakpoint;
6329       mark_breakpoint_location_modified (loc);
6330       break;
6331     case bp_hardware_breakpoint:
6332       loc->loc_type = bp_loc_hardware_breakpoint;
6333       mark_breakpoint_location_modified (loc);
6334       break;
6335     case bp_hardware_watchpoint:
6336     case bp_read_watchpoint:
6337     case bp_access_watchpoint:
6338       loc->loc_type = bp_loc_hardware_watchpoint;
6339       break;
6340     case bp_watchpoint:
6341     case bp_catchpoint:
6342     case bp_tracepoint:
6343     case bp_fast_tracepoint:
6344     case bp_static_tracepoint:
6345       loc->loc_type = bp_loc_other;
6346       break;
6347     default:
6348       internal_error (__FILE__, __LINE__, _("unknown breakpoint type"));
6349     }
6350
6351   loc->refc = 1;
6352 }
6353
6354 /* Allocate a struct bp_location.  */
6355
6356 static struct bp_location *
6357 allocate_bp_location (struct breakpoint *bpt)
6358 {
6359   return bpt->ops->allocate_location (bpt);
6360 }
6361
6362 static void
6363 free_bp_location (struct bp_location *loc)
6364 {
6365   loc->ops->dtor (loc);
6366   xfree (loc);
6367 }
6368
6369 /* Increment reference count.  */
6370
6371 static void
6372 incref_bp_location (struct bp_location *bl)
6373 {
6374   ++bl->refc;
6375 }
6376
6377 /* Decrement reference count.  If the reference count reaches 0,
6378    destroy the bp_location.  Sets *BLP to NULL.  */
6379
6380 static void
6381 decref_bp_location (struct bp_location **blp)
6382 {
6383   gdb_assert ((*blp)->refc > 0);
6384
6385   if (--(*blp)->refc == 0)
6386     free_bp_location (*blp);
6387   *blp = NULL;
6388 }
6389
6390 /* Add breakpoint B at the end of the global breakpoint chain.  */
6391
6392 static void
6393 add_to_breakpoint_chain (struct breakpoint *b)
6394 {
6395   struct breakpoint *b1;
6396
6397   /* Add this breakpoint to the end of the chain so that a list of
6398      breakpoints will come out in order of increasing numbers.  */
6399
6400   b1 = breakpoint_chain;
6401   if (b1 == 0)
6402     breakpoint_chain = b;
6403   else
6404     {
6405       while (b1->next)
6406         b1 = b1->next;
6407       b1->next = b;
6408     }
6409 }
6410
6411 /* Initializes breakpoint B with type BPTYPE and no locations yet.  */
6412
6413 static void
6414 init_raw_breakpoint_without_location (struct breakpoint *b,
6415                                       struct gdbarch *gdbarch,
6416                                       enum bptype bptype,
6417                                       const struct breakpoint_ops *ops)
6418 {
6419   memset (b, 0, sizeof (*b));
6420
6421   gdb_assert (ops != NULL);
6422
6423   b->ops = ops;
6424   b->type = bptype;
6425   b->gdbarch = gdbarch;
6426   b->language = current_language->la_language;
6427   b->input_radix = input_radix;
6428   b->thread = -1;
6429   b->enable_state = bp_enabled;
6430   b->next = 0;
6431   b->silent = 0;
6432   b->ignore_count = 0;
6433   b->commands = NULL;
6434   b->frame_id = null_frame_id;
6435   b->condition_not_parsed = 0;
6436   b->py_bp_object = NULL;
6437   b->related_breakpoint = b;
6438 }
6439
6440 /* Helper to set_raw_breakpoint below.  Creates a breakpoint
6441    that has type BPTYPE and has no locations as yet.  */
6442
6443 static struct breakpoint *
6444 set_raw_breakpoint_without_location (struct gdbarch *gdbarch,
6445                                      enum bptype bptype,
6446                                      const struct breakpoint_ops *ops)
6447 {
6448   struct breakpoint *b = XNEW (struct breakpoint);
6449
6450   init_raw_breakpoint_without_location (b, gdbarch, bptype, ops);
6451   add_to_breakpoint_chain (b);
6452   return b;
6453 }
6454
6455 /* Initialize loc->function_name.  EXPLICIT_LOC says no indirect function
6456    resolutions should be made as the user specified the location explicitly
6457    enough.  */
6458
6459 static void
6460 set_breakpoint_location_function (struct bp_location *loc, int explicit_loc)
6461 {
6462   gdb_assert (loc->owner != NULL);
6463
6464   if (loc->owner->type == bp_breakpoint
6465       || loc->owner->type == bp_hardware_breakpoint
6466       || is_tracepoint (loc->owner))
6467     {
6468       int is_gnu_ifunc;
6469       const char *function_name;
6470
6471       find_pc_partial_function_gnu_ifunc (loc->address, &function_name,
6472                                           NULL, NULL, &is_gnu_ifunc);
6473
6474       if (is_gnu_ifunc && !explicit_loc)
6475         {
6476           struct breakpoint *b = loc->owner;
6477
6478           gdb_assert (loc->pspace == current_program_space);
6479           if (gnu_ifunc_resolve_name (function_name,
6480                                       &loc->requested_address))
6481             {
6482               /* Recalculate ADDRESS based on new REQUESTED_ADDRESS.  */
6483               loc->address = adjust_breakpoint_address (loc->gdbarch,
6484                                                         loc->requested_address,
6485                                                         b->type);
6486             }
6487           else if (b->type == bp_breakpoint && b->loc == loc
6488                    && loc->next == NULL && b->related_breakpoint == b)
6489             {
6490               /* Create only the whole new breakpoint of this type but do not
6491                  mess more complicated breakpoints with multiple locations.  */
6492               b->type = bp_gnu_ifunc_resolver;
6493             }
6494         }
6495
6496       if (function_name)
6497         loc->function_name = xstrdup (function_name);
6498     }
6499 }
6500
6501 /* Attempt to determine architecture of location identified by SAL.  */
6502 struct gdbarch *
6503 get_sal_arch (struct symtab_and_line sal)
6504 {
6505   if (sal.section)
6506     return get_objfile_arch (sal.section->objfile);
6507   if (sal.symtab)
6508     return get_objfile_arch (sal.symtab->objfile);
6509
6510   return NULL;
6511 }
6512
6513 /* Low level routine for partially initializing a breakpoint of type
6514    BPTYPE.  The newly created breakpoint's address, section, source
6515    file name, and line number are provided by SAL.
6516
6517    It is expected that the caller will complete the initialization of
6518    the newly created breakpoint struct as well as output any status
6519    information regarding the creation of a new breakpoint.  */
6520
6521 static void
6522 init_raw_breakpoint (struct breakpoint *b, struct gdbarch *gdbarch,
6523                      struct symtab_and_line sal, enum bptype bptype,
6524                      const struct breakpoint_ops *ops)
6525 {
6526   init_raw_breakpoint_without_location (b, gdbarch, bptype, ops);
6527
6528   add_location_to_breakpoint (b, &sal);
6529
6530   if (bptype != bp_catchpoint)
6531     gdb_assert (sal.pspace != NULL);
6532
6533   /* Store the program space that was used to set the breakpoint,
6534      except for ordinary breakpoints, which are independent of the
6535      program space.  */
6536   if (bptype != bp_breakpoint && bptype != bp_hardware_breakpoint)
6537     b->pspace = sal.pspace;
6538
6539   breakpoints_changed ();
6540 }
6541
6542 /* set_raw_breakpoint is a low level routine for allocating and
6543    partially initializing a breakpoint of type BPTYPE.  The newly
6544    created breakpoint's address, section, source file name, and line
6545    number are provided by SAL.  The newly created and partially
6546    initialized breakpoint is added to the breakpoint chain and
6547    is also returned as the value of this function.
6548
6549    It is expected that the caller will complete the initialization of
6550    the newly created breakpoint struct as well as output any status
6551    information regarding the creation of a new breakpoint.  In
6552    particular, set_raw_breakpoint does NOT set the breakpoint
6553    number!  Care should be taken to not allow an error to occur
6554    prior to completing the initialization of the breakpoint.  If this
6555    should happen, a bogus breakpoint will be left on the chain.  */
6556
6557 struct breakpoint *
6558 set_raw_breakpoint (struct gdbarch *gdbarch,
6559                     struct symtab_and_line sal, enum bptype bptype,
6560                     const struct breakpoint_ops *ops)
6561 {
6562   struct breakpoint *b = XNEW (struct breakpoint);
6563
6564   init_raw_breakpoint (b, gdbarch, sal, bptype, ops);
6565   add_to_breakpoint_chain (b);
6566   return b;
6567 }
6568
6569
6570 /* Note that the breakpoint object B describes a permanent breakpoint
6571    instruction, hard-wired into the inferior's code.  */
6572 void
6573 make_breakpoint_permanent (struct breakpoint *b)
6574 {
6575   struct bp_location *bl;
6576
6577   b->enable_state = bp_permanent;
6578
6579   /* By definition, permanent breakpoints are already present in the
6580      code.  Mark all locations as inserted.  For now,
6581      make_breakpoint_permanent is called in just one place, so it's
6582      hard to say if it's reasonable to have permanent breakpoint with
6583      multiple locations or not, but it's easy to implement.  */
6584   for (bl = b->loc; bl; bl = bl->next)
6585     bl->inserted = 1;
6586 }
6587
6588 /* Call this routine when stepping and nexting to enable a breakpoint
6589    if we do a longjmp() or 'throw' in TP.  FRAME is the frame which
6590    initiated the operation.  */
6591
6592 void
6593 set_longjmp_breakpoint (struct thread_info *tp, struct frame_id frame)
6594 {
6595   struct breakpoint *b, *b_tmp;
6596   int thread = tp->num;
6597
6598   /* To avoid having to rescan all objfile symbols at every step,
6599      we maintain a list of continually-inserted but always disabled
6600      longjmp "master" breakpoints.  Here, we simply create momentary
6601      clones of those and enable them for the requested thread.  */
6602   ALL_BREAKPOINTS_SAFE (b, b_tmp)
6603     if (b->pspace == current_program_space
6604         && (b->type == bp_longjmp_master
6605             || b->type == bp_exception_master))
6606       {
6607         enum bptype type = b->type == bp_longjmp_master ? bp_longjmp : bp_exception;
6608         struct breakpoint *clone;
6609
6610         clone = momentary_breakpoint_from_master (b, type,
6611                                                   &momentary_breakpoint_ops);
6612         clone->thread = thread;
6613       }
6614
6615   tp->initiating_frame = frame;
6616 }
6617
6618 /* Delete all longjmp breakpoints from THREAD.  */
6619 void
6620 delete_longjmp_breakpoint (int thread)
6621 {
6622   struct breakpoint *b, *b_tmp;
6623
6624   ALL_BREAKPOINTS_SAFE (b, b_tmp)
6625     if (b->type == bp_longjmp || b->type == bp_exception)
6626       {
6627         if (b->thread == thread)
6628           delete_breakpoint (b);
6629       }
6630 }
6631
6632 void
6633 delete_longjmp_breakpoint_at_next_stop (int thread)
6634 {
6635   struct breakpoint *b, *b_tmp;
6636
6637   ALL_BREAKPOINTS_SAFE (b, b_tmp)
6638     if (b->type == bp_longjmp || b->type == bp_exception)
6639       {
6640         if (b->thread == thread)
6641           b->disposition = disp_del_at_next_stop;
6642       }
6643 }
6644
6645 void
6646 enable_overlay_breakpoints (void)
6647 {
6648   struct breakpoint *b;
6649
6650   ALL_BREAKPOINTS (b)
6651     if (b->type == bp_overlay_event)
6652     {
6653       b->enable_state = bp_enabled;
6654       update_global_location_list (1);
6655       overlay_events_enabled = 1;
6656     }
6657 }
6658
6659 void
6660 disable_overlay_breakpoints (void)
6661 {
6662   struct breakpoint *b;
6663
6664   ALL_BREAKPOINTS (b)
6665     if (b->type == bp_overlay_event)
6666     {
6667       b->enable_state = bp_disabled;
6668       update_global_location_list (0);
6669       overlay_events_enabled = 0;
6670     }
6671 }
6672
6673 /* Set an active std::terminate breakpoint for each std::terminate
6674    master breakpoint.  */
6675 void
6676 set_std_terminate_breakpoint (void)
6677 {
6678   struct breakpoint *b, *b_tmp;
6679
6680   ALL_BREAKPOINTS_SAFE (b, b_tmp)
6681     if (b->pspace == current_program_space
6682         && b->type == bp_std_terminate_master)
6683       {
6684         momentary_breakpoint_from_master (b, bp_std_terminate,
6685                                           &momentary_breakpoint_ops);
6686       }
6687 }
6688
6689 /* Delete all the std::terminate breakpoints.  */
6690 void
6691 delete_std_terminate_breakpoint (void)
6692 {
6693   struct breakpoint *b, *b_tmp;
6694
6695   ALL_BREAKPOINTS_SAFE (b, b_tmp)
6696     if (b->type == bp_std_terminate)
6697       delete_breakpoint (b);
6698 }
6699
6700 struct breakpoint *
6701 create_thread_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
6702 {
6703   struct breakpoint *b;
6704
6705   b = create_internal_breakpoint (gdbarch, address, bp_thread_event,
6706                                   &internal_breakpoint_ops);
6707
6708   b->enable_state = bp_enabled;
6709   /* addr_string has to be used or breakpoint_re_set will delete me.  */
6710   b->addr_string
6711     = xstrprintf ("*%s", paddress (b->loc->gdbarch, b->loc->address));
6712
6713   update_global_location_list_nothrow (1);
6714
6715   return b;
6716 }
6717
6718 void
6719 remove_thread_event_breakpoints (void)
6720 {
6721   struct breakpoint *b, *b_tmp;
6722
6723   ALL_BREAKPOINTS_SAFE (b, b_tmp)
6724     if (b->type == bp_thread_event
6725         && b->loc->pspace == current_program_space)
6726       delete_breakpoint (b);
6727 }
6728
6729 struct lang_and_radix
6730   {
6731     enum language lang;
6732     int radix;
6733   };
6734
6735 /* Create a breakpoint for JIT code registration and unregistration.  */
6736
6737 struct breakpoint *
6738 create_jit_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
6739 {
6740   struct breakpoint *b;
6741
6742   b = create_internal_breakpoint (gdbarch, address, bp_jit_event,
6743                                   &internal_breakpoint_ops);
6744   update_global_location_list_nothrow (1);
6745   return b;
6746 }
6747
6748 /* Remove JIT code registration and unregistration breakpoint(s).  */
6749
6750 void
6751 remove_jit_event_breakpoints (void)
6752 {
6753   struct breakpoint *b, *b_tmp;
6754
6755   ALL_BREAKPOINTS_SAFE (b, b_tmp)
6756     if (b->type == bp_jit_event
6757         && b->loc->pspace == current_program_space)
6758       delete_breakpoint (b);
6759 }
6760
6761 void
6762 remove_solib_event_breakpoints (void)
6763 {
6764   struct breakpoint *b, *b_tmp;
6765
6766   ALL_BREAKPOINTS_SAFE (b, b_tmp)
6767     if (b->type == bp_shlib_event
6768         && b->loc->pspace == current_program_space)
6769       delete_breakpoint (b);
6770 }
6771
6772 struct breakpoint *
6773 create_solib_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
6774 {
6775   struct breakpoint *b;
6776
6777   b = create_internal_breakpoint (gdbarch, address, bp_shlib_event,
6778                                   &internal_breakpoint_ops);
6779   update_global_location_list_nothrow (1);
6780   return b;
6781 }
6782
6783 /* Disable any breakpoints that are on code in shared libraries.  Only
6784    apply to enabled breakpoints, disabled ones can just stay disabled.  */
6785
6786 void
6787 disable_breakpoints_in_shlibs (void)
6788 {
6789   struct bp_location *loc, **locp_tmp;
6790
6791   ALL_BP_LOCATIONS (loc, locp_tmp)
6792   {
6793     /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
6794     struct breakpoint *b = loc->owner;
6795
6796     /* We apply the check to all breakpoints, including disabled for
6797        those with loc->duplicate set.  This is so that when breakpoint
6798        becomes enabled, or the duplicate is removed, gdb will try to
6799        insert all breakpoints.  If we don't set shlib_disabled here,
6800        we'll try to insert those breakpoints and fail.  */
6801     if (((b->type == bp_breakpoint)
6802          || (b->type == bp_jit_event)
6803          || (b->type == bp_hardware_breakpoint)
6804          || (is_tracepoint (b)))
6805         && loc->pspace == current_program_space
6806         && !loc->shlib_disabled
6807 #ifdef PC_SOLIB
6808         && PC_SOLIB (loc->address)
6809 #else
6810         && solib_name_from_address (loc->pspace, loc->address)
6811 #endif
6812         )
6813       {
6814         loc->shlib_disabled = 1;
6815       }
6816   }
6817 }
6818
6819 /* Disable any breakpoints and tracepoints that are in an unloaded shared
6820    library.  Only apply to enabled breakpoints, disabled ones can just stay
6821    disabled.  */
6822
6823 static void
6824 disable_breakpoints_in_unloaded_shlib (struct so_list *solib)
6825 {
6826   struct bp_location *loc, **locp_tmp;
6827   int disabled_shlib_breaks = 0;
6828
6829   /* SunOS a.out shared libraries are always mapped, so do not
6830      disable breakpoints; they will only be reported as unloaded
6831      through clear_solib when GDB discards its shared library
6832      list.  See clear_solib for more information.  */
6833   if (exec_bfd != NULL
6834       && bfd_get_flavour (exec_bfd) == bfd_target_aout_flavour)
6835     return;
6836
6837   ALL_BP_LOCATIONS (loc, locp_tmp)
6838   {
6839     /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
6840     struct breakpoint *b = loc->owner;
6841
6842     if (solib->pspace == loc->pspace
6843         && !loc->shlib_disabled
6844         && (((b->type == bp_breakpoint
6845               || b->type == bp_jit_event
6846               || b->type == bp_hardware_breakpoint)
6847              && (loc->loc_type == bp_loc_hardware_breakpoint
6848                  || loc->loc_type == bp_loc_software_breakpoint))
6849             || is_tracepoint (b))
6850         && solib_contains_address_p (solib, loc->address))
6851       {
6852         loc->shlib_disabled = 1;
6853         /* At this point, we cannot rely on remove_breakpoint
6854            succeeding so we must mark the breakpoint as not inserted
6855            to prevent future errors occurring in remove_breakpoints.  */
6856         loc->inserted = 0;
6857
6858         /* This may cause duplicate notifications for the same breakpoint.  */
6859         observer_notify_breakpoint_modified (b);
6860
6861         if (!disabled_shlib_breaks)
6862           {
6863             target_terminal_ours_for_output ();
6864             warning (_("Temporarily disabling breakpoints "
6865                        "for unloaded shared library \"%s\""),
6866                      solib->so_name);
6867           }
6868         disabled_shlib_breaks = 1;
6869       }
6870   }
6871 }
6872
6873 /* FORK & VFORK catchpoints.  */
6874
6875 /* An instance of this type is used to represent a fork or vfork
6876    catchpoint.  It includes a "struct breakpoint" as a kind of base
6877    class; users downcast to "struct breakpoint *" when needed.  A
6878    breakpoint is really of this type iff its ops pointer points to
6879    CATCH_FORK_BREAKPOINT_OPS.  */
6880
6881 struct fork_catchpoint
6882 {
6883   /* The base class.  */
6884   struct breakpoint base;
6885
6886   /* Process id of a child process whose forking triggered this
6887      catchpoint.  This field is only valid immediately after this
6888      catchpoint has triggered.  */
6889   ptid_t forked_inferior_pid;
6890 };
6891
6892 /* Implement the "insert" breakpoint_ops method for fork
6893    catchpoints.  */
6894
6895 static int
6896 insert_catch_fork (struct bp_location *bl)
6897 {
6898   return target_insert_fork_catchpoint (PIDGET (inferior_ptid));
6899 }
6900
6901 /* Implement the "remove" breakpoint_ops method for fork
6902    catchpoints.  */
6903
6904 static int
6905 remove_catch_fork (struct bp_location *bl)
6906 {
6907   return target_remove_fork_catchpoint (PIDGET (inferior_ptid));
6908 }
6909
6910 /* Implement the "breakpoint_hit" breakpoint_ops method for fork
6911    catchpoints.  */
6912
6913 static int
6914 breakpoint_hit_catch_fork (const struct bp_location *bl,
6915                            struct address_space *aspace, CORE_ADDR bp_addr,
6916                            const struct target_waitstatus *ws)
6917 {
6918   struct fork_catchpoint *c = (struct fork_catchpoint *) bl->owner;
6919
6920   if (ws->kind != TARGET_WAITKIND_FORKED)
6921     return 0;
6922
6923   c->forked_inferior_pid = ws->value.related_pid;
6924   return 1;
6925 }
6926
6927 /* Implement the "print_it" breakpoint_ops method for fork
6928    catchpoints.  */
6929
6930 static enum print_stop_action
6931 print_it_catch_fork (bpstat bs)
6932 {
6933   struct ui_out *uiout = current_uiout;
6934   struct breakpoint *b = bs->breakpoint_at;
6935   struct fork_catchpoint *c = (struct fork_catchpoint *) bs->breakpoint_at;
6936
6937   annotate_catchpoint (b->number);
6938   if (b->disposition == disp_del)
6939     ui_out_text (uiout, "\nTemporary catchpoint ");
6940   else
6941     ui_out_text (uiout, "\nCatchpoint ");
6942   if (ui_out_is_mi_like_p (uiout))
6943     {
6944       ui_out_field_string (uiout, "reason",
6945                            async_reason_lookup (EXEC_ASYNC_FORK));
6946       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
6947     }
6948   ui_out_field_int (uiout, "bkptno", b->number);
6949   ui_out_text (uiout, " (forked process ");
6950   ui_out_field_int (uiout, "newpid", ptid_get_pid (c->forked_inferior_pid));
6951   ui_out_text (uiout, "), ");
6952   return PRINT_SRC_AND_LOC;
6953 }
6954
6955 /* Implement the "print_one" breakpoint_ops method for fork
6956    catchpoints.  */
6957
6958 static void
6959 print_one_catch_fork (struct breakpoint *b, struct bp_location **last_loc)
6960 {
6961   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
6962   struct value_print_options opts;
6963   struct ui_out *uiout = current_uiout;
6964
6965   get_user_print_options (&opts);
6966
6967   /* Field 4, the address, is omitted (which makes the columns not
6968      line up too nicely with the headers, but the effect is relatively
6969      readable).  */
6970   if (opts.addressprint)
6971     ui_out_field_skip (uiout, "addr");
6972   annotate_field (5);
6973   ui_out_text (uiout, "fork");
6974   if (!ptid_equal (c->forked_inferior_pid, null_ptid))
6975     {
6976       ui_out_text (uiout, ", process ");
6977       ui_out_field_int (uiout, "what",
6978                         ptid_get_pid (c->forked_inferior_pid));
6979       ui_out_spaces (uiout, 1);
6980     }
6981 }
6982
6983 /* Implement the "print_mention" breakpoint_ops method for fork
6984    catchpoints.  */
6985
6986 static void
6987 print_mention_catch_fork (struct breakpoint *b)
6988 {
6989   printf_filtered (_("Catchpoint %d (fork)"), b->number);
6990 }
6991
6992 /* Implement the "print_recreate" breakpoint_ops method for fork
6993    catchpoints.  */
6994
6995 static void
6996 print_recreate_catch_fork (struct breakpoint *b, struct ui_file *fp)
6997 {
6998   fprintf_unfiltered (fp, "catch fork");
6999   print_recreate_thread (b, fp);
7000 }
7001
7002 /* The breakpoint_ops structure to be used in fork catchpoints.  */
7003
7004 static struct breakpoint_ops catch_fork_breakpoint_ops;
7005
7006 /* Implement the "insert" breakpoint_ops method for vfork
7007    catchpoints.  */
7008
7009 static int
7010 insert_catch_vfork (struct bp_location *bl)
7011 {
7012   return target_insert_vfork_catchpoint (PIDGET (inferior_ptid));
7013 }
7014
7015 /* Implement the "remove" breakpoint_ops method for vfork
7016    catchpoints.  */
7017
7018 static int
7019 remove_catch_vfork (struct bp_location *bl)
7020 {
7021   return target_remove_vfork_catchpoint (PIDGET (inferior_ptid));
7022 }
7023
7024 /* Implement the "breakpoint_hit" breakpoint_ops method for vfork
7025    catchpoints.  */
7026
7027 static int
7028 breakpoint_hit_catch_vfork (const struct bp_location *bl,
7029                             struct address_space *aspace, CORE_ADDR bp_addr,
7030                             const struct target_waitstatus *ws)
7031 {
7032   struct fork_catchpoint *c = (struct fork_catchpoint *) bl->owner;
7033
7034   if (ws->kind != TARGET_WAITKIND_VFORKED)
7035     return 0;
7036
7037   c->forked_inferior_pid = ws->value.related_pid;
7038   return 1;
7039 }
7040
7041 /* Implement the "print_it" breakpoint_ops method for vfork
7042    catchpoints.  */
7043
7044 static enum print_stop_action
7045 print_it_catch_vfork (bpstat bs)
7046 {
7047   struct ui_out *uiout = current_uiout;
7048   struct breakpoint *b = bs->breakpoint_at;
7049   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
7050
7051   annotate_catchpoint (b->number);
7052   if (b->disposition == disp_del)
7053     ui_out_text (uiout, "\nTemporary catchpoint ");
7054   else
7055     ui_out_text (uiout, "\nCatchpoint ");
7056   if (ui_out_is_mi_like_p (uiout))
7057     {
7058       ui_out_field_string (uiout, "reason",
7059                            async_reason_lookup (EXEC_ASYNC_VFORK));
7060       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
7061     }
7062   ui_out_field_int (uiout, "bkptno", b->number);
7063   ui_out_text (uiout, " (vforked process ");
7064   ui_out_field_int (uiout, "newpid", ptid_get_pid (c->forked_inferior_pid));
7065   ui_out_text (uiout, "), ");
7066   return PRINT_SRC_AND_LOC;
7067 }
7068
7069 /* Implement the "print_one" breakpoint_ops method for vfork
7070    catchpoints.  */
7071
7072 static void
7073 print_one_catch_vfork (struct breakpoint *b, struct bp_location **last_loc)
7074 {
7075   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
7076   struct value_print_options opts;
7077   struct ui_out *uiout = current_uiout;
7078
7079   get_user_print_options (&opts);
7080   /* Field 4, the address, is omitted (which makes the columns not
7081      line up too nicely with the headers, but the effect is relatively
7082      readable).  */
7083   if (opts.addressprint)
7084     ui_out_field_skip (uiout, "addr");
7085   annotate_field (5);
7086   ui_out_text (uiout, "vfork");
7087   if (!ptid_equal (c->forked_inferior_pid, null_ptid))
7088     {
7089       ui_out_text (uiout, ", process ");
7090       ui_out_field_int (uiout, "what",
7091                         ptid_get_pid (c->forked_inferior_pid));
7092       ui_out_spaces (uiout, 1);
7093     }
7094 }
7095
7096 /* Implement the "print_mention" breakpoint_ops method for vfork
7097    catchpoints.  */
7098
7099 static void
7100 print_mention_catch_vfork (struct breakpoint *b)
7101 {
7102   printf_filtered (_("Catchpoint %d (vfork)"), b->number);
7103 }
7104
7105 /* Implement the "print_recreate" breakpoint_ops method for vfork
7106    catchpoints.  */
7107
7108 static void
7109 print_recreate_catch_vfork (struct breakpoint *b, struct ui_file *fp)
7110 {
7111   fprintf_unfiltered (fp, "catch vfork");
7112   print_recreate_thread (b, fp);
7113 }
7114
7115 /* The breakpoint_ops structure to be used in vfork catchpoints.  */
7116
7117 static struct breakpoint_ops catch_vfork_breakpoint_ops;
7118
7119 /* An instance of this type is used to represent an solib catchpoint.
7120    It includes a "struct breakpoint" as a kind of base class; users
7121    downcast to "struct breakpoint *" when needed.  A breakpoint is
7122    really of this type iff its ops pointer points to
7123    CATCH_SOLIB_BREAKPOINT_OPS.  */
7124
7125 struct solib_catchpoint
7126 {
7127   /* The base class.  */
7128   struct breakpoint base;
7129
7130   /* True for "catch load", false for "catch unload".  */
7131   unsigned char is_load;
7132
7133   /* Regular expression to match, if any.  COMPILED is only valid when
7134      REGEX is non-NULL.  */
7135   char *regex;
7136   regex_t compiled;
7137 };
7138
7139 static void
7140 dtor_catch_solib (struct breakpoint *b)
7141 {
7142   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
7143
7144   if (self->regex)
7145     regfree (&self->compiled);
7146   xfree (self->regex);
7147
7148   base_breakpoint_ops.dtor (b);
7149 }
7150
7151 static int
7152 insert_catch_solib (struct bp_location *ignore)
7153 {
7154   return 0;
7155 }
7156
7157 static int
7158 remove_catch_solib (struct bp_location *ignore)
7159 {
7160   return 0;
7161 }
7162
7163 static int
7164 breakpoint_hit_catch_solib (const struct bp_location *bl,
7165                             struct address_space *aspace,
7166                             CORE_ADDR bp_addr,
7167                             const struct target_waitstatus *ws)
7168 {
7169   struct solib_catchpoint *self = (struct solib_catchpoint *) bl->owner;
7170   struct breakpoint *other;
7171
7172   if (ws->kind == TARGET_WAITKIND_LOADED)
7173     return 1;
7174
7175   ALL_BREAKPOINTS (other)
7176   {
7177     struct bp_location *other_bl;
7178
7179     if (other == bl->owner)
7180       continue;
7181
7182     if (other->type != bp_shlib_event)
7183       continue;
7184
7185     if (self->base.pspace != NULL && other->pspace != self->base.pspace)
7186       continue;
7187
7188     for (other_bl = other->loc; other_bl != NULL; other_bl = other_bl->next)
7189       {
7190         if (other->ops->breakpoint_hit (other_bl, aspace, bp_addr, ws))
7191           return 1;
7192       }
7193   }
7194
7195   return 0;
7196 }
7197
7198 static void
7199 check_status_catch_solib (struct bpstats *bs)
7200 {
7201   struct solib_catchpoint *self
7202     = (struct solib_catchpoint *) bs->breakpoint_at;
7203   int ix;
7204
7205   if (self->is_load)
7206     {
7207       struct so_list *iter;
7208
7209       for (ix = 0;
7210            VEC_iterate (so_list_ptr, current_program_space->added_solibs,
7211                         ix, iter);
7212            ++ix)
7213         {
7214           if (!self->regex
7215               || regexec (&self->compiled, iter->so_name, 0, NULL, 0) == 0)
7216             return;
7217         }
7218     }
7219   else
7220     {
7221       char *iter;
7222
7223       for (ix = 0;
7224            VEC_iterate (char_ptr, current_program_space->deleted_solibs,
7225                         ix, iter);
7226            ++ix)
7227         {
7228           if (!self->regex
7229               || regexec (&self->compiled, iter, 0, NULL, 0) == 0)
7230             return;
7231         }
7232     }
7233
7234   bs->stop = 0;
7235   bs->print_it = print_it_noop;
7236 }
7237
7238 static enum print_stop_action
7239 print_it_catch_solib (bpstat bs)
7240 {
7241   struct breakpoint *b = bs->breakpoint_at;
7242   struct ui_out *uiout = current_uiout;
7243
7244   annotate_catchpoint (b->number);
7245   if (b->disposition == disp_del)
7246     ui_out_text (uiout, "\nTemporary catchpoint ");
7247   else
7248     ui_out_text (uiout, "\nCatchpoint ");
7249   ui_out_field_int (uiout, "bkptno", b->number);
7250   ui_out_text (uiout, "\n");
7251   if (ui_out_is_mi_like_p (uiout))
7252     ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
7253   print_solib_event (1);
7254   return PRINT_SRC_AND_LOC;
7255 }
7256
7257 static void
7258 print_one_catch_solib (struct breakpoint *b, struct bp_location **locs)
7259 {
7260   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
7261   struct value_print_options opts;
7262   struct ui_out *uiout = current_uiout;
7263   char *msg;
7264
7265   get_user_print_options (&opts);
7266   /* Field 4, the address, is omitted (which makes the columns not
7267      line up too nicely with the headers, but the effect is relatively
7268      readable).  */
7269   if (opts.addressprint)
7270     {
7271       annotate_field (4);
7272       ui_out_field_skip (uiout, "addr");
7273     }
7274
7275   annotate_field (5);
7276   if (self->is_load)
7277     {
7278       if (self->regex)
7279         msg = xstrprintf (_("load of library matching %s"), self->regex);
7280       else
7281         msg = xstrdup (_("load of library"));
7282     }
7283   else
7284     {
7285       if (self->regex)
7286         msg = xstrprintf (_("unload of library matching %s"), self->regex);
7287       else
7288         msg = xstrdup (_("unload of library"));
7289     }
7290   ui_out_field_string (uiout, "what", msg);
7291   xfree (msg);
7292 }
7293
7294 static void
7295 print_mention_catch_solib (struct breakpoint *b)
7296 {
7297   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
7298
7299   printf_filtered (_("Catchpoint %d (%s)"), b->number,
7300                    self->is_load ? "load" : "unload");
7301 }
7302
7303 static void
7304 print_recreate_catch_solib (struct breakpoint *b, struct ui_file *fp)
7305 {
7306   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
7307
7308   fprintf_unfiltered (fp, "%s %s",
7309                       b->disposition == disp_del ? "tcatch" : "catch",
7310                       self->is_load ? "load" : "unload");
7311   if (self->regex)
7312     fprintf_unfiltered (fp, " %s", self->regex);
7313   fprintf_unfiltered (fp, "\n");
7314 }
7315
7316 static struct breakpoint_ops catch_solib_breakpoint_ops;
7317
7318 /* A helper function that does all the work for "catch load" and
7319    "catch unload".  */
7320
7321 static void
7322 catch_load_or_unload (char *arg, int from_tty, int is_load,
7323                       struct cmd_list_element *command)
7324 {
7325   struct solib_catchpoint *c;
7326   struct gdbarch *gdbarch = get_current_arch ();
7327   int tempflag;
7328   regex_t compiled;
7329   struct cleanup *cleanup;
7330
7331   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
7332
7333   if (!arg)
7334     arg = "";
7335   arg = skip_spaces (arg);
7336
7337   c = XCNEW (struct solib_catchpoint);
7338   cleanup = make_cleanup (xfree, c);
7339
7340   if (*arg != '\0')
7341     {
7342       int errcode;
7343
7344       errcode = regcomp (&c->compiled, arg, REG_NOSUB);
7345       if (errcode != 0)
7346         {
7347           char *err = get_regcomp_error (errcode, &c->compiled);
7348
7349           make_cleanup (xfree, err);
7350           error (_("Invalid regexp (%s): %s"), err, arg);
7351         }
7352       c->regex = xstrdup (arg);
7353     }
7354
7355   c->is_load = is_load;
7356   init_catchpoint (&c->base, gdbarch, tempflag, NULL,
7357                    &catch_solib_breakpoint_ops);
7358
7359   discard_cleanups (cleanup);
7360   install_breakpoint (0, &c->base, 1);
7361 }
7362
7363 static void
7364 catch_load_command_1 (char *arg, int from_tty,
7365                       struct cmd_list_element *command)
7366 {
7367   catch_load_or_unload (arg, from_tty, 1, command);
7368 }
7369
7370 static void
7371 catch_unload_command_1 (char *arg, int from_tty,
7372                         struct cmd_list_element *command)
7373 {
7374   catch_load_or_unload (arg, from_tty, 0, command);
7375 }
7376
7377 DEF_VEC_I(int);
7378
7379 /* An instance of this type is used to represent a syscall catchpoint.
7380    It includes a "struct breakpoint" as a kind of base class; users
7381    downcast to "struct breakpoint *" when needed.  A breakpoint is
7382    really of this type iff its ops pointer points to
7383    CATCH_SYSCALL_BREAKPOINT_OPS.  */
7384
7385 struct syscall_catchpoint
7386 {
7387   /* The base class.  */
7388   struct breakpoint base;
7389
7390   /* Syscall numbers used for the 'catch syscall' feature.  If no
7391      syscall has been specified for filtering, its value is NULL.
7392      Otherwise, it holds a list of all syscalls to be caught.  The
7393      list elements are allocated with xmalloc.  */
7394   VEC(int) *syscalls_to_be_caught;
7395 };
7396
7397 /* Implement the "dtor" breakpoint_ops method for syscall
7398    catchpoints.  */
7399
7400 static void
7401 dtor_catch_syscall (struct breakpoint *b)
7402 {
7403   struct syscall_catchpoint *c = (struct syscall_catchpoint *) b;
7404
7405   VEC_free (int, c->syscalls_to_be_caught);
7406
7407   base_breakpoint_ops.dtor (b);
7408 }
7409
7410 static const struct inferior_data *catch_syscall_inferior_data = NULL;
7411
7412 struct catch_syscall_inferior_data
7413 {
7414   /* We keep a count of the number of times the user has requested a
7415      particular syscall to be tracked, and pass this information to the
7416      target.  This lets capable targets implement filtering directly.  */
7417
7418   /* Number of times that "any" syscall is requested.  */
7419   int any_syscall_count;
7420
7421   /* Count of each system call.  */
7422   VEC(int) *syscalls_counts;
7423
7424   /* This counts all syscall catch requests, so we can readily determine
7425      if any catching is necessary.  */
7426   int total_syscalls_count;
7427 };
7428
7429 static struct catch_syscall_inferior_data*
7430 get_catch_syscall_inferior_data (struct inferior *inf)
7431 {
7432   struct catch_syscall_inferior_data *inf_data;
7433
7434   inf_data = inferior_data (inf, catch_syscall_inferior_data);
7435   if (inf_data == NULL)
7436     {
7437       inf_data = XZALLOC (struct catch_syscall_inferior_data);
7438       set_inferior_data (inf, catch_syscall_inferior_data, inf_data);
7439     }
7440
7441   return inf_data;
7442 }
7443
7444 static void
7445 catch_syscall_inferior_data_cleanup (struct inferior *inf, void *arg)
7446 {
7447   xfree (arg);
7448 }
7449
7450
7451 /* Implement the "insert" breakpoint_ops method for syscall
7452    catchpoints.  */
7453
7454 static int
7455 insert_catch_syscall (struct bp_location *bl)
7456 {
7457   struct syscall_catchpoint *c = (struct syscall_catchpoint *) bl->owner;
7458   struct inferior *inf = current_inferior ();
7459   struct catch_syscall_inferior_data *inf_data
7460     = get_catch_syscall_inferior_data (inf);
7461
7462   ++inf_data->total_syscalls_count;
7463   if (!c->syscalls_to_be_caught)
7464     ++inf_data->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
7475           if (iter >= VEC_length (int, inf_data->syscalls_counts))
7476             {
7477               int old_size = VEC_length (int, inf_data->syscalls_counts);
7478               uintptr_t vec_addr_offset
7479                 = old_size * ((uintptr_t) sizeof (int));
7480               uintptr_t vec_addr;
7481               VEC_safe_grow (int, inf_data->syscalls_counts, iter + 1);
7482               vec_addr = ((uintptr_t) VEC_address (int,
7483                                                   inf_data->syscalls_counts)
7484                           + vec_addr_offset);
7485               memset ((void *) vec_addr, 0,
7486                       (iter + 1 - old_size) * sizeof (int));
7487             }
7488           elem = VEC_index (int, inf_data->syscalls_counts, iter);
7489           VEC_replace (int, inf_data->syscalls_counts, iter, ++elem);
7490         }
7491     }
7492
7493   return target_set_syscall_catchpoint (PIDGET (inferior_ptid),
7494                                         inf_data->total_syscalls_count != 0,
7495                                         inf_data->any_syscall_count,
7496                                         VEC_length (int,
7497                                                     inf_data->syscalls_counts),
7498                                         VEC_address (int,
7499                                                      inf_data->syscalls_counts));
7500 }
7501
7502 /* Implement the "remove" breakpoint_ops method for syscall
7503    catchpoints.  */
7504
7505 static int
7506 remove_catch_syscall (struct bp_location *bl)
7507 {
7508   struct syscall_catchpoint *c = (struct syscall_catchpoint *) bl->owner;
7509   struct inferior *inf = current_inferior ();
7510   struct catch_syscall_inferior_data *inf_data
7511     = get_catch_syscall_inferior_data (inf);
7512
7513   --inf_data->total_syscalls_count;
7514   if (!c->syscalls_to_be_caught)
7515     --inf_data->any_syscall_count;
7516   else
7517     {
7518       int i, iter;
7519
7520       for (i = 0;
7521            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
7522            i++)
7523         {
7524           int elem;
7525           if (iter >= VEC_length (int, inf_data->syscalls_counts))
7526             /* Shouldn't happen.  */
7527             continue;
7528           elem = VEC_index (int, inf_data->syscalls_counts, iter);
7529           VEC_replace (int, inf_data->syscalls_counts, iter, --elem);
7530         }
7531     }
7532
7533   return target_set_syscall_catchpoint (PIDGET (inferior_ptid),
7534                                         inf_data->total_syscalls_count != 0,
7535                                         inf_data->any_syscall_count,
7536                                         VEC_length (int,
7537                                                     inf_data->syscalls_counts),
7538                                         VEC_address (int,
7539                                                      inf_data->syscalls_counts));
7540 }
7541
7542 /* Implement the "breakpoint_hit" breakpoint_ops method for syscall
7543    catchpoints.  */
7544
7545 static int
7546 breakpoint_hit_catch_syscall (const struct bp_location *bl,
7547                               struct address_space *aspace, CORE_ADDR bp_addr,
7548                               const struct target_waitstatus *ws)
7549 {
7550   /* We must check if we are catching specific syscalls in this
7551      breakpoint.  If we are, then we must guarantee that the called
7552      syscall is the same syscall we are catching.  */
7553   int syscall_number = 0;
7554   const struct syscall_catchpoint *c
7555     = (const struct syscall_catchpoint *) bl->owner;
7556
7557   if (ws->kind != TARGET_WAITKIND_SYSCALL_ENTRY
7558       && ws->kind != TARGET_WAITKIND_SYSCALL_RETURN)
7559     return 0;
7560
7561   syscall_number = ws->value.syscall_number;
7562
7563   /* Now, checking if the syscall is the same.  */
7564   if (c->syscalls_to_be_caught)
7565     {
7566       int i, iter;
7567
7568       for (i = 0;
7569            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
7570            i++)
7571         if (syscall_number == iter)
7572           break;
7573       /* Not the same.  */
7574       if (!iter)
7575         return 0;
7576     }
7577
7578   return 1;
7579 }
7580
7581 /* Implement the "print_it" breakpoint_ops method for syscall
7582    catchpoints.  */
7583
7584 static enum print_stop_action
7585 print_it_catch_syscall (bpstat bs)
7586 {
7587   struct ui_out *uiout = current_uiout;
7588   struct breakpoint *b = bs->breakpoint_at;
7589   /* These are needed because we want to know in which state a
7590      syscall is.  It can be in the TARGET_WAITKIND_SYSCALL_ENTRY
7591      or TARGET_WAITKIND_SYSCALL_RETURN, and depending on it we
7592      must print "called syscall" or "returned from syscall".  */
7593   ptid_t ptid;
7594   struct target_waitstatus last;
7595   struct syscall s;
7596   char *syscall_id;
7597
7598   get_last_target_status (&ptid, &last);
7599
7600   get_syscall_by_number (last.value.syscall_number, &s);
7601
7602   annotate_catchpoint (b->number);
7603
7604   if (b->disposition == disp_del)
7605     ui_out_text (uiout, "\nTemporary catchpoint ");
7606   else
7607     ui_out_text (uiout, "\nCatchpoint ");
7608   if (ui_out_is_mi_like_p (uiout))
7609     {
7610       ui_out_field_string (uiout, "reason",
7611                            async_reason_lookup (last.kind == TARGET_WAITKIND_SYSCALL_ENTRY
7612                                                 ? EXEC_ASYNC_SYSCALL_ENTRY
7613                                                 : EXEC_ASYNC_SYSCALL_RETURN));
7614       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
7615     }
7616   ui_out_field_int (uiout, "bkptno", b->number);
7617
7618   if (last.kind == TARGET_WAITKIND_SYSCALL_ENTRY)
7619     ui_out_text (uiout, " (call to syscall ");
7620   else
7621     ui_out_text (uiout, " (returned from syscall ");
7622
7623   if (s.name == NULL || ui_out_is_mi_like_p (uiout))
7624     ui_out_field_int (uiout, "syscall-number", last.value.syscall_number);
7625   if (s.name != NULL)
7626     ui_out_field_string (uiout, "syscall-name", s.name);
7627
7628   ui_out_text (uiout, "), ");
7629
7630   return PRINT_SRC_AND_LOC;
7631 }
7632
7633 /* Implement the "print_one" breakpoint_ops method for syscall
7634    catchpoints.  */
7635
7636 static void
7637 print_one_catch_syscall (struct breakpoint *b,
7638                          struct bp_location **last_loc)
7639 {
7640   struct syscall_catchpoint *c = (struct syscall_catchpoint *) b;
7641   struct value_print_options opts;
7642   struct ui_out *uiout = current_uiout;
7643
7644   get_user_print_options (&opts);
7645   /* Field 4, the address, is omitted (which makes the columns not
7646      line up too nicely with the headers, but the effect is relatively
7647      readable).  */
7648   if (opts.addressprint)
7649     ui_out_field_skip (uiout, "addr");
7650   annotate_field (5);
7651
7652   if (c->syscalls_to_be_caught
7653       && VEC_length (int, c->syscalls_to_be_caught) > 1)
7654     ui_out_text (uiout, "syscalls \"");
7655   else
7656     ui_out_text (uiout, "syscall \"");
7657
7658   if (c->syscalls_to_be_caught)
7659     {
7660       int i, iter;
7661       char *text = xstrprintf ("%s", "");
7662
7663       for (i = 0;
7664            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
7665            i++)
7666         {
7667           char *x = text;
7668           struct syscall s;
7669           get_syscall_by_number (iter, &s);
7670
7671           if (s.name != NULL)
7672             text = xstrprintf ("%s%s, ", text, s.name);
7673           else
7674             text = xstrprintf ("%s%d, ", text, iter);
7675
7676           /* We have to xfree the last 'text' (now stored at 'x')
7677              because xstrprintf dynamically allocates new space for it
7678              on every call.  */
7679           xfree (x);
7680         }
7681       /* Remove the last comma.  */
7682       text[strlen (text) - 2] = '\0';
7683       ui_out_field_string (uiout, "what", text);
7684     }
7685   else
7686     ui_out_field_string (uiout, "what", "<any syscall>");
7687   ui_out_text (uiout, "\" ");
7688 }
7689
7690 /* Implement the "print_mention" breakpoint_ops method for syscall
7691    catchpoints.  */
7692
7693 static void
7694 print_mention_catch_syscall (struct breakpoint *b)
7695 {
7696   struct syscall_catchpoint *c = (struct syscall_catchpoint *) b;
7697
7698   if (c->syscalls_to_be_caught)
7699     {
7700       int i, iter;
7701
7702       if (VEC_length (int, c->syscalls_to_be_caught) > 1)
7703         printf_filtered (_("Catchpoint %d (syscalls"), b->number);
7704       else
7705         printf_filtered (_("Catchpoint %d (syscall"), b->number);
7706
7707       for (i = 0;
7708            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
7709            i++)
7710         {
7711           struct syscall s;
7712           get_syscall_by_number (iter, &s);
7713
7714           if (s.name)
7715             printf_filtered (" '%s' [%d]", s.name, s.number);
7716           else
7717             printf_filtered (" %d", s.number);
7718         }
7719       printf_filtered (")");
7720     }
7721   else
7722     printf_filtered (_("Catchpoint %d (any syscall)"),
7723                      b->number);
7724 }
7725
7726 /* Implement the "print_recreate" breakpoint_ops method for syscall
7727    catchpoints.  */
7728
7729 static void
7730 print_recreate_catch_syscall (struct breakpoint *b, struct ui_file *fp)
7731 {
7732   struct syscall_catchpoint *c = (struct syscall_catchpoint *) b;
7733
7734   fprintf_unfiltered (fp, "catch syscall");
7735
7736   if (c->syscalls_to_be_caught)
7737     {
7738       int i, iter;
7739
7740       for (i = 0;
7741            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
7742            i++)
7743         {
7744           struct syscall s;
7745
7746           get_syscall_by_number (iter, &s);
7747           if (s.name)
7748             fprintf_unfiltered (fp, " %s", s.name);
7749           else
7750             fprintf_unfiltered (fp, " %d", s.number);
7751         }
7752     }
7753   print_recreate_thread (b, fp);
7754 }
7755
7756 /* The breakpoint_ops structure to be used in syscall catchpoints.  */
7757
7758 static struct breakpoint_ops catch_syscall_breakpoint_ops;
7759
7760 /* Returns non-zero if 'b' is a syscall catchpoint.  */
7761
7762 static int
7763 syscall_catchpoint_p (struct breakpoint *b)
7764 {
7765   return (b->ops == &catch_syscall_breakpoint_ops);
7766 }
7767
7768 /* Initialize a new breakpoint of the bp_catchpoint kind.  If TEMPFLAG
7769    is non-zero, then make the breakpoint temporary.  If COND_STRING is
7770    not NULL, then store it in the breakpoint.  OPS, if not NULL, is
7771    the breakpoint_ops structure associated to the catchpoint.  */
7772
7773 static void
7774 init_catchpoint (struct breakpoint *b,
7775                  struct gdbarch *gdbarch, int tempflag,
7776                  char *cond_string,
7777                  const struct breakpoint_ops *ops)
7778 {
7779   struct symtab_and_line sal;
7780
7781   init_sal (&sal);
7782   sal.pspace = current_program_space;
7783
7784   init_raw_breakpoint (b, gdbarch, sal, bp_catchpoint, ops);
7785
7786   b->cond_string = (cond_string == NULL) ? NULL : xstrdup (cond_string);
7787   b->disposition = tempflag ? disp_del : disp_donttouch;
7788 }
7789
7790 void
7791 install_breakpoint (int internal, struct breakpoint *b, int update_gll)
7792 {
7793   add_to_breakpoint_chain (b);
7794   set_breakpoint_number (internal, b);
7795   if (!internal)
7796     mention (b);
7797   observer_notify_breakpoint_created (b);
7798
7799   if (update_gll)
7800     update_global_location_list (1);
7801 }
7802
7803 static void
7804 create_fork_vfork_event_catchpoint (struct gdbarch *gdbarch,
7805                                     int tempflag, char *cond_string,
7806                                     const struct breakpoint_ops *ops)
7807 {
7808   struct fork_catchpoint *c = XNEW (struct fork_catchpoint);
7809
7810   init_catchpoint (&c->base, gdbarch, tempflag, cond_string, ops);
7811
7812   c->forked_inferior_pid = null_ptid;
7813
7814   install_breakpoint (0, &c->base, 1);
7815 }
7816
7817 /* Exec catchpoints.  */
7818
7819 /* An instance of this type is used to represent an exec catchpoint.
7820    It includes a "struct breakpoint" as a kind of base class; users
7821    downcast to "struct breakpoint *" when needed.  A breakpoint is
7822    really of this type iff its ops pointer points to
7823    CATCH_EXEC_BREAKPOINT_OPS.  */
7824
7825 struct exec_catchpoint
7826 {
7827   /* The base class.  */
7828   struct breakpoint base;
7829
7830   /* Filename of a program whose exec triggered this catchpoint.
7831      This field is only valid immediately after this catchpoint has
7832      triggered.  */
7833   char *exec_pathname;
7834 };
7835
7836 /* Implement the "dtor" breakpoint_ops method for exec
7837    catchpoints.  */
7838
7839 static void
7840 dtor_catch_exec (struct breakpoint *b)
7841 {
7842   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
7843
7844   xfree (c->exec_pathname);
7845
7846   base_breakpoint_ops.dtor (b);
7847 }
7848
7849 static int
7850 insert_catch_exec (struct bp_location *bl)
7851 {
7852   return target_insert_exec_catchpoint (PIDGET (inferior_ptid));
7853 }
7854
7855 static int
7856 remove_catch_exec (struct bp_location *bl)
7857 {
7858   return target_remove_exec_catchpoint (PIDGET (inferior_ptid));
7859 }
7860
7861 static int
7862 breakpoint_hit_catch_exec (const struct bp_location *bl,
7863                            struct address_space *aspace, CORE_ADDR bp_addr,
7864                            const struct target_waitstatus *ws)
7865 {
7866   struct exec_catchpoint *c = (struct exec_catchpoint *) bl->owner;
7867
7868   if (ws->kind != TARGET_WAITKIND_EXECD)
7869     return 0;
7870
7871   c->exec_pathname = xstrdup (ws->value.execd_pathname);
7872   return 1;
7873 }
7874
7875 static enum print_stop_action
7876 print_it_catch_exec (bpstat bs)
7877 {
7878   struct ui_out *uiout = current_uiout;
7879   struct breakpoint *b = bs->breakpoint_at;
7880   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
7881
7882   annotate_catchpoint (b->number);
7883   if (b->disposition == disp_del)
7884     ui_out_text (uiout, "\nTemporary catchpoint ");
7885   else
7886     ui_out_text (uiout, "\nCatchpoint ");
7887   if (ui_out_is_mi_like_p (uiout))
7888     {
7889       ui_out_field_string (uiout, "reason",
7890                            async_reason_lookup (EXEC_ASYNC_EXEC));
7891       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
7892     }
7893   ui_out_field_int (uiout, "bkptno", b->number);
7894   ui_out_text (uiout, " (exec'd ");
7895   ui_out_field_string (uiout, "new-exec", c->exec_pathname);
7896   ui_out_text (uiout, "), ");
7897
7898   return PRINT_SRC_AND_LOC;
7899 }
7900
7901 static void
7902 print_one_catch_exec (struct breakpoint *b, struct bp_location **last_loc)
7903 {
7904   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
7905   struct value_print_options opts;
7906   struct ui_out *uiout = current_uiout;
7907
7908   get_user_print_options (&opts);
7909
7910   /* Field 4, the address, is omitted (which makes the columns
7911      not line up too nicely with the headers, but the effect
7912      is relatively readable).  */
7913   if (opts.addressprint)
7914     ui_out_field_skip (uiout, "addr");
7915   annotate_field (5);
7916   ui_out_text (uiout, "exec");
7917   if (c->exec_pathname != NULL)
7918     {
7919       ui_out_text (uiout, ", program \"");
7920       ui_out_field_string (uiout, "what", c->exec_pathname);
7921       ui_out_text (uiout, "\" ");
7922     }
7923 }
7924
7925 static void
7926 print_mention_catch_exec (struct breakpoint *b)
7927 {
7928   printf_filtered (_("Catchpoint %d (exec)"), b->number);
7929 }
7930
7931 /* Implement the "print_recreate" breakpoint_ops method for exec
7932    catchpoints.  */
7933
7934 static void
7935 print_recreate_catch_exec (struct breakpoint *b, struct ui_file *fp)
7936 {
7937   fprintf_unfiltered (fp, "catch exec");
7938   print_recreate_thread (b, fp);
7939 }
7940
7941 static struct breakpoint_ops catch_exec_breakpoint_ops;
7942
7943 static void
7944 create_syscall_event_catchpoint (int tempflag, VEC(int) *filter,
7945                                  const struct breakpoint_ops *ops)
7946 {
7947   struct syscall_catchpoint *c;
7948   struct gdbarch *gdbarch = get_current_arch ();
7949
7950   c = XNEW (struct syscall_catchpoint);
7951   init_catchpoint (&c->base, gdbarch, tempflag, NULL, ops);
7952   c->syscalls_to_be_caught = filter;
7953
7954   install_breakpoint (0, &c->base, 1);
7955 }
7956
7957 static int
7958 hw_breakpoint_used_count (void)
7959 {
7960   int i = 0;
7961   struct breakpoint *b;
7962   struct bp_location *bl;
7963
7964   ALL_BREAKPOINTS (b)
7965   {
7966     if (b->type == bp_hardware_breakpoint && breakpoint_enabled (b))
7967       for (bl = b->loc; bl; bl = bl->next)
7968         {
7969           /* Special types of hardware breakpoints may use more than
7970              one register.  */
7971           i += b->ops->resources_needed (bl);
7972         }
7973   }
7974
7975   return i;
7976 }
7977
7978 /* Returns the resources B would use if it were a hardware
7979    watchpoint.  */
7980
7981 static int
7982 hw_watchpoint_use_count (struct breakpoint *b)
7983 {
7984   int i = 0;
7985   struct bp_location *bl;
7986
7987   if (!breakpoint_enabled (b))
7988     return 0;
7989
7990   for (bl = b->loc; bl; bl = bl->next)
7991     {
7992       /* Special types of hardware watchpoints may use more than
7993          one register.  */
7994       i += b->ops->resources_needed (bl);
7995     }
7996
7997   return i;
7998 }
7999
8000 /* Returns the sum the used resources of all hardware watchpoints of
8001    type TYPE in the breakpoints list.  Also returns in OTHER_TYPE_USED
8002    the sum of the used resources of all hardware watchpoints of other
8003    types _not_ TYPE.  */
8004
8005 static int
8006 hw_watchpoint_used_count_others (struct breakpoint *except,
8007                                  enum bptype type, int *other_type_used)
8008 {
8009   int i = 0;
8010   struct breakpoint *b;
8011
8012   *other_type_used = 0;
8013   ALL_BREAKPOINTS (b)
8014     {
8015       if (b == except)
8016         continue;
8017       if (!breakpoint_enabled (b))
8018         continue;
8019
8020       if (b->type == type)
8021         i += hw_watchpoint_use_count (b);
8022       else if (is_hardware_watchpoint (b))
8023         *other_type_used = 1;
8024     }
8025
8026   return i;
8027 }
8028
8029 void
8030 disable_watchpoints_before_interactive_call_start (void)
8031 {
8032   struct breakpoint *b;
8033
8034   ALL_BREAKPOINTS (b)
8035   {
8036     if (is_watchpoint (b) && breakpoint_enabled (b))
8037       {
8038         b->enable_state = bp_call_disabled;
8039         update_global_location_list (0);
8040       }
8041   }
8042 }
8043
8044 void
8045 enable_watchpoints_after_interactive_call_stop (void)
8046 {
8047   struct breakpoint *b;
8048
8049   ALL_BREAKPOINTS (b)
8050   {
8051     if (is_watchpoint (b) && b->enable_state == bp_call_disabled)
8052       {
8053         b->enable_state = bp_enabled;
8054         update_global_location_list (1);
8055       }
8056   }
8057 }
8058
8059 void
8060 disable_breakpoints_before_startup (void)
8061 {
8062   current_program_space->executing_startup = 1;
8063   update_global_location_list (0);
8064 }
8065
8066 void
8067 enable_breakpoints_after_startup (void)
8068 {
8069   current_program_space->executing_startup = 0;
8070   breakpoint_re_set ();
8071 }
8072
8073
8074 /* Set a breakpoint that will evaporate an end of command
8075    at address specified by SAL.
8076    Restrict it to frame FRAME if FRAME is nonzero.  */
8077
8078 struct breakpoint *
8079 set_momentary_breakpoint (struct gdbarch *gdbarch, struct symtab_and_line sal,
8080                           struct frame_id frame_id, enum bptype type)
8081 {
8082   struct breakpoint *b;
8083
8084   /* If FRAME_ID is valid, it should be a real frame, not an inlined
8085      one.  */
8086   gdb_assert (!frame_id_inlined_p (frame_id));
8087
8088   b = set_raw_breakpoint (gdbarch, sal, type, &momentary_breakpoint_ops);
8089   b->enable_state = bp_enabled;
8090   b->disposition = disp_donttouch;
8091   b->frame_id = frame_id;
8092
8093   /* If we're debugging a multi-threaded program, then we want
8094      momentary breakpoints to be active in only a single thread of
8095      control.  */
8096   if (in_thread_list (inferior_ptid))
8097     b->thread = pid_to_thread_id (inferior_ptid);
8098
8099   update_global_location_list_nothrow (1);
8100
8101   return b;
8102 }
8103
8104 /* Make a momentary breakpoint based on the master breakpoint ORIG.
8105    The new breakpoint will have type TYPE, and use OPS as it
8106    breakpoint_ops.  */
8107
8108 static struct breakpoint *
8109 momentary_breakpoint_from_master (struct breakpoint *orig,
8110                                   enum bptype type,
8111                                   const struct breakpoint_ops *ops)
8112 {
8113   struct breakpoint *copy;
8114
8115   copy = set_raw_breakpoint_without_location (orig->gdbarch, type, ops);
8116   copy->loc = allocate_bp_location (copy);
8117   set_breakpoint_location_function (copy->loc, 1);
8118
8119   copy->loc->gdbarch = orig->loc->gdbarch;
8120   copy->loc->requested_address = orig->loc->requested_address;
8121   copy->loc->address = orig->loc->address;
8122   copy->loc->section = orig->loc->section;
8123   copy->loc->pspace = orig->loc->pspace;
8124
8125   if (orig->loc->source_file != NULL)
8126     copy->loc->source_file = xstrdup (orig->loc->source_file);
8127
8128   copy->loc->line_number = orig->loc->line_number;
8129   copy->frame_id = orig->frame_id;
8130   copy->thread = orig->thread;
8131   copy->pspace = orig->pspace;
8132
8133   copy->enable_state = bp_enabled;
8134   copy->disposition = disp_donttouch;
8135   copy->number = internal_breakpoint_number--;
8136
8137   update_global_location_list_nothrow (0);
8138   return copy;
8139 }
8140
8141 /* Make a deep copy of momentary breakpoint ORIG.  Returns NULL if
8142    ORIG is NULL.  */
8143
8144 struct breakpoint *
8145 clone_momentary_breakpoint (struct breakpoint *orig)
8146 {
8147   /* If there's nothing to clone, then return nothing.  */
8148   if (orig == NULL)
8149     return NULL;
8150
8151   return momentary_breakpoint_from_master (orig, orig->type, orig->ops);
8152 }
8153
8154 struct breakpoint *
8155 set_momentary_breakpoint_at_pc (struct gdbarch *gdbarch, CORE_ADDR pc,
8156                                 enum bptype type)
8157 {
8158   struct symtab_and_line sal;
8159
8160   sal = find_pc_line (pc, 0);
8161   sal.pc = pc;
8162   sal.section = find_pc_overlay (pc);
8163   sal.explicit_pc = 1;
8164
8165   return set_momentary_breakpoint (gdbarch, sal, null_frame_id, type);
8166 }
8167 \f
8168
8169 /* Tell the user we have just set a breakpoint B.  */
8170
8171 static void
8172 mention (struct breakpoint *b)
8173 {
8174   b->ops->print_mention (b);
8175   if (ui_out_is_mi_like_p (current_uiout))
8176     return;
8177   printf_filtered ("\n");
8178 }
8179 \f
8180
8181 static struct bp_location *
8182 add_location_to_breakpoint (struct breakpoint *b,
8183                             const struct symtab_and_line *sal)
8184 {
8185   struct bp_location *loc, **tmp;
8186   CORE_ADDR adjusted_address;
8187   struct gdbarch *loc_gdbarch = get_sal_arch (*sal);
8188
8189   if (loc_gdbarch == NULL)
8190     loc_gdbarch = b->gdbarch;
8191
8192   /* Adjust the breakpoint's address prior to allocating a location.
8193      Once we call allocate_bp_location(), that mostly uninitialized
8194      location will be placed on the location chain.  Adjustment of the
8195      breakpoint may cause target_read_memory() to be called and we do
8196      not want its scan of the location chain to find a breakpoint and
8197      location that's only been partially initialized.  */
8198   adjusted_address = adjust_breakpoint_address (loc_gdbarch,
8199                                                 sal->pc, b->type);
8200
8201   loc = allocate_bp_location (b);
8202   for (tmp = &(b->loc); *tmp != NULL; tmp = &((*tmp)->next))
8203     ;
8204   *tmp = loc;
8205
8206   loc->requested_address = sal->pc;
8207   loc->address = adjusted_address;
8208   loc->pspace = sal->pspace;
8209   gdb_assert (loc->pspace != NULL);
8210   loc->section = sal->section;
8211   loc->gdbarch = loc_gdbarch;
8212
8213   if (sal->symtab != NULL)
8214     loc->source_file = xstrdup (sal->symtab->filename);
8215   loc->line_number = sal->line;
8216
8217   set_breakpoint_location_function (loc,
8218                                     sal->explicit_pc || sal->explicit_line);
8219   return loc;
8220 }
8221 \f
8222
8223 /* Return 1 if LOC is pointing to a permanent breakpoint, 
8224    return 0 otherwise.  */
8225
8226 static int
8227 bp_loc_is_permanent (struct bp_location *loc)
8228 {
8229   int len;
8230   CORE_ADDR addr;
8231   const gdb_byte *bpoint;
8232   gdb_byte *target_mem;
8233   struct cleanup *cleanup;
8234   int retval = 0;
8235
8236   gdb_assert (loc != NULL);
8237
8238   addr = loc->address;
8239   bpoint = gdbarch_breakpoint_from_pc (loc->gdbarch, &addr, &len);
8240
8241   /* Software breakpoints unsupported?  */
8242   if (bpoint == NULL)
8243     return 0;
8244
8245   target_mem = alloca (len);
8246
8247   /* Enable the automatic memory restoration from breakpoints while
8248      we read the memory.  Otherwise we could say about our temporary
8249      breakpoints they are permanent.  */
8250   cleanup = save_current_space_and_thread ();
8251
8252   switch_to_program_space_and_thread (loc->pspace);
8253   make_show_memory_breakpoints_cleanup (0);
8254
8255   if (target_read_memory (loc->address, target_mem, len) == 0
8256       && memcmp (target_mem, bpoint, len) == 0)
8257     retval = 1;
8258
8259   do_cleanups (cleanup);
8260
8261   return retval;
8262 }
8263
8264
8265
8266 /* Create a breakpoint with SAL as location.  Use ADDR_STRING
8267    as textual description of the location, and COND_STRING
8268    as condition expression.  */
8269
8270 static void
8271 init_breakpoint_sal (struct breakpoint *b, struct gdbarch *gdbarch,
8272                      struct symtabs_and_lines sals, char *addr_string,
8273                      char *filter, char *cond_string,
8274                      enum bptype type, enum bpdisp disposition,
8275                      int thread, int task, int ignore_count,
8276                      const struct breakpoint_ops *ops, int from_tty,
8277                      int enabled, int internal, int display_canonical)
8278 {
8279   int i;
8280
8281   if (type == bp_hardware_breakpoint)
8282     {
8283       int target_resources_ok;
8284
8285       i = hw_breakpoint_used_count ();
8286       target_resources_ok =
8287         target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
8288                                             i + 1, 0);
8289       if (target_resources_ok == 0)
8290         error (_("No hardware breakpoint support in the target."));
8291       else if (target_resources_ok < 0)
8292         error (_("Hardware breakpoints used exceeds limit."));
8293     }
8294
8295   gdb_assert (sals.nelts > 0);
8296
8297   for (i = 0; i < sals.nelts; ++i)
8298     {
8299       struct symtab_and_line sal = sals.sals[i];
8300       struct bp_location *loc;
8301
8302       if (from_tty)
8303         {
8304           struct gdbarch *loc_gdbarch = get_sal_arch (sal);
8305           if (!loc_gdbarch)
8306             loc_gdbarch = gdbarch;
8307
8308           describe_other_breakpoints (loc_gdbarch,
8309                                       sal.pspace, sal.pc, sal.section, thread);
8310         }
8311
8312       if (i == 0)
8313         {
8314           init_raw_breakpoint (b, gdbarch, sal, type, ops);
8315           b->thread = thread;
8316           b->task = task;
8317   
8318           b->cond_string = cond_string;
8319           b->ignore_count = ignore_count;
8320           b->enable_state = enabled ? bp_enabled : bp_disabled;
8321           b->disposition = disposition;
8322
8323           if (type == bp_static_tracepoint)
8324             {
8325               struct tracepoint *t = (struct tracepoint *) b;
8326               struct static_tracepoint_marker marker;
8327
8328               if (strace_marker_p (b))
8329                 {
8330                   /* We already know the marker exists, otherwise, we
8331                      wouldn't see a sal for it.  */
8332                   char *p = &addr_string[3];
8333                   char *endp;
8334                   char *marker_str;
8335
8336                   p = skip_spaces (p);
8337
8338                   endp = skip_to_space (p);
8339
8340                   marker_str = savestring (p, endp - p);
8341                   t->static_trace_marker_id = marker_str;
8342
8343                   printf_filtered (_("Probed static tracepoint "
8344                                      "marker \"%s\"\n"),
8345                                    t->static_trace_marker_id);
8346                 }
8347               else if (target_static_tracepoint_marker_at (sal.pc, &marker))
8348                 {
8349                   t->static_trace_marker_id = xstrdup (marker.str_id);
8350                   release_static_tracepoint_marker (&marker);
8351
8352                   printf_filtered (_("Probed static tracepoint "
8353                                      "marker \"%s\"\n"),
8354                                    t->static_trace_marker_id);
8355                 }
8356               else
8357                 warning (_("Couldn't determine the static "
8358                            "tracepoint marker to probe"));
8359             }
8360
8361           loc = b->loc;
8362         }
8363       else
8364         {
8365           loc = add_location_to_breakpoint (b, &sal);
8366         }
8367
8368       if (bp_loc_is_permanent (loc))
8369         make_breakpoint_permanent (b);
8370
8371       if (b->cond_string)
8372         {
8373           char *arg = b->cond_string;
8374           loc->cond = parse_exp_1 (&arg, block_for_pc (loc->address), 0);
8375           if (*arg)
8376               error (_("Garbage %s follows condition"), arg);
8377         }
8378     }   
8379
8380   b->display_canonical = display_canonical;
8381   if (addr_string)
8382     b->addr_string = addr_string;
8383   else
8384     /* addr_string has to be used or breakpoint_re_set will delete
8385        me.  */
8386     b->addr_string
8387       = xstrprintf ("*%s", paddress (b->loc->gdbarch, b->loc->address));
8388   b->filter = filter;
8389 }
8390
8391 static void
8392 create_breakpoint_sal (struct gdbarch *gdbarch,
8393                        struct symtabs_and_lines sals, char *addr_string,
8394                        char *filter, char *cond_string,
8395                        enum bptype type, enum bpdisp disposition,
8396                        int thread, int task, int ignore_count,
8397                        const struct breakpoint_ops *ops, int from_tty,
8398                        int enabled, int internal, int display_canonical)
8399 {
8400   struct breakpoint *b;
8401   struct cleanup *old_chain;
8402
8403   if (is_tracepoint_type (type))
8404     {
8405       struct tracepoint *t;
8406
8407       t = XCNEW (struct tracepoint);
8408       b = &t->base;
8409     }
8410   else
8411     b = XNEW (struct breakpoint);
8412
8413   old_chain = make_cleanup (xfree, b);
8414
8415   init_breakpoint_sal (b, gdbarch,
8416                        sals, addr_string,
8417                        filter, cond_string,
8418                        type, disposition,
8419                        thread, task, ignore_count,
8420                        ops, from_tty,
8421                        enabled, internal, display_canonical);
8422   discard_cleanups (old_chain);
8423
8424   install_breakpoint (internal, b, 0);
8425 }
8426
8427 /* Add SALS.nelts breakpoints to the breakpoint table.  For each
8428    SALS.sal[i] breakpoint, include the corresponding ADDR_STRING[i]
8429    value.  COND_STRING, if not NULL, specified the condition to be
8430    used for all breakpoints.  Essentially the only case where
8431    SALS.nelts is not 1 is when we set a breakpoint on an overloaded
8432    function.  In that case, it's still not possible to specify
8433    separate conditions for different overloaded functions, so
8434    we take just a single condition string.
8435    
8436    NOTE: If the function succeeds, the caller is expected to cleanup
8437    the arrays ADDR_STRING, COND_STRING, and SALS (but not the
8438    array contents).  If the function fails (error() is called), the
8439    caller is expected to cleanups both the ADDR_STRING, COND_STRING,
8440    COND and SALS arrays and each of those arrays contents.  */
8441
8442 static void
8443 create_breakpoints_sal (struct gdbarch *gdbarch,
8444                         struct linespec_result *canonical,
8445                         char *cond_string,
8446                         enum bptype type, enum bpdisp disposition,
8447                         int thread, int task, int ignore_count,
8448                         const struct breakpoint_ops *ops, int from_tty,
8449                         int enabled, int internal)
8450 {
8451   int i;
8452   struct linespec_sals *lsal;
8453
8454   if (canonical->pre_expanded)
8455     gdb_assert (VEC_length (linespec_sals, canonical->sals) == 1);
8456
8457   for (i = 0; VEC_iterate (linespec_sals, canonical->sals, i, lsal); ++i)
8458     {
8459       /* Note that 'addr_string' can be NULL in the case of a plain
8460          'break', without arguments.  */
8461       char *addr_string = (canonical->addr_string
8462                            ? xstrdup (canonical->addr_string)
8463                            : NULL);
8464       char *filter_string = lsal->canonical ? xstrdup (lsal->canonical) : NULL;
8465       struct cleanup *inner = make_cleanup (xfree, addr_string);
8466
8467       make_cleanup (xfree, filter_string);
8468       create_breakpoint_sal (gdbarch, lsal->sals,
8469                              addr_string,
8470                              filter_string,
8471                              cond_string, type, disposition,
8472                              thread, task, ignore_count, ops,
8473                              from_tty, enabled, internal,
8474                              canonical->special_display);
8475       discard_cleanups (inner);
8476     }
8477 }
8478
8479 /* Parse ADDRESS which is assumed to be a SAL specification possibly
8480    followed by conditionals.  On return, SALS contains an array of SAL
8481    addresses found.  ADDR_STRING contains a vector of (canonical)
8482    address strings.  ADDRESS points to the end of the SAL.
8483
8484    The array and the line spec strings are allocated on the heap, it is
8485    the caller's responsibility to free them.  */
8486
8487 static void
8488 parse_breakpoint_sals (char **address,
8489                        struct linespec_result *canonical)
8490 {
8491   char *addr_start = *address;
8492
8493   /* If no arg given, or if first arg is 'if ', use the default
8494      breakpoint.  */
8495   if ((*address) == NULL
8496       || (strncmp ((*address), "if", 2) == 0 && isspace ((*address)[2])))
8497     {
8498       /* The last displayed codepoint, if it's valid, is our default breakpoint
8499          address.  */
8500       if (last_displayed_sal_is_valid ())
8501         {
8502           struct linespec_sals lsal;
8503           struct symtab_and_line sal;
8504
8505           init_sal (&sal);              /* Initialize to zeroes.  */
8506           lsal.sals.sals = (struct symtab_and_line *)
8507             xmalloc (sizeof (struct symtab_and_line));
8508
8509           /* Set sal's pspace, pc, symtab, and line to the values
8510              corresponding to the last call to print_frame_info.  */
8511           get_last_displayed_sal (&sal);
8512           sal.section = find_pc_overlay (sal.pc);
8513
8514           /* "break" without arguments is equivalent to "break *PC"
8515              where PC is the last displayed codepoint's address.  So
8516              make sure to set sal.explicit_pc to prevent GDB from
8517              trying to expand the list of sals to include all other
8518              instances with the same symtab and line.  */
8519           sal.explicit_pc = 1;
8520
8521           lsal.sals.sals[0] = sal;
8522           lsal.sals.nelts = 1;
8523           lsal.canonical = NULL;
8524
8525           VEC_safe_push (linespec_sals, canonical->sals, &lsal);
8526         }
8527       else
8528         error (_("No default breakpoint address now."));
8529     }
8530   else
8531     {
8532       /* Force almost all breakpoints to be in terms of the
8533          current_source_symtab (which is decode_line_1's default).
8534          This should produce the results we want almost all of the
8535          time while leaving default_breakpoint_* alone.  */
8536       if (last_displayed_sal_is_valid ())
8537         decode_line_full (address, DECODE_LINE_FUNFIRSTLINE,
8538                           get_last_displayed_symtab (),
8539                           get_last_displayed_line (),
8540                           canonical, NULL, NULL);
8541       else
8542         decode_line_full (address, DECODE_LINE_FUNFIRSTLINE,
8543                           (struct symtab *) NULL, 0,
8544                           canonical, NULL, NULL);
8545     }
8546 }
8547
8548
8549 /* Convert each SAL into a real PC.  Verify that the PC can be
8550    inserted as a breakpoint.  If it can't throw an error.  */
8551
8552 static void
8553 breakpoint_sals_to_pc (struct symtabs_and_lines *sals)
8554 {    
8555   int i;
8556
8557   for (i = 0; i < sals->nelts; i++)
8558     resolve_sal_pc (&sals->sals[i]);
8559 }
8560
8561 /* Fast tracepoints may have restrictions on valid locations.  For
8562    instance, a fast tracepoint using a jump instead of a trap will
8563    likely have to overwrite more bytes than a trap would, and so can
8564    only be placed where the instruction is longer than the jump, or a
8565    multi-instruction sequence does not have a jump into the middle of
8566    it, etc.  */
8567
8568 static void
8569 check_fast_tracepoint_sals (struct gdbarch *gdbarch,
8570                             struct symtabs_and_lines *sals)
8571 {
8572   int i, rslt;
8573   struct symtab_and_line *sal;
8574   char *msg;
8575   struct cleanup *old_chain;
8576
8577   for (i = 0; i < sals->nelts; i++)
8578     {
8579       struct gdbarch *sarch;
8580
8581       sal = &sals->sals[i];
8582
8583       sarch = get_sal_arch (*sal);
8584       /* We fall back to GDBARCH if there is no architecture
8585          associated with SAL.  */
8586       if (sarch == NULL)
8587         sarch = gdbarch;
8588       rslt = gdbarch_fast_tracepoint_valid_at (sarch, sal->pc,
8589                                                NULL, &msg);
8590       old_chain = make_cleanup (xfree, msg);
8591
8592       if (!rslt)
8593         error (_("May not have a fast tracepoint at 0x%s%s"),
8594                paddress (sarch, sal->pc), (msg ? msg : ""));
8595
8596       do_cleanups (old_chain);
8597     }
8598 }
8599
8600 /* Given TOK, a string specification of condition and thread, as
8601    accepted by the 'break' command, extract the condition
8602    string and thread number and set *COND_STRING and *THREAD.
8603    PC identifies the context at which the condition should be parsed.
8604    If no condition is found, *COND_STRING is set to NULL.
8605    If no thread is found, *THREAD is set to -1.  */
8606 static void 
8607 find_condition_and_thread (char *tok, CORE_ADDR pc, 
8608                            char **cond_string, int *thread, int *task)
8609 {
8610   *cond_string = NULL;
8611   *thread = -1;
8612   while (tok && *tok)
8613     {
8614       char *end_tok;
8615       int toklen;
8616       char *cond_start = NULL;
8617       char *cond_end = NULL;
8618
8619       tok = skip_spaces (tok);
8620       
8621       end_tok = skip_to_space (tok);
8622       
8623       toklen = end_tok - tok;
8624       
8625       if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
8626         {
8627           struct expression *expr;
8628
8629           tok = cond_start = end_tok + 1;
8630           expr = parse_exp_1 (&tok, block_for_pc (pc), 0);
8631           xfree (expr);
8632           cond_end = tok;
8633           *cond_string = savestring (cond_start, 
8634                                      cond_end - cond_start);
8635         }
8636       else if (toklen >= 1 && strncmp (tok, "thread", toklen) == 0)
8637         {
8638           char *tmptok;
8639           
8640           tok = end_tok + 1;
8641           tmptok = tok;
8642           *thread = strtol (tok, &tok, 0);
8643           if (tok == tmptok)
8644             error (_("Junk after thread keyword."));
8645           if (!valid_thread_id (*thread))
8646             error (_("Unknown thread %d."), *thread);
8647         }
8648       else if (toklen >= 1 && strncmp (tok, "task", toklen) == 0)
8649         {
8650           char *tmptok;
8651
8652           tok = end_tok + 1;
8653           tmptok = tok;
8654           *task = strtol (tok, &tok, 0);
8655           if (tok == tmptok)
8656             error (_("Junk after task keyword."));
8657           if (!valid_task_id (*task))
8658             error (_("Unknown task %d."), *task);
8659         }
8660       else
8661         error (_("Junk at end of arguments."));
8662     }
8663 }
8664
8665 /* Decode a static tracepoint marker spec.  */
8666
8667 static struct symtabs_and_lines
8668 decode_static_tracepoint_spec (char **arg_p)
8669 {
8670   VEC(static_tracepoint_marker_p) *markers = NULL;
8671   struct symtabs_and_lines sals;
8672   struct symtab_and_line sal;
8673   struct symbol *sym;
8674   struct cleanup *old_chain;
8675   char *p = &(*arg_p)[3];
8676   char *endp;
8677   char *marker_str;
8678   int i;
8679
8680   p = skip_spaces (p);
8681
8682   endp = skip_to_space (p);
8683
8684   marker_str = savestring (p, endp - p);
8685   old_chain = make_cleanup (xfree, marker_str);
8686
8687   markers = target_static_tracepoint_markers_by_strid (marker_str);
8688   if (VEC_empty(static_tracepoint_marker_p, markers))
8689     error (_("No known static tracepoint marker named %s"), marker_str);
8690
8691   sals.nelts = VEC_length(static_tracepoint_marker_p, markers);
8692   sals.sals = xmalloc (sizeof *sals.sals * sals.nelts);
8693
8694   for (i = 0; i < sals.nelts; i++)
8695     {
8696       struct static_tracepoint_marker *marker;
8697
8698       marker = VEC_index (static_tracepoint_marker_p, markers, i);
8699
8700       init_sal (&sals.sals[i]);
8701
8702       sals.sals[i] = find_pc_line (marker->address, 0);
8703       sals.sals[i].pc = marker->address;
8704
8705       release_static_tracepoint_marker (marker);
8706     }
8707
8708   do_cleanups (old_chain);
8709
8710   *arg_p = endp;
8711   return sals;
8712 }
8713
8714 /* Set a breakpoint.  This function is shared between CLI and MI
8715    functions for setting a breakpoint.  This function has two major
8716    modes of operations, selected by the PARSE_CONDITION_AND_THREAD
8717    parameter.  If non-zero, the function will parse arg, extracting
8718    breakpoint location, address and thread.  Otherwise, ARG is just
8719    the location of breakpoint, with condition and thread specified by
8720    the COND_STRING and THREAD parameters.  If INTERNAL is non-zero,
8721    the breakpoint number will be allocated from the internal
8722    breakpoint count.  Returns true if any breakpoint was created;
8723    false otherwise.  */
8724
8725 int
8726 create_breakpoint (struct gdbarch *gdbarch,
8727                    char *arg, char *cond_string, int thread,
8728                    int parse_condition_and_thread,
8729                    int tempflag, enum bptype type_wanted,
8730                    int ignore_count,
8731                    enum auto_boolean pending_break_support,
8732                    const struct breakpoint_ops *ops,
8733                    int from_tty, int enabled, int internal)
8734 {
8735   volatile struct gdb_exception e;
8736   char *copy_arg = NULL;
8737   char *addr_start = arg;
8738   struct linespec_result canonical;
8739   struct cleanup *old_chain;
8740   struct cleanup *bkpt_chain = NULL;
8741   int i;
8742   int pending = 0;
8743   int task = 0;
8744   int prev_bkpt_count = breakpoint_count;
8745
8746   gdb_assert (ops != NULL);
8747
8748   init_linespec_result (&canonical);
8749
8750   TRY_CATCH (e, RETURN_MASK_ALL)
8751     {
8752       ops->create_sals_from_address (&arg, &canonical, type_wanted,
8753                                      addr_start, &copy_arg);
8754     }
8755
8756   /* If caller is interested in rc value from parse, set value.  */
8757   switch (e.reason)
8758     {
8759     case GDB_NO_ERROR:
8760       if (VEC_empty (linespec_sals, canonical.sals))
8761         return 0;
8762       break;
8763     case RETURN_ERROR:
8764       switch (e.error)
8765         {
8766         case NOT_FOUND_ERROR:
8767
8768           /* If pending breakpoint support is turned off, throw
8769              error.  */
8770
8771           if (pending_break_support == AUTO_BOOLEAN_FALSE)
8772             throw_exception (e);
8773
8774           exception_print (gdb_stderr, e);
8775
8776           /* If pending breakpoint support is auto query and the user
8777              selects no, then simply return the error code.  */
8778           if (pending_break_support == AUTO_BOOLEAN_AUTO
8779               && !nquery (_("Make %s pending on future shared library load? "),
8780                           bptype_string (type_wanted)))
8781             return 0;
8782
8783           /* At this point, either the user was queried about setting
8784              a pending breakpoint and selected yes, or pending
8785              breakpoint behavior is on and thus a pending breakpoint
8786              is defaulted on behalf of the user.  */
8787           {
8788             struct linespec_sals lsal;
8789
8790             copy_arg = xstrdup (addr_start);
8791             lsal.canonical = xstrdup (copy_arg);
8792             lsal.sals.nelts = 1;
8793             lsal.sals.sals = XNEW (struct symtab_and_line);
8794             init_sal (&lsal.sals.sals[0]);
8795             pending = 1;
8796             VEC_safe_push (linespec_sals, canonical.sals, &lsal);
8797           }
8798           break;
8799         default:
8800           throw_exception (e);
8801         }
8802       break;
8803     default:
8804       throw_exception (e);
8805     }
8806
8807   /* Create a chain of things that always need to be cleaned up.  */
8808   old_chain = make_cleanup_destroy_linespec_result (&canonical);
8809
8810   /* ----------------------------- SNIP -----------------------------
8811      Anything added to the cleanup chain beyond this point is assumed
8812      to be part of a breakpoint.  If the breakpoint create succeeds
8813      then the memory is not reclaimed.  */
8814   bkpt_chain = make_cleanup (null_cleanup, 0);
8815
8816   /* Resolve all line numbers to PC's and verify that the addresses
8817      are ok for the target.  */
8818   if (!pending)
8819     {
8820       int ix;
8821       struct linespec_sals *iter;
8822
8823       for (ix = 0; VEC_iterate (linespec_sals, canonical.sals, ix, iter); ++ix)
8824         breakpoint_sals_to_pc (&iter->sals);
8825     }
8826
8827   /* Fast tracepoints may have additional restrictions on location.  */
8828   if (!pending && type_wanted == bp_fast_tracepoint)
8829     {
8830       int ix;
8831       struct linespec_sals *iter;
8832
8833       for (ix = 0; VEC_iterate (linespec_sals, canonical.sals, ix, iter); ++ix)
8834         check_fast_tracepoint_sals (gdbarch, &iter->sals);
8835     }
8836
8837   /* Verify that condition can be parsed, before setting any
8838      breakpoints.  Allocate a separate condition expression for each
8839      breakpoint.  */
8840   if (!pending)
8841     {
8842       struct linespec_sals *lsal;
8843
8844       lsal = VEC_index (linespec_sals, canonical.sals, 0);
8845
8846       if (parse_condition_and_thread)
8847         {
8848             /* Here we only parse 'arg' to separate condition
8849                from thread number, so parsing in context of first
8850                sal is OK.  When setting the breakpoint we'll 
8851                re-parse it in context of each sal.  */
8852             cond_string = NULL;
8853             thread = -1;
8854             find_condition_and_thread (arg, lsal->sals.sals[0].pc, &cond_string,
8855                                        &thread, &task);
8856             if (cond_string)
8857                 make_cleanup (xfree, cond_string);
8858         }
8859       else
8860         {
8861             /* Create a private copy of condition string.  */
8862             if (cond_string)
8863             {
8864                 cond_string = xstrdup (cond_string);
8865                 make_cleanup (xfree, cond_string);
8866             }
8867         }
8868
8869       ops->create_breakpoints_sal (gdbarch, &canonical, lsal,
8870                                    cond_string, type_wanted,
8871                                    tempflag ? disp_del : disp_donttouch,
8872                                    thread, task, ignore_count, ops,
8873                                    from_tty, enabled, internal);
8874     }
8875   else
8876     {
8877       struct breakpoint *b;
8878
8879       make_cleanup (xfree, copy_arg);
8880
8881       if (is_tracepoint_type (type_wanted))
8882         {
8883           struct tracepoint *t;
8884
8885           t = XCNEW (struct tracepoint);
8886           b = &t->base;
8887         }
8888       else
8889         b = XNEW (struct breakpoint);
8890
8891       init_raw_breakpoint_without_location (b, gdbarch, type_wanted, ops);
8892
8893       b->addr_string = copy_arg;
8894       b->cond_string = NULL;
8895       b->ignore_count = ignore_count;
8896       b->disposition = tempflag ? disp_del : disp_donttouch;
8897       b->condition_not_parsed = 1;
8898       b->enable_state = enabled ? bp_enabled : bp_disabled;
8899       if ((type_wanted != bp_breakpoint
8900            && type_wanted != bp_hardware_breakpoint) || thread != -1)
8901         b->pspace = current_program_space;
8902
8903       install_breakpoint (internal, b, 0);
8904     }
8905   
8906   if (VEC_length (linespec_sals, canonical.sals) > 1)
8907     {
8908       warning (_("Multiple breakpoints were set.\nUse the "
8909                  "\"delete\" command to delete unwanted breakpoints."));
8910       prev_breakpoint_count = prev_bkpt_count;
8911     }
8912
8913   /* That's it.  Discard the cleanups for data inserted into the
8914      breakpoint.  */
8915   discard_cleanups (bkpt_chain);
8916   /* But cleanup everything else.  */
8917   do_cleanups (old_chain);
8918
8919   /* error call may happen here - have BKPT_CHAIN already discarded.  */
8920   update_global_location_list (1);
8921
8922   return 1;
8923 }
8924
8925 /* Set a breakpoint.
8926    ARG is a string describing breakpoint address,
8927    condition, and thread.
8928    FLAG specifies if a breakpoint is hardware on,
8929    and if breakpoint is temporary, using BP_HARDWARE_FLAG
8930    and BP_TEMPFLAG.  */
8931
8932 static void
8933 break_command_1 (char *arg, int flag, int from_tty)
8934 {
8935   int tempflag = flag & BP_TEMPFLAG;
8936   enum bptype type_wanted = (flag & BP_HARDWAREFLAG
8937                              ? bp_hardware_breakpoint
8938                              : bp_breakpoint);
8939
8940   create_breakpoint (get_current_arch (),
8941                      arg,
8942                      NULL, 0, 1 /* parse arg */,
8943                      tempflag, type_wanted,
8944                      0 /* Ignore count */,
8945                      pending_break_support,
8946                      &bkpt_breakpoint_ops,
8947                      from_tty,
8948                      1 /* enabled */,
8949                      0 /* internal */);
8950 }
8951
8952 /* Helper function for break_command_1 and disassemble_command.  */
8953
8954 void
8955 resolve_sal_pc (struct symtab_and_line *sal)
8956 {
8957   CORE_ADDR pc;
8958
8959   if (sal->pc == 0 && sal->symtab != NULL)
8960     {
8961       if (!find_line_pc (sal->symtab, sal->line, &pc))
8962         error (_("No line %d in file \"%s\"."),
8963                sal->line, sal->symtab->filename);
8964       sal->pc = pc;
8965
8966       /* If this SAL corresponds to a breakpoint inserted using a line
8967          number, then skip the function prologue if necessary.  */
8968       if (sal->explicit_line)
8969         skip_prologue_sal (sal);
8970     }
8971
8972   if (sal->section == 0 && sal->symtab != NULL)
8973     {
8974       struct blockvector *bv;
8975       struct block *b;
8976       struct symbol *sym;
8977
8978       bv = blockvector_for_pc_sect (sal->pc, 0, &b, sal->symtab);
8979       if (bv != NULL)
8980         {
8981           sym = block_linkage_function (b);
8982           if (sym != NULL)
8983             {
8984               fixup_symbol_section (sym, sal->symtab->objfile);
8985               sal->section = SYMBOL_OBJ_SECTION (sym);
8986             }
8987           else
8988             {
8989               /* It really is worthwhile to have the section, so we'll
8990                  just have to look harder. This case can be executed
8991                  if we have line numbers but no functions (as can
8992                  happen in assembly source).  */
8993
8994               struct minimal_symbol *msym;
8995               struct cleanup *old_chain = save_current_space_and_thread ();
8996
8997               switch_to_program_space_and_thread (sal->pspace);
8998
8999               msym = lookup_minimal_symbol_by_pc (sal->pc);
9000               if (msym)
9001                 sal->section = SYMBOL_OBJ_SECTION (msym);
9002
9003               do_cleanups (old_chain);
9004             }
9005         }
9006     }
9007 }
9008
9009 void
9010 break_command (char *arg, int from_tty)
9011 {
9012   break_command_1 (arg, 0, from_tty);
9013 }
9014
9015 void
9016 tbreak_command (char *arg, int from_tty)
9017 {
9018   break_command_1 (arg, BP_TEMPFLAG, from_tty);
9019 }
9020
9021 static void
9022 hbreak_command (char *arg, int from_tty)
9023 {
9024   break_command_1 (arg, BP_HARDWAREFLAG, from_tty);
9025 }
9026
9027 static void
9028 thbreak_command (char *arg, int from_tty)
9029 {
9030   break_command_1 (arg, (BP_TEMPFLAG | BP_HARDWAREFLAG), from_tty);
9031 }
9032
9033 static void
9034 stop_command (char *arg, int from_tty)
9035 {
9036   printf_filtered (_("Specify the type of breakpoint to set.\n\
9037 Usage: stop in <function | address>\n\
9038        stop at <line>\n"));
9039 }
9040
9041 static void
9042 stopin_command (char *arg, int from_tty)
9043 {
9044   int badInput = 0;
9045
9046   if (arg == (char *) NULL)
9047     badInput = 1;
9048   else if (*arg != '*')
9049     {
9050       char *argptr = arg;
9051       int hasColon = 0;
9052
9053       /* Look for a ':'.  If this is a line number specification, then
9054          say it is bad, otherwise, it should be an address or
9055          function/method name.  */
9056       while (*argptr && !hasColon)
9057         {
9058           hasColon = (*argptr == ':');
9059           argptr++;
9060         }
9061
9062       if (hasColon)
9063         badInput = (*argptr != ':');    /* Not a class::method */
9064       else
9065         badInput = isdigit (*arg);      /* a simple line number */
9066     }
9067
9068   if (badInput)
9069     printf_filtered (_("Usage: stop in <function | address>\n"));
9070   else
9071     break_command_1 (arg, 0, from_tty);
9072 }
9073
9074 static void
9075 stopat_command (char *arg, int from_tty)
9076 {
9077   int badInput = 0;
9078
9079   if (arg == (char *) NULL || *arg == '*')      /* no line number */
9080     badInput = 1;
9081   else
9082     {
9083       char *argptr = arg;
9084       int hasColon = 0;
9085
9086       /* Look for a ':'.  If there is a '::' then get out, otherwise
9087          it is probably a line number.  */
9088       while (*argptr && !hasColon)
9089         {
9090           hasColon = (*argptr == ':');
9091           argptr++;
9092         }
9093
9094       if (hasColon)
9095         badInput = (*argptr == ':');    /* we have class::method */
9096       else
9097         badInput = !isdigit (*arg);     /* not a line number */
9098     }
9099
9100   if (badInput)
9101     printf_filtered (_("Usage: stop at <line>\n"));
9102   else
9103     break_command_1 (arg, 0, from_tty);
9104 }
9105
9106 /* Implement the "breakpoint_hit" breakpoint_ops method for
9107    ranged breakpoints.  */
9108
9109 static int
9110 breakpoint_hit_ranged_breakpoint (const struct bp_location *bl,
9111                                   struct address_space *aspace,
9112                                   CORE_ADDR bp_addr,
9113                                   const struct target_waitstatus *ws)
9114 {
9115   if (ws->kind != TARGET_WAITKIND_STOPPED
9116       || ws->value.sig != TARGET_SIGNAL_TRAP)
9117     return 0;
9118
9119   return breakpoint_address_match_range (bl->pspace->aspace, bl->address,
9120                                          bl->length, aspace, bp_addr);
9121 }
9122
9123 /* Implement the "resources_needed" breakpoint_ops method for
9124    ranged breakpoints.  */
9125
9126 static int
9127 resources_needed_ranged_breakpoint (const struct bp_location *bl)
9128 {
9129   return target_ranged_break_num_registers ();
9130 }
9131
9132 /* Implement the "print_it" breakpoint_ops method for
9133    ranged breakpoints.  */
9134
9135 static enum print_stop_action
9136 print_it_ranged_breakpoint (bpstat bs)
9137 {
9138   struct breakpoint *b = bs->breakpoint_at;
9139   struct bp_location *bl = b->loc;
9140   struct ui_out *uiout = current_uiout;
9141
9142   gdb_assert (b->type == bp_hardware_breakpoint);
9143
9144   /* Ranged breakpoints have only one location.  */
9145   gdb_assert (bl && bl->next == NULL);
9146
9147   annotate_breakpoint (b->number);
9148   if (b->disposition == disp_del)
9149     ui_out_text (uiout, "\nTemporary ranged breakpoint ");
9150   else
9151     ui_out_text (uiout, "\nRanged breakpoint ");
9152   if (ui_out_is_mi_like_p (uiout))
9153     {
9154       ui_out_field_string (uiout, "reason",
9155                       async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
9156       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
9157     }
9158   ui_out_field_int (uiout, "bkptno", b->number);
9159   ui_out_text (uiout, ", ");
9160
9161   return PRINT_SRC_AND_LOC;
9162 }
9163
9164 /* Implement the "print_one" breakpoint_ops method for
9165    ranged breakpoints.  */
9166
9167 static void
9168 print_one_ranged_breakpoint (struct breakpoint *b,
9169                              struct bp_location **last_loc)
9170 {
9171   struct bp_location *bl = b->loc;
9172   struct value_print_options opts;
9173   struct ui_out *uiout = current_uiout;
9174
9175   /* Ranged breakpoints have only one location.  */
9176   gdb_assert (bl && bl->next == NULL);
9177
9178   get_user_print_options (&opts);
9179
9180   if (opts.addressprint)
9181     /* We don't print the address range here, it will be printed later
9182        by print_one_detail_ranged_breakpoint.  */
9183     ui_out_field_skip (uiout, "addr");
9184   annotate_field (5);
9185   print_breakpoint_location (b, bl);
9186   *last_loc = bl;
9187 }
9188
9189 /* Implement the "print_one_detail" breakpoint_ops method for
9190    ranged breakpoints.  */
9191
9192 static void
9193 print_one_detail_ranged_breakpoint (const struct breakpoint *b,
9194                                     struct ui_out *uiout)
9195 {
9196   CORE_ADDR address_start, address_end;
9197   struct bp_location *bl = b->loc;
9198   struct ui_stream *stb = ui_out_stream_new (uiout);
9199   struct cleanup *cleanup = make_cleanup_ui_out_stream_delete (stb);
9200
9201   gdb_assert (bl);
9202
9203   address_start = bl->address;
9204   address_end = address_start + bl->length - 1;
9205
9206   ui_out_text (uiout, "\taddress range: ");
9207   fprintf_unfiltered (stb->stream, "[%s, %s]",
9208                       print_core_address (bl->gdbarch, address_start),
9209                       print_core_address (bl->gdbarch, address_end));
9210   ui_out_field_stream (uiout, "addr", stb);
9211   ui_out_text (uiout, "\n");
9212
9213   do_cleanups (cleanup);
9214 }
9215
9216 /* Implement the "print_mention" breakpoint_ops method for
9217    ranged breakpoints.  */
9218
9219 static void
9220 print_mention_ranged_breakpoint (struct breakpoint *b)
9221 {
9222   struct bp_location *bl = b->loc;
9223   struct ui_out *uiout = current_uiout;
9224
9225   gdb_assert (bl);
9226   gdb_assert (b->type == bp_hardware_breakpoint);
9227
9228   if (ui_out_is_mi_like_p (uiout))
9229     return;
9230
9231   printf_filtered (_("Hardware assisted ranged breakpoint %d from %s to %s."),
9232                    b->number, paddress (bl->gdbarch, bl->address),
9233                    paddress (bl->gdbarch, bl->address + bl->length - 1));
9234 }
9235
9236 /* Implement the "print_recreate" breakpoint_ops method for
9237    ranged breakpoints.  */
9238
9239 static void
9240 print_recreate_ranged_breakpoint (struct breakpoint *b, struct ui_file *fp)
9241 {
9242   fprintf_unfiltered (fp, "break-range %s, %s", b->addr_string,
9243                       b->addr_string_range_end);
9244   print_recreate_thread (b, fp);
9245 }
9246
9247 /* The breakpoint_ops structure to be used in ranged breakpoints.  */
9248
9249 static struct breakpoint_ops ranged_breakpoint_ops;
9250
9251 /* Find the address where the end of the breakpoint range should be
9252    placed, given the SAL of the end of the range.  This is so that if
9253    the user provides a line number, the end of the range is set to the
9254    last instruction of the given line.  */
9255
9256 static CORE_ADDR
9257 find_breakpoint_range_end (struct symtab_and_line sal)
9258 {
9259   CORE_ADDR end;
9260
9261   /* If the user provided a PC value, use it.  Otherwise,
9262      find the address of the end of the given location.  */
9263   if (sal.explicit_pc)
9264     end = sal.pc;
9265   else
9266     {
9267       int ret;
9268       CORE_ADDR start;
9269
9270       ret = find_line_pc_range (sal, &start, &end);
9271       if (!ret)
9272         error (_("Could not find location of the end of the range."));
9273
9274       /* find_line_pc_range returns the start of the next line.  */
9275       end--;
9276     }
9277
9278   return end;
9279 }
9280
9281 /* Implement the "break-range" CLI command.  */
9282
9283 static void
9284 break_range_command (char *arg, int from_tty)
9285 {
9286   char *arg_start, *addr_string_start, *addr_string_end;
9287   struct linespec_result canonical_start, canonical_end;
9288   int bp_count, can_use_bp, length;
9289   CORE_ADDR end;
9290   struct breakpoint *b;
9291   struct symtab_and_line sal_start, sal_end;
9292   struct cleanup *cleanup_bkpt;
9293   struct linespec_sals *lsal_start, *lsal_end;
9294
9295   /* We don't support software ranged breakpoints.  */
9296   if (target_ranged_break_num_registers () < 0)
9297     error (_("This target does not support hardware ranged breakpoints."));
9298
9299   bp_count = hw_breakpoint_used_count ();
9300   bp_count += target_ranged_break_num_registers ();
9301   can_use_bp = target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
9302                                                    bp_count, 0);
9303   if (can_use_bp < 0)
9304     error (_("Hardware breakpoints used exceeds limit."));
9305
9306   arg = skip_spaces (arg);
9307   if (arg == NULL || arg[0] == '\0')
9308     error(_("No address range specified."));
9309
9310   init_linespec_result (&canonical_start);
9311
9312   arg_start = arg;
9313   parse_breakpoint_sals (&arg, &canonical_start);
9314
9315   cleanup_bkpt = make_cleanup_destroy_linespec_result (&canonical_start);
9316
9317   if (arg[0] != ',')
9318     error (_("Too few arguments."));
9319   else if (VEC_empty (linespec_sals, canonical_start.sals))
9320     error (_("Could not find location of the beginning of the range."));
9321
9322   lsal_start = VEC_index (linespec_sals, canonical_start.sals, 0);
9323
9324   if (VEC_length (linespec_sals, canonical_start.sals) > 1
9325       || lsal_start->sals.nelts != 1)
9326     error (_("Cannot create a ranged breakpoint with multiple locations."));
9327
9328   sal_start = lsal_start->sals.sals[0];
9329   addr_string_start = savestring (arg_start, arg - arg_start);
9330   make_cleanup (xfree, addr_string_start);
9331
9332   arg++;        /* Skip the comma.  */
9333   arg = skip_spaces (arg);
9334
9335   /* Parse the end location.  */
9336
9337   init_linespec_result (&canonical_end);
9338   arg_start = arg;
9339
9340   /* We call decode_line_full directly here instead of using
9341      parse_breakpoint_sals because we need to specify the start location's
9342      symtab and line as the default symtab and line for the end of the
9343      range.  This makes it possible to have ranges like "foo.c:27, +14",
9344      where +14 means 14 lines from the start location.  */
9345   decode_line_full (&arg, DECODE_LINE_FUNFIRSTLINE,
9346                     sal_start.symtab, sal_start.line,
9347                     &canonical_end, NULL, NULL);
9348
9349   make_cleanup_destroy_linespec_result (&canonical_end);
9350
9351   if (VEC_empty (linespec_sals, canonical_end.sals))
9352     error (_("Could not find location of the end of the range."));
9353
9354   lsal_end = VEC_index (linespec_sals, canonical_end.sals, 0);
9355   if (VEC_length (linespec_sals, canonical_end.sals) > 1
9356       || lsal_end->sals.nelts != 1)
9357     error (_("Cannot create a ranged breakpoint with multiple locations."));
9358
9359   sal_end = lsal_end->sals.sals[0];
9360   addr_string_end = savestring (arg_start, arg - arg_start);
9361   make_cleanup (xfree, addr_string_end);
9362
9363   end = find_breakpoint_range_end (sal_end);
9364   if (sal_start.pc > end)
9365     error (_("Invalid address range, end precedes start."));
9366
9367   length = end - sal_start.pc + 1;
9368   if (length < 0)
9369     /* Length overflowed.  */
9370     error (_("Address range too large."));
9371   else if (length == 1)
9372     {
9373       /* This range is simple enough to be handled by
9374          the `hbreak' command.  */
9375       hbreak_command (addr_string_start, 1);
9376
9377       do_cleanups (cleanup_bkpt);
9378
9379       return;
9380     }
9381
9382   /* Now set up the breakpoint.  */
9383   b = set_raw_breakpoint (get_current_arch (), sal_start,
9384                           bp_hardware_breakpoint, &ranged_breakpoint_ops);
9385   set_breakpoint_count (breakpoint_count + 1);
9386   b->number = breakpoint_count;
9387   b->disposition = disp_donttouch;
9388   b->addr_string = xstrdup (addr_string_start);
9389   b->addr_string_range_end = xstrdup (addr_string_end);
9390   b->loc->length = length;
9391
9392   do_cleanups (cleanup_bkpt);
9393
9394   mention (b);
9395   observer_notify_breakpoint_created (b);
9396   update_global_location_list (1);
9397 }
9398
9399 /*  Return non-zero if EXP is verified as constant.  Returned zero
9400     means EXP is variable.  Also the constant detection may fail for
9401     some constant expressions and in such case still falsely return
9402     zero.  */
9403
9404 static int
9405 watchpoint_exp_is_const (const struct expression *exp)
9406 {
9407   int i = exp->nelts;
9408
9409   while (i > 0)
9410     {
9411       int oplenp, argsp;
9412
9413       /* We are only interested in the descriptor of each element.  */
9414       operator_length (exp, i, &oplenp, &argsp);
9415       i -= oplenp;
9416
9417       switch (exp->elts[i].opcode)
9418         {
9419         case BINOP_ADD:
9420         case BINOP_SUB:
9421         case BINOP_MUL:
9422         case BINOP_DIV:
9423         case BINOP_REM:
9424         case BINOP_MOD:
9425         case BINOP_LSH:
9426         case BINOP_RSH:
9427         case BINOP_LOGICAL_AND:
9428         case BINOP_LOGICAL_OR:
9429         case BINOP_BITWISE_AND:
9430         case BINOP_BITWISE_IOR:
9431         case BINOP_BITWISE_XOR:
9432         case BINOP_EQUAL:
9433         case BINOP_NOTEQUAL:
9434         case BINOP_LESS:
9435         case BINOP_GTR:
9436         case BINOP_LEQ:
9437         case BINOP_GEQ:
9438         case BINOP_REPEAT:
9439         case BINOP_COMMA:
9440         case BINOP_EXP:
9441         case BINOP_MIN:
9442         case BINOP_MAX:
9443         case BINOP_INTDIV:
9444         case BINOP_CONCAT:
9445         case BINOP_IN:
9446         case BINOP_RANGE:
9447         case TERNOP_COND:
9448         case TERNOP_SLICE:
9449         case TERNOP_SLICE_COUNT:
9450
9451         case OP_LONG:
9452         case OP_DOUBLE:
9453         case OP_DECFLOAT:
9454         case OP_LAST:
9455         case OP_COMPLEX:
9456         case OP_STRING:
9457         case OP_BITSTRING:
9458         case OP_ARRAY:
9459         case OP_TYPE:
9460         case OP_NAME:
9461         case OP_OBJC_NSSTRING:
9462
9463         case UNOP_NEG:
9464         case UNOP_LOGICAL_NOT:
9465         case UNOP_COMPLEMENT:
9466         case UNOP_ADDR:
9467         case UNOP_HIGH:
9468         case UNOP_CAST:
9469           /* Unary, binary and ternary operators: We have to check
9470              their operands.  If they are constant, then so is the
9471              result of that operation.  For instance, if A and B are
9472              determined to be constants, then so is "A + B".
9473
9474              UNOP_IND is one exception to the rule above, because the
9475              value of *ADDR is not necessarily a constant, even when
9476              ADDR is.  */
9477           break;
9478
9479         case OP_VAR_VALUE:
9480           /* Check whether the associated symbol is a constant.
9481
9482              We use SYMBOL_CLASS rather than TYPE_CONST because it's
9483              possible that a buggy compiler could mark a variable as
9484              constant even when it is not, and TYPE_CONST would return
9485              true in this case, while SYMBOL_CLASS wouldn't.
9486
9487              We also have to check for function symbols because they
9488              are always constant.  */
9489           {
9490             struct symbol *s = exp->elts[i + 2].symbol;
9491
9492             if (SYMBOL_CLASS (s) != LOC_BLOCK
9493                 && SYMBOL_CLASS (s) != LOC_CONST
9494                 && SYMBOL_CLASS (s) != LOC_CONST_BYTES)
9495               return 0;
9496             break;
9497           }
9498
9499         /* The default action is to return 0 because we are using
9500            the optimistic approach here: If we don't know something,
9501            then it is not a constant.  */
9502         default:
9503           return 0;
9504         }
9505     }
9506
9507   return 1;
9508 }
9509
9510 /* Implement the "dtor" breakpoint_ops method for watchpoints.  */
9511
9512 static void
9513 dtor_watchpoint (struct breakpoint *self)
9514 {
9515   struct watchpoint *w = (struct watchpoint *) self;
9516
9517   xfree (w->cond_exp);
9518   xfree (w->exp);
9519   xfree (w->exp_string);
9520   xfree (w->exp_string_reparse);
9521   value_free (w->val);
9522
9523   base_breakpoint_ops.dtor (self);
9524 }
9525
9526 /* Implement the "re_set" breakpoint_ops method for watchpoints.  */
9527
9528 static void
9529 re_set_watchpoint (struct breakpoint *b)
9530 {
9531   struct watchpoint *w = (struct watchpoint *) b;
9532
9533   /* Watchpoint can be either on expression using entirely global
9534      variables, or it can be on local variables.
9535
9536      Watchpoints of the first kind are never auto-deleted, and even
9537      persist across program restarts.  Since they can use variables
9538      from shared libraries, we need to reparse expression as libraries
9539      are loaded and unloaded.
9540
9541      Watchpoints on local variables can also change meaning as result
9542      of solib event.  For example, if a watchpoint uses both a local
9543      and a global variables in expression, it's a local watchpoint,
9544      but unloading of a shared library will make the expression
9545      invalid.  This is not a very common use case, but we still
9546      re-evaluate expression, to avoid surprises to the user.
9547
9548      Note that for local watchpoints, we re-evaluate it only if
9549      watchpoints frame id is still valid.  If it's not, it means the
9550      watchpoint is out of scope and will be deleted soon.  In fact,
9551      I'm not sure we'll ever be called in this case.
9552
9553      If a local watchpoint's frame id is still valid, then
9554      w->exp_valid_block is likewise valid, and we can safely use it.
9555
9556      Don't do anything about disabled watchpoints, since they will be
9557      reevaluated again when enabled.  */
9558   update_watchpoint (w, 1 /* reparse */);
9559 }
9560
9561 /* Implement the "insert" breakpoint_ops method for hardware watchpoints.  */
9562
9563 static int
9564 insert_watchpoint (struct bp_location *bl)
9565 {
9566   struct watchpoint *w = (struct watchpoint *) bl->owner;
9567   int length = w->exact ? 1 : bl->length;
9568
9569   return target_insert_watchpoint (bl->address, length, bl->watchpoint_type,
9570                                    w->cond_exp);
9571 }
9572
9573 /* Implement the "remove" breakpoint_ops method for hardware watchpoints.  */
9574
9575 static int
9576 remove_watchpoint (struct bp_location *bl)
9577 {
9578   struct watchpoint *w = (struct watchpoint *) bl->owner;
9579   int length = w->exact ? 1 : bl->length;
9580
9581   return target_remove_watchpoint (bl->address, length, bl->watchpoint_type,
9582                                    w->cond_exp);
9583 }
9584
9585 static int
9586 breakpoint_hit_watchpoint (const struct bp_location *bl,
9587                            struct address_space *aspace, CORE_ADDR bp_addr,
9588                            const struct target_waitstatus *ws)
9589 {
9590   struct breakpoint *b = bl->owner;
9591   struct watchpoint *w = (struct watchpoint *) b;
9592
9593   /* Continuable hardware watchpoints are treated as non-existent if the
9594      reason we stopped wasn't a hardware watchpoint (we didn't stop on
9595      some data address).  Otherwise gdb won't stop on a break instruction
9596      in the code (not from a breakpoint) when a hardware watchpoint has
9597      been defined.  Also skip watchpoints which we know did not trigger
9598      (did not match the data address).  */
9599   if (is_hardware_watchpoint (b)
9600       && w->watchpoint_triggered == watch_triggered_no)
9601     return 0;
9602
9603   return 1;
9604 }
9605
9606 static void
9607 check_status_watchpoint (bpstat bs)
9608 {
9609   gdb_assert (is_watchpoint (bs->breakpoint_at));
9610
9611   bpstat_check_watchpoint (bs);
9612 }
9613
9614 /* Implement the "resources_needed" breakpoint_ops method for
9615    hardware watchpoints.  */
9616
9617 static int
9618 resources_needed_watchpoint (const struct bp_location *bl)
9619 {
9620   struct watchpoint *w = (struct watchpoint *) bl->owner;
9621   int length = w->exact? 1 : bl->length;
9622
9623   return target_region_ok_for_hw_watchpoint (bl->address, length);
9624 }
9625
9626 /* Implement the "works_in_software_mode" breakpoint_ops method for
9627    hardware watchpoints.  */
9628
9629 static int
9630 works_in_software_mode_watchpoint (const struct breakpoint *b)
9631 {
9632   /* Read and access watchpoints only work with hardware support.  */
9633   return b->type == bp_watchpoint || b->type == bp_hardware_watchpoint;
9634 }
9635
9636 static enum print_stop_action
9637 print_it_watchpoint (bpstat bs)
9638 {
9639   struct cleanup *old_chain;
9640   struct breakpoint *b;
9641   const struct bp_location *bl;
9642   struct ui_stream *stb;
9643   enum print_stop_action result;
9644   struct watchpoint *w;
9645   struct ui_out *uiout = current_uiout;
9646
9647   gdb_assert (bs->bp_location_at != NULL);
9648
9649   bl = bs->bp_location_at;
9650   b = bs->breakpoint_at;
9651   w = (struct watchpoint *) b;
9652
9653   stb = ui_out_stream_new (uiout);
9654   old_chain = make_cleanup_ui_out_stream_delete (stb);
9655
9656   switch (b->type)
9657     {
9658     case bp_watchpoint:
9659     case bp_hardware_watchpoint:
9660       annotate_watchpoint (b->number);
9661       if (ui_out_is_mi_like_p (uiout))
9662         ui_out_field_string
9663           (uiout, "reason",
9664            async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
9665       mention (b);
9666       make_cleanup_ui_out_tuple_begin_end (uiout, "value");
9667       ui_out_text (uiout, "\nOld value = ");
9668       watchpoint_value_print (bs->old_val, stb->stream);
9669       ui_out_field_stream (uiout, "old", stb);
9670       ui_out_text (uiout, "\nNew value = ");
9671       watchpoint_value_print (w->val, stb->stream);
9672       ui_out_field_stream (uiout, "new", stb);
9673       ui_out_text (uiout, "\n");
9674       /* More than one watchpoint may have been triggered.  */
9675       result = PRINT_UNKNOWN;
9676       break;
9677
9678     case bp_read_watchpoint:
9679       if (ui_out_is_mi_like_p (uiout))
9680         ui_out_field_string
9681           (uiout, "reason",
9682            async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
9683       mention (b);
9684       make_cleanup_ui_out_tuple_begin_end (uiout, "value");
9685       ui_out_text (uiout, "\nValue = ");
9686       watchpoint_value_print (w->val, stb->stream);
9687       ui_out_field_stream (uiout, "value", stb);
9688       ui_out_text (uiout, "\n");
9689       result = PRINT_UNKNOWN;
9690       break;
9691
9692     case bp_access_watchpoint:
9693       if (bs->old_val != NULL)
9694         {
9695           annotate_watchpoint (b->number);
9696           if (ui_out_is_mi_like_p (uiout))
9697             ui_out_field_string
9698               (uiout, "reason",
9699                async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
9700           mention (b);
9701           make_cleanup_ui_out_tuple_begin_end (uiout, "value");
9702           ui_out_text (uiout, "\nOld value = ");
9703           watchpoint_value_print (bs->old_val, stb->stream);
9704           ui_out_field_stream (uiout, "old", stb);
9705           ui_out_text (uiout, "\nNew value = ");
9706         }
9707       else
9708         {
9709           mention (b);
9710           if (ui_out_is_mi_like_p (uiout))
9711             ui_out_field_string
9712               (uiout, "reason",
9713                async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
9714           make_cleanup_ui_out_tuple_begin_end (uiout, "value");
9715           ui_out_text (uiout, "\nValue = ");
9716         }
9717       watchpoint_value_print (w->val, stb->stream);
9718       ui_out_field_stream (uiout, "new", stb);
9719       ui_out_text (uiout, "\n");
9720       result = PRINT_UNKNOWN;
9721       break;
9722     default:
9723       result = PRINT_UNKNOWN;
9724     }
9725
9726   do_cleanups (old_chain);
9727   return result;
9728 }
9729
9730 /* Implement the "print_mention" breakpoint_ops method for hardware
9731    watchpoints.  */
9732
9733 static void
9734 print_mention_watchpoint (struct breakpoint *b)
9735 {
9736   struct cleanup *ui_out_chain;
9737   struct watchpoint *w = (struct watchpoint *) b;
9738   struct ui_out *uiout = current_uiout;
9739
9740   switch (b->type)
9741     {
9742     case bp_watchpoint:
9743       ui_out_text (uiout, "Watchpoint ");
9744       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "wpt");
9745       break;
9746     case bp_hardware_watchpoint:
9747       ui_out_text (uiout, "Hardware watchpoint ");
9748       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "wpt");
9749       break;
9750     case bp_read_watchpoint:
9751       ui_out_text (uiout, "Hardware read watchpoint ");
9752       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-rwpt");
9753       break;
9754     case bp_access_watchpoint:
9755       ui_out_text (uiout, "Hardware access (read/write) watchpoint ");
9756       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-awpt");
9757       break;
9758     default:
9759       internal_error (__FILE__, __LINE__,
9760                       _("Invalid hardware watchpoint type."));
9761     }
9762
9763   ui_out_field_int (uiout, "number", b->number);
9764   ui_out_text (uiout, ": ");
9765   ui_out_field_string (uiout, "exp", w->exp_string);
9766   do_cleanups (ui_out_chain);
9767 }
9768
9769 /* Implement the "print_recreate" breakpoint_ops method for
9770    watchpoints.  */
9771
9772 static void
9773 print_recreate_watchpoint (struct breakpoint *b, struct ui_file *fp)
9774 {
9775   struct watchpoint *w = (struct watchpoint *) b;
9776
9777   switch (b->type)
9778     {
9779     case bp_watchpoint:
9780     case bp_hardware_watchpoint:
9781       fprintf_unfiltered (fp, "watch");
9782       break;
9783     case bp_read_watchpoint:
9784       fprintf_unfiltered (fp, "rwatch");
9785       break;
9786     case bp_access_watchpoint:
9787       fprintf_unfiltered (fp, "awatch");
9788       break;
9789     default:
9790       internal_error (__FILE__, __LINE__,
9791                       _("Invalid watchpoint type."));
9792     }
9793
9794   fprintf_unfiltered (fp, " %s", w->exp_string);
9795   print_recreate_thread (b, fp);
9796 }
9797
9798 /* The breakpoint_ops structure to be used in hardware watchpoints.  */
9799
9800 static struct breakpoint_ops watchpoint_breakpoint_ops;
9801
9802 /* Implement the "insert" breakpoint_ops method for
9803    masked hardware watchpoints.  */
9804
9805 static int
9806 insert_masked_watchpoint (struct bp_location *bl)
9807 {
9808   struct watchpoint *w = (struct watchpoint *) bl->owner;
9809
9810   return target_insert_mask_watchpoint (bl->address, w->hw_wp_mask,
9811                                         bl->watchpoint_type);
9812 }
9813
9814 /* Implement the "remove" breakpoint_ops method for
9815    masked hardware watchpoints.  */
9816
9817 static int
9818 remove_masked_watchpoint (struct bp_location *bl)
9819 {
9820   struct watchpoint *w = (struct watchpoint *) bl->owner;
9821
9822   return target_remove_mask_watchpoint (bl->address, w->hw_wp_mask,
9823                                         bl->watchpoint_type);
9824 }
9825
9826 /* Implement the "resources_needed" breakpoint_ops method for
9827    masked hardware watchpoints.  */
9828
9829 static int
9830 resources_needed_masked_watchpoint (const struct bp_location *bl)
9831 {
9832   struct watchpoint *w = (struct watchpoint *) bl->owner;
9833
9834   return target_masked_watch_num_registers (bl->address, w->hw_wp_mask);
9835 }
9836
9837 /* Implement the "works_in_software_mode" breakpoint_ops method for
9838    masked hardware watchpoints.  */
9839
9840 static int
9841 works_in_software_mode_masked_watchpoint (const struct breakpoint *b)
9842 {
9843   return 0;
9844 }
9845
9846 /* Implement the "print_it" breakpoint_ops method for
9847    masked hardware watchpoints.  */
9848
9849 static enum print_stop_action
9850 print_it_masked_watchpoint (bpstat bs)
9851 {
9852   struct breakpoint *b = bs->breakpoint_at;
9853   struct ui_out *uiout = current_uiout;
9854
9855   /* Masked watchpoints have only one location.  */
9856   gdb_assert (b->loc && b->loc->next == NULL);
9857
9858   switch (b->type)
9859     {
9860     case bp_hardware_watchpoint:
9861       annotate_watchpoint (b->number);
9862       if (ui_out_is_mi_like_p (uiout))
9863         ui_out_field_string
9864           (uiout, "reason",
9865            async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
9866       break;
9867
9868     case bp_read_watchpoint:
9869       if (ui_out_is_mi_like_p (uiout))
9870         ui_out_field_string
9871           (uiout, "reason",
9872            async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
9873       break;
9874
9875     case bp_access_watchpoint:
9876       if (ui_out_is_mi_like_p (uiout))
9877         ui_out_field_string
9878           (uiout, "reason",
9879            async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
9880       break;
9881     default:
9882       internal_error (__FILE__, __LINE__,
9883                       _("Invalid hardware watchpoint type."));
9884     }
9885
9886   mention (b);
9887   ui_out_text (uiout, _("\n\
9888 Check the underlying instruction at PC for the memory\n\
9889 address and value which triggered this watchpoint.\n"));
9890   ui_out_text (uiout, "\n");
9891
9892   /* More than one watchpoint may have been triggered.  */
9893   return PRINT_UNKNOWN;
9894 }
9895
9896 /* Implement the "print_one_detail" breakpoint_ops method for
9897    masked hardware watchpoints.  */
9898
9899 static void
9900 print_one_detail_masked_watchpoint (const struct breakpoint *b,
9901                                     struct ui_out *uiout)
9902 {
9903   struct watchpoint *w = (struct watchpoint *) b;
9904
9905   /* Masked watchpoints have only one location.  */
9906   gdb_assert (b->loc && b->loc->next == NULL);
9907
9908   ui_out_text (uiout, "\tmask ");
9909   ui_out_field_core_addr (uiout, "mask", b->loc->gdbarch, w->hw_wp_mask);
9910   ui_out_text (uiout, "\n");
9911 }
9912
9913 /* Implement the "print_mention" breakpoint_ops method for
9914    masked hardware watchpoints.  */
9915
9916 static void
9917 print_mention_masked_watchpoint (struct breakpoint *b)
9918 {
9919   struct watchpoint *w = (struct watchpoint *) b;
9920   struct ui_out *uiout = current_uiout;
9921   struct cleanup *ui_out_chain;
9922
9923   switch (b->type)
9924     {
9925     case bp_hardware_watchpoint:
9926       ui_out_text (uiout, "Masked hardware watchpoint ");
9927       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "wpt");
9928       break;
9929     case bp_read_watchpoint:
9930       ui_out_text (uiout, "Masked hardware read watchpoint ");
9931       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-rwpt");
9932       break;
9933     case bp_access_watchpoint:
9934       ui_out_text (uiout, "Masked hardware access (read/write) watchpoint ");
9935       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-awpt");
9936       break;
9937     default:
9938       internal_error (__FILE__, __LINE__,
9939                       _("Invalid hardware watchpoint type."));
9940     }
9941
9942   ui_out_field_int (uiout, "number", b->number);
9943   ui_out_text (uiout, ": ");
9944   ui_out_field_string (uiout, "exp", w->exp_string);
9945   do_cleanups (ui_out_chain);
9946 }
9947
9948 /* Implement the "print_recreate" breakpoint_ops method for
9949    masked hardware watchpoints.  */
9950
9951 static void
9952 print_recreate_masked_watchpoint (struct breakpoint *b, struct ui_file *fp)
9953 {
9954   struct watchpoint *w = (struct watchpoint *) b;
9955   char tmp[40];
9956
9957   switch (b->type)
9958     {
9959     case bp_hardware_watchpoint:
9960       fprintf_unfiltered (fp, "watch");
9961       break;
9962     case bp_read_watchpoint:
9963       fprintf_unfiltered (fp, "rwatch");
9964       break;
9965     case bp_access_watchpoint:
9966       fprintf_unfiltered (fp, "awatch");
9967       break;
9968     default:
9969       internal_error (__FILE__, __LINE__,
9970                       _("Invalid hardware watchpoint type."));
9971     }
9972
9973   sprintf_vma (tmp, w->hw_wp_mask);
9974   fprintf_unfiltered (fp, " %s mask 0x%s", w->exp_string, tmp);
9975   print_recreate_thread (b, fp);
9976 }
9977
9978 /* The breakpoint_ops structure to be used in masked hardware watchpoints.  */
9979
9980 static struct breakpoint_ops masked_watchpoint_breakpoint_ops;
9981
9982 /* Tell whether the given watchpoint is a masked hardware watchpoint.  */
9983
9984 static int
9985 is_masked_watchpoint (const struct breakpoint *b)
9986 {
9987   return b->ops == &masked_watchpoint_breakpoint_ops;
9988 }
9989
9990 /* accessflag:  hw_write:  watch write, 
9991                 hw_read:   watch read, 
9992                 hw_access: watch access (read or write) */
9993 static void
9994 watch_command_1 (char *arg, int accessflag, int from_tty,
9995                  int just_location, int internal)
9996 {
9997   volatile struct gdb_exception e;
9998   struct breakpoint *b, *scope_breakpoint = NULL;
9999   struct expression *exp;
10000   struct block *exp_valid_block = NULL, *cond_exp_valid_block = NULL;
10001   struct value *val, *mark, *result;
10002   struct frame_info *frame;
10003   char *exp_start = NULL;
10004   char *exp_end = NULL;
10005   char *tok, *end_tok;
10006   int toklen = -1;
10007   char *cond_start = NULL;
10008   char *cond_end = NULL;
10009   enum bptype bp_type;
10010   int thread = -1;
10011   int pc = 0;
10012   /* Flag to indicate whether we are going to use masks for
10013      the hardware watchpoint.  */
10014   int use_mask = 0;
10015   CORE_ADDR mask = 0;
10016   struct watchpoint *w;
10017
10018   /* Make sure that we actually have parameters to parse.  */
10019   if (arg != NULL && arg[0] != '\0')
10020     {
10021       char *value_start;
10022
10023       /* Look for "parameter value" pairs at the end
10024          of the arguments string.  */
10025       for (tok = arg + strlen (arg) - 1; tok > arg; tok--)
10026         {
10027           /* Skip whitespace at the end of the argument list.  */
10028           while (tok > arg && (*tok == ' ' || *tok == '\t'))
10029             tok--;
10030
10031           /* Find the beginning of the last token.
10032              This is the value of the parameter.  */
10033           while (tok > arg && (*tok != ' ' && *tok != '\t'))
10034             tok--;
10035           value_start = tok + 1;
10036
10037           /* Skip whitespace.  */
10038           while (tok > arg && (*tok == ' ' || *tok == '\t'))
10039             tok--;
10040
10041           end_tok = tok;
10042
10043           /* Find the beginning of the second to last token.
10044              This is the parameter itself.  */
10045           while (tok > arg && (*tok != ' ' && *tok != '\t'))
10046             tok--;
10047           tok++;
10048           toklen = end_tok - tok + 1;
10049
10050           if (toklen == 6 && !strncmp (tok, "thread", 6))
10051             {
10052               /* At this point we've found a "thread" token, which means
10053                  the user is trying to set a watchpoint that triggers
10054                  only in a specific thread.  */
10055               char *endp;
10056
10057               if (thread != -1)
10058                 error(_("You can specify only one thread."));
10059
10060               /* Extract the thread ID from the next token.  */
10061               thread = strtol (value_start, &endp, 0);
10062
10063               /* Check if the user provided a valid numeric value for the
10064                  thread ID.  */
10065               if (*endp != ' ' && *endp != '\t' && *endp != '\0')
10066                 error (_("Invalid thread ID specification %s."), value_start);
10067
10068               /* Check if the thread actually exists.  */
10069               if (!valid_thread_id (thread))
10070                 error (_("Unknown thread %d."), thread);
10071             }
10072           else if (toklen == 4 && !strncmp (tok, "mask", 4))
10073             {
10074               /* We've found a "mask" token, which means the user wants to
10075                  create a hardware watchpoint that is going to have the mask
10076                  facility.  */
10077               struct value *mask_value, *mark;
10078
10079               if (use_mask)
10080                 error(_("You can specify only one mask."));
10081
10082               use_mask = just_location = 1;
10083
10084               mark = value_mark ();
10085               mask_value = parse_to_comma_and_eval (&value_start);
10086               mask = value_as_address (mask_value);
10087               value_free_to_mark (mark);
10088             }
10089           else
10090             /* We didn't recognize what we found.  We should stop here.  */
10091             break;
10092
10093           /* Truncate the string and get rid of the "parameter value" pair before
10094              the arguments string is parsed by the parse_exp_1 function.  */
10095           *tok = '\0';
10096         }
10097     }
10098
10099   /* Parse the rest of the arguments.  */
10100   innermost_block = NULL;
10101   exp_start = arg;
10102   exp = parse_exp_1 (&arg, 0, 0);
10103   exp_end = arg;
10104   /* Remove trailing whitespace from the expression before saving it.
10105      This makes the eventual display of the expression string a bit
10106      prettier.  */
10107   while (exp_end > exp_start && (exp_end[-1] == ' ' || exp_end[-1] == '\t'))
10108     --exp_end;
10109
10110   /* Checking if the expression is not constant.  */
10111   if (watchpoint_exp_is_const (exp))
10112     {
10113       int len;
10114
10115       len = exp_end - exp_start;
10116       while (len > 0 && isspace (exp_start[len - 1]))
10117         len--;
10118       error (_("Cannot watch constant value `%.*s'."), len, exp_start);
10119     }
10120
10121   exp_valid_block = innermost_block;
10122   mark = value_mark ();
10123   fetch_subexp_value (exp, &pc, &val, &result, NULL);
10124
10125   if (just_location)
10126     {
10127       int ret;
10128
10129       exp_valid_block = NULL;
10130       val = value_addr (result);
10131       release_value (val);
10132       value_free_to_mark (mark);
10133
10134       if (use_mask)
10135         {
10136           ret = target_masked_watch_num_registers (value_as_address (val),
10137                                                    mask);
10138           if (ret == -1)
10139             error (_("This target does not support masked watchpoints."));
10140           else if (ret == -2)
10141             error (_("Invalid mask or memory region."));
10142         }
10143     }
10144   else if (val != NULL)
10145     release_value (val);
10146
10147   tok = skip_spaces (arg);
10148   end_tok = skip_to_space (tok);
10149
10150   toklen = end_tok - tok;
10151   if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
10152     {
10153       struct expression *cond;
10154
10155       innermost_block = NULL;
10156       tok = cond_start = end_tok + 1;
10157       cond = parse_exp_1 (&tok, 0, 0);
10158
10159       /* The watchpoint expression may not be local, but the condition
10160          may still be.  E.g.: `watch global if local > 0'.  */
10161       cond_exp_valid_block = innermost_block;
10162
10163       xfree (cond);
10164       cond_end = tok;
10165     }
10166   if (*tok)
10167     error (_("Junk at end of command."));
10168
10169   if (accessflag == hw_read)
10170     bp_type = bp_read_watchpoint;
10171   else if (accessflag == hw_access)
10172     bp_type = bp_access_watchpoint;
10173   else
10174     bp_type = bp_hardware_watchpoint;
10175
10176   frame = block_innermost_frame (exp_valid_block);
10177
10178   /* If the expression is "local", then set up a "watchpoint scope"
10179      breakpoint at the point where we've left the scope of the watchpoint
10180      expression.  Create the scope breakpoint before the watchpoint, so
10181      that we will encounter it first in bpstat_stop_status.  */
10182   if (exp_valid_block && frame)
10183     {
10184       if (frame_id_p (frame_unwind_caller_id (frame)))
10185         {
10186           scope_breakpoint
10187             = create_internal_breakpoint (frame_unwind_caller_arch (frame),
10188                                           frame_unwind_caller_pc (frame),
10189                                           bp_watchpoint_scope,
10190                                           &momentary_breakpoint_ops);
10191
10192           scope_breakpoint->enable_state = bp_enabled;
10193
10194           /* Automatically delete the breakpoint when it hits.  */
10195           scope_breakpoint->disposition = disp_del;
10196
10197           /* Only break in the proper frame (help with recursion).  */
10198           scope_breakpoint->frame_id = frame_unwind_caller_id (frame);
10199
10200           /* Set the address at which we will stop.  */
10201           scope_breakpoint->loc->gdbarch
10202             = frame_unwind_caller_arch (frame);
10203           scope_breakpoint->loc->requested_address
10204             = frame_unwind_caller_pc (frame);
10205           scope_breakpoint->loc->address
10206             = adjust_breakpoint_address (scope_breakpoint->loc->gdbarch,
10207                                          scope_breakpoint->loc->requested_address,
10208                                          scope_breakpoint->type);
10209         }
10210     }
10211
10212   /* Now set up the breakpoint.  */
10213
10214   w = XCNEW (struct watchpoint);
10215   b = &w->base;
10216   if (use_mask)
10217     init_raw_breakpoint_without_location (b, NULL, bp_type,
10218                                           &masked_watchpoint_breakpoint_ops);
10219   else
10220     init_raw_breakpoint_without_location (b, NULL, bp_type,
10221                                           &watchpoint_breakpoint_ops);
10222   b->thread = thread;
10223   b->disposition = disp_donttouch;
10224   b->pspace = current_program_space;
10225   w->exp = exp;
10226   w->exp_valid_block = exp_valid_block;
10227   w->cond_exp_valid_block = cond_exp_valid_block;
10228   if (just_location)
10229     {
10230       struct type *t = value_type (val);
10231       CORE_ADDR addr = value_as_address (val);
10232       char *name;
10233
10234       t = check_typedef (TYPE_TARGET_TYPE (check_typedef (t)));
10235       name = type_to_string (t);
10236
10237       w->exp_string_reparse = xstrprintf ("* (%s *) %s", name,
10238                                           core_addr_to_string (addr));
10239       xfree (name);
10240
10241       w->exp_string = xstrprintf ("-location %.*s",
10242                                   (int) (exp_end - exp_start), exp_start);
10243
10244       /* The above expression is in C.  */
10245       b->language = language_c;
10246     }
10247   else
10248     w->exp_string = savestring (exp_start, exp_end - exp_start);
10249
10250   if (use_mask)
10251     {
10252       w->hw_wp_mask = mask;
10253     }
10254   else
10255     {
10256       w->val = val;
10257       w->val_valid = 1;
10258     }
10259
10260   if (cond_start)
10261     b->cond_string = savestring (cond_start, cond_end - cond_start);
10262   else
10263     b->cond_string = 0;
10264
10265   if (frame)
10266     {
10267       w->watchpoint_frame = get_frame_id (frame);
10268       w->watchpoint_thread = inferior_ptid;
10269     }
10270   else
10271     {
10272       w->watchpoint_frame = null_frame_id;
10273       w->watchpoint_thread = null_ptid;
10274     }
10275
10276   if (scope_breakpoint != NULL)
10277     {
10278       /* The scope breakpoint is related to the watchpoint.  We will
10279          need to act on them together.  */
10280       b->related_breakpoint = scope_breakpoint;
10281       scope_breakpoint->related_breakpoint = b;
10282     }
10283
10284   if (!just_location)
10285     value_free_to_mark (mark);
10286
10287   TRY_CATCH (e, RETURN_MASK_ALL)
10288     {
10289       /* Finally update the new watchpoint.  This creates the locations
10290          that should be inserted.  */
10291       update_watchpoint (w, 1);
10292     }
10293   if (e.reason < 0)
10294     {
10295       delete_breakpoint (b);
10296       throw_exception (e);
10297     }
10298
10299   install_breakpoint (internal, b, 1);
10300 }
10301
10302 /* Return count of debug registers needed to watch the given expression.
10303    If the watchpoint cannot be handled in hardware return zero.  */
10304
10305 static int
10306 can_use_hardware_watchpoint (struct value *v)
10307 {
10308   int found_memory_cnt = 0;
10309   struct value *head = v;
10310
10311   /* Did the user specifically forbid us to use hardware watchpoints? */
10312   if (!can_use_hw_watchpoints)
10313     return 0;
10314
10315   /* Make sure that the value of the expression depends only upon
10316      memory contents, and values computed from them within GDB.  If we
10317      find any register references or function calls, we can't use a
10318      hardware watchpoint.
10319
10320      The idea here is that evaluating an expression generates a series
10321      of values, one holding the value of every subexpression.  (The
10322      expression a*b+c has five subexpressions: a, b, a*b, c, and
10323      a*b+c.)  GDB's values hold almost enough information to establish
10324      the criteria given above --- they identify memory lvalues,
10325      register lvalues, computed values, etcetera.  So we can evaluate
10326      the expression, and then scan the chain of values that leaves
10327      behind to decide whether we can detect any possible change to the
10328      expression's final value using only hardware watchpoints.
10329
10330      However, I don't think that the values returned by inferior
10331      function calls are special in any way.  So this function may not
10332      notice that an expression involving an inferior function call
10333      can't be watched with hardware watchpoints.  FIXME.  */
10334   for (; v; v = value_next (v))
10335     {
10336       if (VALUE_LVAL (v) == lval_memory)
10337         {
10338           if (v != head && value_lazy (v))
10339             /* A lazy memory lvalue in the chain is one that GDB never
10340                needed to fetch; we either just used its address (e.g.,
10341                `a' in `a.b') or we never needed it at all (e.g., `a'
10342                in `a,b').  This doesn't apply to HEAD; if that is
10343                lazy then it was not readable, but watch it anyway.  */
10344             ;
10345           else
10346             {
10347               /* Ahh, memory we actually used!  Check if we can cover
10348                  it with hardware watchpoints.  */
10349               struct type *vtype = check_typedef (value_type (v));
10350
10351               /* We only watch structs and arrays if user asked for it
10352                  explicitly, never if they just happen to appear in a
10353                  middle of some value chain.  */
10354               if (v == head
10355                   || (TYPE_CODE (vtype) != TYPE_CODE_STRUCT
10356                       && TYPE_CODE (vtype) != TYPE_CODE_ARRAY))
10357                 {
10358                   CORE_ADDR vaddr = value_address (v);
10359                   int len;
10360                   int num_regs;
10361
10362                   len = (target_exact_watchpoints
10363                          && is_scalar_type_recursive (vtype))?
10364                     1 : TYPE_LENGTH (value_type (v));
10365
10366                   num_regs = target_region_ok_for_hw_watchpoint (vaddr, len);
10367                   if (!num_regs)
10368                     return 0;
10369                   else
10370                     found_memory_cnt += num_regs;
10371                 }
10372             }
10373         }
10374       else if (VALUE_LVAL (v) != not_lval
10375                && deprecated_value_modifiable (v) == 0)
10376         return 0;       /* These are values from the history (e.g., $1).  */
10377       else if (VALUE_LVAL (v) == lval_register)
10378         return 0;       /* Cannot watch a register with a HW watchpoint.  */
10379     }
10380
10381   /* The expression itself looks suitable for using a hardware
10382      watchpoint, but give the target machine a chance to reject it.  */
10383   return found_memory_cnt;
10384 }
10385
10386 void
10387 watch_command_wrapper (char *arg, int from_tty, int internal)
10388 {
10389   watch_command_1 (arg, hw_write, from_tty, 0, internal);
10390 }
10391
10392 /* A helper function that looks for an argument at the start of a
10393    string.  The argument must also either be at the end of the string,
10394    or be followed by whitespace.  Returns 1 if it finds the argument,
10395    0 otherwise.  If the argument is found, it updates *STR.  */
10396
10397 static int
10398 check_for_argument (char **str, char *arg, int arg_len)
10399 {
10400   if (strncmp (*str, arg, arg_len) == 0
10401       && ((*str)[arg_len] == '\0' || isspace ((*str)[arg_len])))
10402     {
10403       *str += arg_len;
10404       return 1;
10405     }
10406   return 0;
10407 }
10408
10409 /* A helper function that looks for the "-location" argument and then
10410    calls watch_command_1.  */
10411
10412 static void
10413 watch_maybe_just_location (char *arg, int accessflag, int from_tty)
10414 {
10415   int just_location = 0;
10416
10417   if (arg
10418       && (check_for_argument (&arg, "-location", sizeof ("-location") - 1)
10419           || check_for_argument (&arg, "-l", sizeof ("-l") - 1)))
10420     {
10421       arg = skip_spaces (arg);
10422       just_location = 1;
10423     }
10424
10425   watch_command_1 (arg, accessflag, from_tty, just_location, 0);
10426 }
10427
10428 static void
10429 watch_command (char *arg, int from_tty)
10430 {
10431   watch_maybe_just_location (arg, hw_write, from_tty);
10432 }
10433
10434 void
10435 rwatch_command_wrapper (char *arg, int from_tty, int internal)
10436 {
10437   watch_command_1 (arg, hw_read, from_tty, 0, internal);
10438 }
10439
10440 static void
10441 rwatch_command (char *arg, int from_tty)
10442 {
10443   watch_maybe_just_location (arg, hw_read, from_tty);
10444 }
10445
10446 void
10447 awatch_command_wrapper (char *arg, int from_tty, int internal)
10448 {
10449   watch_command_1 (arg, hw_access, from_tty, 0, internal);
10450 }
10451
10452 static void
10453 awatch_command (char *arg, int from_tty)
10454 {
10455   watch_maybe_just_location (arg, hw_access, from_tty);
10456 }
10457 \f
10458
10459 /* Helper routines for the until_command routine in infcmd.c.  Here
10460    because it uses the mechanisms of breakpoints.  */
10461
10462 struct until_break_command_continuation_args
10463 {
10464   struct breakpoint *breakpoint;
10465   struct breakpoint *breakpoint2;
10466   int thread_num;
10467 };
10468
10469 /* This function is called by fetch_inferior_event via the
10470    cmd_continuation pointer, to complete the until command.  It takes
10471    care of cleaning up the temporary breakpoints set up by the until
10472    command.  */
10473 static void
10474 until_break_command_continuation (void *arg, int err)
10475 {
10476   struct until_break_command_continuation_args *a = arg;
10477
10478   delete_breakpoint (a->breakpoint);
10479   if (a->breakpoint2)
10480     delete_breakpoint (a->breakpoint2);
10481   delete_longjmp_breakpoint (a->thread_num);
10482 }
10483
10484 void
10485 until_break_command (char *arg, int from_tty, int anywhere)
10486 {
10487   struct symtabs_and_lines sals;
10488   struct symtab_and_line sal;
10489   struct frame_info *frame = get_selected_frame (NULL);
10490   struct gdbarch *frame_gdbarch = get_frame_arch (frame);
10491   struct frame_id stack_frame_id = get_stack_frame_id (frame);
10492   struct frame_id caller_frame_id = frame_unwind_caller_id (frame);
10493   struct breakpoint *breakpoint;
10494   struct breakpoint *breakpoint2 = NULL;
10495   struct cleanup *old_chain;
10496   int thread;
10497   struct thread_info *tp;
10498
10499   clear_proceed_status ();
10500
10501   /* Set a breakpoint where the user wants it and at return from
10502      this function.  */
10503
10504   if (last_displayed_sal_is_valid ())
10505     sals = decode_line_1 (&arg, DECODE_LINE_FUNFIRSTLINE,
10506                           get_last_displayed_symtab (),
10507                           get_last_displayed_line ());
10508   else
10509     sals = decode_line_1 (&arg, DECODE_LINE_FUNFIRSTLINE,
10510                           (struct symtab *) NULL, 0);
10511
10512   if (sals.nelts != 1)
10513     error (_("Couldn't get information on specified line."));
10514
10515   sal = sals.sals[0];
10516   xfree (sals.sals);    /* malloc'd, so freed.  */
10517
10518   if (*arg)
10519     error (_("Junk at end of arguments."));
10520
10521   resolve_sal_pc (&sal);
10522
10523   tp = inferior_thread ();
10524   thread = tp->num;
10525
10526   old_chain = make_cleanup (null_cleanup, NULL);
10527
10528   /* Installing a breakpoint invalidates the frame chain (as it may
10529      need to switch threads), so do any frame handling first.  */
10530
10531   /* Keep within the current frame, or in frames called by the current
10532      one.  */
10533
10534   if (frame_id_p (caller_frame_id))
10535     {
10536       struct symtab_and_line sal2;
10537
10538       sal2 = find_pc_line (frame_unwind_caller_pc (frame), 0);
10539       sal2.pc = frame_unwind_caller_pc (frame);
10540       breakpoint2 = set_momentary_breakpoint (frame_unwind_caller_arch (frame),
10541                                               sal2,
10542                                               caller_frame_id,
10543                                               bp_until);
10544       make_cleanup_delete_breakpoint (breakpoint2);
10545
10546       set_longjmp_breakpoint (tp, caller_frame_id);
10547       make_cleanup (delete_longjmp_breakpoint_cleanup, &thread);
10548     }
10549
10550   /* set_momentary_breakpoint could invalidate FRAME.  */
10551   frame = NULL;
10552
10553   if (anywhere)
10554     /* If the user told us to continue until a specified location,
10555        we don't specify a frame at which we need to stop.  */
10556     breakpoint = set_momentary_breakpoint (frame_gdbarch, sal,
10557                                            null_frame_id, bp_until);
10558   else
10559     /* Otherwise, specify the selected frame, because we want to stop
10560        only at the very same frame.  */
10561     breakpoint = set_momentary_breakpoint (frame_gdbarch, sal,
10562                                            stack_frame_id, bp_until);
10563   make_cleanup_delete_breakpoint (breakpoint);
10564
10565   proceed (-1, TARGET_SIGNAL_DEFAULT, 0);
10566
10567   /* If we are running asynchronously, and proceed call above has
10568      actually managed to start the target, arrange for breakpoints to
10569      be deleted when the target stops.  Otherwise, we're already
10570      stopped and delete breakpoints via cleanup chain.  */
10571
10572   if (target_can_async_p () && is_running (inferior_ptid))
10573     {
10574       struct until_break_command_continuation_args *args;
10575       args = xmalloc (sizeof (*args));
10576
10577       args->breakpoint = breakpoint;
10578       args->breakpoint2 = breakpoint2;
10579       args->thread_num = thread;
10580
10581       discard_cleanups (old_chain);
10582       add_continuation (inferior_thread (),
10583                         until_break_command_continuation, args,
10584                         xfree);
10585     }
10586   else
10587     do_cleanups (old_chain);
10588 }
10589
10590 /* This function attempts to parse an optional "if <cond>" clause
10591    from the arg string.  If one is not found, it returns NULL.
10592
10593    Else, it returns a pointer to the condition string.  (It does not
10594    attempt to evaluate the string against a particular block.)  And,
10595    it updates arg to point to the first character following the parsed
10596    if clause in the arg string.  */
10597
10598 static char *
10599 ep_parse_optional_if_clause (char **arg)
10600 {
10601   char *cond_string;
10602
10603   if (((*arg)[0] != 'i') || ((*arg)[1] != 'f') || !isspace ((*arg)[2]))
10604     return NULL;
10605
10606   /* Skip the "if" keyword.  */
10607   (*arg) += 2;
10608
10609   /* Skip any extra leading whitespace, and record the start of the
10610      condition string.  */
10611   *arg = skip_spaces (*arg);
10612   cond_string = *arg;
10613
10614   /* Assume that the condition occupies the remainder of the arg
10615      string.  */
10616   (*arg) += strlen (cond_string);
10617
10618   return cond_string;
10619 }
10620
10621 /* Commands to deal with catching events, such as signals, exceptions,
10622    process start/exit, etc.  */
10623
10624 typedef enum
10625 {
10626   catch_fork_temporary, catch_vfork_temporary,
10627   catch_fork_permanent, catch_vfork_permanent
10628 }
10629 catch_fork_kind;
10630
10631 static void
10632 catch_fork_command_1 (char *arg, int from_tty, 
10633                       struct cmd_list_element *command)
10634 {
10635   struct gdbarch *gdbarch = get_current_arch ();
10636   char *cond_string = NULL;
10637   catch_fork_kind fork_kind;
10638   int tempflag;
10639
10640   fork_kind = (catch_fork_kind) (uintptr_t) get_cmd_context (command);
10641   tempflag = (fork_kind == catch_fork_temporary
10642               || fork_kind == catch_vfork_temporary);
10643
10644   if (!arg)
10645     arg = "";
10646   arg = skip_spaces (arg);
10647
10648   /* The allowed syntax is:
10649      catch [v]fork
10650      catch [v]fork if <cond>
10651
10652      First, check if there's an if clause.  */
10653   cond_string = ep_parse_optional_if_clause (&arg);
10654
10655   if ((*arg != '\0') && !isspace (*arg))
10656     error (_("Junk at end of arguments."));
10657
10658   /* If this target supports it, create a fork or vfork catchpoint
10659      and enable reporting of such events.  */
10660   switch (fork_kind)
10661     {
10662     case catch_fork_temporary:
10663     case catch_fork_permanent:
10664       create_fork_vfork_event_catchpoint (gdbarch, tempflag, cond_string,
10665                                           &catch_fork_breakpoint_ops);
10666       break;
10667     case catch_vfork_temporary:
10668     case catch_vfork_permanent:
10669       create_fork_vfork_event_catchpoint (gdbarch, tempflag, cond_string,
10670                                           &catch_vfork_breakpoint_ops);
10671       break;
10672     default:
10673       error (_("unsupported or unknown fork kind; cannot catch it"));
10674       break;
10675     }
10676 }
10677
10678 static void
10679 catch_exec_command_1 (char *arg, int from_tty, 
10680                       struct cmd_list_element *command)
10681 {
10682   struct exec_catchpoint *c;
10683   struct gdbarch *gdbarch = get_current_arch ();
10684   int tempflag;
10685   char *cond_string = NULL;
10686
10687   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
10688
10689   if (!arg)
10690     arg = "";
10691   arg = skip_spaces (arg);
10692
10693   /* The allowed syntax is:
10694      catch exec
10695      catch exec if <cond>
10696
10697      First, check if there's an if clause.  */
10698   cond_string = ep_parse_optional_if_clause (&arg);
10699
10700   if ((*arg != '\0') && !isspace (*arg))
10701     error (_("Junk at end of arguments."));
10702
10703   c = XNEW (struct exec_catchpoint);
10704   init_catchpoint (&c->base, gdbarch, tempflag, cond_string,
10705                    &catch_exec_breakpoint_ops);
10706   c->exec_pathname = NULL;
10707
10708   install_breakpoint (0, &c->base, 1);
10709 }
10710
10711 static enum print_stop_action
10712 print_it_exception_catchpoint (bpstat bs)
10713 {
10714   struct ui_out *uiout = current_uiout;
10715   struct breakpoint *b = bs->breakpoint_at;
10716   int bp_temp, bp_throw;
10717
10718   annotate_catchpoint (b->number);
10719
10720   bp_throw = strstr (b->addr_string, "throw") != NULL;
10721   if (b->loc->address != b->loc->requested_address)
10722     breakpoint_adjustment_warning (b->loc->requested_address,
10723                                    b->loc->address,
10724                                    b->number, 1);
10725   bp_temp = b->disposition == disp_del;
10726   ui_out_text (uiout, 
10727                bp_temp ? "Temporary catchpoint "
10728                        : "Catchpoint ");
10729   if (!ui_out_is_mi_like_p (uiout))
10730     ui_out_field_int (uiout, "bkptno", b->number);
10731   ui_out_text (uiout,
10732                bp_throw ? " (exception thrown), "
10733                         : " (exception caught), ");
10734   if (ui_out_is_mi_like_p (uiout))
10735     {
10736       ui_out_field_string (uiout, "reason", 
10737                            async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
10738       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
10739       ui_out_field_int (uiout, "bkptno", b->number);
10740     }
10741   return PRINT_SRC_AND_LOC;
10742 }
10743
10744 static void
10745 print_one_exception_catchpoint (struct breakpoint *b, 
10746                                 struct bp_location **last_loc)
10747 {
10748   struct value_print_options opts;
10749   struct ui_out *uiout = current_uiout;
10750
10751   get_user_print_options (&opts);
10752   if (opts.addressprint)
10753     {
10754       annotate_field (4);
10755       if (b->loc == NULL || b->loc->shlib_disabled)
10756         ui_out_field_string (uiout, "addr", "<PENDING>");
10757       else
10758         ui_out_field_core_addr (uiout, "addr",
10759                                 b->loc->gdbarch, b->loc->address);
10760     }
10761   annotate_field (5);
10762   if (b->loc)
10763     *last_loc = b->loc;
10764   if (strstr (b->addr_string, "throw") != NULL)
10765     ui_out_field_string (uiout, "what", "exception throw");
10766   else
10767     ui_out_field_string (uiout, "what", "exception catch");
10768 }
10769
10770 static void
10771 print_mention_exception_catchpoint (struct breakpoint *b)
10772 {
10773   struct ui_out *uiout = current_uiout;
10774   int bp_temp;
10775   int bp_throw;
10776
10777   bp_temp = b->disposition == disp_del;
10778   bp_throw = strstr (b->addr_string, "throw") != NULL;
10779   ui_out_text (uiout, bp_temp ? _("Temporary catchpoint ")
10780                               : _("Catchpoint "));
10781   ui_out_field_int (uiout, "bkptno", b->number);
10782   ui_out_text (uiout, bp_throw ? _(" (throw)")
10783                                : _(" (catch)"));
10784 }
10785
10786 /* Implement the "print_recreate" breakpoint_ops method for throw and
10787    catch catchpoints.  */
10788
10789 static void
10790 print_recreate_exception_catchpoint (struct breakpoint *b, 
10791                                      struct ui_file *fp)
10792 {
10793   int bp_temp;
10794   int bp_throw;
10795
10796   bp_temp = b->disposition == disp_del;
10797   bp_throw = strstr (b->addr_string, "throw") != NULL;
10798   fprintf_unfiltered (fp, bp_temp ? "tcatch " : "catch ");
10799   fprintf_unfiltered (fp, bp_throw ? "throw" : "catch");
10800   print_recreate_thread (b, fp);
10801 }
10802
10803 static struct breakpoint_ops gnu_v3_exception_catchpoint_ops;
10804
10805 static int
10806 handle_gnu_v3_exceptions (int tempflag, char *cond_string,
10807                           enum exception_event_kind ex_event, int from_tty)
10808 {
10809   char *trigger_func_name;
10810  
10811   if (ex_event == EX_EVENT_CATCH)
10812     trigger_func_name = "__cxa_begin_catch";
10813   else
10814     trigger_func_name = "__cxa_throw";
10815
10816   create_breakpoint (get_current_arch (),
10817                      trigger_func_name, cond_string, -1,
10818                      0 /* condition and thread are valid.  */,
10819                      tempflag, bp_breakpoint,
10820                      0,
10821                      AUTO_BOOLEAN_TRUE /* pending */,
10822                      &gnu_v3_exception_catchpoint_ops, from_tty,
10823                      1 /* enabled */,
10824                      0 /* internal */);
10825
10826   return 1;
10827 }
10828
10829 /* Deal with "catch catch" and "catch throw" commands.  */
10830
10831 static void
10832 catch_exception_command_1 (enum exception_event_kind ex_event, char *arg,
10833                            int tempflag, int from_tty)
10834 {
10835   char *cond_string = NULL;
10836
10837   if (!arg)
10838     arg = "";
10839   arg = skip_spaces (arg);
10840
10841   cond_string = ep_parse_optional_if_clause (&arg);
10842
10843   if ((*arg != '\0') && !isspace (*arg))
10844     error (_("Junk at end of arguments."));
10845
10846   if (ex_event != EX_EVENT_THROW
10847       && ex_event != EX_EVENT_CATCH)
10848     error (_("Unsupported or unknown exception event; cannot catch it"));
10849
10850   if (handle_gnu_v3_exceptions (tempflag, cond_string, ex_event, from_tty))
10851     return;
10852
10853   warning (_("Unsupported with this platform/compiler combination."));
10854 }
10855
10856 /* Implementation of "catch catch" command.  */
10857
10858 static void
10859 catch_catch_command (char *arg, int from_tty, struct cmd_list_element *command)
10860 {
10861   int tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
10862
10863   catch_exception_command_1 (EX_EVENT_CATCH, arg, tempflag, from_tty);
10864 }
10865
10866 /* Implementation of "catch throw" command.  */
10867
10868 static void
10869 catch_throw_command (char *arg, int from_tty, struct cmd_list_element *command)
10870 {
10871   int tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
10872
10873   catch_exception_command_1 (EX_EVENT_THROW, arg, tempflag, from_tty);
10874 }
10875
10876 void
10877 init_ada_exception_breakpoint (struct breakpoint *b,
10878                                struct gdbarch *gdbarch,
10879                                struct symtab_and_line sal,
10880                                char *addr_string,
10881                                const struct breakpoint_ops *ops,
10882                                int tempflag,
10883                                int from_tty)
10884 {
10885   if (from_tty)
10886     {
10887       struct gdbarch *loc_gdbarch = get_sal_arch (sal);
10888       if (!loc_gdbarch)
10889         loc_gdbarch = gdbarch;
10890
10891       describe_other_breakpoints (loc_gdbarch,
10892                                   sal.pspace, sal.pc, sal.section, -1);
10893       /* FIXME: brobecker/2006-12-28: Actually, re-implement a special
10894          version for exception catchpoints, because two catchpoints
10895          used for different exception names will use the same address.
10896          In this case, a "breakpoint ... also set at..." warning is
10897          unproductive.  Besides, the warning phrasing is also a bit
10898          inappropriate, we should use the word catchpoint, and tell
10899          the user what type of catchpoint it is.  The above is good
10900          enough for now, though.  */
10901     }
10902
10903   init_raw_breakpoint (b, gdbarch, sal, bp_breakpoint, ops);
10904
10905   b->enable_state = bp_enabled;
10906   b->disposition = tempflag ? disp_del : disp_donttouch;
10907   b->addr_string = addr_string;
10908   b->language = language_ada;
10909 }
10910
10911 /* Splits the argument using space as delimiter.  Returns an xmalloc'd
10912    filter list, or NULL if no filtering is required.  */
10913 static VEC(int) *
10914 catch_syscall_split_args (char *arg)
10915 {
10916   VEC(int) *result = NULL;
10917   struct cleanup *cleanup = make_cleanup (VEC_cleanup (int), &result);
10918
10919   while (*arg != '\0')
10920     {
10921       int i, syscall_number;
10922       char *endptr;
10923       char cur_name[128];
10924       struct syscall s;
10925
10926       /* Skip whitespace.  */
10927       while (isspace (*arg))
10928         arg++;
10929
10930       for (i = 0; i < 127 && arg[i] && !isspace (arg[i]); ++i)
10931         cur_name[i] = arg[i];
10932       cur_name[i] = '\0';
10933       arg += i;
10934
10935       /* Check if the user provided a syscall name or a number.  */
10936       syscall_number = (int) strtol (cur_name, &endptr, 0);
10937       if (*endptr == '\0')
10938         get_syscall_by_number (syscall_number, &s);
10939       else
10940         {
10941           /* We have a name.  Let's check if it's valid and convert it
10942              to a number.  */
10943           get_syscall_by_name (cur_name, &s);
10944
10945           if (s.number == UNKNOWN_SYSCALL)
10946             /* Here we have to issue an error instead of a warning,
10947                because GDB cannot do anything useful if there's no
10948                syscall number to be caught.  */
10949             error (_("Unknown syscall name '%s'."), cur_name);
10950         }
10951
10952       /* Ok, it's valid.  */
10953       VEC_safe_push (int, result, s.number);
10954     }
10955
10956   discard_cleanups (cleanup);
10957   return result;
10958 }
10959
10960 /* Implement the "catch syscall" command.  */
10961
10962 static void
10963 catch_syscall_command_1 (char *arg, int from_tty, 
10964                          struct cmd_list_element *command)
10965 {
10966   int tempflag;
10967   VEC(int) *filter;
10968   struct syscall s;
10969   struct gdbarch *gdbarch = get_current_arch ();
10970
10971   /* Checking if the feature if supported.  */
10972   if (gdbarch_get_syscall_number_p (gdbarch) == 0)
10973     error (_("The feature 'catch syscall' is not supported on \
10974 this architecture yet."));
10975
10976   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
10977
10978   arg = skip_spaces (arg);
10979
10980   /* We need to do this first "dummy" translation in order
10981      to get the syscall XML file loaded or, most important,
10982      to display a warning to the user if there's no XML file
10983      for his/her architecture.  */
10984   get_syscall_by_number (0, &s);
10985
10986   /* The allowed syntax is:
10987      catch syscall
10988      catch syscall <name | number> [<name | number> ... <name | number>]
10989
10990      Let's check if there's a syscall name.  */
10991
10992   if (arg != NULL)
10993     filter = catch_syscall_split_args (arg);
10994   else
10995     filter = NULL;
10996
10997   create_syscall_event_catchpoint (tempflag, filter,
10998                                    &catch_syscall_breakpoint_ops);
10999 }
11000
11001 static void
11002 catch_command (char *arg, int from_tty)
11003 {
11004   error (_("Catch requires an event name."));
11005 }
11006 \f
11007
11008 static void
11009 tcatch_command (char *arg, int from_tty)
11010 {
11011   error (_("Catch requires an event name."));
11012 }
11013
11014 /* A qsort comparison function that sorts breakpoints in order.  */
11015
11016 static int
11017 compare_breakpoints (const void *a, const void *b)
11018 {
11019   const breakpoint_p *ba = a;
11020   uintptr_t ua = (uintptr_t) *ba;
11021   const breakpoint_p *bb = b;
11022   uintptr_t ub = (uintptr_t) *bb;
11023
11024   if ((*ba)->number < (*bb)->number)
11025     return -1;
11026   else if ((*ba)->number > (*bb)->number)
11027     return 1;
11028
11029   /* Now sort by address, in case we see, e..g, two breakpoints with
11030      the number 0.  */
11031   if (ua < ub)
11032     return -1;
11033   return ub > ub ? 1 : 0;
11034 }
11035
11036 /* Delete breakpoints by address or line.  */
11037
11038 static void
11039 clear_command (char *arg, int from_tty)
11040 {
11041   struct breakpoint *b, *prev;
11042   VEC(breakpoint_p) *found = 0;
11043   int ix;
11044   int default_match;
11045   struct symtabs_and_lines sals;
11046   struct symtab_and_line sal;
11047   int i;
11048   struct cleanup *cleanups = make_cleanup (null_cleanup, NULL);
11049
11050   if (arg)
11051     {
11052       sals = decode_line_spec (arg, (DECODE_LINE_FUNFIRSTLINE
11053                                      | DECODE_LINE_LIST_MODE));
11054       default_match = 0;
11055     }
11056   else
11057     {
11058       sals.sals = (struct symtab_and_line *)
11059         xmalloc (sizeof (struct symtab_and_line));
11060       make_cleanup (xfree, sals.sals);
11061       init_sal (&sal);          /* Initialize to zeroes.  */
11062
11063       /* Set sal's line, symtab, pc, and pspace to the values
11064          corresponding to the last call to print_frame_info.  If the
11065          codepoint is not valid, this will set all the fields to 0.  */
11066       get_last_displayed_sal (&sal);
11067       if (sal.symtab == 0)
11068         error (_("No source file specified."));
11069
11070       sals.sals[0] = sal;
11071       sals.nelts = 1;
11072
11073       default_match = 1;
11074     }
11075
11076   /* We don't call resolve_sal_pc here.  That's not as bad as it
11077      seems, because all existing breakpoints typically have both
11078      file/line and pc set.  So, if clear is given file/line, we can
11079      match this to existing breakpoint without obtaining pc at all.
11080
11081      We only support clearing given the address explicitly 
11082      present in breakpoint table.  Say, we've set breakpoint 
11083      at file:line.  There were several PC values for that file:line,
11084      due to optimization, all in one block.
11085
11086      We've picked one PC value.  If "clear" is issued with another
11087      PC corresponding to the same file:line, the breakpoint won't
11088      be cleared.  We probably can still clear the breakpoint, but 
11089      since the other PC value is never presented to user, user
11090      can only find it by guessing, and it does not seem important
11091      to support that.  */
11092
11093   /* For each line spec given, delete bps which correspond to it.  Do
11094      it in two passes, solely to preserve the current behavior that
11095      from_tty is forced true if we delete more than one
11096      breakpoint.  */
11097
11098   found = NULL;
11099   make_cleanup (VEC_cleanup (breakpoint_p), &found);
11100   for (i = 0; i < sals.nelts; i++)
11101     {
11102       int is_abs, sal_name_len;
11103
11104       /* If exact pc given, clear bpts at that pc.
11105          If line given (pc == 0), clear all bpts on specified line.
11106          If defaulting, clear all bpts on default line
11107          or at default pc.
11108
11109          defaulting    sal.pc != 0    tests to do
11110
11111          0              1             pc
11112          1              1             pc _and_ line
11113          0              0             line
11114          1              0             <can't happen> */
11115
11116       sal = sals.sals[i];
11117       is_abs = sal.symtab == NULL ? 1 : IS_ABSOLUTE_PATH (sal.symtab->filename);
11118       sal_name_len = is_abs ? 0 : strlen (sal.symtab->filename);
11119
11120       /* Find all matching breakpoints and add them to 'found'.  */
11121       ALL_BREAKPOINTS (b)
11122         {
11123           int match = 0;
11124           /* Are we going to delete b?  */
11125           if (b->type != bp_none && !is_watchpoint (b))
11126             {
11127               struct bp_location *loc = b->loc;
11128               for (; loc; loc = loc->next)
11129                 {
11130                   /* If the user specified file:line, don't allow a PC
11131                      match.  This matches historical gdb behavior.  */
11132                   int pc_match = (!sal.explicit_line
11133                                   && sal.pc
11134                                   && (loc->pspace == sal.pspace)
11135                                   && (loc->address == sal.pc)
11136                                   && (!section_is_overlay (loc->section)
11137                                       || loc->section == sal.section));
11138                   int line_match = 0;
11139
11140                   if ((default_match || sal.explicit_line)
11141                       && loc->source_file != NULL
11142                       && sal.symtab != NULL
11143                       && sal.pspace == loc->pspace
11144                       && loc->line_number == sal.line)
11145                     {
11146                       if (filename_cmp (loc->source_file,
11147                                         sal.symtab->filename) == 0)
11148                         line_match = 1;
11149                       else if (!IS_ABSOLUTE_PATH (sal.symtab->filename)
11150                                && compare_filenames_for_search (loc->source_file,
11151                                                                 sal.symtab->filename,
11152                                                                 sal_name_len))
11153                         line_match = 1;
11154                     }
11155
11156                   if (pc_match || line_match)
11157                     {
11158                       match = 1;
11159                       break;
11160                     }
11161                 }
11162             }
11163
11164           if (match)
11165             VEC_safe_push(breakpoint_p, found, b);
11166         }
11167     }
11168
11169   /* Now go thru the 'found' chain and delete them.  */
11170   if (VEC_empty(breakpoint_p, found))
11171     {
11172       if (arg)
11173         error (_("No breakpoint at %s."), arg);
11174       else
11175         error (_("No breakpoint at this line."));
11176     }
11177
11178   /* Remove duplicates from the vec.  */
11179   qsort (VEC_address (breakpoint_p, found),
11180          VEC_length (breakpoint_p, found),
11181          sizeof (breakpoint_p),
11182          compare_breakpoints);
11183   prev = VEC_index (breakpoint_p, found, 0);
11184   for (ix = 1; VEC_iterate (breakpoint_p, found, ix, b); ++ix)
11185     {
11186       if (b == prev)
11187         {
11188           VEC_ordered_remove (breakpoint_p, found, ix);
11189           --ix;
11190         }
11191     }
11192
11193   if (VEC_length(breakpoint_p, found) > 1)
11194     from_tty = 1;       /* Always report if deleted more than one.  */
11195   if (from_tty)
11196     {
11197       if (VEC_length(breakpoint_p, found) == 1)
11198         printf_unfiltered (_("Deleted breakpoint "));
11199       else
11200         printf_unfiltered (_("Deleted breakpoints "));
11201     }
11202   breakpoints_changed ();
11203
11204   for (ix = 0; VEC_iterate(breakpoint_p, found, ix, b); ix++)
11205     {
11206       if (from_tty)
11207         printf_unfiltered ("%d ", b->number);
11208       delete_breakpoint (b);
11209     }
11210   if (from_tty)
11211     putchar_unfiltered ('\n');
11212
11213   do_cleanups (cleanups);
11214 }
11215 \f
11216 /* Delete breakpoint in BS if they are `delete' breakpoints and
11217    all breakpoints that are marked for deletion, whether hit or not.
11218    This is called after any breakpoint is hit, or after errors.  */
11219
11220 void
11221 breakpoint_auto_delete (bpstat bs)
11222 {
11223   struct breakpoint *b, *b_tmp;
11224
11225   for (; bs; bs = bs->next)
11226     if (bs->breakpoint_at
11227         && bs->breakpoint_at->disposition == disp_del
11228         && bs->stop)
11229       delete_breakpoint (bs->breakpoint_at);
11230
11231   ALL_BREAKPOINTS_SAFE (b, b_tmp)
11232   {
11233     if (b->disposition == disp_del_at_next_stop)
11234       delete_breakpoint (b);
11235   }
11236 }
11237
11238 /* A comparison function for bp_location AP and BP being interfaced to
11239    qsort.  Sort elements primarily by their ADDRESS (no matter what
11240    does breakpoint_address_is_meaningful say for its OWNER),
11241    secondarily by ordering first bp_permanent OWNERed elements and
11242    terciarily just ensuring the array is sorted stable way despite
11243    qsort being an unstable algorithm.  */
11244
11245 static int
11246 bp_location_compare (const void *ap, const void *bp)
11247 {
11248   struct bp_location *a = *(void **) ap;
11249   struct bp_location *b = *(void **) bp;
11250   /* A and B come from existing breakpoints having non-NULL OWNER.  */
11251   int a_perm = a->owner->enable_state == bp_permanent;
11252   int b_perm = b->owner->enable_state == bp_permanent;
11253
11254   if (a->address != b->address)
11255     return (a->address > b->address) - (a->address < b->address);
11256
11257   /* Sort locations at the same address by their pspace number, keeping
11258      locations of the same inferior (in a multi-inferior environment)
11259      grouped.  */
11260
11261   if (a->pspace->num != b->pspace->num)
11262     return ((a->pspace->num > b->pspace->num)
11263             - (a->pspace->num < b->pspace->num));
11264
11265   /* Sort permanent breakpoints first.  */
11266   if (a_perm != b_perm)
11267     return (a_perm < b_perm) - (a_perm > b_perm);
11268
11269   /* Make the internal GDB representation stable across GDB runs
11270      where A and B memory inside GDB can differ.  Breakpoint locations of
11271      the same type at the same address can be sorted in arbitrary order.  */
11272
11273   if (a->owner->number != b->owner->number)
11274     return ((a->owner->number > b->owner->number)
11275             - (a->owner->number < b->owner->number));
11276
11277   return (a > b) - (a < b);
11278 }
11279
11280 /* Set bp_location_placed_address_before_address_max and
11281    bp_location_shadow_len_after_address_max according to the current
11282    content of the bp_location array.  */
11283
11284 static void
11285 bp_location_target_extensions_update (void)
11286 {
11287   struct bp_location *bl, **blp_tmp;
11288
11289   bp_location_placed_address_before_address_max = 0;
11290   bp_location_shadow_len_after_address_max = 0;
11291
11292   ALL_BP_LOCATIONS (bl, blp_tmp)
11293     {
11294       CORE_ADDR start, end, addr;
11295
11296       if (!bp_location_has_shadow (bl))
11297         continue;
11298
11299       start = bl->target_info.placed_address;
11300       end = start + bl->target_info.shadow_len;
11301
11302       gdb_assert (bl->address >= start);
11303       addr = bl->address - start;
11304       if (addr > bp_location_placed_address_before_address_max)
11305         bp_location_placed_address_before_address_max = addr;
11306
11307       /* Zero SHADOW_LEN would not pass bp_location_has_shadow.  */
11308
11309       gdb_assert (bl->address < end);
11310       addr = end - bl->address;
11311       if (addr > bp_location_shadow_len_after_address_max)
11312         bp_location_shadow_len_after_address_max = addr;
11313     }
11314 }
11315
11316 /* Download tracepoint locations if they haven't been.  */
11317
11318 static void
11319 download_tracepoint_locations (void)
11320 {
11321   struct bp_location *bl, **blp_tmp;
11322   struct cleanup *old_chain;
11323
11324   if (!target_can_download_tracepoint ())
11325     return;
11326
11327   old_chain = save_current_space_and_thread ();
11328
11329   ALL_BP_LOCATIONS (bl, blp_tmp)
11330     {
11331       struct tracepoint *t;
11332
11333       if (!is_tracepoint (bl->owner))
11334         continue;
11335
11336       if ((bl->owner->type == bp_fast_tracepoint
11337            ? !may_insert_fast_tracepoints
11338            : !may_insert_tracepoints))
11339         continue;
11340
11341       /* In tracepoint, locations are _never_ duplicated, so
11342          should_be_inserted is equivalent to
11343          unduplicated_should_be_inserted.  */
11344       if (!should_be_inserted (bl) || bl->inserted)
11345         continue;
11346
11347       switch_to_program_space_and_thread (bl->pspace);
11348
11349       target_download_tracepoint (bl);
11350
11351       bl->inserted = 1;
11352       t = (struct tracepoint *) bl->owner;
11353       t->number_on_target = bl->owner->number;
11354     }
11355
11356   do_cleanups (old_chain);
11357 }
11358
11359 /* Swap the insertion/duplication state between two locations.  */
11360
11361 static void
11362 swap_insertion (struct bp_location *left, struct bp_location *right)
11363 {
11364   const int left_inserted = left->inserted;
11365   const int left_duplicate = left->duplicate;
11366   const int left_needs_update = left->needs_update;
11367   const struct bp_target_info left_target_info = left->target_info;
11368
11369   /* Locations of tracepoints can never be duplicated.  */
11370   if (is_tracepoint (left->owner))
11371     gdb_assert (!left->duplicate);
11372   if (is_tracepoint (right->owner))
11373     gdb_assert (!right->duplicate);
11374
11375   left->inserted = right->inserted;
11376   left->duplicate = right->duplicate;
11377   left->needs_update = right->needs_update;
11378   left->target_info = right->target_info;
11379   right->inserted = left_inserted;
11380   right->duplicate = left_duplicate;
11381   right->needs_update = left_needs_update;
11382   right->target_info = left_target_info;
11383 }
11384
11385 /* Force the re-insertion of the locations at ADDRESS.  This is called
11386    once a new/deleted/modified duplicate location is found and we are evaluating
11387    conditions on the target's side.  Such conditions need to be updated on
11388    the target.  */
11389
11390 static void
11391 force_breakpoint_reinsertion (struct bp_location *bl)
11392 {
11393   struct bp_location **locp = NULL, **loc2p;
11394   struct bp_location *loc;
11395   CORE_ADDR address = 0;
11396   int pspace_num;
11397
11398   address = bl->address;
11399   pspace_num = bl->pspace->num;
11400
11401   /* This is only meaningful if the target is
11402      evaluating conditions and if the user has
11403      opted for condition evaluation on the target's
11404      side.  */
11405   if (gdb_evaluates_breakpoint_condition_p ()
11406       || !target_supports_evaluation_of_breakpoint_conditions ())
11407     return;
11408
11409   /* Flag all breakpoint locations with this address and
11410      the same program space as the location
11411      as "its condition has changed".  We need to
11412      update the conditions on the target's side.  */
11413   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, address)
11414     {
11415       loc = *loc2p;
11416
11417       if (!is_breakpoint (loc->owner)
11418           || pspace_num != loc->pspace->num)
11419         continue;
11420
11421       /* Flag the location appropriately.  We use a different state to
11422          let everyone know that we already updated the set of locations
11423          with addr bl->address and program space bl->pspace.  This is so
11424          we don't have to keep calling these functions just to mark locations
11425          that have already been marked.  */
11426       loc->condition_changed = condition_updated;
11427
11428       /* Free the agent expression bytecode as well.  We will compute
11429          it later on.  */
11430       if (loc->cond_bytecode)
11431         {
11432           free_agent_expr (loc->cond_bytecode);
11433           loc->cond_bytecode = NULL;
11434         }
11435     }
11436 }
11437
11438 /* If SHOULD_INSERT is false, do not insert any breakpoint locations
11439    into the inferior, only remove already-inserted locations that no
11440    longer should be inserted.  Functions that delete a breakpoint or
11441    breakpoints should pass false, so that deleting a breakpoint
11442    doesn't have the side effect of inserting the locations of other
11443    breakpoints that are marked not-inserted, but should_be_inserted
11444    returns true on them.
11445
11446    This behaviour is useful is situations close to tear-down -- e.g.,
11447    after an exec, while the target still has execution, but breakpoint
11448    shadows of the previous executable image should *NOT* be restored
11449    to the new image; or before detaching, where the target still has
11450    execution and wants to delete breakpoints from GDB's lists, and all
11451    breakpoints had already been removed from the inferior.  */
11452
11453 static void
11454 update_global_location_list (int should_insert)
11455 {
11456   struct breakpoint *b;
11457   struct bp_location **locp, *loc;
11458   struct cleanup *cleanups;
11459   /* Last breakpoint location address that was marked for update.  */
11460   CORE_ADDR last_addr = 0;
11461   /* Last breakpoint location program space that was marked for update.  */
11462   int last_pspace_num = -1;
11463
11464   /* Used in the duplicates detection below.  When iterating over all
11465      bp_locations, points to the first bp_location of a given address.
11466      Breakpoints and watchpoints of different types are never
11467      duplicates of each other.  Keep one pointer for each type of
11468      breakpoint/watchpoint, so we only need to loop over all locations
11469      once.  */
11470   struct bp_location *bp_loc_first;  /* breakpoint */
11471   struct bp_location *wp_loc_first;  /* hardware watchpoint */
11472   struct bp_location *awp_loc_first; /* access watchpoint */
11473   struct bp_location *rwp_loc_first; /* read watchpoint */
11474
11475   /* Saved former bp_location array which we compare against the newly
11476      built bp_location from the current state of ALL_BREAKPOINTS.  */
11477   struct bp_location **old_location, **old_locp;
11478   unsigned old_location_count;
11479
11480   old_location = bp_location;
11481   old_location_count = bp_location_count;
11482   bp_location = NULL;
11483   bp_location_count = 0;
11484   cleanups = make_cleanup (xfree, old_location);
11485
11486   ALL_BREAKPOINTS (b)
11487     for (loc = b->loc; loc; loc = loc->next)
11488       bp_location_count++;
11489
11490   bp_location = xmalloc (sizeof (*bp_location) * bp_location_count);
11491   locp = bp_location;
11492   ALL_BREAKPOINTS (b)
11493     for (loc = b->loc; loc; loc = loc->next)
11494       *locp++ = loc;
11495   qsort (bp_location, bp_location_count, sizeof (*bp_location),
11496          bp_location_compare);
11497
11498   bp_location_target_extensions_update ();
11499
11500   /* Identify bp_location instances that are no longer present in the
11501      new list, and therefore should be freed.  Note that it's not
11502      necessary that those locations should be removed from inferior --
11503      if there's another location at the same address (previously
11504      marked as duplicate), we don't need to remove/insert the
11505      location.
11506      
11507      LOCP is kept in sync with OLD_LOCP, each pointing to the current
11508      and former bp_location array state respectively.  */
11509
11510   locp = bp_location;
11511   for (old_locp = old_location; old_locp < old_location + old_location_count;
11512        old_locp++)
11513     {
11514       struct bp_location *old_loc = *old_locp;
11515       struct bp_location **loc2p;
11516
11517       /* Tells if 'old_loc' is found among the new locations.  If
11518          not, we have to free it.  */
11519       int found_object = 0;
11520       /* Tells if the location should remain inserted in the target.  */
11521       int keep_in_target = 0;
11522       int removed = 0;
11523
11524       /* Skip LOCP entries which will definitely never be needed.
11525          Stop either at or being the one matching OLD_LOC.  */
11526       while (locp < bp_location + bp_location_count
11527              && (*locp)->address < old_loc->address)
11528         locp++;
11529
11530       for (loc2p = locp;
11531            (loc2p < bp_location + bp_location_count
11532             && (*loc2p)->address == old_loc->address);
11533            loc2p++)
11534         {
11535           /* Check if this is a new/duplicated location or a duplicated
11536              location that had its condition modified.  If so, we want to send
11537              its condition to the target if evaluation of conditions is taking
11538              place there.  */
11539           if ((*loc2p)->condition_changed == condition_modified
11540               && (last_addr != old_loc->address
11541                   || last_pspace_num != old_loc->pspace->num))
11542             {
11543               force_breakpoint_reinsertion (*loc2p);
11544               last_pspace_num = old_loc->pspace->num;
11545             }
11546
11547           if (*loc2p == old_loc)
11548             found_object = 1;
11549         }
11550
11551       /* We have already handled this address, update it so that we don't
11552          have to go through updates again.  */
11553       last_addr = old_loc->address;
11554
11555       /* Target-side condition evaluation: Handle deleted locations.  */
11556       if (!found_object)
11557         force_breakpoint_reinsertion (old_loc);
11558
11559       /* If this location is no longer present, and inserted, look if
11560          there's maybe a new location at the same address.  If so,
11561          mark that one inserted, and don't remove this one.  This is
11562          needed so that we don't have a time window where a breakpoint
11563          at certain location is not inserted.  */
11564
11565       if (old_loc->inserted)
11566         {
11567           /* If the location is inserted now, we might have to remove
11568              it.  */
11569
11570           if (found_object && should_be_inserted (old_loc))
11571             {
11572               /* The location is still present in the location list,
11573                  and still should be inserted.  Don't do anything.  */
11574               keep_in_target = 1;
11575             }
11576           else
11577             {
11578               /* This location still exists, but it won't be kept in the
11579                  target since it may have been disabled.  We proceed to
11580                  remove its target-side condition.  */
11581
11582               /* The location is either no longer present, or got
11583                  disabled.  See if there's another location at the
11584                  same address, in which case we don't need to remove
11585                  this one from the target.  */
11586
11587               /* OLD_LOC comes from existing struct breakpoint.  */
11588               if (breakpoint_address_is_meaningful (old_loc->owner))
11589                 {
11590                   for (loc2p = locp;
11591                        (loc2p < bp_location + bp_location_count
11592                         && (*loc2p)->address == old_loc->address);
11593                        loc2p++)
11594                     {
11595                       struct bp_location *loc2 = *loc2p;
11596
11597                       if (breakpoint_locations_match (loc2, old_loc))
11598                         {
11599                           /* Read watchpoint locations are switched to
11600                              access watchpoints, if the former are not
11601                              supported, but the latter are.  */
11602                           if (is_hardware_watchpoint (old_loc->owner))
11603                             {
11604                               gdb_assert (is_hardware_watchpoint (loc2->owner));
11605                               loc2->watchpoint_type = old_loc->watchpoint_type;
11606                             }
11607
11608                           /* loc2 is a duplicated location. We need to check
11609                              if it should be inserted in case it will be
11610                              unduplicated.  */
11611                           if (loc2 != old_loc
11612                               && unduplicated_should_be_inserted (loc2))
11613                             {
11614                               swap_insertion (old_loc, loc2);
11615                               keep_in_target = 1;
11616                               break;
11617                             }
11618                         }
11619                     }
11620                 }
11621             }
11622
11623           if (!keep_in_target)
11624             {
11625               if (remove_breakpoint (old_loc, mark_uninserted))
11626                 {
11627                   /* This is just about all we can do.  We could keep
11628                      this location on the global list, and try to
11629                      remove it next time, but there's no particular
11630                      reason why we will succeed next time.
11631                      
11632                      Note that at this point, old_loc->owner is still
11633                      valid, as delete_breakpoint frees the breakpoint
11634                      only after calling us.  */
11635                   printf_filtered (_("warning: Error removing "
11636                                      "breakpoint %d\n"), 
11637                                    old_loc->owner->number);
11638                 }
11639               removed = 1;
11640             }
11641         }
11642
11643       if (!found_object)
11644         {
11645           if (removed && non_stop
11646               && breakpoint_address_is_meaningful (old_loc->owner)
11647               && !is_hardware_watchpoint (old_loc->owner))
11648             {
11649               /* This location was removed from the target.  In
11650                  non-stop mode, a race condition is possible where
11651                  we've removed a breakpoint, but stop events for that
11652                  breakpoint are already queued and will arrive later.
11653                  We apply an heuristic to be able to distinguish such
11654                  SIGTRAPs from other random SIGTRAPs: we keep this
11655                  breakpoint location for a bit, and will retire it
11656                  after we see some number of events.  The theory here
11657                  is that reporting of events should, "on the average",
11658                  be fair, so after a while we'll see events from all
11659                  threads that have anything of interest, and no longer
11660                  need to keep this breakpoint location around.  We
11661                  don't hold locations forever so to reduce chances of
11662                  mistaking a non-breakpoint SIGTRAP for a breakpoint
11663                  SIGTRAP.
11664
11665                  The heuristic failing can be disastrous on
11666                  decr_pc_after_break targets.
11667
11668                  On decr_pc_after_break targets, like e.g., x86-linux,
11669                  if we fail to recognize a late breakpoint SIGTRAP,
11670                  because events_till_retirement has reached 0 too
11671                  soon, we'll fail to do the PC adjustment, and report
11672                  a random SIGTRAP to the user.  When the user resumes
11673                  the inferior, it will most likely immediately crash
11674                  with SIGILL/SIGBUS/SIGSEGV, or worse, get silently
11675                  corrupted, because of being resumed e.g., in the
11676                  middle of a multi-byte instruction, or skipped a
11677                  one-byte instruction.  This was actually seen happen
11678                  on native x86-linux, and should be less rare on
11679                  targets that do not support new thread events, like
11680                  remote, due to the heuristic depending on
11681                  thread_count.
11682
11683                  Mistaking a random SIGTRAP for a breakpoint trap
11684                  causes similar symptoms (PC adjustment applied when
11685                  it shouldn't), but then again, playing with SIGTRAPs
11686                  behind the debugger's back is asking for trouble.
11687
11688                  Since hardware watchpoint traps are always
11689                  distinguishable from other traps, so we don't need to
11690                  apply keep hardware watchpoint moribund locations
11691                  around.  We simply always ignore hardware watchpoint
11692                  traps we can no longer explain.  */
11693
11694               old_loc->events_till_retirement = 3 * (thread_count () + 1);
11695               old_loc->owner = NULL;
11696
11697               VEC_safe_push (bp_location_p, moribund_locations, old_loc);
11698             }
11699           else
11700             {
11701               old_loc->owner = NULL;
11702               decref_bp_location (&old_loc);
11703             }
11704         }
11705     }
11706
11707   /* Rescan breakpoints at the same address and section, marking the
11708      first one as "first" and any others as "duplicates".  This is so
11709      that the bpt instruction is only inserted once.  If we have a
11710      permanent breakpoint at the same place as BPT, make that one the
11711      official one, and the rest as duplicates.  Permanent breakpoints
11712      are sorted first for the same address.
11713
11714      Do the same for hardware watchpoints, but also considering the
11715      watchpoint's type (regular/access/read) and length.  */
11716
11717   bp_loc_first = NULL;
11718   wp_loc_first = NULL;
11719   awp_loc_first = NULL;
11720   rwp_loc_first = NULL;
11721   ALL_BP_LOCATIONS (loc, locp)
11722     {
11723       /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always
11724          non-NULL.  */
11725       struct bp_location **loc_first_p;
11726       b = loc->owner;
11727
11728       if (!should_be_inserted (loc)
11729           || !breakpoint_address_is_meaningful (b)
11730           /* Don't detect duplicate for tracepoint locations because they are
11731            never duplicated.  See the comments in field `duplicate' of
11732            `struct bp_location'.  */
11733           || is_tracepoint (b))
11734         {
11735           /* Clear the condition modification flag.  */
11736           loc->condition_changed = condition_unchanged;
11737           continue;
11738         }
11739
11740       /* Permanent breakpoint should always be inserted.  */
11741       if (b->enable_state == bp_permanent && ! loc->inserted)
11742         internal_error (__FILE__, __LINE__,
11743                         _("allegedly permanent breakpoint is not "
11744                         "actually inserted"));
11745
11746       if (b->type == bp_hardware_watchpoint)
11747         loc_first_p = &wp_loc_first;
11748       else if (b->type == bp_read_watchpoint)
11749         loc_first_p = &rwp_loc_first;
11750       else if (b->type == bp_access_watchpoint)
11751         loc_first_p = &awp_loc_first;
11752       else
11753         loc_first_p = &bp_loc_first;
11754
11755       if (*loc_first_p == NULL
11756           || (overlay_debugging && loc->section != (*loc_first_p)->section)
11757           || !breakpoint_locations_match (loc, *loc_first_p))
11758         {
11759           *loc_first_p = loc;
11760           loc->duplicate = 0;
11761
11762           if (is_breakpoint (loc->owner) && loc->condition_changed)
11763             {
11764               loc->needs_update = 1;
11765               /* Clear the condition modification flag.  */
11766               loc->condition_changed = condition_unchanged;
11767             }
11768           continue;
11769         }
11770
11771
11772       /* This and the above ensure the invariant that the first location
11773          is not duplicated, and is the inserted one.
11774          All following are marked as duplicated, and are not inserted.  */
11775       if (loc->inserted)
11776         swap_insertion (loc, *loc_first_p);
11777       loc->duplicate = 1;
11778
11779       /* Clear the condition modification flag.  */
11780       loc->condition_changed = condition_unchanged;
11781
11782       if ((*loc_first_p)->owner->enable_state == bp_permanent && loc->inserted
11783           && b->enable_state != bp_permanent)
11784         internal_error (__FILE__, __LINE__,
11785                         _("another breakpoint was inserted on top of "
11786                         "a permanent breakpoint"));
11787     }
11788
11789   if (breakpoints_always_inserted_mode ()
11790       && (have_live_inferiors ()
11791           || (gdbarch_has_global_breakpoints (target_gdbarch))))
11792     {
11793       if (should_insert)
11794         insert_breakpoint_locations ();
11795       else
11796         {
11797           /* Though should_insert is false, we may need to update conditions
11798              on the target's side if it is evaluating such conditions.  We
11799              only update conditions for locations that are marked
11800              "needs_update".  */
11801           update_inserted_breakpoint_locations ();
11802         }
11803     }
11804
11805   if (should_insert)
11806     download_tracepoint_locations ();
11807
11808   do_cleanups (cleanups);
11809 }
11810
11811 void
11812 breakpoint_retire_moribund (void)
11813 {
11814   struct bp_location *loc;
11815   int ix;
11816
11817   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
11818     if (--(loc->events_till_retirement) == 0)
11819       {
11820         decref_bp_location (&loc);
11821         VEC_unordered_remove (bp_location_p, moribund_locations, ix);
11822         --ix;
11823       }
11824 }
11825
11826 static void
11827 update_global_location_list_nothrow (int inserting)
11828 {
11829   volatile struct gdb_exception e;
11830
11831   TRY_CATCH (e, RETURN_MASK_ERROR)
11832     update_global_location_list (inserting);
11833 }
11834
11835 /* Clear BKP from a BPS.  */
11836
11837 static void
11838 bpstat_remove_bp_location (bpstat bps, struct breakpoint *bpt)
11839 {
11840   bpstat bs;
11841
11842   for (bs = bps; bs; bs = bs->next)
11843     if (bs->breakpoint_at == bpt)
11844       {
11845         bs->breakpoint_at = NULL;
11846         bs->old_val = NULL;
11847         /* bs->commands will be freed later.  */
11848       }
11849 }
11850
11851 /* Callback for iterate_over_threads.  */
11852 static int
11853 bpstat_remove_breakpoint_callback (struct thread_info *th, void *data)
11854 {
11855   struct breakpoint *bpt = data;
11856
11857   bpstat_remove_bp_location (th->control.stop_bpstat, bpt);
11858   return 0;
11859 }
11860
11861 /* Helper for breakpoint and tracepoint breakpoint_ops->mention
11862    callbacks.  */
11863
11864 static void
11865 say_where (struct breakpoint *b)
11866 {
11867   struct ui_out *uiout = current_uiout;
11868   struct value_print_options opts;
11869
11870   get_user_print_options (&opts);
11871
11872   /* i18n: cagney/2005-02-11: Below needs to be merged into a
11873      single string.  */
11874   if (b->loc == NULL)
11875     {
11876       printf_filtered (_(" (%s) pending."), b->addr_string);
11877     }
11878   else
11879     {
11880       if (opts.addressprint || b->loc->source_file == NULL)
11881         {
11882           printf_filtered (" at ");
11883           fputs_filtered (paddress (b->loc->gdbarch, b->loc->address),
11884                           gdb_stdout);
11885         }
11886       if (b->loc->source_file)
11887         {
11888           /* If there is a single location, we can print the location
11889              more nicely.  */
11890           if (b->loc->next == NULL)
11891             printf_filtered (": file %s, line %d.",
11892                              b->loc->source_file, b->loc->line_number);
11893           else
11894             /* This is not ideal, but each location may have a
11895                different file name, and this at least reflects the
11896                real situation somewhat.  */
11897             printf_filtered (": %s.", b->addr_string);
11898         }
11899
11900       if (b->loc->next)
11901         {
11902           struct bp_location *loc = b->loc;
11903           int n = 0;
11904           for (; loc; loc = loc->next)
11905             ++n;
11906           printf_filtered (" (%d locations)", n);
11907         }
11908     }
11909 }
11910
11911 /* Default bp_location_ops methods.  */
11912
11913 static void
11914 bp_location_dtor (struct bp_location *self)
11915 {
11916   xfree (self->cond);
11917   if (self->cond_bytecode)
11918     free_agent_expr (self->cond_bytecode);
11919   xfree (self->function_name);
11920   xfree (self->source_file);
11921 }
11922
11923 static const struct bp_location_ops bp_location_ops =
11924 {
11925   bp_location_dtor
11926 };
11927
11928 /* Default breakpoint_ops methods all breakpoint_ops ultimately
11929    inherit from.  */
11930
11931 static void
11932 base_breakpoint_dtor (struct breakpoint *self)
11933 {
11934   decref_counted_command_line (&self->commands);
11935   xfree (self->cond_string);
11936   xfree (self->addr_string);
11937   xfree (self->filter);
11938   xfree (self->addr_string_range_end);
11939 }
11940
11941 static struct bp_location *
11942 base_breakpoint_allocate_location (struct breakpoint *self)
11943 {
11944   struct bp_location *loc;
11945
11946   loc = XNEW (struct bp_location);
11947   init_bp_location (loc, &bp_location_ops, self);
11948   return loc;
11949 }
11950
11951 static void
11952 base_breakpoint_re_set (struct breakpoint *b)
11953 {
11954   /* Nothing to re-set. */
11955 }
11956
11957 #define internal_error_pure_virtual_called() \
11958   gdb_assert_not_reached ("pure virtual function called")
11959
11960 static int
11961 base_breakpoint_insert_location (struct bp_location *bl)
11962 {
11963   internal_error_pure_virtual_called ();
11964 }
11965
11966 static int
11967 base_breakpoint_remove_location (struct bp_location *bl)
11968 {
11969   internal_error_pure_virtual_called ();
11970 }
11971
11972 static int
11973 base_breakpoint_breakpoint_hit (const struct bp_location *bl,
11974                                 struct address_space *aspace,
11975                                 CORE_ADDR bp_addr,
11976                                 const struct target_waitstatus *ws)
11977 {
11978   internal_error_pure_virtual_called ();
11979 }
11980
11981 static void
11982 base_breakpoint_check_status (bpstat bs)
11983 {
11984   /* Always stop.   */
11985 }
11986
11987 /* A "works_in_software_mode" breakpoint_ops method that just internal
11988    errors.  */
11989
11990 static int
11991 base_breakpoint_works_in_software_mode (const struct breakpoint *b)
11992 {
11993   internal_error_pure_virtual_called ();
11994 }
11995
11996 /* A "resources_needed" breakpoint_ops method that just internal
11997    errors.  */
11998
11999 static int
12000 base_breakpoint_resources_needed (const struct bp_location *bl)
12001 {
12002   internal_error_pure_virtual_called ();
12003 }
12004
12005 static enum print_stop_action
12006 base_breakpoint_print_it (bpstat bs)
12007 {
12008   internal_error_pure_virtual_called ();
12009 }
12010
12011 static void
12012 base_breakpoint_print_one_detail (const struct breakpoint *self,
12013                                   struct ui_out *uiout)
12014 {
12015   /* nothing */
12016 }
12017
12018 static void
12019 base_breakpoint_print_mention (struct breakpoint *b)
12020 {
12021   internal_error_pure_virtual_called ();
12022 }
12023
12024 static void
12025 base_breakpoint_print_recreate (struct breakpoint *b, struct ui_file *fp)
12026 {
12027   internal_error_pure_virtual_called ();
12028 }
12029
12030 static void
12031 base_breakpoint_create_sals_from_address (char **arg,
12032                                           struct linespec_result *canonical,
12033                                           enum bptype type_wanted,
12034                                           char *addr_start,
12035                                           char **copy_arg)
12036 {
12037   internal_error_pure_virtual_called ();
12038 }
12039
12040 static void
12041 base_breakpoint_create_breakpoints_sal (struct gdbarch *gdbarch,
12042                                         struct linespec_result *c,
12043                                         struct linespec_sals *lsal,
12044                                         char *cond_string,
12045                                         enum bptype type_wanted,
12046                                         enum bpdisp disposition,
12047                                         int thread,
12048                                         int task, int ignore_count,
12049                                         const struct breakpoint_ops *o,
12050                                         int from_tty, int enabled,
12051                                         int internal)
12052 {
12053   internal_error_pure_virtual_called ();
12054 }
12055
12056 static void
12057 base_breakpoint_decode_linespec (struct breakpoint *b, char **s,
12058                                  struct symtabs_and_lines *sals)
12059 {
12060   internal_error_pure_virtual_called ();
12061 }
12062
12063 static struct breakpoint_ops base_breakpoint_ops =
12064 {
12065   base_breakpoint_dtor,
12066   base_breakpoint_allocate_location,
12067   base_breakpoint_re_set,
12068   base_breakpoint_insert_location,
12069   base_breakpoint_remove_location,
12070   base_breakpoint_breakpoint_hit,
12071   base_breakpoint_check_status,
12072   base_breakpoint_resources_needed,
12073   base_breakpoint_works_in_software_mode,
12074   base_breakpoint_print_it,
12075   NULL,
12076   base_breakpoint_print_one_detail,
12077   base_breakpoint_print_mention,
12078   base_breakpoint_print_recreate,
12079   base_breakpoint_create_sals_from_address,
12080   base_breakpoint_create_breakpoints_sal,
12081   base_breakpoint_decode_linespec,
12082 };
12083
12084 /* Default breakpoint_ops methods.  */
12085
12086 static void
12087 bkpt_re_set (struct breakpoint *b)
12088 {
12089   /* FIXME: is this still reachable?  */
12090   if (b->addr_string == NULL)
12091     {
12092       /* Anything without a string can't be re-set.  */
12093       delete_breakpoint (b);
12094       return;
12095     }
12096
12097   breakpoint_re_set_default (b);
12098 }
12099
12100 static int
12101 bkpt_insert_location (struct bp_location *bl)
12102 {
12103   if (bl->loc_type == bp_loc_hardware_breakpoint)
12104     return target_insert_hw_breakpoint (bl->gdbarch,
12105                                         &bl->target_info);
12106   else
12107     return target_insert_breakpoint (bl->gdbarch,
12108                                      &bl->target_info);
12109 }
12110
12111 static int
12112 bkpt_remove_location (struct bp_location *bl)
12113 {
12114   if (bl->loc_type == bp_loc_hardware_breakpoint)
12115     return target_remove_hw_breakpoint (bl->gdbarch, &bl->target_info);
12116   else
12117     return target_remove_breakpoint (bl->gdbarch, &bl->target_info);
12118 }
12119
12120 static int
12121 bkpt_breakpoint_hit (const struct bp_location *bl,
12122                      struct address_space *aspace, CORE_ADDR bp_addr,
12123                      const struct target_waitstatus *ws)
12124 {
12125   struct breakpoint *b = bl->owner;
12126
12127   if (ws->kind != TARGET_WAITKIND_STOPPED
12128       || ws->value.sig != TARGET_SIGNAL_TRAP)
12129     return 0;
12130
12131   if (!breakpoint_address_match (bl->pspace->aspace, bl->address,
12132                                  aspace, bp_addr))
12133     return 0;
12134
12135   if (overlay_debugging         /* unmapped overlay section */
12136       && section_is_overlay (bl->section)
12137       && !section_is_mapped (bl->section))
12138     return 0;
12139
12140   return 1;
12141 }
12142
12143 static int
12144 bkpt_resources_needed (const struct bp_location *bl)
12145 {
12146   gdb_assert (bl->owner->type == bp_hardware_breakpoint);
12147
12148   return 1;
12149 }
12150
12151 static enum print_stop_action
12152 bkpt_print_it (bpstat bs)
12153 {
12154   struct breakpoint *b;
12155   const struct bp_location *bl;
12156   int bp_temp;
12157   struct ui_out *uiout = current_uiout;
12158
12159   gdb_assert (bs->bp_location_at != NULL);
12160
12161   bl = bs->bp_location_at;
12162   b = bs->breakpoint_at;
12163
12164   bp_temp = b->disposition == disp_del;
12165   if (bl->address != bl->requested_address)
12166     breakpoint_adjustment_warning (bl->requested_address,
12167                                    bl->address,
12168                                    b->number, 1);
12169   annotate_breakpoint (b->number);
12170   if (bp_temp)
12171     ui_out_text (uiout, "\nTemporary breakpoint ");
12172   else
12173     ui_out_text (uiout, "\nBreakpoint ");
12174   if (ui_out_is_mi_like_p (uiout))
12175     {
12176       ui_out_field_string (uiout, "reason",
12177                            async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
12178       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
12179     }
12180   ui_out_field_int (uiout, "bkptno", b->number);
12181   ui_out_text (uiout, ", ");
12182
12183   return PRINT_SRC_AND_LOC;
12184 }
12185
12186 static void
12187 bkpt_print_mention (struct breakpoint *b)
12188 {
12189   if (ui_out_is_mi_like_p (current_uiout))
12190     return;
12191
12192   switch (b->type)
12193     {
12194     case bp_breakpoint:
12195     case bp_gnu_ifunc_resolver:
12196       if (b->disposition == disp_del)
12197         printf_filtered (_("Temporary breakpoint"));
12198       else
12199         printf_filtered (_("Breakpoint"));
12200       printf_filtered (_(" %d"), b->number);
12201       if (b->type == bp_gnu_ifunc_resolver)
12202         printf_filtered (_(" at gnu-indirect-function resolver"));
12203       break;
12204     case bp_hardware_breakpoint:
12205       printf_filtered (_("Hardware assisted breakpoint %d"), b->number);
12206       break;
12207     }
12208
12209   say_where (b);
12210 }
12211
12212 static void
12213 bkpt_print_recreate (struct breakpoint *tp, struct ui_file *fp)
12214 {
12215   if (tp->type == bp_breakpoint && tp->disposition == disp_del)
12216     fprintf_unfiltered (fp, "tbreak");
12217   else if (tp->type == bp_breakpoint)
12218     fprintf_unfiltered (fp, "break");
12219   else if (tp->type == bp_hardware_breakpoint
12220            && tp->disposition == disp_del)
12221     fprintf_unfiltered (fp, "thbreak");
12222   else if (tp->type == bp_hardware_breakpoint)
12223     fprintf_unfiltered (fp, "hbreak");
12224   else
12225     internal_error (__FILE__, __LINE__,
12226                     _("unhandled breakpoint type %d"), (int) tp->type);
12227
12228   fprintf_unfiltered (fp, " %s", tp->addr_string);
12229   print_recreate_thread (tp, fp);
12230 }
12231
12232 static void
12233 bkpt_create_sals_from_address (char **arg,
12234                                struct linespec_result *canonical,
12235                                enum bptype type_wanted,
12236                                char *addr_start, char **copy_arg)
12237 {
12238   create_sals_from_address_default (arg, canonical, type_wanted,
12239                                     addr_start, copy_arg);
12240 }
12241
12242 static void
12243 bkpt_create_breakpoints_sal (struct gdbarch *gdbarch,
12244                              struct linespec_result *canonical,
12245                              struct linespec_sals *lsal,
12246                              char *cond_string,
12247                              enum bptype type_wanted,
12248                              enum bpdisp disposition,
12249                              int thread,
12250                              int task, int ignore_count,
12251                              const struct breakpoint_ops *ops,
12252                              int from_tty, int enabled,
12253                              int internal)
12254 {
12255   create_breakpoints_sal_default (gdbarch, canonical, lsal,
12256                                   cond_string, type_wanted,
12257                                   disposition, thread, task,
12258                                   ignore_count, ops, from_tty,
12259                                   enabled, internal);
12260 }
12261
12262 static void
12263 bkpt_decode_linespec (struct breakpoint *b, char **s,
12264                       struct symtabs_and_lines *sals)
12265 {
12266   decode_linespec_default (b, s, sals);
12267 }
12268
12269 /* Virtual table for internal breakpoints.  */
12270
12271 static void
12272 internal_bkpt_re_set (struct breakpoint *b)
12273 {
12274   switch (b->type)
12275     {
12276       /* Delete overlay event and longjmp master breakpoints; they
12277          will be reset later by breakpoint_re_set.  */
12278     case bp_overlay_event:
12279     case bp_longjmp_master:
12280     case bp_std_terminate_master:
12281     case bp_exception_master:
12282       delete_breakpoint (b);
12283       break;
12284
12285       /* This breakpoint is special, it's set up when the inferior
12286          starts and we really don't want to touch it.  */
12287     case bp_shlib_event:
12288
12289       /* Like bp_shlib_event, this breakpoint type is special.  Once
12290          it is set up, we do not want to touch it.  */
12291     case bp_thread_event:
12292       break;
12293     }
12294 }
12295
12296 static void
12297 internal_bkpt_check_status (bpstat bs)
12298 {
12299   if (bs->breakpoint_at->type == bp_shlib_event)
12300     {
12301       /* If requested, stop when the dynamic linker notifies GDB of
12302          events.  This allows the user to get control and place
12303          breakpoints in initializer routines for dynamically loaded
12304          objects (among other things).  */
12305       bs->stop = stop_on_solib_events;
12306       bs->print = stop_on_solib_events;
12307     }
12308   else
12309     bs->stop = 0;
12310 }
12311
12312 static enum print_stop_action
12313 internal_bkpt_print_it (bpstat bs)
12314 {
12315   struct ui_out *uiout = current_uiout;
12316   struct breakpoint *b;
12317
12318   b = bs->breakpoint_at;
12319
12320   switch (b->type)
12321     {
12322     case bp_shlib_event:
12323       /* Did we stop because the user set the stop_on_solib_events
12324          variable?  (If so, we report this as a generic, "Stopped due
12325          to shlib event" message.) */
12326       print_solib_event (0);
12327       break;
12328
12329     case bp_thread_event:
12330       /* Not sure how we will get here.
12331          GDB should not stop for these breakpoints.  */
12332       printf_filtered (_("Thread Event Breakpoint: gdb should not stop!\n"));
12333       break;
12334
12335     case bp_overlay_event:
12336       /* By analogy with the thread event, GDB should not stop for these.  */
12337       printf_filtered (_("Overlay Event Breakpoint: gdb should not stop!\n"));
12338       break;
12339
12340     case bp_longjmp_master:
12341       /* These should never be enabled.  */
12342       printf_filtered (_("Longjmp Master Breakpoint: gdb should not stop!\n"));
12343       break;
12344
12345     case bp_std_terminate_master:
12346       /* These should never be enabled.  */
12347       printf_filtered (_("std::terminate Master Breakpoint: "
12348                          "gdb should not stop!\n"));
12349       break;
12350
12351     case bp_exception_master:
12352       /* These should never be enabled.  */
12353       printf_filtered (_("Exception Master Breakpoint: "
12354                          "gdb should not stop!\n"));
12355       break;
12356     }
12357
12358   return PRINT_NOTHING;
12359 }
12360
12361 static void
12362 internal_bkpt_print_mention (struct breakpoint *b)
12363 {
12364   /* Nothing to mention.  These breakpoints are internal.  */
12365 }
12366
12367 /* Virtual table for momentary breakpoints  */
12368
12369 static void
12370 momentary_bkpt_re_set (struct breakpoint *b)
12371 {
12372   /* Keep temporary breakpoints, which can be encountered when we step
12373      over a dlopen call and SOLIB_ADD is resetting the breakpoints.
12374      Otherwise these should have been blown away via the cleanup chain
12375      or by breakpoint_init_inferior when we rerun the executable.  */
12376 }
12377
12378 static void
12379 momentary_bkpt_check_status (bpstat bs)
12380 {
12381   /* Nothing.  The point of these breakpoints is causing a stop.  */
12382 }
12383
12384 static enum print_stop_action
12385 momentary_bkpt_print_it (bpstat bs)
12386 {
12387   struct ui_out *uiout = current_uiout;
12388
12389   if (ui_out_is_mi_like_p (uiout))
12390     {
12391       struct breakpoint *b = bs->breakpoint_at;
12392
12393       switch (b->type)
12394         {
12395         case bp_finish:
12396           ui_out_field_string
12397             (uiout, "reason",
12398              async_reason_lookup (EXEC_ASYNC_FUNCTION_FINISHED));
12399           break;
12400
12401         case bp_until:
12402           ui_out_field_string
12403             (uiout, "reason",
12404              async_reason_lookup (EXEC_ASYNC_LOCATION_REACHED));
12405           break;
12406         }
12407     }
12408
12409   return PRINT_UNKNOWN;
12410 }
12411
12412 static void
12413 momentary_bkpt_print_mention (struct breakpoint *b)
12414 {
12415   /* Nothing to mention.  These breakpoints are internal.  */
12416 }
12417
12418 /* The breakpoint_ops structure to be used in tracepoints.  */
12419
12420 static void
12421 tracepoint_re_set (struct breakpoint *b)
12422 {
12423   breakpoint_re_set_default (b);
12424 }
12425
12426 static int
12427 tracepoint_breakpoint_hit (const struct bp_location *bl,
12428                            struct address_space *aspace, CORE_ADDR bp_addr,
12429                            const struct target_waitstatus *ws)
12430 {
12431   /* By definition, the inferior does not report stops at
12432      tracepoints.  */
12433   return 0;
12434 }
12435
12436 static void
12437 tracepoint_print_one_detail (const struct breakpoint *self,
12438                              struct ui_out *uiout)
12439 {
12440   struct tracepoint *tp = (struct tracepoint *) self;
12441   if (tp->static_trace_marker_id)
12442     {
12443       gdb_assert (self->type == bp_static_tracepoint);
12444
12445       ui_out_text (uiout, "\tmarker id is ");
12446       ui_out_field_string (uiout, "static-tracepoint-marker-string-id",
12447                            tp->static_trace_marker_id);
12448       ui_out_text (uiout, "\n");
12449     }
12450 }
12451
12452 static void
12453 tracepoint_print_mention (struct breakpoint *b)
12454 {
12455   if (ui_out_is_mi_like_p (current_uiout))
12456     return;
12457
12458   switch (b->type)
12459     {
12460     case bp_tracepoint:
12461       printf_filtered (_("Tracepoint"));
12462       printf_filtered (_(" %d"), b->number);
12463       break;
12464     case bp_fast_tracepoint:
12465       printf_filtered (_("Fast tracepoint"));
12466       printf_filtered (_(" %d"), b->number);
12467       break;
12468     case bp_static_tracepoint:
12469       printf_filtered (_("Static tracepoint"));
12470       printf_filtered (_(" %d"), b->number);
12471       break;
12472     default:
12473       internal_error (__FILE__, __LINE__,
12474                       _("unhandled tracepoint type %d"), (int) b->type);
12475     }
12476
12477   say_where (b);
12478 }
12479
12480 static void
12481 tracepoint_print_recreate (struct breakpoint *self, struct ui_file *fp)
12482 {
12483   struct tracepoint *tp = (struct tracepoint *) self;
12484
12485   if (self->type == bp_fast_tracepoint)
12486     fprintf_unfiltered (fp, "ftrace");
12487   if (self->type == bp_static_tracepoint)
12488     fprintf_unfiltered (fp, "strace");
12489   else if (self->type == bp_tracepoint)
12490     fprintf_unfiltered (fp, "trace");
12491   else
12492     internal_error (__FILE__, __LINE__,
12493                     _("unhandled tracepoint type %d"), (int) self->type);
12494
12495   fprintf_unfiltered (fp, " %s", self->addr_string);
12496   print_recreate_thread (self, fp);
12497
12498   if (tp->pass_count)
12499     fprintf_unfiltered (fp, "  passcount %d\n", tp->pass_count);
12500 }
12501
12502 static void
12503 tracepoint_create_sals_from_address (char **arg,
12504                                      struct linespec_result *canonical,
12505                                      enum bptype type_wanted,
12506                                      char *addr_start, char **copy_arg)
12507 {
12508   create_sals_from_address_default (arg, canonical, type_wanted,
12509                                     addr_start, copy_arg);
12510 }
12511
12512 static void
12513 tracepoint_create_breakpoints_sal (struct gdbarch *gdbarch,
12514                                    struct linespec_result *canonical,
12515                                    struct linespec_sals *lsal,
12516                                    char *cond_string,
12517                                    enum bptype type_wanted,
12518                                    enum bpdisp disposition,
12519                                    int thread,
12520                                    int task, int ignore_count,
12521                                    const struct breakpoint_ops *ops,
12522                                    int from_tty, int enabled,
12523                                    int internal)
12524 {
12525   create_breakpoints_sal_default (gdbarch, canonical, lsal,
12526                                   cond_string, type_wanted,
12527                                   disposition, thread, task,
12528                                   ignore_count, ops, from_tty,
12529                                   enabled, internal);
12530 }
12531
12532 static void
12533 tracepoint_decode_linespec (struct breakpoint *b, char **s,
12534                             struct symtabs_and_lines *sals)
12535 {
12536   decode_linespec_default (b, s, sals);
12537 }
12538
12539 struct breakpoint_ops tracepoint_breakpoint_ops;
12540
12541 /* The breakpoint_ops structure to be used on static tracepoints with
12542    markers (`-m').  */
12543
12544 static void
12545 strace_marker_create_sals_from_address (char **arg,
12546                                         struct linespec_result *canonical,
12547                                         enum bptype type_wanted,
12548                                         char *addr_start, char **copy_arg)
12549 {
12550   struct linespec_sals lsal;
12551
12552   lsal.sals = decode_static_tracepoint_spec (arg);
12553
12554   *copy_arg = savestring (addr_start, *arg - addr_start);
12555
12556   canonical->addr_string = xstrdup (*copy_arg);
12557   lsal.canonical = xstrdup (*copy_arg);
12558   VEC_safe_push (linespec_sals, canonical->sals, &lsal);
12559 }
12560
12561 static void
12562 strace_marker_create_breakpoints_sal (struct gdbarch *gdbarch,
12563                                       struct linespec_result *canonical,
12564                                       struct linespec_sals *lsal,
12565                                       char *cond_string,
12566                                       enum bptype type_wanted,
12567                                       enum bpdisp disposition,
12568                                       int thread,
12569                                       int task, int ignore_count,
12570                                       const struct breakpoint_ops *ops,
12571                                       int from_tty, int enabled,
12572                                       int internal)
12573 {
12574   int i;
12575
12576   /* If the user is creating a static tracepoint by marker id
12577      (strace -m MARKER_ID), then store the sals index, so that
12578      breakpoint_re_set can try to match up which of the newly
12579      found markers corresponds to this one, and, don't try to
12580      expand multiple locations for each sal, given than SALS
12581      already should contain all sals for MARKER_ID.  */
12582
12583   for (i = 0; i < lsal->sals.nelts; ++i)
12584     {
12585       struct symtabs_and_lines expanded;
12586       struct tracepoint *tp;
12587       struct cleanup *old_chain;
12588       char *addr_string;
12589
12590       expanded.nelts = 1;
12591       expanded.sals = &lsal->sals.sals[i];
12592
12593       addr_string = xstrdup (canonical->addr_string);
12594       old_chain = make_cleanup (xfree, addr_string);
12595
12596       tp = XCNEW (struct tracepoint);
12597       init_breakpoint_sal (&tp->base, gdbarch, expanded,
12598                            addr_string, NULL,
12599                            cond_string, type_wanted, disposition,
12600                            thread, task, ignore_count, ops,
12601                            from_tty, enabled, internal,
12602                            canonical->special_display);
12603       /* Given that its possible to have multiple markers with
12604          the same string id, if the user is creating a static
12605          tracepoint by marker id ("strace -m MARKER_ID"), then
12606          store the sals index, so that breakpoint_re_set can
12607          try to match up which of the newly found markers
12608          corresponds to this one  */
12609       tp->static_trace_marker_id_idx = i;
12610
12611       install_breakpoint (internal, &tp->base, 0);
12612
12613       discard_cleanups (old_chain);
12614     }
12615 }
12616
12617 static void
12618 strace_marker_decode_linespec (struct breakpoint *b, char **s,
12619                                struct symtabs_and_lines *sals)
12620 {
12621   struct tracepoint *tp = (struct tracepoint *) b;
12622
12623   *sals = decode_static_tracepoint_spec (s);
12624   if (sals->nelts > tp->static_trace_marker_id_idx)
12625     {
12626       sals->sals[0] = sals->sals[tp->static_trace_marker_id_idx];
12627       sals->nelts = 1;
12628     }
12629   else
12630     error (_("marker %s not found"), tp->static_trace_marker_id);
12631 }
12632
12633 static struct breakpoint_ops strace_marker_breakpoint_ops;
12634
12635 static int
12636 strace_marker_p (struct breakpoint *b)
12637 {
12638   return b->ops == &strace_marker_breakpoint_ops;
12639 }
12640
12641 /* Delete a breakpoint and clean up all traces of it in the data
12642    structures.  */
12643
12644 void
12645 delete_breakpoint (struct breakpoint *bpt)
12646 {
12647   struct breakpoint *b;
12648
12649   gdb_assert (bpt != NULL);
12650
12651   /* Has this bp already been deleted?  This can happen because
12652      multiple lists can hold pointers to bp's.  bpstat lists are
12653      especial culprits.
12654
12655      One example of this happening is a watchpoint's scope bp.  When
12656      the scope bp triggers, we notice that the watchpoint is out of
12657      scope, and delete it.  We also delete its scope bp.  But the
12658      scope bp is marked "auto-deleting", and is already on a bpstat.
12659      That bpstat is then checked for auto-deleting bp's, which are
12660      deleted.
12661
12662      A real solution to this problem might involve reference counts in
12663      bp's, and/or giving them pointers back to their referencing
12664      bpstat's, and teaching delete_breakpoint to only free a bp's
12665      storage when no more references were extent.  A cheaper bandaid
12666      was chosen.  */
12667   if (bpt->type == bp_none)
12668     return;
12669
12670   /* At least avoid this stale reference until the reference counting
12671      of breakpoints gets resolved.  */
12672   if (bpt->related_breakpoint != bpt)
12673     {
12674       struct breakpoint *related;
12675       struct watchpoint *w;
12676
12677       if (bpt->type == bp_watchpoint_scope)
12678         w = (struct watchpoint *) bpt->related_breakpoint;
12679       else if (bpt->related_breakpoint->type == bp_watchpoint_scope)
12680         w = (struct watchpoint *) bpt;
12681       else
12682         w = NULL;
12683       if (w != NULL)
12684         watchpoint_del_at_next_stop (w);
12685
12686       /* Unlink bpt from the bpt->related_breakpoint ring.  */
12687       for (related = bpt; related->related_breakpoint != bpt;
12688            related = related->related_breakpoint);
12689       related->related_breakpoint = bpt->related_breakpoint;
12690       bpt->related_breakpoint = bpt;
12691     }
12692
12693   /* watch_command_1 creates a watchpoint but only sets its number if
12694      update_watchpoint succeeds in creating its bp_locations.  If there's
12695      a problem in that process, we'll be asked to delete the half-created
12696      watchpoint.  In that case, don't announce the deletion.  */
12697   if (bpt->number)
12698     observer_notify_breakpoint_deleted (bpt);
12699
12700   if (breakpoint_chain == bpt)
12701     breakpoint_chain = bpt->next;
12702
12703   ALL_BREAKPOINTS (b)
12704     if (b->next == bpt)
12705     {
12706       b->next = bpt->next;
12707       break;
12708     }
12709
12710   /* Be sure no bpstat's are pointing at the breakpoint after it's
12711      been freed.  */
12712   /* FIXME, how can we find all bpstat's?  We just check stop_bpstat
12713      in all threads for now.  Note that we cannot just remove bpstats
12714      pointing at bpt from the stop_bpstat list entirely, as breakpoint
12715      commands are associated with the bpstat; if we remove it here,
12716      then the later call to bpstat_do_actions (&stop_bpstat); in
12717      event-top.c won't do anything, and temporary breakpoints with
12718      commands won't work.  */
12719
12720   iterate_over_threads (bpstat_remove_breakpoint_callback, bpt);
12721
12722   /* Now that breakpoint is removed from breakpoint list, update the
12723      global location list.  This will remove locations that used to
12724      belong to this breakpoint.  Do this before freeing the breakpoint
12725      itself, since remove_breakpoint looks at location's owner.  It
12726      might be better design to have location completely
12727      self-contained, but it's not the case now.  */
12728   update_global_location_list (0);
12729
12730   bpt->ops->dtor (bpt);
12731   /* On the chance that someone will soon try again to delete this
12732      same bp, we mark it as deleted before freeing its storage.  */
12733   bpt->type = bp_none;
12734   xfree (bpt);
12735 }
12736
12737 static void
12738 do_delete_breakpoint_cleanup (void *b)
12739 {
12740   delete_breakpoint (b);
12741 }
12742
12743 struct cleanup *
12744 make_cleanup_delete_breakpoint (struct breakpoint *b)
12745 {
12746   return make_cleanup (do_delete_breakpoint_cleanup, b);
12747 }
12748
12749 /* Iterator function to call a user-provided callback function once
12750    for each of B and its related breakpoints.  */
12751
12752 static void
12753 iterate_over_related_breakpoints (struct breakpoint *b,
12754                                   void (*function) (struct breakpoint *,
12755                                                     void *),
12756                                   void *data)
12757 {
12758   struct breakpoint *related;
12759
12760   related = b;
12761   do
12762     {
12763       struct breakpoint *next;
12764
12765       /* FUNCTION may delete RELATED.  */
12766       next = related->related_breakpoint;
12767
12768       if (next == related)
12769         {
12770           /* RELATED is the last ring entry.  */
12771           function (related, data);
12772
12773           /* FUNCTION may have deleted it, so we'd never reach back to
12774              B.  There's nothing left to do anyway, so just break
12775              out.  */
12776           break;
12777         }
12778       else
12779         function (related, data);
12780
12781       related = next;
12782     }
12783   while (related != b);
12784 }
12785
12786 static void
12787 do_delete_breakpoint (struct breakpoint *b, void *ignore)
12788 {
12789   delete_breakpoint (b);
12790 }
12791
12792 /* A callback for map_breakpoint_numbers that calls
12793    delete_breakpoint.  */
12794
12795 static void
12796 do_map_delete_breakpoint (struct breakpoint *b, void *ignore)
12797 {
12798   iterate_over_related_breakpoints (b, do_delete_breakpoint, NULL);
12799 }
12800
12801 void
12802 delete_command (char *arg, int from_tty)
12803 {
12804   struct breakpoint *b, *b_tmp;
12805
12806   dont_repeat ();
12807
12808   if (arg == 0)
12809     {
12810       int breaks_to_delete = 0;
12811
12812       /* Delete all breakpoints if no argument.  Do not delete
12813          internal breakpoints, these have to be deleted with an
12814          explicit breakpoint number argument.  */
12815       ALL_BREAKPOINTS (b)
12816         if (user_breakpoint_p (b))
12817           {
12818             breaks_to_delete = 1;
12819             break;
12820           }
12821
12822       /* Ask user only if there are some breakpoints to delete.  */
12823       if (!from_tty
12824           || (breaks_to_delete && query (_("Delete all breakpoints? "))))
12825         {
12826           ALL_BREAKPOINTS_SAFE (b, b_tmp)
12827             if (user_breakpoint_p (b))
12828               delete_breakpoint (b);
12829         }
12830     }
12831   else
12832     map_breakpoint_numbers (arg, do_map_delete_breakpoint, NULL);
12833 }
12834
12835 static int
12836 all_locations_are_pending (struct bp_location *loc)
12837 {
12838   for (; loc; loc = loc->next)
12839     if (!loc->shlib_disabled
12840         && !loc->pspace->executing_startup)
12841       return 0;
12842   return 1;
12843 }
12844
12845 /* Subroutine of update_breakpoint_locations to simplify it.
12846    Return non-zero if multiple fns in list LOC have the same name.
12847    Null names are ignored.  */
12848
12849 static int
12850 ambiguous_names_p (struct bp_location *loc)
12851 {
12852   struct bp_location *l;
12853   htab_t htab = htab_create_alloc (13, htab_hash_string,
12854                                    (int (*) (const void *, 
12855                                              const void *)) streq,
12856                                    NULL, xcalloc, xfree);
12857
12858   for (l = loc; l != NULL; l = l->next)
12859     {
12860       const char **slot;
12861       const char *name = l->function_name;
12862
12863       /* Allow for some names to be NULL, ignore them.  */
12864       if (name == NULL)
12865         continue;
12866
12867       slot = (const char **) htab_find_slot (htab, (const void *) name,
12868                                              INSERT);
12869       /* NOTE: We can assume slot != NULL here because xcalloc never
12870          returns NULL.  */
12871       if (*slot != NULL)
12872         {
12873           htab_delete (htab);
12874           return 1;
12875         }
12876       *slot = name;
12877     }
12878
12879   htab_delete (htab);
12880   return 0;
12881 }
12882
12883 /* When symbols change, it probably means the sources changed as well,
12884    and it might mean the static tracepoint markers are no longer at
12885    the same address or line numbers they used to be at last we
12886    checked.  Losing your static tracepoints whenever you rebuild is
12887    undesirable.  This function tries to resync/rematch gdb static
12888    tracepoints with the markers on the target, for static tracepoints
12889    that have not been set by marker id.  Static tracepoint that have
12890    been set by marker id are reset by marker id in breakpoint_re_set.
12891    The heuristic is:
12892
12893    1) For a tracepoint set at a specific address, look for a marker at
12894    the old PC.  If one is found there, assume to be the same marker.
12895    If the name / string id of the marker found is different from the
12896    previous known name, assume that means the user renamed the marker
12897    in the sources, and output a warning.
12898
12899    2) For a tracepoint set at a given line number, look for a marker
12900    at the new address of the old line number.  If one is found there,
12901    assume to be the same marker.  If the name / string id of the
12902    marker found is different from the previous known name, assume that
12903    means the user renamed the marker in the sources, and output a
12904    warning.
12905
12906    3) If a marker is no longer found at the same address or line, it
12907    may mean the marker no longer exists.  But it may also just mean
12908    the code changed a bit.  Maybe the user added a few lines of code
12909    that made the marker move up or down (in line number terms).  Ask
12910    the target for info about the marker with the string id as we knew
12911    it.  If found, update line number and address in the matching
12912    static tracepoint.  This will get confused if there's more than one
12913    marker with the same ID (possible in UST, although unadvised
12914    precisely because it confuses tools).  */
12915
12916 static struct symtab_and_line
12917 update_static_tracepoint (struct breakpoint *b, struct symtab_and_line sal)
12918 {
12919   struct tracepoint *tp = (struct tracepoint *) b;
12920   struct static_tracepoint_marker marker;
12921   CORE_ADDR pc;
12922   int i;
12923
12924   pc = sal.pc;
12925   if (sal.line)
12926     find_line_pc (sal.symtab, sal.line, &pc);
12927
12928   if (target_static_tracepoint_marker_at (pc, &marker))
12929     {
12930       if (strcmp (tp->static_trace_marker_id, marker.str_id) != 0)
12931         warning (_("static tracepoint %d changed probed marker from %s to %s"),
12932                  b->number,
12933                  tp->static_trace_marker_id, marker.str_id);
12934
12935       xfree (tp->static_trace_marker_id);
12936       tp->static_trace_marker_id = xstrdup (marker.str_id);
12937       release_static_tracepoint_marker (&marker);
12938
12939       return sal;
12940     }
12941
12942   /* Old marker wasn't found on target at lineno.  Try looking it up
12943      by string ID.  */
12944   if (!sal.explicit_pc
12945       && sal.line != 0
12946       && sal.symtab != NULL
12947       && tp->static_trace_marker_id != NULL)
12948     {
12949       VEC(static_tracepoint_marker_p) *markers;
12950
12951       markers
12952         = target_static_tracepoint_markers_by_strid (tp->static_trace_marker_id);
12953
12954       if (!VEC_empty(static_tracepoint_marker_p, markers))
12955         {
12956           struct symtab_and_line sal2;
12957           struct symbol *sym;
12958           struct static_tracepoint_marker *tpmarker;
12959           struct ui_out *uiout = current_uiout;
12960
12961           tpmarker = VEC_index (static_tracepoint_marker_p, markers, 0);
12962
12963           xfree (tp->static_trace_marker_id);
12964           tp->static_trace_marker_id = xstrdup (tpmarker->str_id);
12965
12966           warning (_("marker for static tracepoint %d (%s) not "
12967                      "found at previous line number"),
12968                    b->number, tp->static_trace_marker_id);
12969
12970           init_sal (&sal2);
12971
12972           sal2.pc = tpmarker->address;
12973
12974           sal2 = find_pc_line (tpmarker->address, 0);
12975           sym = find_pc_sect_function (tpmarker->address, NULL);
12976           ui_out_text (uiout, "Now in ");
12977           if (sym)
12978             {
12979               ui_out_field_string (uiout, "func",
12980                                    SYMBOL_PRINT_NAME (sym));
12981               ui_out_text (uiout, " at ");
12982             }
12983           ui_out_field_string (uiout, "file", sal2.symtab->filename);
12984           ui_out_text (uiout, ":");
12985
12986           if (ui_out_is_mi_like_p (uiout))
12987             {
12988               char *fullname = symtab_to_fullname (sal2.symtab);
12989
12990               if (fullname)
12991                 ui_out_field_string (uiout, "fullname", fullname);
12992             }
12993
12994           ui_out_field_int (uiout, "line", sal2.line);
12995           ui_out_text (uiout, "\n");
12996
12997           b->loc->line_number = sal2.line;
12998
12999           xfree (b->loc->source_file);
13000           if (sym)
13001             b->loc->source_file = xstrdup (sal2.symtab->filename);
13002           else
13003             b->loc->source_file = NULL;
13004
13005           xfree (b->addr_string);
13006           b->addr_string = xstrprintf ("%s:%d",
13007                                        sal2.symtab->filename,
13008                                        b->loc->line_number);
13009
13010           /* Might be nice to check if function changed, and warn if
13011              so.  */
13012
13013           release_static_tracepoint_marker (tpmarker);
13014         }
13015     }
13016   return sal;
13017 }
13018
13019 /* Returns 1 iff locations A and B are sufficiently same that
13020    we don't need to report breakpoint as changed.  */
13021
13022 static int
13023 locations_are_equal (struct bp_location *a, struct bp_location *b)
13024 {
13025   while (a && b)
13026     {
13027       if (a->address != b->address)
13028         return 0;
13029
13030       if (a->shlib_disabled != b->shlib_disabled)
13031         return 0;
13032
13033       if (a->enabled != b->enabled)
13034         return 0;
13035
13036       a = a->next;
13037       b = b->next;
13038     }
13039
13040   if ((a == NULL) != (b == NULL))
13041     return 0;
13042
13043   return 1;
13044 }
13045
13046 /* Create new breakpoint locations for B (a hardware or software breakpoint)
13047    based on SALS and SALS_END.  If SALS_END.NELTS is not zero, then B is
13048    a ranged breakpoint.  */
13049
13050 void
13051 update_breakpoint_locations (struct breakpoint *b,
13052                              struct symtabs_and_lines sals,
13053                              struct symtabs_and_lines sals_end)
13054 {
13055   int i;
13056   struct bp_location *existing_locations = b->loc;
13057
13058   if (sals_end.nelts != 0 && (sals.nelts != 1 || sals_end.nelts != 1))
13059     {
13060       /* Ranged breakpoints have only one start location and one end
13061          location.  */
13062       b->enable_state = bp_disabled;
13063       update_global_location_list (1);
13064       printf_unfiltered (_("Could not reset ranged breakpoint %d: "
13065                            "multiple locations found\n"),
13066                          b->number);
13067       return;
13068     }
13069
13070   /* If there's no new locations, and all existing locations are
13071      pending, don't do anything.  This optimizes the common case where
13072      all locations are in the same shared library, that was unloaded.
13073      We'd like to retain the location, so that when the library is
13074      loaded again, we don't loose the enabled/disabled status of the
13075      individual locations.  */
13076   if (all_locations_are_pending (existing_locations) && sals.nelts == 0)
13077     return;
13078
13079   b->loc = NULL;
13080
13081   for (i = 0; i < sals.nelts; ++i)
13082     {
13083       struct bp_location *new_loc;
13084
13085       switch_to_program_space_and_thread (sals.sals[i].pspace);
13086
13087       new_loc = add_location_to_breakpoint (b, &(sals.sals[i]));
13088
13089       /* Reparse conditions, they might contain references to the
13090          old symtab.  */
13091       if (b->cond_string != NULL)
13092         {
13093           char *s;
13094           volatile struct gdb_exception e;
13095
13096           s = b->cond_string;
13097           TRY_CATCH (e, RETURN_MASK_ERROR)
13098             {
13099               new_loc->cond = parse_exp_1 (&s, block_for_pc (sals.sals[i].pc), 
13100                                            0);
13101             }
13102           if (e.reason < 0)
13103             {
13104               warning (_("failed to reevaluate condition "
13105                          "for breakpoint %d: %s"), 
13106                        b->number, e.message);
13107               new_loc->enabled = 0;
13108             }
13109         }
13110
13111       if (sals_end.nelts)
13112         {
13113           CORE_ADDR end = find_breakpoint_range_end (sals_end.sals[0]);
13114
13115           new_loc->length = end - sals.sals[0].pc + 1;
13116         }
13117     }
13118
13119   /* Update locations of permanent breakpoints.  */
13120   if (b->enable_state == bp_permanent)
13121     make_breakpoint_permanent (b);
13122
13123   /* If possible, carry over 'disable' status from existing
13124      breakpoints.  */
13125   {
13126     struct bp_location *e = existing_locations;
13127     /* If there are multiple breakpoints with the same function name,
13128        e.g. for inline functions, comparing function names won't work.
13129        Instead compare pc addresses; this is just a heuristic as things
13130        may have moved, but in practice it gives the correct answer
13131        often enough until a better solution is found.  */
13132     int have_ambiguous_names = ambiguous_names_p (b->loc);
13133
13134     for (; e; e = e->next)
13135       {
13136         if (!e->enabled && e->function_name)
13137           {
13138             struct bp_location *l = b->loc;
13139             if (have_ambiguous_names)
13140               {
13141                 for (; l; l = l->next)
13142                   if (breakpoint_locations_match (e, l))
13143                     {
13144                       l->enabled = 0;
13145                       break;
13146                     }
13147               }
13148             else
13149               {
13150                 for (; l; l = l->next)
13151                   if (l->function_name
13152                       && strcmp (e->function_name, l->function_name) == 0)
13153                     {
13154                       l->enabled = 0;
13155                       break;
13156                     }
13157               }
13158           }
13159       }
13160   }
13161
13162   if (!locations_are_equal (existing_locations, b->loc))
13163     observer_notify_breakpoint_modified (b);
13164
13165   update_global_location_list (1);
13166 }
13167
13168 /* Find the SaL locations corresponding to the given ADDR_STRING.
13169    On return, FOUND will be 1 if any SaL was found, zero otherwise.  */
13170
13171 static struct symtabs_and_lines
13172 addr_string_to_sals (struct breakpoint *b, char *addr_string, int *found)
13173 {
13174   char *s;
13175   struct symtabs_and_lines sals = {0};
13176   volatile struct gdb_exception e;
13177
13178   gdb_assert (b->ops != NULL);
13179   s = addr_string;
13180
13181   TRY_CATCH (e, RETURN_MASK_ERROR)
13182     {
13183       b->ops->decode_linespec (b, &s, &sals);
13184     }
13185   if (e.reason < 0)
13186     {
13187       int not_found_and_ok = 0;
13188       /* For pending breakpoints, it's expected that parsing will
13189          fail until the right shared library is loaded.  User has
13190          already told to create pending breakpoints and don't need
13191          extra messages.  If breakpoint is in bp_shlib_disabled
13192          state, then user already saw the message about that
13193          breakpoint being disabled, and don't want to see more
13194          errors.  */
13195       if (e.error == NOT_FOUND_ERROR
13196           && (b->condition_not_parsed 
13197               || (b->loc && b->loc->shlib_disabled)
13198               || (b->loc && b->loc->pspace->executing_startup)
13199               || b->enable_state == bp_disabled))
13200         not_found_and_ok = 1;
13201
13202       if (!not_found_and_ok)
13203         {
13204           /* We surely don't want to warn about the same breakpoint
13205              10 times.  One solution, implemented here, is disable
13206              the breakpoint on error.  Another solution would be to
13207              have separate 'warning emitted' flag.  Since this
13208              happens only when a binary has changed, I don't know
13209              which approach is better.  */
13210           b->enable_state = bp_disabled;
13211           throw_exception (e);
13212         }
13213     }
13214
13215   if (e.reason == 0 || e.error != NOT_FOUND_ERROR)
13216     {
13217       int i;
13218
13219       for (i = 0; i < sals.nelts; ++i)
13220         resolve_sal_pc (&sals.sals[i]);
13221       if (b->condition_not_parsed && s && s[0])
13222         {
13223           char *cond_string = 0;
13224           int thread = -1;
13225           int task = 0;
13226
13227           find_condition_and_thread (s, sals.sals[0].pc,
13228                                      &cond_string, &thread, &task);
13229           if (cond_string)
13230             b->cond_string = cond_string;
13231           b->thread = thread;
13232           b->task = task;
13233           b->condition_not_parsed = 0;
13234         }
13235
13236       if (b->type == bp_static_tracepoint && !strace_marker_p (b))
13237         sals.sals[0] = update_static_tracepoint (b, sals.sals[0]);
13238
13239       *found = 1;
13240     }
13241   else
13242     *found = 0;
13243
13244   return sals;
13245 }
13246
13247 /* The default re_set method, for typical hardware or software
13248    breakpoints.  Reevaluate the breakpoint and recreate its
13249    locations.  */
13250
13251 static void
13252 breakpoint_re_set_default (struct breakpoint *b)
13253 {
13254   int found;
13255   struct symtabs_and_lines sals, sals_end;
13256   struct symtabs_and_lines expanded = {0};
13257   struct symtabs_and_lines expanded_end = {0};
13258
13259   sals = addr_string_to_sals (b, b->addr_string, &found);
13260   if (found)
13261     {
13262       make_cleanup (xfree, sals.sals);
13263       expanded = sals;
13264     }
13265
13266   if (b->addr_string_range_end)
13267     {
13268       sals_end = addr_string_to_sals (b, b->addr_string_range_end, &found);
13269       if (found)
13270         {
13271           make_cleanup (xfree, sals_end.sals);
13272           expanded_end = sals_end;
13273         }
13274     }
13275
13276   update_breakpoint_locations (b, expanded, expanded_end);
13277 }
13278
13279 /* Default method for creating SALs from an address string.  It basically
13280    calls parse_breakpoint_sals.  Return 1 for success, zero for failure.  */
13281
13282 static void
13283 create_sals_from_address_default (char **arg,
13284                                   struct linespec_result *canonical,
13285                                   enum bptype type_wanted,
13286                                   char *addr_start, char **copy_arg)
13287 {
13288   parse_breakpoint_sals (arg, canonical);
13289 }
13290
13291 /* Call create_breakpoints_sal for the given arguments.  This is the default
13292    function for the `create_breakpoints_sal' method of
13293    breakpoint_ops.  */
13294
13295 static void
13296 create_breakpoints_sal_default (struct gdbarch *gdbarch,
13297                                 struct linespec_result *canonical,
13298                                 struct linespec_sals *lsal,
13299                                 char *cond_string,
13300                                 enum bptype type_wanted,
13301                                 enum bpdisp disposition,
13302                                 int thread,
13303                                 int task, int ignore_count,
13304                                 const struct breakpoint_ops *ops,
13305                                 int from_tty, int enabled,
13306                                 int internal)
13307 {
13308   create_breakpoints_sal (gdbarch, canonical, cond_string,
13309                           type_wanted, disposition,
13310                           thread, task, ignore_count, ops, from_tty,
13311                           enabled, internal);
13312 }
13313
13314 /* Decode the line represented by S by calling decode_line_full.  This is the
13315    default function for the `decode_linespec' method of breakpoint_ops.  */
13316
13317 static void
13318 decode_linespec_default (struct breakpoint *b, char **s,
13319                          struct symtabs_and_lines *sals)
13320 {
13321   struct linespec_result canonical;
13322
13323   init_linespec_result (&canonical);
13324   decode_line_full (s, DECODE_LINE_FUNFIRSTLINE,
13325                     (struct symtab *) NULL, 0,
13326                     &canonical, multiple_symbols_all,
13327                     b->filter);
13328
13329   /* We should get 0 or 1 resulting SALs.  */
13330   gdb_assert (VEC_length (linespec_sals, canonical.sals) < 2);
13331
13332   if (VEC_length (linespec_sals, canonical.sals) > 0)
13333     {
13334       struct linespec_sals *lsal;
13335
13336       lsal = VEC_index (linespec_sals, canonical.sals, 0);
13337       *sals = lsal->sals;
13338       /* Arrange it so the destructor does not free the
13339          contents.  */
13340       lsal->sals.sals = NULL;
13341     }
13342
13343   destroy_linespec_result (&canonical);
13344 }
13345
13346 /* Prepare the global context for a re-set of breakpoint B.  */
13347
13348 static struct cleanup *
13349 prepare_re_set_context (struct breakpoint *b)
13350 {
13351   struct cleanup *cleanups;
13352
13353   input_radix = b->input_radix;
13354   cleanups = save_current_space_and_thread ();
13355   if (b->pspace != NULL)
13356     switch_to_program_space_and_thread (b->pspace);
13357   set_language (b->language);
13358
13359   return cleanups;
13360 }
13361
13362 /* Reset a breakpoint given it's struct breakpoint * BINT.
13363    The value we return ends up being the return value from catch_errors.
13364    Unused in this case.  */
13365
13366 static int
13367 breakpoint_re_set_one (void *bint)
13368 {
13369   /* Get past catch_errs.  */
13370   struct breakpoint *b = (struct breakpoint *) bint;
13371   struct cleanup *cleanups;
13372
13373   cleanups = prepare_re_set_context (b);
13374   b->ops->re_set (b);
13375   do_cleanups (cleanups);
13376   return 0;
13377 }
13378
13379 /* Re-set all breakpoints after symbols have been re-loaded.  */
13380 void
13381 breakpoint_re_set (void)
13382 {
13383   struct breakpoint *b, *b_tmp;
13384   enum language save_language;
13385   int save_input_radix;
13386   struct cleanup *old_chain;
13387
13388   save_language = current_language->la_language;
13389   save_input_radix = input_radix;
13390   old_chain = save_current_program_space ();
13391
13392   ALL_BREAKPOINTS_SAFE (b, b_tmp)
13393   {
13394     /* Format possible error msg.  */
13395     char *message = xstrprintf ("Error in re-setting breakpoint %d: ",
13396                                 b->number);
13397     struct cleanup *cleanups = make_cleanup (xfree, message);
13398     catch_errors (breakpoint_re_set_one, b, message, RETURN_MASK_ALL);
13399     do_cleanups (cleanups);
13400   }
13401   set_language (save_language);
13402   input_radix = save_input_radix;
13403
13404   jit_breakpoint_re_set ();
13405
13406   do_cleanups (old_chain);
13407
13408   create_overlay_event_breakpoint ();
13409   create_longjmp_master_breakpoint ();
13410   create_std_terminate_master_breakpoint ();
13411   create_exception_master_breakpoint ();
13412
13413   /* While we're at it, reset the skip list too.  */
13414   skip_re_set ();
13415 }
13416 \f
13417 /* Reset the thread number of this breakpoint:
13418
13419    - If the breakpoint is for all threads, leave it as-is.
13420    - Else, reset it to the current thread for inferior_ptid.  */
13421 void
13422 breakpoint_re_set_thread (struct breakpoint *b)
13423 {
13424   if (b->thread != -1)
13425     {
13426       if (in_thread_list (inferior_ptid))
13427         b->thread = pid_to_thread_id (inferior_ptid);
13428
13429       /* We're being called after following a fork.  The new fork is
13430          selected as current, and unless this was a vfork will have a
13431          different program space from the original thread.  Reset that
13432          as well.  */
13433       b->loc->pspace = current_program_space;
13434     }
13435 }
13436
13437 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
13438    If from_tty is nonzero, it prints a message to that effect,
13439    which ends with a period (no newline).  */
13440
13441 void
13442 set_ignore_count (int bptnum, int count, int from_tty)
13443 {
13444   struct breakpoint *b;
13445
13446   if (count < 0)
13447     count = 0;
13448
13449   ALL_BREAKPOINTS (b)
13450     if (b->number == bptnum)
13451     {
13452       if (is_tracepoint (b))
13453         {
13454           if (from_tty && count != 0)
13455             printf_filtered (_("Ignore count ignored for tracepoint %d."),
13456                              bptnum);
13457           return;
13458         }
13459       
13460       b->ignore_count = count;
13461       if (from_tty)
13462         {
13463           if (count == 0)
13464             printf_filtered (_("Will stop next time "
13465                                "breakpoint %d is reached."),
13466                              bptnum);
13467           else if (count == 1)
13468             printf_filtered (_("Will ignore next crossing of breakpoint %d."),
13469                              bptnum);
13470           else
13471             printf_filtered (_("Will ignore next %d "
13472                                "crossings of breakpoint %d."),
13473                              count, bptnum);
13474         }
13475       breakpoints_changed ();
13476       observer_notify_breakpoint_modified (b);
13477       return;
13478     }
13479
13480   error (_("No breakpoint number %d."), bptnum);
13481 }
13482
13483 /* Command to set ignore-count of breakpoint N to COUNT.  */
13484
13485 static void
13486 ignore_command (char *args, int from_tty)
13487 {
13488   char *p = args;
13489   int num;
13490
13491   if (p == 0)
13492     error_no_arg (_("a breakpoint number"));
13493
13494   num = get_number (&p);
13495   if (num == 0)
13496     error (_("bad breakpoint number: '%s'"), args);
13497   if (*p == 0)
13498     error (_("Second argument (specified ignore-count) is missing."));
13499
13500   set_ignore_count (num,
13501                     longest_to_int (value_as_long (parse_and_eval (p))),
13502                     from_tty);
13503   if (from_tty)
13504     printf_filtered ("\n");
13505 }
13506 \f
13507 /* Call FUNCTION on each of the breakpoints
13508    whose numbers are given in ARGS.  */
13509
13510 static void
13511 map_breakpoint_numbers (char *args, void (*function) (struct breakpoint *,
13512                                                       void *),
13513                         void *data)
13514 {
13515   int num;
13516   struct breakpoint *b, *tmp;
13517   int match;
13518   struct get_number_or_range_state state;
13519
13520   if (args == 0)
13521     error_no_arg (_("one or more breakpoint numbers"));
13522
13523   init_number_or_range (&state, args);
13524
13525   while (!state.finished)
13526     {
13527       char *p = state.string;
13528
13529       match = 0;
13530
13531       num = get_number_or_range (&state);
13532       if (num == 0)
13533         {
13534           warning (_("bad breakpoint number at or near '%s'"), p);
13535         }
13536       else
13537         {
13538           ALL_BREAKPOINTS_SAFE (b, tmp)
13539             if (b->number == num)
13540               {
13541                 match = 1;
13542                 function (b, data);
13543                 break;
13544               }
13545           if (match == 0)
13546             printf_unfiltered (_("No breakpoint number %d.\n"), num);
13547         }
13548     }
13549 }
13550
13551 static struct bp_location *
13552 find_location_by_number (char *number)
13553 {
13554   char *dot = strchr (number, '.');
13555   char *p1;
13556   int bp_num;
13557   int loc_num;
13558   struct breakpoint *b;
13559   struct bp_location *loc;  
13560
13561   *dot = '\0';
13562
13563   p1 = number;
13564   bp_num = get_number (&p1);
13565   if (bp_num == 0)
13566     error (_("Bad breakpoint number '%s'"), number);
13567
13568   ALL_BREAKPOINTS (b)
13569     if (b->number == bp_num)
13570       {
13571         break;
13572       }
13573
13574   if (!b || b->number != bp_num)
13575     error (_("Bad breakpoint number '%s'"), number);
13576   
13577   p1 = dot+1;
13578   loc_num = get_number (&p1);
13579   if (loc_num == 0)
13580     error (_("Bad breakpoint location number '%s'"), number);
13581
13582   --loc_num;
13583   loc = b->loc;
13584   for (;loc_num && loc; --loc_num, loc = loc->next)
13585     ;
13586   if (!loc)
13587     error (_("Bad breakpoint location number '%s'"), dot+1);
13588     
13589   return loc;  
13590 }
13591
13592
13593 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
13594    If from_tty is nonzero, it prints a message to that effect,
13595    which ends with a period (no newline).  */
13596
13597 void
13598 disable_breakpoint (struct breakpoint *bpt)
13599 {
13600   /* Never disable a watchpoint scope breakpoint; we want to
13601      hit them when we leave scope so we can delete both the
13602      watchpoint and its scope breakpoint at that time.  */
13603   if (bpt->type == bp_watchpoint_scope)
13604     return;
13605
13606   /* You can't disable permanent breakpoints.  */
13607   if (bpt->enable_state == bp_permanent)
13608     return;
13609
13610   bpt->enable_state = bp_disabled;
13611
13612   /* Mark breakpoint locations modified.  */
13613   mark_breakpoint_modified (bpt);
13614
13615   if (target_supports_enable_disable_tracepoint ()
13616       && current_trace_status ()->running && is_tracepoint (bpt))
13617     {
13618       struct bp_location *location;
13619      
13620       for (location = bpt->loc; location; location = location->next)
13621         target_disable_tracepoint (location);
13622     }
13623
13624   update_global_location_list (0);
13625
13626   observer_notify_breakpoint_modified (bpt);
13627 }
13628
13629 /* A callback for iterate_over_related_breakpoints.  */
13630
13631 static void
13632 do_disable_breakpoint (struct breakpoint *b, void *ignore)
13633 {
13634   disable_breakpoint (b);
13635 }
13636
13637 /* A callback for map_breakpoint_numbers that calls
13638    disable_breakpoint.  */
13639
13640 static void
13641 do_map_disable_breakpoint (struct breakpoint *b, void *ignore)
13642 {
13643   iterate_over_related_breakpoints (b, do_disable_breakpoint, NULL);
13644 }
13645
13646 static void
13647 disable_command (char *args, int from_tty)
13648 {
13649   if (args == 0)
13650     {
13651       struct breakpoint *bpt;
13652
13653       ALL_BREAKPOINTS (bpt)
13654         if (user_breakpoint_p (bpt))
13655           disable_breakpoint (bpt);
13656     }
13657   else if (strchr (args, '.'))
13658     {
13659       struct bp_location *loc = find_location_by_number (args);
13660       if (loc)
13661         {
13662           if (loc->enabled)
13663             {
13664               loc->enabled = 0;
13665               mark_breakpoint_location_modified (loc);
13666             }
13667           if (target_supports_enable_disable_tracepoint ()
13668               && current_trace_status ()->running && loc->owner
13669               && is_tracepoint (loc->owner))
13670             target_disable_tracepoint (loc);
13671         }
13672       update_global_location_list (0);
13673     }
13674   else
13675     map_breakpoint_numbers (args, do_map_disable_breakpoint, NULL);
13676 }
13677
13678 static void
13679 enable_breakpoint_disp (struct breakpoint *bpt, enum bpdisp disposition,
13680                         int count)
13681 {
13682   int target_resources_ok;
13683
13684   if (bpt->type == bp_hardware_breakpoint)
13685     {
13686       int i;
13687       i = hw_breakpoint_used_count ();
13688       target_resources_ok = 
13689         target_can_use_hardware_watchpoint (bp_hardware_breakpoint, 
13690                                             i + 1, 0);
13691       if (target_resources_ok == 0)
13692         error (_("No hardware breakpoint support in the target."));
13693       else if (target_resources_ok < 0)
13694         error (_("Hardware breakpoints used exceeds limit."));
13695     }
13696
13697   if (is_watchpoint (bpt))
13698     {
13699       /* Initialize it just to avoid a GCC false warning.  */
13700       enum enable_state orig_enable_state = 0;
13701       volatile struct gdb_exception e;
13702
13703       TRY_CATCH (e, RETURN_MASK_ALL)
13704         {
13705           struct watchpoint *w = (struct watchpoint *) bpt;
13706
13707           orig_enable_state = bpt->enable_state;
13708           bpt->enable_state = bp_enabled;
13709           update_watchpoint (w, 1 /* reparse */);
13710         }
13711       if (e.reason < 0)
13712         {
13713           bpt->enable_state = orig_enable_state;
13714           exception_fprintf (gdb_stderr, e, _("Cannot enable watchpoint %d: "),
13715                              bpt->number);
13716           return;
13717         }
13718     }
13719
13720   if (bpt->enable_state != bp_permanent)
13721     bpt->enable_state = bp_enabled;
13722
13723   bpt->enable_state = bp_enabled;
13724
13725   /* Mark breakpoint locations modified.  */
13726   mark_breakpoint_modified (bpt);
13727
13728   if (target_supports_enable_disable_tracepoint ()
13729       && current_trace_status ()->running && is_tracepoint (bpt))
13730     {
13731       struct bp_location *location;
13732
13733       for (location = bpt->loc; location; location = location->next)
13734         target_enable_tracepoint (location);
13735     }
13736
13737   bpt->disposition = disposition;
13738   bpt->enable_count = count;
13739   update_global_location_list (1);
13740   breakpoints_changed ();
13741   
13742   observer_notify_breakpoint_modified (bpt);
13743 }
13744
13745
13746 void
13747 enable_breakpoint (struct breakpoint *bpt)
13748 {
13749   enable_breakpoint_disp (bpt, bpt->disposition, 0);
13750 }
13751
13752 static void
13753 do_enable_breakpoint (struct breakpoint *bpt, void *arg)
13754 {
13755   enable_breakpoint (bpt);
13756 }
13757
13758 /* A callback for map_breakpoint_numbers that calls
13759    enable_breakpoint.  */
13760
13761 static void
13762 do_map_enable_breakpoint (struct breakpoint *b, void *ignore)
13763 {
13764   iterate_over_related_breakpoints (b, do_enable_breakpoint, NULL);
13765 }
13766
13767 /* The enable command enables the specified breakpoints (or all defined
13768    breakpoints) so they once again become (or continue to be) effective
13769    in stopping the inferior.  */
13770
13771 static void
13772 enable_command (char *args, int from_tty)
13773 {
13774   if (args == 0)
13775     {
13776       struct breakpoint *bpt;
13777
13778       ALL_BREAKPOINTS (bpt)
13779         if (user_breakpoint_p (bpt))
13780           enable_breakpoint (bpt);
13781     }
13782   else if (strchr (args, '.'))
13783     {
13784       struct bp_location *loc = find_location_by_number (args);
13785       if (loc)
13786         {
13787           if (!loc->enabled)
13788             {
13789               loc->enabled = 1;
13790               mark_breakpoint_location_modified (loc);
13791             }
13792           if (target_supports_enable_disable_tracepoint ()
13793               && current_trace_status ()->running && loc->owner
13794               && is_tracepoint (loc->owner))
13795             target_enable_tracepoint (loc);
13796         }
13797       update_global_location_list (1);
13798     }
13799   else
13800     map_breakpoint_numbers (args, do_map_enable_breakpoint, NULL);
13801 }
13802
13803 /* This struct packages up disposition data for application to multiple
13804    breakpoints.  */
13805
13806 struct disp_data
13807 {
13808   enum bpdisp disp;
13809   int count;
13810 };
13811
13812 static void
13813 do_enable_breakpoint_disp (struct breakpoint *bpt, void *arg)
13814 {
13815   struct disp_data disp_data = *(struct disp_data *) arg;
13816
13817   enable_breakpoint_disp (bpt, disp_data.disp, disp_data.count);
13818 }
13819
13820 static void
13821 do_map_enable_once_breakpoint (struct breakpoint *bpt, void *ignore)
13822 {
13823   struct disp_data disp = { disp_disable, 1 };
13824
13825   iterate_over_related_breakpoints (bpt, do_enable_breakpoint_disp, &disp);
13826 }
13827
13828 static void
13829 enable_once_command (char *args, int from_tty)
13830 {
13831   map_breakpoint_numbers (args, do_map_enable_once_breakpoint, NULL);
13832 }
13833
13834 static void
13835 do_map_enable_count_breakpoint (struct breakpoint *bpt, void *countptr)
13836 {
13837   struct disp_data disp = { disp_disable, *(int *) countptr };
13838
13839   iterate_over_related_breakpoints (bpt, do_enable_breakpoint_disp, &disp);
13840 }
13841
13842 static void
13843 enable_count_command (char *args, int from_tty)
13844 {
13845   int count = get_number (&args);
13846
13847   map_breakpoint_numbers (args, do_map_enable_count_breakpoint, &count);
13848 }
13849
13850 static void
13851 do_map_enable_delete_breakpoint (struct breakpoint *bpt, void *ignore)
13852 {
13853   struct disp_data disp = { disp_del, 1 };
13854
13855   iterate_over_related_breakpoints (bpt, do_enable_breakpoint_disp, &disp);
13856 }
13857
13858 static void
13859 enable_delete_command (char *args, int from_tty)
13860 {
13861   map_breakpoint_numbers (args, do_map_enable_delete_breakpoint, NULL);
13862 }
13863 \f
13864 static void
13865 set_breakpoint_cmd (char *args, int from_tty)
13866 {
13867 }
13868
13869 static void
13870 show_breakpoint_cmd (char *args, int from_tty)
13871 {
13872 }
13873
13874 /* Invalidate last known value of any hardware watchpoint if
13875    the memory which that value represents has been written to by
13876    GDB itself.  */
13877
13878 static void
13879 invalidate_bp_value_on_memory_change (CORE_ADDR addr, int len,
13880                                       const bfd_byte *data)
13881 {
13882   struct breakpoint *bp;
13883
13884   ALL_BREAKPOINTS (bp)
13885     if (bp->enable_state == bp_enabled
13886         && bp->type == bp_hardware_watchpoint)
13887       {
13888         struct watchpoint *wp = (struct watchpoint *) bp;
13889
13890         if (wp->val_valid && wp->val)
13891           {
13892             struct bp_location *loc;
13893
13894             for (loc = bp->loc; loc != NULL; loc = loc->next)
13895               if (loc->loc_type == bp_loc_hardware_watchpoint
13896                   && loc->address + loc->length > addr
13897                   && addr + len > loc->address)
13898                 {
13899                   value_free (wp->val);
13900                   wp->val = NULL;
13901                   wp->val_valid = 0;
13902                 }
13903           }
13904       }
13905 }
13906
13907 /* Use the last displayed codepoint's values, or nothing
13908    if they aren't valid.  */
13909
13910 struct symtabs_and_lines
13911 decode_line_spec_1 (char *string, int flags)
13912 {
13913   struct symtabs_and_lines sals;
13914
13915   if (string == 0)
13916     error (_("Empty line specification."));
13917   if (last_displayed_sal_is_valid ())
13918     sals = decode_line_1 (&string, flags,
13919                           get_last_displayed_symtab (),
13920                           get_last_displayed_line ());
13921   else
13922     sals = decode_line_1 (&string, flags, (struct symtab *) NULL, 0);
13923   if (*string)
13924     error (_("Junk at end of line specification: %s"), string);
13925   return sals;
13926 }
13927
13928 /* Create and insert a raw software breakpoint at PC.  Return an
13929    identifier, which should be used to remove the breakpoint later.
13930    In general, places which call this should be using something on the
13931    breakpoint chain instead; this function should be eliminated
13932    someday.  */
13933
13934 void *
13935 deprecated_insert_raw_breakpoint (struct gdbarch *gdbarch,
13936                                   struct address_space *aspace, CORE_ADDR pc)
13937 {
13938   struct bp_target_info *bp_tgt;
13939
13940   bp_tgt = XZALLOC (struct bp_target_info);
13941
13942   bp_tgt->placed_address_space = aspace;
13943   bp_tgt->placed_address = pc;
13944
13945   if (target_insert_breakpoint (gdbarch, bp_tgt) != 0)
13946     {
13947       /* Could not insert the breakpoint.  */
13948       xfree (bp_tgt);
13949       return NULL;
13950     }
13951
13952   return bp_tgt;
13953 }
13954
13955 /* Remove a breakpoint BP inserted by
13956    deprecated_insert_raw_breakpoint.  */
13957
13958 int
13959 deprecated_remove_raw_breakpoint (struct gdbarch *gdbarch, void *bp)
13960 {
13961   struct bp_target_info *bp_tgt = bp;
13962   int ret;
13963
13964   ret = target_remove_breakpoint (gdbarch, bp_tgt);
13965   xfree (bp_tgt);
13966
13967   return ret;
13968 }
13969
13970 /* One (or perhaps two) breakpoints used for software single
13971    stepping.  */
13972
13973 static void *single_step_breakpoints[2];
13974 static struct gdbarch *single_step_gdbarch[2];
13975
13976 /* Create and insert a breakpoint for software single step.  */
13977
13978 void
13979 insert_single_step_breakpoint (struct gdbarch *gdbarch,
13980                                struct address_space *aspace, 
13981                                CORE_ADDR next_pc)
13982 {
13983   void **bpt_p;
13984
13985   if (single_step_breakpoints[0] == NULL)
13986     {
13987       bpt_p = &single_step_breakpoints[0];
13988       single_step_gdbarch[0] = gdbarch;
13989     }
13990   else
13991     {
13992       gdb_assert (single_step_breakpoints[1] == NULL);
13993       bpt_p = &single_step_breakpoints[1];
13994       single_step_gdbarch[1] = gdbarch;
13995     }
13996
13997   /* NOTE drow/2006-04-11: A future improvement to this function would
13998      be to only create the breakpoints once, and actually put them on
13999      the breakpoint chain.  That would let us use set_raw_breakpoint.
14000      We could adjust the addresses each time they were needed.  Doing
14001      this requires corresponding changes elsewhere where single step
14002      breakpoints are handled, however.  So, for now, we use this.  */
14003
14004   *bpt_p = deprecated_insert_raw_breakpoint (gdbarch, aspace, next_pc);
14005   if (*bpt_p == NULL)
14006     error (_("Could not insert single-step breakpoint at %s"),
14007              paddress (gdbarch, next_pc));
14008 }
14009
14010 /* Check if the breakpoints used for software single stepping
14011    were inserted or not.  */
14012
14013 int
14014 single_step_breakpoints_inserted (void)
14015 {
14016   return (single_step_breakpoints[0] != NULL
14017           || single_step_breakpoints[1] != NULL);
14018 }
14019
14020 /* Remove and delete any breakpoints used for software single step.  */
14021
14022 void
14023 remove_single_step_breakpoints (void)
14024 {
14025   gdb_assert (single_step_breakpoints[0] != NULL);
14026
14027   /* See insert_single_step_breakpoint for more about this deprecated
14028      call.  */
14029   deprecated_remove_raw_breakpoint (single_step_gdbarch[0],
14030                                     single_step_breakpoints[0]);
14031   single_step_gdbarch[0] = NULL;
14032   single_step_breakpoints[0] = NULL;
14033
14034   if (single_step_breakpoints[1] != NULL)
14035     {
14036       deprecated_remove_raw_breakpoint (single_step_gdbarch[1],
14037                                         single_step_breakpoints[1]);
14038       single_step_gdbarch[1] = NULL;
14039       single_step_breakpoints[1] = NULL;
14040     }
14041 }
14042
14043 /* Delete software single step breakpoints without removing them from
14044    the inferior.  This is intended to be used if the inferior's address
14045    space where they were inserted is already gone, e.g. after exit or
14046    exec.  */
14047
14048 void
14049 cancel_single_step_breakpoints (void)
14050 {
14051   int i;
14052
14053   for (i = 0; i < 2; i++)
14054     if (single_step_breakpoints[i])
14055       {
14056         xfree (single_step_breakpoints[i]);
14057         single_step_breakpoints[i] = NULL;
14058         single_step_gdbarch[i] = NULL;
14059       }
14060 }
14061
14062 /* Detach software single-step breakpoints from INFERIOR_PTID without
14063    removing them.  */
14064
14065 static void
14066 detach_single_step_breakpoints (void)
14067 {
14068   int i;
14069
14070   for (i = 0; i < 2; i++)
14071     if (single_step_breakpoints[i])
14072       target_remove_breakpoint (single_step_gdbarch[i],
14073                                 single_step_breakpoints[i]);
14074 }
14075
14076 /* Check whether a software single-step breakpoint is inserted at
14077    PC.  */
14078
14079 static int
14080 single_step_breakpoint_inserted_here_p (struct address_space *aspace, 
14081                                         CORE_ADDR pc)
14082 {
14083   int i;
14084
14085   for (i = 0; i < 2; i++)
14086     {
14087       struct bp_target_info *bp_tgt = single_step_breakpoints[i];
14088       if (bp_tgt
14089           && breakpoint_address_match (bp_tgt->placed_address_space,
14090                                        bp_tgt->placed_address,
14091                                        aspace, pc))
14092         return 1;
14093     }
14094
14095   return 0;
14096 }
14097
14098 /* Returns 0 if 'bp' is NOT a syscall catchpoint,
14099    non-zero otherwise.  */
14100 static int
14101 is_syscall_catchpoint_enabled (struct breakpoint *bp)
14102 {
14103   if (syscall_catchpoint_p (bp)
14104       && bp->enable_state != bp_disabled
14105       && bp->enable_state != bp_call_disabled)
14106     return 1;
14107   else
14108     return 0;
14109 }
14110
14111 int
14112 catch_syscall_enabled (void)
14113 {
14114   struct catch_syscall_inferior_data *inf_data
14115     = get_catch_syscall_inferior_data (current_inferior ());
14116
14117   return inf_data->total_syscalls_count != 0;
14118 }
14119
14120 int
14121 catching_syscall_number (int syscall_number)
14122 {
14123   struct breakpoint *bp;
14124
14125   ALL_BREAKPOINTS (bp)
14126     if (is_syscall_catchpoint_enabled (bp))
14127       {
14128         struct syscall_catchpoint *c = (struct syscall_catchpoint *) bp;
14129
14130         if (c->syscalls_to_be_caught)
14131           {
14132             int i, iter;
14133             for (i = 0;
14134                  VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
14135                  i++)
14136               if (syscall_number == iter)
14137                 return 1;
14138           }
14139         else
14140           return 1;
14141       }
14142
14143   return 0;
14144 }
14145
14146 /* Complete syscall names.  Used by "catch syscall".  */
14147 static char **
14148 catch_syscall_completer (struct cmd_list_element *cmd,
14149                          char *text, char *word)
14150 {
14151   const char **list = get_syscall_names ();
14152   char **retlist
14153     = (list == NULL) ? NULL : complete_on_enum (list, text, word);
14154
14155   xfree (list);
14156   return retlist;
14157 }
14158
14159 /* Tracepoint-specific operations.  */
14160
14161 /* Set tracepoint count to NUM.  */
14162 static void
14163 set_tracepoint_count (int num)
14164 {
14165   tracepoint_count = num;
14166   set_internalvar_integer (lookup_internalvar ("tpnum"), num);
14167 }
14168
14169 static void
14170 trace_command (char *arg, int from_tty)
14171 {
14172   if (create_breakpoint (get_current_arch (),
14173                          arg,
14174                          NULL, 0, 1 /* parse arg */,
14175                          0 /* tempflag */,
14176                          bp_tracepoint /* type_wanted */,
14177                          0 /* Ignore count */,
14178                          pending_break_support,
14179                          &tracepoint_breakpoint_ops,
14180                          from_tty,
14181                          1 /* enabled */,
14182                          0 /* internal */))
14183     set_tracepoint_count (breakpoint_count);
14184 }
14185
14186 static void
14187 ftrace_command (char *arg, int from_tty)
14188 {
14189   if (create_breakpoint (get_current_arch (),
14190                          arg,
14191                          NULL, 0, 1 /* parse arg */,
14192                          0 /* tempflag */,
14193                          bp_fast_tracepoint /* type_wanted */,
14194                          0 /* Ignore count */,
14195                          pending_break_support,
14196                          &tracepoint_breakpoint_ops,
14197                          from_tty,
14198                          1 /* enabled */,
14199                          0 /* internal */))
14200     set_tracepoint_count (breakpoint_count);
14201 }
14202
14203 /* strace command implementation.  Creates a static tracepoint.  */
14204
14205 static void
14206 strace_command (char *arg, int from_tty)
14207 {
14208   struct breakpoint_ops *ops;
14209
14210   /* Decide if we are dealing with a static tracepoint marker (`-m'),
14211      or with a normal static tracepoint.  */
14212   if (arg && strncmp (arg, "-m", 2) == 0 && isspace (arg[2]))
14213     ops = &strace_marker_breakpoint_ops;
14214   else
14215     ops = &tracepoint_breakpoint_ops;
14216
14217   if (create_breakpoint (get_current_arch (),
14218                          arg,
14219                          NULL, 0, 1 /* parse arg */,
14220                          0 /* tempflag */,
14221                          bp_static_tracepoint /* type_wanted */,
14222                          0 /* Ignore count */,
14223                          pending_break_support,
14224                          ops,
14225                          from_tty,
14226                          1 /* enabled */,
14227                          0 /* internal */))
14228     set_tracepoint_count (breakpoint_count);
14229 }
14230
14231 /* Set up a fake reader function that gets command lines from a linked
14232    list that was acquired during tracepoint uploading.  */
14233
14234 static struct uploaded_tp *this_utp;
14235 static int next_cmd;
14236
14237 static char *
14238 read_uploaded_action (void)
14239 {
14240   char *rslt;
14241
14242   VEC_iterate (char_ptr, this_utp->cmd_strings, next_cmd, rslt);
14243
14244   next_cmd++;
14245
14246   return rslt;
14247 }
14248
14249 /* Given information about a tracepoint as recorded on a target (which
14250    can be either a live system or a trace file), attempt to create an
14251    equivalent GDB tracepoint.  This is not a reliable process, since
14252    the target does not necessarily have all the information used when
14253    the tracepoint was originally defined.  */
14254   
14255 struct tracepoint *
14256 create_tracepoint_from_upload (struct uploaded_tp *utp)
14257 {
14258   char *addr_str, small_buf[100];
14259   struct tracepoint *tp;
14260
14261   if (utp->at_string)
14262     addr_str = utp->at_string;
14263   else
14264     {
14265       /* In the absence of a source location, fall back to raw
14266          address.  Since there is no way to confirm that the address
14267          means the same thing as when the trace was started, warn the
14268          user.  */
14269       warning (_("Uploaded tracepoint %d has no "
14270                  "source location, using raw address"),
14271                utp->number);
14272       sprintf (small_buf, "*%s", hex_string (utp->addr));
14273       addr_str = small_buf;
14274     }
14275
14276   /* There's not much we can do with a sequence of bytecodes.  */
14277   if (utp->cond && !utp->cond_string)
14278     warning (_("Uploaded tracepoint %d condition "
14279                "has no source form, ignoring it"),
14280              utp->number);
14281
14282   if (!create_breakpoint (get_current_arch (),
14283                           addr_str,
14284                           utp->cond_string, -1, 0 /* parse cond/thread */,
14285                           0 /* tempflag */,
14286                           utp->type /* type_wanted */,
14287                           0 /* Ignore count */,
14288                           pending_break_support,
14289                           &tracepoint_breakpoint_ops,
14290                           0 /* from_tty */,
14291                           utp->enabled /* enabled */,
14292                           0 /* internal */))
14293     return NULL;
14294
14295   set_tracepoint_count (breakpoint_count);
14296   
14297   /* Get the tracepoint we just created.  */
14298   tp = get_tracepoint (tracepoint_count);
14299   gdb_assert (tp != NULL);
14300
14301   if (utp->pass > 0)
14302     {
14303       sprintf (small_buf, "%d %d", utp->pass, tp->base.number);
14304
14305       trace_pass_command (small_buf, 0);
14306     }
14307
14308   /* If we have uploaded versions of the original commands, set up a
14309      special-purpose "reader" function and call the usual command line
14310      reader, then pass the result to the breakpoint command-setting
14311      function.  */
14312   if (!VEC_empty (char_ptr, utp->cmd_strings))
14313     {
14314       struct command_line *cmd_list;
14315
14316       this_utp = utp;
14317       next_cmd = 0;
14318
14319       cmd_list = read_command_lines_1 (read_uploaded_action, 1, NULL, NULL);
14320
14321       breakpoint_set_commands (&tp->base, cmd_list);
14322     }
14323   else if (!VEC_empty (char_ptr, utp->actions)
14324            || !VEC_empty (char_ptr, utp->step_actions))
14325     warning (_("Uploaded tracepoint %d actions "
14326                "have no source form, ignoring them"),
14327              utp->number);
14328
14329   /* Copy any status information that might be available.  */
14330   tp->base.hit_count = utp->hit_count;
14331   tp->traceframe_usage = utp->traceframe_usage;
14332
14333   return tp;
14334 }
14335   
14336 /* Print information on tracepoint number TPNUM_EXP, or all if
14337    omitted.  */
14338
14339 static void
14340 tracepoints_info (char *args, int from_tty)
14341 {
14342   struct ui_out *uiout = current_uiout;
14343   int num_printed;
14344
14345   num_printed = breakpoint_1 (args, 0, is_tracepoint);
14346
14347   if (num_printed == 0)
14348     {
14349       if (args == NULL || *args == '\0')
14350         ui_out_message (uiout, 0, "No tracepoints.\n");
14351       else
14352         ui_out_message (uiout, 0, "No tracepoint matching '%s'.\n", args);
14353     }
14354
14355   default_collect_info ();
14356 }
14357
14358 /* The 'enable trace' command enables tracepoints.
14359    Not supported by all targets.  */
14360 static void
14361 enable_trace_command (char *args, int from_tty)
14362 {
14363   enable_command (args, from_tty);
14364 }
14365
14366 /* The 'disable trace' command disables tracepoints.
14367    Not supported by all targets.  */
14368 static void
14369 disable_trace_command (char *args, int from_tty)
14370 {
14371   disable_command (args, from_tty);
14372 }
14373
14374 /* Remove a tracepoint (or all if no argument).  */
14375 static void
14376 delete_trace_command (char *arg, int from_tty)
14377 {
14378   struct breakpoint *b, *b_tmp;
14379
14380   dont_repeat ();
14381
14382   if (arg == 0)
14383     {
14384       int breaks_to_delete = 0;
14385
14386       /* Delete all breakpoints if no argument.
14387          Do not delete internal or call-dummy breakpoints, these
14388          have to be deleted with an explicit breakpoint number 
14389          argument.  */
14390       ALL_TRACEPOINTS (b)
14391         if (is_tracepoint (b) && user_breakpoint_p (b))
14392           {
14393             breaks_to_delete = 1;
14394             break;
14395           }
14396
14397       /* Ask user only if there are some breakpoints to delete.  */
14398       if (!from_tty
14399           || (breaks_to_delete && query (_("Delete all tracepoints? "))))
14400         {
14401           ALL_BREAKPOINTS_SAFE (b, b_tmp)
14402             if (is_tracepoint (b) && user_breakpoint_p (b))
14403               delete_breakpoint (b);
14404         }
14405     }
14406   else
14407     map_breakpoint_numbers (arg, do_map_delete_breakpoint, NULL);
14408 }
14409
14410 /* Helper function for trace_pass_command.  */
14411
14412 static void
14413 trace_pass_set_count (struct tracepoint *tp, int count, int from_tty)
14414 {
14415   tp->pass_count = count;
14416   observer_notify_tracepoint_modified (tp->base.number);
14417   if (from_tty)
14418     printf_filtered (_("Setting tracepoint %d's passcount to %d\n"),
14419                      tp->base.number, count);
14420 }
14421
14422 /* Set passcount for tracepoint.
14423
14424    First command argument is passcount, second is tracepoint number.
14425    If tracepoint number omitted, apply to most recently defined.
14426    Also accepts special argument "all".  */
14427
14428 static void
14429 trace_pass_command (char *args, int from_tty)
14430 {
14431   struct tracepoint *t1;
14432   unsigned int count;
14433
14434   if (args == 0 || *args == 0)
14435     error (_("passcount command requires an "
14436              "argument (count + optional TP num)"));
14437
14438   count = strtoul (args, &args, 10);    /* Count comes first, then TP num.  */
14439
14440   while (*args && isspace ((int) *args))
14441     args++;
14442
14443   if (*args && strncasecmp (args, "all", 3) == 0)
14444     {
14445       struct breakpoint *b;
14446
14447       args += 3;                        /* Skip special argument "all".  */
14448       if (*args)
14449         error (_("Junk at end of arguments."));
14450
14451       ALL_TRACEPOINTS (b)
14452       {
14453         t1 = (struct tracepoint *) b;
14454         trace_pass_set_count (t1, count, from_tty);
14455       }
14456     }
14457   else if (*args == '\0')
14458     {
14459       t1 = get_tracepoint_by_number (&args, NULL, 1);
14460       if (t1)
14461         trace_pass_set_count (t1, count, from_tty);
14462     }
14463   else
14464     {
14465       struct get_number_or_range_state state;
14466
14467       init_number_or_range (&state, args);
14468       while (!state.finished)
14469         {
14470           t1 = get_tracepoint_by_number (&args, &state, 1);
14471           if (t1)
14472             trace_pass_set_count (t1, count, from_tty);
14473         }
14474     }
14475 }
14476
14477 struct tracepoint *
14478 get_tracepoint (int num)
14479 {
14480   struct breakpoint *t;
14481
14482   ALL_TRACEPOINTS (t)
14483     if (t->number == num)
14484       return (struct tracepoint *) t;
14485
14486   return NULL;
14487 }
14488
14489 /* Find the tracepoint with the given target-side number (which may be
14490    different from the tracepoint number after disconnecting and
14491    reconnecting).  */
14492
14493 struct tracepoint *
14494 get_tracepoint_by_number_on_target (int num)
14495 {
14496   struct breakpoint *b;
14497
14498   ALL_TRACEPOINTS (b)
14499     {
14500       struct tracepoint *t = (struct tracepoint *) b;
14501
14502       if (t->number_on_target == num)
14503         return t;
14504     }
14505
14506   return NULL;
14507 }
14508
14509 /* Utility: parse a tracepoint number and look it up in the list.
14510    If STATE is not NULL, use, get_number_or_range_state and ignore ARG.
14511    If OPTIONAL_P is true, then if the argument is missing, the most
14512    recent tracepoint (tracepoint_count) is returned.  */
14513 struct tracepoint *
14514 get_tracepoint_by_number (char **arg,
14515                           struct get_number_or_range_state *state,
14516                           int optional_p)
14517 {
14518   extern int tracepoint_count;
14519   struct breakpoint *t;
14520   int tpnum;
14521   char *instring = arg == NULL ? NULL : *arg;
14522
14523   if (state)
14524     {
14525       gdb_assert (!state->finished);
14526       tpnum = get_number_or_range (state);
14527     }
14528   else if (arg == NULL || *arg == NULL || ! **arg)
14529     {
14530       if (optional_p)
14531         tpnum = tracepoint_count;
14532       else
14533         error_no_arg (_("tracepoint number"));
14534     }
14535   else
14536     tpnum = get_number (arg);
14537
14538   if (tpnum <= 0)
14539     {
14540       if (instring && *instring)
14541         printf_filtered (_("bad tracepoint number at or near '%s'\n"), 
14542                          instring);
14543       else
14544         printf_filtered (_("Tracepoint argument missing "
14545                            "and no previous tracepoint\n"));
14546       return NULL;
14547     }
14548
14549   ALL_TRACEPOINTS (t)
14550     if (t->number == tpnum)
14551     {
14552       return (struct tracepoint *) t;
14553     }
14554
14555   printf_unfiltered ("No tracepoint number %d.\n", tpnum);
14556   return NULL;
14557 }
14558
14559 void
14560 print_recreate_thread (struct breakpoint *b, struct ui_file *fp)
14561 {
14562   if (b->thread != -1)
14563     fprintf_unfiltered (fp, " thread %d", b->thread);
14564
14565   if (b->task != 0)
14566     fprintf_unfiltered (fp, " task %d", b->task);
14567
14568   fprintf_unfiltered (fp, "\n");
14569 }
14570
14571 /* Save information on user settable breakpoints (watchpoints, etc) to
14572    a new script file named FILENAME.  If FILTER is non-NULL, call it
14573    on each breakpoint and only include the ones for which it returns
14574    non-zero.  */
14575
14576 static void
14577 save_breakpoints (char *filename, int from_tty,
14578                   int (*filter) (const struct breakpoint *))
14579 {
14580   struct breakpoint *tp;
14581   int any = 0;
14582   char *pathname;
14583   struct cleanup *cleanup;
14584   struct ui_file *fp;
14585   int extra_trace_bits = 0;
14586
14587   if (filename == 0 || *filename == 0)
14588     error (_("Argument required (file name in which to save)"));
14589
14590   /* See if we have anything to save.  */
14591   ALL_BREAKPOINTS (tp)
14592   {
14593     /* Skip internal and momentary breakpoints.  */
14594     if (!user_breakpoint_p (tp))
14595       continue;
14596
14597     /* If we have a filter, only save the breakpoints it accepts.  */
14598     if (filter && !filter (tp))
14599       continue;
14600
14601     any = 1;
14602
14603     if (is_tracepoint (tp))
14604       {
14605         extra_trace_bits = 1;
14606
14607         /* We can stop searching.  */
14608         break;
14609       }
14610   }
14611
14612   if (!any)
14613     {
14614       warning (_("Nothing to save."));
14615       return;
14616     }
14617
14618   pathname = tilde_expand (filename);
14619   cleanup = make_cleanup (xfree, pathname);
14620   fp = gdb_fopen (pathname, "w");
14621   if (!fp)
14622     error (_("Unable to open file '%s' for saving (%s)"),
14623            filename, safe_strerror (errno));
14624   make_cleanup_ui_file_delete (fp);
14625
14626   if (extra_trace_bits)
14627     save_trace_state_variables (fp);
14628
14629   ALL_BREAKPOINTS (tp)
14630   {
14631     /* Skip internal and momentary breakpoints.  */
14632     if (!user_breakpoint_p (tp))
14633       continue;
14634
14635     /* If we have a filter, only save the breakpoints it accepts.  */
14636     if (filter && !filter (tp))
14637       continue;
14638
14639     tp->ops->print_recreate (tp, fp);
14640
14641     /* Note, we can't rely on tp->number for anything, as we can't
14642        assume the recreated breakpoint numbers will match.  Use $bpnum
14643        instead.  */
14644
14645     if (tp->cond_string)
14646       fprintf_unfiltered (fp, "  condition $bpnum %s\n", tp->cond_string);
14647
14648     if (tp->ignore_count)
14649       fprintf_unfiltered (fp, "  ignore $bpnum %d\n", tp->ignore_count);
14650
14651     if (tp->commands)
14652       {
14653         volatile struct gdb_exception ex;       
14654
14655         fprintf_unfiltered (fp, "  commands\n");
14656         
14657         ui_out_redirect (current_uiout, fp);
14658         TRY_CATCH (ex, RETURN_MASK_ALL)
14659           {
14660             print_command_lines (current_uiout, tp->commands->commands, 2);
14661           }
14662         ui_out_redirect (current_uiout, NULL);
14663
14664         if (ex.reason < 0)
14665           throw_exception (ex);
14666
14667         fprintf_unfiltered (fp, "  end\n");
14668       }
14669
14670     if (tp->enable_state == bp_disabled)
14671       fprintf_unfiltered (fp, "disable\n");
14672
14673     /* If this is a multi-location breakpoint, check if the locations
14674        should be individually disabled.  Watchpoint locations are
14675        special, and not user visible.  */
14676     if (!is_watchpoint (tp) && tp->loc && tp->loc->next)
14677       {
14678         struct bp_location *loc;
14679         int n = 1;
14680
14681         for (loc = tp->loc; loc != NULL; loc = loc->next, n++)
14682           if (!loc->enabled)
14683             fprintf_unfiltered (fp, "disable $bpnum.%d\n", n);
14684       }
14685   }
14686
14687   if (extra_trace_bits && *default_collect)
14688     fprintf_unfiltered (fp, "set default-collect %s\n", default_collect);
14689
14690   do_cleanups (cleanup);
14691   if (from_tty)
14692     printf_filtered (_("Saved to file '%s'.\n"), filename);
14693 }
14694
14695 /* The `save breakpoints' command.  */
14696
14697 static void
14698 save_breakpoints_command (char *args, int from_tty)
14699 {
14700   save_breakpoints (args, from_tty, NULL);
14701 }
14702
14703 /* The `save tracepoints' command.  */
14704
14705 static void
14706 save_tracepoints_command (char *args, int from_tty)
14707 {
14708   save_breakpoints (args, from_tty, is_tracepoint);
14709 }
14710
14711 /* Create a vector of all tracepoints.  */
14712
14713 VEC(breakpoint_p) *
14714 all_tracepoints (void)
14715 {
14716   VEC(breakpoint_p) *tp_vec = 0;
14717   struct breakpoint *tp;
14718
14719   ALL_TRACEPOINTS (tp)
14720   {
14721     VEC_safe_push (breakpoint_p, tp_vec, tp);
14722   }
14723
14724   return tp_vec;
14725 }
14726
14727 \f
14728 /* This help string is used for the break, hbreak, tbreak and thbreak
14729    commands.  It is defined as a macro to prevent duplication.
14730    COMMAND should be a string constant containing the name of the
14731    command.  */
14732 #define BREAK_ARGS_HELP(command) \
14733 command" [LOCATION] [thread THREADNUM] [if CONDITION]\n\
14734 LOCATION may be a line number, function name, or \"*\" and an address.\n\
14735 If a line number is specified, break at start of code for that line.\n\
14736 If a function is specified, break at start of code for that function.\n\
14737 If an address is specified, break at that exact address.\n\
14738 With no LOCATION, uses current execution address of the selected\n\
14739 stack frame.  This is useful for breaking on return to a stack frame.\n\
14740 \n\
14741 THREADNUM is the number from \"info threads\".\n\
14742 CONDITION is a boolean expression.\n\
14743 \n\
14744 Multiple breakpoints at one place are permitted, and useful if their\n\
14745 conditions are different.\n\
14746 \n\
14747 Do \"help breakpoints\" for info on other commands dealing with breakpoints."
14748
14749 /* List of subcommands for "catch".  */
14750 static struct cmd_list_element *catch_cmdlist;
14751
14752 /* List of subcommands for "tcatch".  */
14753 static struct cmd_list_element *tcatch_cmdlist;
14754
14755 void
14756 add_catch_command (char *name, char *docstring,
14757                    void (*sfunc) (char *args, int from_tty,
14758                                   struct cmd_list_element *command),
14759                    char **(*completer) (struct cmd_list_element *cmd,
14760                                          char *text, char *word),
14761                    void *user_data_catch,
14762                    void *user_data_tcatch)
14763 {
14764   struct cmd_list_element *command;
14765
14766   command = add_cmd (name, class_breakpoint, NULL, docstring,
14767                      &catch_cmdlist);
14768   set_cmd_sfunc (command, sfunc);
14769   set_cmd_context (command, user_data_catch);
14770   set_cmd_completer (command, completer);
14771
14772   command = add_cmd (name, class_breakpoint, NULL, docstring,
14773                      &tcatch_cmdlist);
14774   set_cmd_sfunc (command, sfunc);
14775   set_cmd_context (command, user_data_tcatch);
14776   set_cmd_completer (command, completer);
14777 }
14778
14779 static void
14780 clear_syscall_counts (struct inferior *inf)
14781 {
14782   struct catch_syscall_inferior_data *inf_data
14783     = get_catch_syscall_inferior_data (inf);
14784
14785   inf_data->total_syscalls_count = 0;
14786   inf_data->any_syscall_count = 0;
14787   VEC_free (int, inf_data->syscalls_counts);
14788 }
14789
14790 static void
14791 save_command (char *arg, int from_tty)
14792 {
14793   printf_unfiltered (_("\"save\" must be followed by "
14794                        "the name of a save subcommand.\n"));
14795   help_list (save_cmdlist, "save ", -1, gdb_stdout);
14796 }
14797
14798 struct breakpoint *
14799 iterate_over_breakpoints (int (*callback) (struct breakpoint *, void *),
14800                           void *data)
14801 {
14802   struct breakpoint *b, *b_tmp;
14803
14804   ALL_BREAKPOINTS_SAFE (b, b_tmp)
14805     {
14806       if ((*callback) (b, data))
14807         return b;
14808     }
14809
14810   return NULL;
14811 }
14812
14813 /* Zero if any of the breakpoint's locations could be a location where
14814    functions have been inlined, nonzero otherwise.  */
14815
14816 static int
14817 is_non_inline_function (struct breakpoint *b)
14818 {
14819   /* The shared library event breakpoint is set on the address of a
14820      non-inline function.  */
14821   if (b->type == bp_shlib_event)
14822     return 1;
14823
14824   return 0;
14825 }
14826
14827 /* Nonzero if the specified PC cannot be a location where functions
14828    have been inlined.  */
14829
14830 int
14831 pc_at_non_inline_function (struct address_space *aspace, CORE_ADDR pc,
14832                            const struct target_waitstatus *ws)
14833 {
14834   struct breakpoint *b;
14835   struct bp_location *bl;
14836
14837   ALL_BREAKPOINTS (b)
14838     {
14839       if (!is_non_inline_function (b))
14840         continue;
14841
14842       for (bl = b->loc; bl != NULL; bl = bl->next)
14843         {
14844           if (!bl->shlib_disabled
14845               && bpstat_check_location (bl, aspace, pc, ws))
14846             return 1;
14847         }
14848     }
14849
14850   return 0;
14851 }
14852
14853 void
14854 initialize_breakpoint_ops (void)
14855 {
14856   static int initialized = 0;
14857
14858   struct breakpoint_ops *ops;
14859
14860   if (initialized)
14861     return;
14862   initialized = 1;
14863
14864   /* The breakpoint_ops structure to be inherit by all kinds of
14865      breakpoints (real breakpoints, i.e., user "break" breakpoints,
14866      internal and momentary breakpoints, etc.).  */
14867   ops = &bkpt_base_breakpoint_ops;
14868   *ops = base_breakpoint_ops;
14869   ops->re_set = bkpt_re_set;
14870   ops->insert_location = bkpt_insert_location;
14871   ops->remove_location = bkpt_remove_location;
14872   ops->breakpoint_hit = bkpt_breakpoint_hit;
14873   ops->create_sals_from_address = bkpt_create_sals_from_address;
14874   ops->create_breakpoints_sal = bkpt_create_breakpoints_sal;
14875   ops->decode_linespec = bkpt_decode_linespec;
14876
14877   /* The breakpoint_ops structure to be used in regular breakpoints.  */
14878   ops = &bkpt_breakpoint_ops;
14879   *ops = bkpt_base_breakpoint_ops;
14880   ops->re_set = bkpt_re_set;
14881   ops->resources_needed = bkpt_resources_needed;
14882   ops->print_it = bkpt_print_it;
14883   ops->print_mention = bkpt_print_mention;
14884   ops->print_recreate = bkpt_print_recreate;
14885
14886   /* Ranged breakpoints.  */
14887   ops = &ranged_breakpoint_ops;
14888   *ops = bkpt_breakpoint_ops;
14889   ops->breakpoint_hit = breakpoint_hit_ranged_breakpoint;
14890   ops->resources_needed = resources_needed_ranged_breakpoint;
14891   ops->print_it = print_it_ranged_breakpoint;
14892   ops->print_one = print_one_ranged_breakpoint;
14893   ops->print_one_detail = print_one_detail_ranged_breakpoint;
14894   ops->print_mention = print_mention_ranged_breakpoint;
14895   ops->print_recreate = print_recreate_ranged_breakpoint;
14896
14897   /* Internal breakpoints.  */
14898   ops = &internal_breakpoint_ops;
14899   *ops = bkpt_base_breakpoint_ops;
14900   ops->re_set = internal_bkpt_re_set;
14901   ops->check_status = internal_bkpt_check_status;
14902   ops->print_it = internal_bkpt_print_it;
14903   ops->print_mention = internal_bkpt_print_mention;
14904
14905   /* Momentary breakpoints.  */
14906   ops = &momentary_breakpoint_ops;
14907   *ops = bkpt_base_breakpoint_ops;
14908   ops->re_set = momentary_bkpt_re_set;
14909   ops->check_status = momentary_bkpt_check_status;
14910   ops->print_it = momentary_bkpt_print_it;
14911   ops->print_mention = momentary_bkpt_print_mention;
14912
14913   /* GNU v3 exception catchpoints.  */
14914   ops = &gnu_v3_exception_catchpoint_ops;
14915   *ops = bkpt_breakpoint_ops;
14916   ops->print_it = print_it_exception_catchpoint;
14917   ops->print_one = print_one_exception_catchpoint;
14918   ops->print_mention = print_mention_exception_catchpoint;
14919   ops->print_recreate = print_recreate_exception_catchpoint;
14920
14921   /* Watchpoints.  */
14922   ops = &watchpoint_breakpoint_ops;
14923   *ops = base_breakpoint_ops;
14924   ops->dtor = dtor_watchpoint;
14925   ops->re_set = re_set_watchpoint;
14926   ops->insert_location = insert_watchpoint;
14927   ops->remove_location = remove_watchpoint;
14928   ops->breakpoint_hit = breakpoint_hit_watchpoint;
14929   ops->check_status = check_status_watchpoint;
14930   ops->resources_needed = resources_needed_watchpoint;
14931   ops->works_in_software_mode = works_in_software_mode_watchpoint;
14932   ops->print_it = print_it_watchpoint;
14933   ops->print_mention = print_mention_watchpoint;
14934   ops->print_recreate = print_recreate_watchpoint;
14935
14936   /* Masked watchpoints.  */
14937   ops = &masked_watchpoint_breakpoint_ops;
14938   *ops = watchpoint_breakpoint_ops;
14939   ops->insert_location = insert_masked_watchpoint;
14940   ops->remove_location = remove_masked_watchpoint;
14941   ops->resources_needed = resources_needed_masked_watchpoint;
14942   ops->works_in_software_mode = works_in_software_mode_masked_watchpoint;
14943   ops->print_it = print_it_masked_watchpoint;
14944   ops->print_one_detail = print_one_detail_masked_watchpoint;
14945   ops->print_mention = print_mention_masked_watchpoint;
14946   ops->print_recreate = print_recreate_masked_watchpoint;
14947
14948   /* Tracepoints.  */
14949   ops = &tracepoint_breakpoint_ops;
14950   *ops = base_breakpoint_ops;
14951   ops->re_set = tracepoint_re_set;
14952   ops->breakpoint_hit = tracepoint_breakpoint_hit;
14953   ops->print_one_detail = tracepoint_print_one_detail;
14954   ops->print_mention = tracepoint_print_mention;
14955   ops->print_recreate = tracepoint_print_recreate;
14956   ops->create_sals_from_address = tracepoint_create_sals_from_address;
14957   ops->create_breakpoints_sal = tracepoint_create_breakpoints_sal;
14958   ops->decode_linespec = tracepoint_decode_linespec;
14959
14960   /* Static tracepoints with marker (`-m').  */
14961   ops = &strace_marker_breakpoint_ops;
14962   *ops = tracepoint_breakpoint_ops;
14963   ops->create_sals_from_address = strace_marker_create_sals_from_address;
14964   ops->create_breakpoints_sal = strace_marker_create_breakpoints_sal;
14965   ops->decode_linespec = strace_marker_decode_linespec;
14966
14967   /* Fork catchpoints.  */
14968   ops = &catch_fork_breakpoint_ops;
14969   *ops = base_breakpoint_ops;
14970   ops->insert_location = insert_catch_fork;
14971   ops->remove_location = remove_catch_fork;
14972   ops->breakpoint_hit = breakpoint_hit_catch_fork;
14973   ops->print_it = print_it_catch_fork;
14974   ops->print_one = print_one_catch_fork;
14975   ops->print_mention = print_mention_catch_fork;
14976   ops->print_recreate = print_recreate_catch_fork;
14977
14978   /* Vfork catchpoints.  */
14979   ops = &catch_vfork_breakpoint_ops;
14980   *ops = base_breakpoint_ops;
14981   ops->insert_location = insert_catch_vfork;
14982   ops->remove_location = remove_catch_vfork;
14983   ops->breakpoint_hit = breakpoint_hit_catch_vfork;
14984   ops->print_it = print_it_catch_vfork;
14985   ops->print_one = print_one_catch_vfork;
14986   ops->print_mention = print_mention_catch_vfork;
14987   ops->print_recreate = print_recreate_catch_vfork;
14988
14989   /* Exec catchpoints.  */
14990   ops = &catch_exec_breakpoint_ops;
14991   *ops = base_breakpoint_ops;
14992   ops->dtor = dtor_catch_exec;
14993   ops->insert_location = insert_catch_exec;
14994   ops->remove_location = remove_catch_exec;
14995   ops->breakpoint_hit = breakpoint_hit_catch_exec;
14996   ops->print_it = print_it_catch_exec;
14997   ops->print_one = print_one_catch_exec;
14998   ops->print_mention = print_mention_catch_exec;
14999   ops->print_recreate = print_recreate_catch_exec;
15000
15001   /* Syscall catchpoints.  */
15002   ops = &catch_syscall_breakpoint_ops;
15003   *ops = base_breakpoint_ops;
15004   ops->dtor = dtor_catch_syscall;
15005   ops->insert_location = insert_catch_syscall;
15006   ops->remove_location = remove_catch_syscall;
15007   ops->breakpoint_hit = breakpoint_hit_catch_syscall;
15008   ops->print_it = print_it_catch_syscall;
15009   ops->print_one = print_one_catch_syscall;
15010   ops->print_mention = print_mention_catch_syscall;
15011   ops->print_recreate = print_recreate_catch_syscall;
15012
15013   /* Solib-related catchpoints.  */
15014   ops = &catch_solib_breakpoint_ops;
15015   *ops = base_breakpoint_ops;
15016   ops->dtor = dtor_catch_solib;
15017   ops->insert_location = insert_catch_solib;
15018   ops->remove_location = remove_catch_solib;
15019   ops->breakpoint_hit = breakpoint_hit_catch_solib;
15020   ops->check_status = check_status_catch_solib;
15021   ops->print_it = print_it_catch_solib;
15022   ops->print_one = print_one_catch_solib;
15023   ops->print_mention = print_mention_catch_solib;
15024   ops->print_recreate = print_recreate_catch_solib;
15025 }
15026
15027 void
15028 _initialize_breakpoint (void)
15029 {
15030   struct cmd_list_element *c;
15031
15032   initialize_breakpoint_ops ();
15033
15034   observer_attach_solib_unloaded (disable_breakpoints_in_unloaded_shlib);
15035   observer_attach_inferior_exit (clear_syscall_counts);
15036   observer_attach_memory_changed (invalidate_bp_value_on_memory_change);
15037
15038   breakpoint_objfile_key = register_objfile_data ();
15039
15040   catch_syscall_inferior_data
15041     = register_inferior_data_with_cleanup (catch_syscall_inferior_data_cleanup);
15042
15043   breakpoint_chain = 0;
15044   /* Don't bother to call set_breakpoint_count.  $bpnum isn't useful
15045      before a breakpoint is set.  */
15046   breakpoint_count = 0;
15047
15048   tracepoint_count = 0;
15049
15050   add_com ("ignore", class_breakpoint, ignore_command, _("\
15051 Set ignore-count of breakpoint number N to COUNT.\n\
15052 Usage is `ignore N COUNT'."));
15053   if (xdb_commands)
15054     add_com_alias ("bc", "ignore", class_breakpoint, 1);
15055
15056   add_com ("commands", class_breakpoint, commands_command, _("\
15057 Set commands to be executed when a breakpoint is hit.\n\
15058 Give breakpoint number as argument after \"commands\".\n\
15059 With no argument, the targeted breakpoint is the last one set.\n\
15060 The commands themselves follow starting on the next line.\n\
15061 Type a line containing \"end\" to indicate the end of them.\n\
15062 Give \"silent\" as the first line to make the breakpoint silent;\n\
15063 then no output is printed when it is hit, except what the commands print."));
15064
15065   add_com ("condition", class_breakpoint, condition_command, _("\
15066 Specify breakpoint number N to break only if COND is true.\n\
15067 Usage is `condition N COND', where N is an integer and COND is an\n\
15068 expression to be evaluated whenever breakpoint N is reached."));
15069
15070   c = add_com ("tbreak", class_breakpoint, tbreak_command, _("\
15071 Set a temporary breakpoint.\n\
15072 Like \"break\" except the breakpoint is only temporary,\n\
15073 so it will be deleted when hit.  Equivalent to \"break\" followed\n\
15074 by using \"enable delete\" on the breakpoint number.\n\
15075 \n"
15076 BREAK_ARGS_HELP ("tbreak")));
15077   set_cmd_completer (c, location_completer);
15078
15079   c = add_com ("hbreak", class_breakpoint, hbreak_command, _("\
15080 Set a hardware assisted breakpoint.\n\
15081 Like \"break\" except the breakpoint requires hardware support,\n\
15082 some target hardware may not have this support.\n\
15083 \n"
15084 BREAK_ARGS_HELP ("hbreak")));
15085   set_cmd_completer (c, location_completer);
15086
15087   c = add_com ("thbreak", class_breakpoint, thbreak_command, _("\
15088 Set a temporary hardware assisted breakpoint.\n\
15089 Like \"hbreak\" except the breakpoint is only temporary,\n\
15090 so it will be deleted when hit.\n\
15091 \n"
15092 BREAK_ARGS_HELP ("thbreak")));
15093   set_cmd_completer (c, location_completer);
15094
15095   add_prefix_cmd ("enable", class_breakpoint, enable_command, _("\
15096 Enable some breakpoints.\n\
15097 Give breakpoint numbers (separated by spaces) as arguments.\n\
15098 With no subcommand, breakpoints are enabled until you command otherwise.\n\
15099 This is used to cancel the effect of the \"disable\" command.\n\
15100 With a subcommand you can enable temporarily."),
15101                   &enablelist, "enable ", 1, &cmdlist);
15102   if (xdb_commands)
15103     add_com ("ab", class_breakpoint, enable_command, _("\
15104 Enable some breakpoints.\n\
15105 Give breakpoint numbers (separated by spaces) as arguments.\n\
15106 With no subcommand, breakpoints are enabled until you command otherwise.\n\
15107 This is used to cancel the effect of the \"disable\" command.\n\
15108 With a subcommand you can enable temporarily."));
15109
15110   add_com_alias ("en", "enable", class_breakpoint, 1);
15111
15112   add_prefix_cmd ("breakpoints", class_breakpoint, enable_command, _("\
15113 Enable some breakpoints.\n\
15114 Give breakpoint numbers (separated by spaces) as arguments.\n\
15115 This is used to cancel the effect of the \"disable\" command.\n\
15116 May be abbreviated to simply \"enable\".\n"),
15117                    &enablebreaklist, "enable breakpoints ", 1, &enablelist);
15118
15119   add_cmd ("once", no_class, enable_once_command, _("\
15120 Enable breakpoints for one hit.  Give breakpoint numbers.\n\
15121 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
15122            &enablebreaklist);
15123
15124   add_cmd ("delete", no_class, enable_delete_command, _("\
15125 Enable breakpoints and delete when hit.  Give breakpoint numbers.\n\
15126 If a breakpoint is hit while enabled in this fashion, it is deleted."),
15127            &enablebreaklist);
15128
15129   add_cmd ("count", no_class, enable_count_command, _("\
15130 Enable breakpoints for COUNT hits.  Give count and then breakpoint numbers.\n\
15131 If a breakpoint is hit while enabled in this fashion,\n\
15132 the count is decremented; when it reaches zero, the breakpoint is disabled."),
15133            &enablebreaklist);
15134
15135   add_cmd ("delete", no_class, enable_delete_command, _("\
15136 Enable breakpoints and delete when hit.  Give breakpoint numbers.\n\
15137 If a breakpoint is hit while enabled in this fashion, it is deleted."),
15138            &enablelist);
15139
15140   add_cmd ("once", no_class, enable_once_command, _("\
15141 Enable breakpoints for one hit.  Give breakpoint numbers.\n\
15142 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
15143            &enablelist);
15144
15145   add_cmd ("count", no_class, enable_count_command, _("\
15146 Enable breakpoints for COUNT hits.  Give count and then breakpoint numbers.\n\
15147 If a breakpoint is hit while enabled in this fashion,\n\
15148 the count is decremented; when it reaches zero, the breakpoint is disabled."),
15149            &enablelist);
15150
15151   add_prefix_cmd ("disable", class_breakpoint, disable_command, _("\
15152 Disable some breakpoints.\n\
15153 Arguments are breakpoint numbers with spaces in between.\n\
15154 To disable all breakpoints, give no argument.\n\
15155 A disabled breakpoint is not forgotten, but has no effect until re-enabled."),
15156                   &disablelist, "disable ", 1, &cmdlist);
15157   add_com_alias ("dis", "disable", class_breakpoint, 1);
15158   add_com_alias ("disa", "disable", class_breakpoint, 1);
15159   if (xdb_commands)
15160     add_com ("sb", class_breakpoint, disable_command, _("\
15161 Disable some breakpoints.\n\
15162 Arguments are breakpoint numbers with spaces in between.\n\
15163 To disable all breakpoints, give no argument.\n\
15164 A disabled breakpoint is not forgotten, but has no effect until re-enabled."));
15165
15166   add_cmd ("breakpoints", class_alias, disable_command, _("\
15167 Disable some breakpoints.\n\
15168 Arguments are breakpoint numbers with spaces in between.\n\
15169 To disable all breakpoints, give no argument.\n\
15170 A disabled breakpoint is not forgotten, but has no effect until re-enabled.\n\
15171 This command may be abbreviated \"disable\"."),
15172            &disablelist);
15173
15174   add_prefix_cmd ("delete", class_breakpoint, delete_command, _("\
15175 Delete some breakpoints or auto-display expressions.\n\
15176 Arguments are breakpoint numbers with spaces in between.\n\
15177 To delete all breakpoints, give no argument.\n\
15178 \n\
15179 Also a prefix command for deletion of other GDB objects.\n\
15180 The \"unset\" command is also an alias for \"delete\"."),
15181                   &deletelist, "delete ", 1, &cmdlist);
15182   add_com_alias ("d", "delete", class_breakpoint, 1);
15183   add_com_alias ("del", "delete", class_breakpoint, 1);
15184   if (xdb_commands)
15185     add_com ("db", class_breakpoint, delete_command, _("\
15186 Delete some breakpoints.\n\
15187 Arguments are breakpoint numbers with spaces in between.\n\
15188 To delete all breakpoints, give no argument.\n"));
15189
15190   add_cmd ("breakpoints", class_alias, delete_command, _("\
15191 Delete some breakpoints or auto-display expressions.\n\
15192 Arguments are breakpoint numbers with spaces in between.\n\
15193 To delete all breakpoints, give no argument.\n\
15194 This command may be abbreviated \"delete\"."),
15195            &deletelist);
15196
15197   add_com ("clear", class_breakpoint, clear_command, _("\
15198 Clear breakpoint at specified line or function.\n\
15199 Argument may be line number, function name, or \"*\" and an address.\n\
15200 If line number is specified, all breakpoints in that line are cleared.\n\
15201 If function is specified, breakpoints at beginning of function are cleared.\n\
15202 If an address is specified, breakpoints at that address are cleared.\n\
15203 \n\
15204 With no argument, clears all breakpoints in the line that the selected frame\n\
15205 is executing in.\n\
15206 \n\
15207 See also the \"delete\" command which clears breakpoints by number."));
15208   add_com_alias ("cl", "clear", class_breakpoint, 1);
15209
15210   c = add_com ("break", class_breakpoint, break_command, _("\
15211 Set breakpoint at specified line or function.\n"
15212 BREAK_ARGS_HELP ("break")));
15213   set_cmd_completer (c, location_completer);
15214
15215   add_com_alias ("b", "break", class_run, 1);
15216   add_com_alias ("br", "break", class_run, 1);
15217   add_com_alias ("bre", "break", class_run, 1);
15218   add_com_alias ("brea", "break", class_run, 1);
15219
15220   if (xdb_commands)
15221    add_com_alias ("ba", "break", class_breakpoint, 1);
15222
15223   if (dbx_commands)
15224     {
15225       add_abbrev_prefix_cmd ("stop", class_breakpoint, stop_command, _("\
15226 Break in function/address or break at a line in the current file."),
15227                              &stoplist, "stop ", 1, &cmdlist);
15228       add_cmd ("in", class_breakpoint, stopin_command,
15229                _("Break in function or address."), &stoplist);
15230       add_cmd ("at", class_breakpoint, stopat_command,
15231                _("Break at a line in the current file."), &stoplist);
15232       add_com ("status", class_info, breakpoints_info, _("\
15233 Status of user-settable breakpoints, or breakpoint number NUMBER.\n\
15234 The \"Type\" column indicates one of:\n\
15235 \tbreakpoint     - normal breakpoint\n\
15236 \twatchpoint     - watchpoint\n\
15237 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
15238 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
15239 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
15240 address and file/line number respectively.\n\
15241 \n\
15242 Convenience variable \"$_\" and default examine address for \"x\"\n\
15243 are set to the address of the last breakpoint listed unless the command\n\
15244 is prefixed with \"server \".\n\n\
15245 Convenience variable \"$bpnum\" contains the number of the last\n\
15246 breakpoint set."));
15247     }
15248
15249   add_info ("breakpoints", breakpoints_info, _("\
15250 Status of specified breakpoints (all user-settable breakpoints if no argument).\n\
15251 The \"Type\" column indicates one of:\n\
15252 \tbreakpoint     - normal breakpoint\n\
15253 \twatchpoint     - watchpoint\n\
15254 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
15255 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
15256 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
15257 address and file/line number respectively.\n\
15258 \n\
15259 Convenience variable \"$_\" and default examine address for \"x\"\n\
15260 are set to the address of the last breakpoint listed unless the command\n\
15261 is prefixed with \"server \".\n\n\
15262 Convenience variable \"$bpnum\" contains the number of the last\n\
15263 breakpoint set."));
15264
15265   add_info_alias ("b", "breakpoints", 1);
15266
15267   if (xdb_commands)
15268     add_com ("lb", class_breakpoint, breakpoints_info, _("\
15269 Status of user-settable breakpoints, or breakpoint number NUMBER.\n\
15270 The \"Type\" column indicates one of:\n\
15271 \tbreakpoint     - normal breakpoint\n\
15272 \twatchpoint     - watchpoint\n\
15273 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
15274 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
15275 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
15276 address and file/line number respectively.\n\
15277 \n\
15278 Convenience variable \"$_\" and default examine address for \"x\"\n\
15279 are set to the address of the last breakpoint listed unless the command\n\
15280 is prefixed with \"server \".\n\n\
15281 Convenience variable \"$bpnum\" contains the number of the last\n\
15282 breakpoint set."));
15283
15284   add_cmd ("breakpoints", class_maintenance, maintenance_info_breakpoints, _("\
15285 Status of all breakpoints, or breakpoint number NUMBER.\n\
15286 The \"Type\" column indicates one of:\n\
15287 \tbreakpoint     - normal breakpoint\n\
15288 \twatchpoint     - watchpoint\n\
15289 \tlongjmp        - internal breakpoint used to step through longjmp()\n\
15290 \tlongjmp resume - internal breakpoint at the target of longjmp()\n\
15291 \tuntil          - internal breakpoint used by the \"until\" command\n\
15292 \tfinish         - internal breakpoint used by the \"finish\" command\n\
15293 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
15294 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
15295 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
15296 address and file/line number respectively.\n\
15297 \n\
15298 Convenience variable \"$_\" and default examine address for \"x\"\n\
15299 are set to the address of the last breakpoint listed unless the command\n\
15300 is prefixed with \"server \".\n\n\
15301 Convenience variable \"$bpnum\" contains the number of the last\n\
15302 breakpoint set."),
15303            &maintenanceinfolist);
15304
15305   add_prefix_cmd ("catch", class_breakpoint, catch_command, _("\
15306 Set catchpoints to catch events."),
15307                   &catch_cmdlist, "catch ",
15308                   0/*allow-unknown*/, &cmdlist);
15309
15310   add_prefix_cmd ("tcatch", class_breakpoint, tcatch_command, _("\
15311 Set temporary catchpoints to catch events."),
15312                   &tcatch_cmdlist, "tcatch ",
15313                   0/*allow-unknown*/, &cmdlist);
15314
15315   /* Add catch and tcatch sub-commands.  */
15316   add_catch_command ("catch", _("\
15317 Catch an exception, when caught."),
15318                      catch_catch_command,
15319                      NULL,
15320                      CATCH_PERMANENT,
15321                      CATCH_TEMPORARY);
15322   add_catch_command ("throw", _("\
15323 Catch an exception, when thrown."),
15324                      catch_throw_command,
15325                      NULL,
15326                      CATCH_PERMANENT,
15327                      CATCH_TEMPORARY);
15328   add_catch_command ("fork", _("Catch calls to fork."),
15329                      catch_fork_command_1,
15330                      NULL,
15331                      (void *) (uintptr_t) catch_fork_permanent,
15332                      (void *) (uintptr_t) catch_fork_temporary);
15333   add_catch_command ("vfork", _("Catch calls to vfork."),
15334                      catch_fork_command_1,
15335                      NULL,
15336                      (void *) (uintptr_t) catch_vfork_permanent,
15337                      (void *) (uintptr_t) catch_vfork_temporary);
15338   add_catch_command ("exec", _("Catch calls to exec."),
15339                      catch_exec_command_1,
15340                      NULL,
15341                      CATCH_PERMANENT,
15342                      CATCH_TEMPORARY);
15343   add_catch_command ("load", _("Catch loads of shared libraries.\n\
15344 Usage: catch load [REGEX]\n\
15345 If REGEX is given, only stop for libraries matching the regular expression."),
15346                      catch_load_command_1,
15347                      NULL,
15348                      CATCH_PERMANENT,
15349                      CATCH_TEMPORARY);
15350   add_catch_command ("unload", _("Catch unloads of shared libraries.\n\
15351 Usage: catch unload [REGEX]\n\
15352 If REGEX is given, only stop for libraries matching the regular expression."),
15353                      catch_unload_command_1,
15354                      NULL,
15355                      CATCH_PERMANENT,
15356                      CATCH_TEMPORARY);
15357   add_catch_command ("syscall", _("\
15358 Catch system calls by their names and/or numbers.\n\
15359 Arguments say which system calls to catch.  If no arguments\n\
15360 are given, every system call will be caught.\n\
15361 Arguments, if given, should be one or more system call names\n\
15362 (if your system supports that), or system call numbers."),
15363                      catch_syscall_command_1,
15364                      catch_syscall_completer,
15365                      CATCH_PERMANENT,
15366                      CATCH_TEMPORARY);
15367
15368   c = add_com ("watch", class_breakpoint, watch_command, _("\
15369 Set a watchpoint for an expression.\n\
15370 Usage: watch [-l|-location] EXPRESSION\n\
15371 A watchpoint stops execution of your program whenever the value of\n\
15372 an expression changes.\n\
15373 If -l or -location is given, this evaluates EXPRESSION and watches\n\
15374 the memory to which it refers."));
15375   set_cmd_completer (c, expression_completer);
15376
15377   c = add_com ("rwatch", class_breakpoint, rwatch_command, _("\
15378 Set a read watchpoint for an expression.\n\
15379 Usage: rwatch [-l|-location] EXPRESSION\n\
15380 A watchpoint stops execution of your program whenever the value of\n\
15381 an expression is read.\n\
15382 If -l or -location is given, this evaluates EXPRESSION and watches\n\
15383 the memory to which it refers."));
15384   set_cmd_completer (c, expression_completer);
15385
15386   c = add_com ("awatch", class_breakpoint, awatch_command, _("\
15387 Set a watchpoint for an expression.\n\
15388 Usage: awatch [-l|-location] EXPRESSION\n\
15389 A watchpoint stops execution of your program whenever the value of\n\
15390 an expression is either read or written.\n\
15391 If -l or -location is given, this evaluates EXPRESSION and watches\n\
15392 the memory to which it refers."));
15393   set_cmd_completer (c, expression_completer);
15394
15395   add_info ("watchpoints", watchpoints_info, _("\
15396 Status of specified watchpoints (all watchpoints if no argument)."));
15397
15398   /* XXX: cagney/2005-02-23: This should be a boolean, and should
15399      respond to changes - contrary to the description.  */
15400   add_setshow_zinteger_cmd ("can-use-hw-watchpoints", class_support,
15401                             &can_use_hw_watchpoints, _("\
15402 Set debugger's willingness to use watchpoint hardware."), _("\
15403 Show debugger's willingness to use watchpoint hardware."), _("\
15404 If zero, gdb will not use hardware for new watchpoints, even if\n\
15405 such is available.  (However, any hardware watchpoints that were\n\
15406 created before setting this to nonzero, will continue to use watchpoint\n\
15407 hardware.)"),
15408                             NULL,
15409                             show_can_use_hw_watchpoints,
15410                             &setlist, &showlist);
15411
15412   can_use_hw_watchpoints = 1;
15413
15414   /* Tracepoint manipulation commands.  */
15415
15416   c = add_com ("trace", class_breakpoint, trace_command, _("\
15417 Set a tracepoint at specified line or function.\n\
15418 \n"
15419 BREAK_ARGS_HELP ("trace") "\n\
15420 Do \"help tracepoints\" for info on other tracepoint commands."));
15421   set_cmd_completer (c, location_completer);
15422
15423   add_com_alias ("tp", "trace", class_alias, 0);
15424   add_com_alias ("tr", "trace", class_alias, 1);
15425   add_com_alias ("tra", "trace", class_alias, 1);
15426   add_com_alias ("trac", "trace", class_alias, 1);
15427
15428   c = add_com ("ftrace", class_breakpoint, ftrace_command, _("\
15429 Set a fast tracepoint at specified line or function.\n\
15430 \n"
15431 BREAK_ARGS_HELP ("ftrace") "\n\
15432 Do \"help tracepoints\" for info on other tracepoint commands."));
15433   set_cmd_completer (c, location_completer);
15434
15435   c = add_com ("strace", class_breakpoint, strace_command, _("\
15436 Set a static tracepoint at specified line, function or marker.\n\
15437 \n\
15438 strace [LOCATION] [if CONDITION]\n\
15439 LOCATION may be a line number, function name, \"*\" and an address,\n\
15440 or -m MARKER_ID.\n\
15441 If a line number is specified, probe the marker at start of code\n\
15442 for that line.  If a function is specified, probe the marker at start\n\
15443 of code for that function.  If an address is specified, probe the marker\n\
15444 at that exact address.  If a marker id is specified, probe the marker\n\
15445 with that name.  With no LOCATION, uses current execution address of\n\
15446 the selected stack frame.\n\
15447 Static tracepoints accept an extra collect action -- ``collect $_sdata''.\n\
15448 This collects arbitrary user data passed in the probe point call to the\n\
15449 tracing library.  You can inspect it when analyzing the trace buffer,\n\
15450 by printing the $_sdata variable like any other convenience variable.\n\
15451 \n\
15452 CONDITION is a boolean expression.\n\
15453 \n\
15454 Multiple tracepoints at one place are permitted, and useful if their\n\
15455 conditions are different.\n\
15456 \n\
15457 Do \"help breakpoints\" for info on other commands dealing with breakpoints.\n\
15458 Do \"help tracepoints\" for info on other tracepoint commands."));
15459   set_cmd_completer (c, location_completer);
15460
15461   add_info ("tracepoints", tracepoints_info, _("\
15462 Status of specified tracepoints (all tracepoints if no argument).\n\
15463 Convenience variable \"$tpnum\" contains the number of the\n\
15464 last tracepoint set."));
15465
15466   add_info_alias ("tp", "tracepoints", 1);
15467
15468   add_cmd ("tracepoints", class_trace, delete_trace_command, _("\
15469 Delete specified tracepoints.\n\
15470 Arguments are tracepoint numbers, separated by spaces.\n\
15471 No argument means delete all tracepoints."),
15472            &deletelist);
15473
15474   c = add_cmd ("tracepoints", class_trace, disable_trace_command, _("\
15475 Disable specified tracepoints.\n\
15476 Arguments are tracepoint numbers, separated by spaces.\n\
15477 No argument means disable all tracepoints."),
15478            &disablelist);
15479   deprecate_cmd (c, "disable");
15480
15481   c = add_cmd ("tracepoints", class_trace, enable_trace_command, _("\
15482 Enable specified tracepoints.\n\
15483 Arguments are tracepoint numbers, separated by spaces.\n\
15484 No argument means enable all tracepoints."),
15485            &enablelist);
15486   deprecate_cmd (c, "enable");
15487
15488   add_com ("passcount", class_trace, trace_pass_command, _("\
15489 Set the passcount for a tracepoint.\n\
15490 The trace will end when the tracepoint has been passed 'count' times.\n\
15491 Usage: passcount COUNT TPNUM, where TPNUM may also be \"all\";\n\
15492 if TPNUM is omitted, passcount refers to the last tracepoint defined."));
15493
15494   add_prefix_cmd ("save", class_breakpoint, save_command,
15495                   _("Save breakpoint definitions as a script."),
15496                   &save_cmdlist, "save ",
15497                   0/*allow-unknown*/, &cmdlist);
15498
15499   c = add_cmd ("breakpoints", class_breakpoint, save_breakpoints_command, _("\
15500 Save current breakpoint definitions as a script.\n\
15501 This includes all types of breakpoints (breakpoints, watchpoints,\n\
15502 catchpoints, tracepoints).  Use the 'source' command in another debug\n\
15503 session to restore them."),
15504                &save_cmdlist);
15505   set_cmd_completer (c, filename_completer);
15506
15507   c = add_cmd ("tracepoints", class_trace, save_tracepoints_command, _("\
15508 Save current tracepoint definitions as a script.\n\
15509 Use the 'source' command in another debug session to restore them."),
15510                &save_cmdlist);
15511   set_cmd_completer (c, filename_completer);
15512
15513   c = add_com_alias ("save-tracepoints", "save tracepoints", class_trace, 0);
15514   deprecate_cmd (c, "save tracepoints");
15515
15516   add_prefix_cmd ("breakpoint", class_maintenance, set_breakpoint_cmd, _("\
15517 Breakpoint specific settings\n\
15518 Configure various breakpoint-specific variables such as\n\
15519 pending breakpoint behavior"),
15520                   &breakpoint_set_cmdlist, "set breakpoint ",
15521                   0/*allow-unknown*/, &setlist);
15522   add_prefix_cmd ("breakpoint", class_maintenance, show_breakpoint_cmd, _("\
15523 Breakpoint specific settings\n\
15524 Configure various breakpoint-specific variables such as\n\
15525 pending breakpoint behavior"),
15526                   &breakpoint_show_cmdlist, "show breakpoint ",
15527                   0/*allow-unknown*/, &showlist);
15528
15529   add_setshow_auto_boolean_cmd ("pending", no_class,
15530                                 &pending_break_support, _("\
15531 Set debugger's behavior regarding pending breakpoints."), _("\
15532 Show debugger's behavior regarding pending breakpoints."), _("\
15533 If on, an unrecognized breakpoint location will cause gdb to create a\n\
15534 pending breakpoint.  If off, an unrecognized breakpoint location results in\n\
15535 an error.  If auto, an unrecognized breakpoint location results in a\n\
15536 user-query to see if a pending breakpoint should be created."),
15537                                 NULL,
15538                                 show_pending_break_support,
15539                                 &breakpoint_set_cmdlist,
15540                                 &breakpoint_show_cmdlist);
15541
15542   pending_break_support = AUTO_BOOLEAN_AUTO;
15543
15544   add_setshow_boolean_cmd ("auto-hw", no_class,
15545                            &automatic_hardware_breakpoints, _("\
15546 Set automatic usage of hardware breakpoints."), _("\
15547 Show automatic usage of hardware breakpoints."), _("\
15548 If set, the debugger will automatically use hardware breakpoints for\n\
15549 breakpoints set with \"break\" but falling in read-only memory.  If not set,\n\
15550 a warning will be emitted for such breakpoints."),
15551                            NULL,
15552                            show_automatic_hardware_breakpoints,
15553                            &breakpoint_set_cmdlist,
15554                            &breakpoint_show_cmdlist);
15555
15556   add_setshow_enum_cmd ("always-inserted", class_support,
15557                         always_inserted_enums, &always_inserted_mode, _("\
15558 Set mode for inserting breakpoints."), _("\
15559 Show mode for inserting breakpoints."), _("\
15560 When this mode is off, breakpoints are inserted in inferior when it is\n\
15561 resumed, and removed when execution stops.  When this mode is on,\n\
15562 breakpoints are inserted immediately and removed only when the user\n\
15563 deletes the breakpoint.  When this mode is auto (which is the default),\n\
15564 the behaviour depends on the non-stop setting (see help set non-stop).\n\
15565 In this case, if gdb is controlling the inferior in non-stop mode, gdb\n\
15566 behaves as if always-inserted mode is on; if gdb is controlling the\n\
15567 inferior in all-stop mode, gdb behaves as if always-inserted mode is off."),
15568                            NULL,
15569                            &show_always_inserted_mode,
15570                            &breakpoint_set_cmdlist,
15571                            &breakpoint_show_cmdlist);
15572
15573   add_setshow_enum_cmd ("condition-evaluation", class_breakpoint,
15574                         condition_evaluation_enums,
15575                         &condition_evaluation_mode_1, _("\
15576 Set mode of breakpoint condition evaluation."), _("\
15577 Show mode of breakpoint condition evaluation."), _("\
15578 When this is set to \"host\", breakpoint conditions will be\n\
15579 evaluated on the host's side by GDB.  When it is set to \"target\",\n\
15580 breakpoint conditions will be downloaded to the target (if the target\n\
15581 supports such feature) and conditions will be evaluated on the target's side.\n\
15582 If this is set to \"auto\" (default), this will be automatically set to\n\
15583 \"target\" if it supports condition evaluation, otherwise it will\n\
15584 be set to \"gdb\""),
15585                            &set_condition_evaluation_mode,
15586                            &show_condition_evaluation_mode,
15587                            &breakpoint_set_cmdlist,
15588                            &breakpoint_show_cmdlist);
15589
15590   add_com ("break-range", class_breakpoint, break_range_command, _("\
15591 Set a breakpoint for an address range.\n\
15592 break-range START-LOCATION, END-LOCATION\n\
15593 where START-LOCATION and END-LOCATION can be one of the following:\n\
15594   LINENUM, for that line in the current file,\n\
15595   FILE:LINENUM, for that line in that file,\n\
15596   +OFFSET, for that number of lines after the current line\n\
15597            or the start of the range\n\
15598   FUNCTION, for the first line in that function,\n\
15599   FILE:FUNCTION, to distinguish among like-named static functions.\n\
15600   *ADDRESS, for the instruction at that address.\n\
15601 \n\
15602 The breakpoint will stop execution of the inferior whenever it executes\n\
15603 an instruction at any address within the [START-LOCATION, END-LOCATION]\n\
15604 range (including START-LOCATION and END-LOCATION)."));
15605
15606   automatic_hardware_breakpoints = 1;
15607
15608   observer_attach_about_to_proceed (breakpoint_about_to_proceed);
15609 }