2012-02-24 Jan Kratochvil <jan.kratochvil@redhat.com>
[external/binutils.git] / gdb / breakpoint.c
1 /* Everything about breakpoints, for GDB.
2
3    Copyright (C) 1986-2012 Free Software Foundation, Inc.
4
5    This file is part of GDB.
6
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
19
20 #include "defs.h"
21 #include "arch-utils.h"
22 #include <ctype.h>
23 #include "hashtab.h"
24 #include "symtab.h"
25 #include "frame.h"
26 #include "breakpoint.h"
27 #include "tracepoint.h"
28 #include "gdbtypes.h"
29 #include "expression.h"
30 #include "gdbcore.h"
31 #include "gdbcmd.h"
32 #include "value.h"
33 #include "command.h"
34 #include "inferior.h"
35 #include "gdbthread.h"
36 #include "target.h"
37 #include "language.h"
38 #include "gdb_string.h"
39 #include "gdb-demangle.h"
40 #include "filenames.h"
41 #include "annotate.h"
42 #include "symfile.h"
43 #include "objfiles.h"
44 #include "source.h"
45 #include "linespec.h"
46 #include "completer.h"
47 #include "gdb.h"
48 #include "ui-out.h"
49 #include "cli/cli-script.h"
50 #include "gdb_assert.h"
51 #include "block.h"
52 #include "solib.h"
53 #include "solist.h"
54 #include "observer.h"
55 #include "exceptions.h"
56 #include "memattr.h"
57 #include "ada-lang.h"
58 #include "top.h"
59 #include "valprint.h"
60 #include "jit.h"
61 #include "xml-syscall.h"
62 #include "parser-defs.h"
63 #include "cli/cli-utils.h"
64 #include "continuations.h"
65 #include "stack.h"
66 #include "skip.h"
67 #include "record.h"
68 #include "gdb_regex.h"
69 #include "ax-gdb.h"
70
71 /* readline include files */
72 #include "readline/readline.h"
73 #include "readline/history.h"
74
75 /* readline defines this.  */
76 #undef savestring
77
78 #include "mi/mi-common.h"
79 #include "python/python.h"
80
81 /* Prototypes for local functions.  */
82
83 static void enable_delete_command (char *, int);
84
85 static void enable_once_command (char *, int);
86
87 static void enable_count_command (char *, int);
88
89 static void disable_command (char *, int);
90
91 static void enable_command (char *, int);
92
93 static void map_breakpoint_numbers (char *, void (*) (struct breakpoint *,
94                                                       void *),
95                                     void *);
96
97 static void ignore_command (char *, int);
98
99 static int breakpoint_re_set_one (void *);
100
101 static void breakpoint_re_set_default (struct breakpoint *);
102
103 static void create_sals_from_address_default (char **,
104                                               struct linespec_result *,
105                                               enum bptype, char *,
106                                               char **);
107
108 static void create_breakpoints_sal_default (struct gdbarch *,
109                                             struct linespec_result *,
110                                             struct linespec_sals *,
111                                             char *, enum bptype,
112                                             enum bpdisp, int, int,
113                                             int,
114                                             const struct breakpoint_ops *,
115                                             int, int, int);
116
117 static void decode_linespec_default (struct breakpoint *, char **,
118                                      struct symtabs_and_lines *);
119
120 static void clear_command (char *, int);
121
122 static void catch_command (char *, int);
123
124 static int can_use_hardware_watchpoint (struct value *);
125
126 static void break_command_1 (char *, int, int);
127
128 static void mention (struct breakpoint *);
129
130 static struct breakpoint *set_raw_breakpoint_without_location (struct gdbarch *,
131                                                                enum bptype,
132                                                                const struct breakpoint_ops *);
133 static struct bp_location *add_location_to_breakpoint (struct breakpoint *,
134                                                        const struct symtab_and_line *);
135
136 /* This function is used in gdbtk sources and thus can not be made
137    static.  */
138 struct breakpoint *set_raw_breakpoint (struct gdbarch *gdbarch,
139                                        struct symtab_and_line,
140                                        enum bptype,
141                                        const struct breakpoint_ops *);
142
143 static struct breakpoint *
144   momentary_breakpoint_from_master (struct breakpoint *orig,
145                                     enum bptype type,
146                                     const struct breakpoint_ops *ops);
147
148 static void breakpoint_adjustment_warning (CORE_ADDR, CORE_ADDR, int, int);
149
150 static CORE_ADDR adjust_breakpoint_address (struct gdbarch *gdbarch,
151                                             CORE_ADDR bpaddr,
152                                             enum bptype bptype);
153
154 static void describe_other_breakpoints (struct gdbarch *,
155                                         struct program_space *, CORE_ADDR,
156                                         struct obj_section *, int);
157
158 static int breakpoint_address_match (struct address_space *aspace1,
159                                      CORE_ADDR addr1,
160                                      struct address_space *aspace2,
161                                      CORE_ADDR addr2);
162
163 static int watchpoint_locations_match (struct bp_location *loc1,
164                                        struct bp_location *loc2);
165
166 static int breakpoint_location_address_match (struct bp_location *bl,
167                                               struct address_space *aspace,
168                                               CORE_ADDR addr);
169
170 static void breakpoints_info (char *, int);
171
172 static void watchpoints_info (char *, int);
173
174 static int breakpoint_1 (char *, int, 
175                          int (*) (const struct breakpoint *));
176
177 static int breakpoint_cond_eval (void *);
178
179 static void cleanup_executing_breakpoints (void *);
180
181 static void commands_command (char *, int);
182
183 static void condition_command (char *, int);
184
185 typedef enum
186   {
187     mark_inserted,
188     mark_uninserted
189   }
190 insertion_state_t;
191
192 static int remove_breakpoint (struct bp_location *, insertion_state_t);
193 static int remove_breakpoint_1 (struct bp_location *, insertion_state_t);
194
195 static enum print_stop_action print_bp_stop_message (bpstat bs);
196
197 static int watchpoint_check (void *);
198
199 static void maintenance_info_breakpoints (char *, int);
200
201 static int hw_breakpoint_used_count (void);
202
203 static int hw_watchpoint_use_count (struct breakpoint *);
204
205 static int hw_watchpoint_used_count_others (struct breakpoint *except,
206                                             enum bptype type,
207                                             int *other_type_used);
208
209 static void hbreak_command (char *, int);
210
211 static void thbreak_command (char *, int);
212
213 static void enable_breakpoint_disp (struct breakpoint *, enum bpdisp,
214                                     int count);
215
216 static void stop_command (char *arg, int from_tty);
217
218 static void stopin_command (char *arg, int from_tty);
219
220 static void stopat_command (char *arg, int from_tty);
221
222 static char *ep_parse_optional_if_clause (char **arg);
223
224 static void catch_exception_command_1 (enum exception_event_kind ex_event, 
225                                        char *arg, int tempflag, int from_tty);
226
227 static void tcatch_command (char *arg, int from_tty);
228
229 static void detach_single_step_breakpoints (void);
230
231 static int single_step_breakpoint_inserted_here_p (struct address_space *,
232                                                    CORE_ADDR pc);
233
234 static void free_bp_location (struct bp_location *loc);
235 static void incref_bp_location (struct bp_location *loc);
236 static void decref_bp_location (struct bp_location **loc);
237
238 static struct bp_location *allocate_bp_location (struct breakpoint *bpt);
239
240 static void update_global_location_list (int);
241
242 static void update_global_location_list_nothrow (int);
243
244 static int is_hardware_watchpoint (const struct breakpoint *bpt);
245
246 static void insert_breakpoint_locations (void);
247
248 static int syscall_catchpoint_p (struct breakpoint *b);
249
250 static void tracepoints_info (char *, int);
251
252 static void delete_trace_command (char *, int);
253
254 static void enable_trace_command (char *, int);
255
256 static void disable_trace_command (char *, int);
257
258 static void trace_pass_command (char *, int);
259
260 static int is_masked_watchpoint (const struct breakpoint *b);
261
262 static struct bp_location **get_first_locp_gte_addr (CORE_ADDR address);
263
264 /* Return 1 if B refers to a static tracepoint set by marker ("-m"), zero
265    otherwise.  */
266
267 static int strace_marker_p (struct breakpoint *b);
268
269 static void init_catchpoint (struct breakpoint *b,
270                              struct gdbarch *gdbarch, int tempflag,
271                              char *cond_string,
272                              const struct breakpoint_ops *ops);
273
274 /* The abstract base class all breakpoint_ops structures inherit
275    from.  */
276 static struct breakpoint_ops base_breakpoint_ops;
277
278 /* The breakpoint_ops structure to be inherited by all breakpoint_ops
279    that are implemented on top of software or hardware breakpoints
280    (user breakpoints, internal and momentary breakpoints, etc.).  */
281 static struct breakpoint_ops bkpt_base_breakpoint_ops;
282
283 /* Internal breakpoints class type.  */
284 static struct breakpoint_ops internal_breakpoint_ops;
285
286 /* Momentary breakpoints class type.  */
287 static struct breakpoint_ops momentary_breakpoint_ops;
288
289 /* The breakpoint_ops structure to be used in regular user created
290    breakpoints.  */
291 struct breakpoint_ops bkpt_breakpoint_ops;
292
293 /* A reference-counted struct command_line.  This lets multiple
294    breakpoints share a single command list.  */
295 struct counted_command_line
296 {
297   /* The reference count.  */
298   int refc;
299
300   /* The command list.  */
301   struct command_line *commands;
302 };
303
304 struct command_line *
305 breakpoint_commands (struct breakpoint *b)
306 {
307   return b->commands ? b->commands->commands : NULL;
308 }
309
310 /* Flag indicating that a command has proceeded the inferior past the
311    current breakpoint.  */
312
313 static int breakpoint_proceeded;
314
315 const char *
316 bpdisp_text (enum bpdisp disp)
317 {
318   /* NOTE: the following values are a part of MI protocol and
319      represent values of 'disp' field returned when inferior stops at
320      a breakpoint.  */
321   static const char * const bpdisps[] = {"del", "dstp", "dis", "keep"};
322
323   return bpdisps[(int) disp];
324 }
325
326 /* Prototypes for exported functions.  */
327 /* If FALSE, gdb will not use hardware support for watchpoints, even
328    if such is available.  */
329 static int can_use_hw_watchpoints;
330
331 static void
332 show_can_use_hw_watchpoints (struct ui_file *file, int from_tty,
333                              struct cmd_list_element *c,
334                              const char *value)
335 {
336   fprintf_filtered (file,
337                     _("Debugger's willingness to use "
338                       "watchpoint hardware is %s.\n"),
339                     value);
340 }
341
342 /* If AUTO_BOOLEAN_FALSE, gdb will not attempt to create pending breakpoints.
343    If AUTO_BOOLEAN_TRUE, gdb will automatically create pending breakpoints
344    for unrecognized breakpoint locations.
345    If AUTO_BOOLEAN_AUTO, gdb will query when breakpoints are unrecognized.  */
346 static enum auto_boolean pending_break_support;
347 static void
348 show_pending_break_support (struct ui_file *file, int from_tty,
349                             struct cmd_list_element *c,
350                             const char *value)
351 {
352   fprintf_filtered (file,
353                     _("Debugger's behavior regarding "
354                       "pending breakpoints is %s.\n"),
355                     value);
356 }
357
358 /* If 1, gdb will automatically use hardware breakpoints for breakpoints
359    set with "break" but falling in read-only memory.
360    If 0, gdb will warn about such breakpoints, but won't automatically
361    use hardware breakpoints.  */
362 static int automatic_hardware_breakpoints;
363 static void
364 show_automatic_hardware_breakpoints (struct ui_file *file, int from_tty,
365                                      struct cmd_list_element *c,
366                                      const char *value)
367 {
368   fprintf_filtered (file,
369                     _("Automatic usage of hardware breakpoints is %s.\n"),
370                     value);
371 }
372
373 /* If on, gdb will keep breakpoints inserted even as inferior is
374    stopped, and immediately insert any new breakpoints.  If off, gdb
375    will insert breakpoints into inferior only when resuming it, and
376    will remove breakpoints upon stop.  If auto, GDB will behave as ON
377    if in non-stop mode, and as OFF if all-stop mode.*/
378
379 static const char always_inserted_auto[] = "auto";
380 static const char always_inserted_on[] = "on";
381 static const char always_inserted_off[] = "off";
382 static const char *const always_inserted_enums[] = {
383   always_inserted_auto,
384   always_inserted_off,
385   always_inserted_on,
386   NULL
387 };
388 static const char *always_inserted_mode = always_inserted_auto;
389 static void
390 show_always_inserted_mode (struct ui_file *file, int from_tty,
391                      struct cmd_list_element *c, const char *value)
392 {
393   if (always_inserted_mode == always_inserted_auto)
394     fprintf_filtered (file,
395                       _("Always inserted breakpoint "
396                         "mode is %s (currently %s).\n"),
397                       value,
398                       breakpoints_always_inserted_mode () ? "on" : "off");
399   else
400     fprintf_filtered (file, _("Always inserted breakpoint mode is %s.\n"),
401                       value);
402 }
403
404 int
405 breakpoints_always_inserted_mode (void)
406 {
407   return ((always_inserted_mode == always_inserted_on
408            || (always_inserted_mode == always_inserted_auto && non_stop))
409           && !RECORD_IS_USED);
410 }
411
412 static const char condition_evaluation_both[] = "host or target";
413
414 /* Modes for breakpoint condition evaluation.  */
415 static const char condition_evaluation_auto[] = "auto";
416 static const char condition_evaluation_host[] = "host";
417 static const char condition_evaluation_target[] = "target";
418 static const char *const condition_evaluation_enums[] = {
419   condition_evaluation_auto,
420   condition_evaluation_host,
421   condition_evaluation_target,
422   NULL
423 };
424
425 /* Global that holds the current mode for breakpoint condition evaluation.  */
426 static const char *condition_evaluation_mode_1 = condition_evaluation_auto;
427
428 /* Global that we use to display information to the user (gets its value from
429    condition_evaluation_mode_1.  */
430 static const char *condition_evaluation_mode = condition_evaluation_auto;
431
432 /* Translate a condition evaluation mode MODE into either "host"
433    or "target".  This is used mostly to translate from "auto" to the
434    real setting that is being used.  It returns the translated
435    evaluation mode.  */
436
437 static const char *
438 translate_condition_evaluation_mode (const char *mode)
439 {
440   if (mode == condition_evaluation_auto)
441     {
442       if (target_supports_evaluation_of_breakpoint_conditions ())
443         return condition_evaluation_target;
444       else
445         return condition_evaluation_host;
446     }
447   else
448     return mode;
449 }
450
451 /* Discovers what condition_evaluation_auto translates to.  */
452
453 static const char *
454 breakpoint_condition_evaluation_mode (void)
455 {
456   return translate_condition_evaluation_mode (condition_evaluation_mode);
457 }
458
459 /* Return true if GDB should evaluate breakpoint conditions or false
460    otherwise.  */
461
462 static int
463 gdb_evaluates_breakpoint_condition_p (void)
464 {
465   const char *mode = breakpoint_condition_evaluation_mode ();
466
467   return (mode == condition_evaluation_host);
468 }
469
470 void _initialize_breakpoint (void);
471
472 /* Are we executing breakpoint commands?  */
473 static int executing_breakpoint_commands;
474
475 /* Are overlay event breakpoints enabled? */
476 static int overlay_events_enabled;
477
478 /* See description in breakpoint.h. */
479 int target_exact_watchpoints = 0;
480
481 /* Walk the following statement or block through all breakpoints.
482    ALL_BREAKPOINTS_SAFE does so even if the statement deletes the
483    current breakpoint.  */
484
485 #define ALL_BREAKPOINTS(B)  for (B = breakpoint_chain; B; B = B->next)
486
487 #define ALL_BREAKPOINTS_SAFE(B,TMP)     \
488         for (B = breakpoint_chain;      \
489              B ? (TMP=B->next, 1): 0;   \
490              B = TMP)
491
492 /* Similar iterator for the low-level breakpoints.  SAFE variant is
493    not provided so update_global_location_list must not be called
494    while executing the block of ALL_BP_LOCATIONS.  */
495
496 #define ALL_BP_LOCATIONS(B,BP_TMP)                                      \
497         for (BP_TMP = bp_location;                                      \
498              BP_TMP < bp_location + bp_location_count && (B = *BP_TMP); \
499              BP_TMP++)
500
501 /* Iterates through locations with address ADDRESS for the currently selected
502    program space.  BP_LOCP_TMP points to each object.  BP_LOCP_START points
503    to where the loop should start from.
504    If BP_LOCP_START is a NULL pointer, the macro automatically seeks the
505    appropriate location to start with.  */
506
507 #define ALL_BP_LOCATIONS_AT_ADDR(BP_LOCP_TMP, BP_LOCP_START, ADDRESS)   \
508         for (BP_LOCP_START = BP_LOCP_START == NULL ? get_first_locp_gte_addr (ADDRESS) : BP_LOCP_START, \
509              BP_LOCP_TMP = BP_LOCP_START;                               \
510              BP_LOCP_START                                              \
511              && (BP_LOCP_TMP < bp_location + bp_location_count          \
512              && (*BP_LOCP_TMP)->address == ADDRESS);                    \
513              BP_LOCP_TMP++)
514
515 /* Iterator for tracepoints only.  */
516
517 #define ALL_TRACEPOINTS(B)  \
518   for (B = breakpoint_chain; B; B = B->next)  \
519     if (is_tracepoint (B))
520
521 /* Chains of all breakpoints defined.  */
522
523 struct breakpoint *breakpoint_chain;
524
525 /* Array is sorted by bp_location_compare - primarily by the ADDRESS.  */
526
527 static struct bp_location **bp_location;
528
529 /* Number of elements of BP_LOCATION.  */
530
531 static unsigned bp_location_count;
532
533 /* Maximum alignment offset between bp_target_info.PLACED_ADDRESS and
534    ADDRESS for the current elements of BP_LOCATION which get a valid
535    result from bp_location_has_shadow.  You can use it for roughly
536    limiting the subrange of BP_LOCATION to scan for shadow bytes for
537    an address you need to read.  */
538
539 static CORE_ADDR bp_location_placed_address_before_address_max;
540
541 /* Maximum offset plus alignment between bp_target_info.PLACED_ADDRESS
542    + bp_target_info.SHADOW_LEN and ADDRESS for the current elements of
543    BP_LOCATION which get a valid result from bp_location_has_shadow.
544    You can use it for roughly limiting the subrange of BP_LOCATION to
545    scan for shadow bytes for an address you need to read.  */
546
547 static CORE_ADDR bp_location_shadow_len_after_address_max;
548
549 /* The locations that no longer correspond to any breakpoint, unlinked
550    from bp_location array, but for which a hit may still be reported
551    by a target.  */
552 VEC(bp_location_p) *moribund_locations = NULL;
553
554 /* Number of last breakpoint made.  */
555
556 static int breakpoint_count;
557
558 /* The value of `breakpoint_count' before the last command that
559    created breakpoints.  If the last (break-like) command created more
560    than one breakpoint, then the difference between BREAKPOINT_COUNT
561    and PREV_BREAKPOINT_COUNT is more than one.  */
562 static int prev_breakpoint_count;
563
564 /* Number of last tracepoint made.  */
565
566 static int tracepoint_count;
567
568 static struct cmd_list_element *breakpoint_set_cmdlist;
569 static struct cmd_list_element *breakpoint_show_cmdlist;
570 struct cmd_list_element *save_cmdlist;
571
572 /* Return whether a breakpoint is an active enabled breakpoint.  */
573 static int
574 breakpoint_enabled (struct breakpoint *b)
575 {
576   return (b->enable_state == bp_enabled);
577 }
578
579 /* Set breakpoint count to NUM.  */
580
581 static void
582 set_breakpoint_count (int num)
583 {
584   prev_breakpoint_count = breakpoint_count;
585   breakpoint_count = num;
586   set_internalvar_integer (lookup_internalvar ("bpnum"), num);
587 }
588
589 /* Used by `start_rbreak_breakpoints' below, to record the current
590    breakpoint count before "rbreak" creates any breakpoint.  */
591 static int rbreak_start_breakpoint_count;
592
593 /* Called at the start an "rbreak" command to record the first
594    breakpoint made.  */
595
596 void
597 start_rbreak_breakpoints (void)
598 {
599   rbreak_start_breakpoint_count = breakpoint_count;
600 }
601
602 /* Called at the end of an "rbreak" command to record the last
603    breakpoint made.  */
604
605 void
606 end_rbreak_breakpoints (void)
607 {
608   prev_breakpoint_count = rbreak_start_breakpoint_count;
609 }
610
611 /* Used in run_command to zero the hit count when a new run starts.  */
612
613 void
614 clear_breakpoint_hit_counts (void)
615 {
616   struct breakpoint *b;
617
618   ALL_BREAKPOINTS (b)
619     b->hit_count = 0;
620 }
621
622 /* Allocate a new counted_command_line with reference count of 1.
623    The new structure owns COMMANDS.  */
624
625 static struct counted_command_line *
626 alloc_counted_command_line (struct command_line *commands)
627 {
628   struct counted_command_line *result
629     = xmalloc (sizeof (struct counted_command_line));
630
631   result->refc = 1;
632   result->commands = commands;
633   return result;
634 }
635
636 /* Increment reference count.  This does nothing if CMD is NULL.  */
637
638 static void
639 incref_counted_command_line (struct counted_command_line *cmd)
640 {
641   if (cmd)
642     ++cmd->refc;
643 }
644
645 /* Decrement reference count.  If the reference count reaches 0,
646    destroy the counted_command_line.  Sets *CMDP to NULL.  This does
647    nothing if *CMDP is NULL.  */
648
649 static void
650 decref_counted_command_line (struct counted_command_line **cmdp)
651 {
652   if (*cmdp)
653     {
654       if (--(*cmdp)->refc == 0)
655         {
656           free_command_lines (&(*cmdp)->commands);
657           xfree (*cmdp);
658         }
659       *cmdp = NULL;
660     }
661 }
662
663 /* A cleanup function that calls decref_counted_command_line.  */
664
665 static void
666 do_cleanup_counted_command_line (void *arg)
667 {
668   decref_counted_command_line (arg);
669 }
670
671 /* Create a cleanup that calls decref_counted_command_line on the
672    argument.  */
673
674 static struct cleanup *
675 make_cleanup_decref_counted_command_line (struct counted_command_line **cmdp)
676 {
677   return make_cleanup (do_cleanup_counted_command_line, cmdp);
678 }
679
680 \f
681 /* Return the breakpoint with the specified number, or NULL
682    if the number does not refer to an existing breakpoint.  */
683
684 struct breakpoint *
685 get_breakpoint (int num)
686 {
687   struct breakpoint *b;
688
689   ALL_BREAKPOINTS (b)
690     if (b->number == num)
691       return b;
692   
693   return NULL;
694 }
695
696 \f
697
698 /* Mark locations as "conditions have changed" in case the target supports
699    evaluating conditions on its side.  */
700
701 static void
702 mark_breakpoint_modified (struct breakpoint *b)
703 {
704   struct bp_location *loc;
705
706   /* This is only meaningful if the target is
707      evaluating conditions and if the user has
708      opted for condition evaluation on the target's
709      side.  */
710   if (gdb_evaluates_breakpoint_condition_p ()
711       || !target_supports_evaluation_of_breakpoint_conditions ())
712     return;
713
714   if (!is_breakpoint (b))
715     return;
716
717   for (loc = b->loc; loc; loc = loc->next)
718     loc->condition_changed = condition_modified;
719 }
720
721 /* Mark location as "conditions have changed" in case the target supports
722    evaluating conditions on its side.  */
723
724 static void
725 mark_breakpoint_location_modified (struct bp_location *loc)
726 {
727   /* This is only meaningful if the target is
728      evaluating conditions and if the user has
729      opted for condition evaluation on the target's
730      side.  */
731   if (gdb_evaluates_breakpoint_condition_p ()
732       || !target_supports_evaluation_of_breakpoint_conditions ())
733
734     return;
735
736   if (!is_breakpoint (loc->owner))
737     return;
738
739   loc->condition_changed = condition_modified;
740 }
741
742 /* Sets the condition-evaluation mode using the static global
743    condition_evaluation_mode.  */
744
745 static void
746 set_condition_evaluation_mode (char *args, int from_tty,
747                                struct cmd_list_element *c)
748 {
749   struct breakpoint *b;
750   const char *old_mode, *new_mode;
751
752   if ((condition_evaluation_mode_1 == condition_evaluation_target)
753       && !target_supports_evaluation_of_breakpoint_conditions ())
754     {
755       condition_evaluation_mode_1 = condition_evaluation_mode;
756       warning (_("Target does not support breakpoint condition evaluation.\n"
757                  "Using host evaluation mode instead."));
758       return;
759     }
760
761   new_mode = translate_condition_evaluation_mode (condition_evaluation_mode_1);
762   old_mode = translate_condition_evaluation_mode (condition_evaluation_mode);
763
764   /* Only update the mode if the user picked a different one.  */
765   if (new_mode != old_mode)
766     {
767       struct bp_location *loc, **loc_tmp;
768       /* If the user switched to a different evaluation mode, we
769          need to synch the changes with the target as follows:
770
771          "host" -> "target": Send all (valid) conditions to the target.
772          "target" -> "host": Remove all the conditions from the target.
773       */
774
775       /* Flip the switch.  */
776       condition_evaluation_mode = condition_evaluation_mode_1;
777
778       if (new_mode == condition_evaluation_target)
779         {
780           /* Mark everything modified and synch conditions with the
781              target.  */
782           ALL_BP_LOCATIONS (loc, loc_tmp)
783             mark_breakpoint_location_modified (loc);
784         }
785       else
786         {
787           /* Manually mark non-duplicate locations to synch conditions
788              with the target.  We do this to remove all the conditions the
789              target knows about.  */
790           ALL_BP_LOCATIONS (loc, loc_tmp)
791             if (is_breakpoint (loc->owner) && loc->inserted)
792               loc->needs_update = 1;
793         }
794
795       /* Do the update.  */
796       update_global_location_list (1);
797     }
798
799   return;
800 }
801
802 /* Shows the current mode of breakpoint condition evaluation.  Explicitly shows
803    what "auto" is translating to.  */
804
805 static void
806 show_condition_evaluation_mode (struct ui_file *file, int from_tty,
807                                 struct cmd_list_element *c, const char *value)
808 {
809   if (condition_evaluation_mode == condition_evaluation_auto)
810     fprintf_filtered (file,
811                       _("Breakpoint condition evaluation "
812                         "mode is %s (currently %s).\n"),
813                       value,
814                       breakpoint_condition_evaluation_mode ());
815   else
816     fprintf_filtered (file, _("Breakpoint condition evaluation mode is %s.\n"),
817                       value);
818 }
819
820 /* A comparison function for bp_location AP and BP that is used by
821    bsearch.  This comparison function only cares about addresses, unlike
822    the more general bp_location_compare function.  */
823
824 static int
825 bp_location_compare_addrs (const void *ap, const void *bp)
826 {
827   struct bp_location *a = *(void **) ap;
828   struct bp_location *b = *(void **) bp;
829
830   if (a->address == b->address)
831     return 0;
832   else
833     return ((a->address > b->address) - (a->address < b->address));
834 }
835
836 /* Helper function to skip all bp_locations with addresses
837    less than ADDRESS.  It returns the first bp_location that
838    is greater than or equal to ADDRESS.  If none is found, just
839    return NULL.  */
840
841 static struct bp_location **
842 get_first_locp_gte_addr (CORE_ADDR address)
843 {
844   struct bp_location dummy_loc;
845   struct bp_location *dummy_locp = &dummy_loc;
846   struct bp_location **locp_found = NULL;
847
848   /* Initialize the dummy location's address field.  */
849   memset (&dummy_loc, 0, sizeof (struct bp_location));
850   dummy_loc.address = address;
851
852   /* Find a close match to the first location at ADDRESS.  */
853   locp_found = bsearch (&dummy_locp, bp_location, bp_location_count,
854                         sizeof (struct bp_location **),
855                         bp_location_compare_addrs);
856
857   /* Nothing was found, nothing left to do.  */
858   if (locp_found == NULL)
859     return NULL;
860
861   /* We may have found a location that is at ADDRESS but is not the first in the
862      location's list.  Go backwards (if possible) and locate the first one.  */
863   while ((locp_found - 1) >= bp_location
864          && (*(locp_found - 1))->address == address)
865     locp_found--;
866
867   return locp_found;
868 }
869
870 void
871 set_breakpoint_condition (struct breakpoint *b, char *exp,
872                           int from_tty)
873 {
874   xfree (b->cond_string);
875   b->cond_string = NULL;
876
877   if (is_watchpoint (b))
878     {
879       struct watchpoint *w = (struct watchpoint *) b;
880
881       xfree (w->cond_exp);
882       w->cond_exp = NULL;
883     }
884   else
885     {
886       struct bp_location *loc;
887
888       for (loc = b->loc; loc; loc = loc->next)
889         {
890           xfree (loc->cond);
891           loc->cond = NULL;
892
893           /* No need to free the condition agent expression
894              bytecode (if we have one).  We will handle this
895              when we go through update_global_location_list.  */
896         }
897     }
898
899   if (*exp == 0)
900     {
901       if (from_tty)
902         printf_filtered (_("Breakpoint %d now unconditional.\n"), b->number);
903     }
904   else
905     {
906       char *arg = exp;
907
908       /* I don't know if it matters whether this is the string the user
909          typed in or the decompiled expression.  */
910       b->cond_string = xstrdup (arg);
911       b->condition_not_parsed = 0;
912
913       if (is_watchpoint (b))
914         {
915           struct watchpoint *w = (struct watchpoint *) b;
916
917           innermost_block = NULL;
918           arg = exp;
919           w->cond_exp = parse_exp_1 (&arg, 0, 0);
920           if (*arg)
921             error (_("Junk at end of expression"));
922           w->cond_exp_valid_block = innermost_block;
923         }
924       else
925         {
926           struct bp_location *loc;
927
928           for (loc = b->loc; loc; loc = loc->next)
929             {
930               arg = exp;
931               loc->cond =
932                 parse_exp_1 (&arg, block_for_pc (loc->address), 0);
933               if (*arg)
934                 error (_("Junk at end of expression"));
935             }
936         }
937     }
938   mark_breakpoint_modified (b);
939
940   breakpoints_changed ();
941   observer_notify_breakpoint_modified (b);
942 }
943
944 /* condition N EXP -- set break condition of breakpoint N to EXP.  */
945
946 static void
947 condition_command (char *arg, int from_tty)
948 {
949   struct breakpoint *b;
950   char *p;
951   int bnum;
952
953   if (arg == 0)
954     error_no_arg (_("breakpoint number"));
955
956   p = arg;
957   bnum = get_number (&p);
958   if (bnum == 0)
959     error (_("Bad breakpoint argument: '%s'"), arg);
960
961   ALL_BREAKPOINTS (b)
962     if (b->number == bnum)
963       {
964         /* Check if this breakpoint has a Python object assigned to
965            it, and if it has a definition of the "stop"
966            method.  This method and conditions entered into GDB from
967            the CLI are mutually exclusive.  */
968         if (b->py_bp_object
969             && gdbpy_breakpoint_has_py_cond (b->py_bp_object))
970           error (_("Cannot set a condition where a Python 'stop' "
971                    "method has been defined in the breakpoint."));
972         set_breakpoint_condition (b, p, from_tty);
973
974         if (is_breakpoint (b))
975           update_global_location_list (1);
976
977         return;
978       }
979
980   error (_("No breakpoint number %d."), bnum);
981 }
982
983 /* Check that COMMAND do not contain commands that are suitable
984    only for tracepoints and not suitable for ordinary breakpoints.
985    Throw if any such commands is found.  */
986
987 static void
988 check_no_tracepoint_commands (struct command_line *commands)
989 {
990   struct command_line *c;
991
992   for (c = commands; c; c = c->next)
993     {
994       int i;
995
996       if (c->control_type == while_stepping_control)
997         error (_("The 'while-stepping' command can "
998                  "only be used for tracepoints"));
999
1000       for (i = 0; i < c->body_count; ++i)
1001         check_no_tracepoint_commands ((c->body_list)[i]);
1002
1003       /* Not that command parsing removes leading whitespace and comment
1004          lines and also empty lines.  So, we only need to check for
1005          command directly.  */
1006       if (strstr (c->line, "collect ") == c->line)
1007         error (_("The 'collect' command can only be used for tracepoints"));
1008
1009       if (strstr (c->line, "teval ") == c->line)
1010         error (_("The 'teval' command can only be used for tracepoints"));
1011     }
1012 }
1013
1014 /* Encapsulate tests for different types of tracepoints.  */
1015
1016 static int
1017 is_tracepoint_type (enum bptype type)
1018 {
1019   return (type == bp_tracepoint
1020           || type == bp_fast_tracepoint
1021           || type == bp_static_tracepoint);
1022 }
1023
1024 int
1025 is_tracepoint (const struct breakpoint *b)
1026 {
1027   return is_tracepoint_type (b->type);
1028 }
1029
1030 /* A helper function that validates that COMMANDS are valid for a
1031    breakpoint.  This function will throw an exception if a problem is
1032    found.  */
1033
1034 static void
1035 validate_commands_for_breakpoint (struct breakpoint *b,
1036                                   struct command_line *commands)
1037 {
1038   if (is_tracepoint (b))
1039     {
1040       /* We need to verify that each top-level element of commands is
1041          valid for tracepoints, that there's at most one
1042          while-stepping element, and that while-stepping's body has
1043          valid tracing commands excluding nested while-stepping.  */
1044       struct command_line *c;
1045       struct command_line *while_stepping = 0;
1046       for (c = commands; c; c = c->next)
1047         {
1048           if (c->control_type == while_stepping_control)
1049             {
1050               if (b->type == bp_fast_tracepoint)
1051                 error (_("The 'while-stepping' command "
1052                          "cannot be used for fast tracepoint"));
1053               else if (b->type == bp_static_tracepoint)
1054                 error (_("The 'while-stepping' command "
1055                          "cannot be used for static tracepoint"));
1056
1057               if (while_stepping)
1058                 error (_("The 'while-stepping' command "
1059                          "can be used only once"));
1060               else
1061                 while_stepping = c;
1062             }
1063         }
1064       if (while_stepping)
1065         {
1066           struct command_line *c2;
1067
1068           gdb_assert (while_stepping->body_count == 1);
1069           c2 = while_stepping->body_list[0];
1070           for (; c2; c2 = c2->next)
1071             {
1072               if (c2->control_type == while_stepping_control)
1073                 error (_("The 'while-stepping' command cannot be nested"));
1074             }
1075         }
1076     }
1077   else
1078     {
1079       check_no_tracepoint_commands (commands);
1080     }
1081 }
1082
1083 /* Return a vector of all the static tracepoints set at ADDR.  The
1084    caller is responsible for releasing the vector.  */
1085
1086 VEC(breakpoint_p) *
1087 static_tracepoints_here (CORE_ADDR addr)
1088 {
1089   struct breakpoint *b;
1090   VEC(breakpoint_p) *found = 0;
1091   struct bp_location *loc;
1092
1093   ALL_BREAKPOINTS (b)
1094     if (b->type == bp_static_tracepoint)
1095       {
1096         for (loc = b->loc; loc; loc = loc->next)
1097           if (loc->address == addr)
1098             VEC_safe_push(breakpoint_p, found, b);
1099       }
1100
1101   return found;
1102 }
1103
1104 /* Set the command list of B to COMMANDS.  If breakpoint is tracepoint,
1105    validate that only allowed commands are included.  */
1106
1107 void
1108 breakpoint_set_commands (struct breakpoint *b, 
1109                          struct command_line *commands)
1110 {
1111   validate_commands_for_breakpoint (b, commands);
1112
1113   decref_counted_command_line (&b->commands);
1114   b->commands = alloc_counted_command_line (commands);
1115   breakpoints_changed ();
1116   observer_notify_breakpoint_modified (b);
1117 }
1118
1119 /* Set the internal `silent' flag on the breakpoint.  Note that this
1120    is not the same as the "silent" that may appear in the breakpoint's
1121    commands.  */
1122
1123 void
1124 breakpoint_set_silent (struct breakpoint *b, int silent)
1125 {
1126   int old_silent = b->silent;
1127
1128   b->silent = silent;
1129   if (old_silent != silent)
1130     observer_notify_breakpoint_modified (b);
1131 }
1132
1133 /* Set the thread for this breakpoint.  If THREAD is -1, make the
1134    breakpoint work for any thread.  */
1135
1136 void
1137 breakpoint_set_thread (struct breakpoint *b, int thread)
1138 {
1139   int old_thread = b->thread;
1140
1141   b->thread = thread;
1142   if (old_thread != thread)
1143     observer_notify_breakpoint_modified (b);
1144 }
1145
1146 /* Set the task for this breakpoint.  If TASK is 0, make the
1147    breakpoint work for any task.  */
1148
1149 void
1150 breakpoint_set_task (struct breakpoint *b, int task)
1151 {
1152   int old_task = b->task;
1153
1154   b->task = task;
1155   if (old_task != task)
1156     observer_notify_breakpoint_modified (b);
1157 }
1158
1159 void
1160 check_tracepoint_command (char *line, void *closure)
1161 {
1162   struct breakpoint *b = closure;
1163
1164   validate_actionline (&line, b);
1165 }
1166
1167 /* A structure used to pass information through
1168    map_breakpoint_numbers.  */
1169
1170 struct commands_info
1171 {
1172   /* True if the command was typed at a tty.  */
1173   int from_tty;
1174
1175   /* The breakpoint range spec.  */
1176   char *arg;
1177
1178   /* Non-NULL if the body of the commands are being read from this
1179      already-parsed command.  */
1180   struct command_line *control;
1181
1182   /* The command lines read from the user, or NULL if they have not
1183      yet been read.  */
1184   struct counted_command_line *cmd;
1185 };
1186
1187 /* A callback for map_breakpoint_numbers that sets the commands for
1188    commands_command.  */
1189
1190 static void
1191 do_map_commands_command (struct breakpoint *b, void *data)
1192 {
1193   struct commands_info *info = data;
1194
1195   if (info->cmd == NULL)
1196     {
1197       struct command_line *l;
1198
1199       if (info->control != NULL)
1200         l = copy_command_lines (info->control->body_list[0]);
1201       else
1202         {
1203           struct cleanup *old_chain;
1204           char *str;
1205
1206           str = xstrprintf (_("Type commands for breakpoint(s) "
1207                               "%s, one per line."),
1208                             info->arg);
1209
1210           old_chain = make_cleanup (xfree, str);
1211
1212           l = read_command_lines (str,
1213                                   info->from_tty, 1,
1214                                   (is_tracepoint (b)
1215                                    ? check_tracepoint_command : 0),
1216                                   b);
1217
1218           do_cleanups (old_chain);
1219         }
1220
1221       info->cmd = alloc_counted_command_line (l);
1222     }
1223
1224   /* If a breakpoint was on the list more than once, we don't need to
1225      do anything.  */
1226   if (b->commands != info->cmd)
1227     {
1228       validate_commands_for_breakpoint (b, info->cmd->commands);
1229       incref_counted_command_line (info->cmd);
1230       decref_counted_command_line (&b->commands);
1231       b->commands = info->cmd;
1232       breakpoints_changed ();
1233       observer_notify_breakpoint_modified (b);
1234     }
1235 }
1236
1237 static void
1238 commands_command_1 (char *arg, int from_tty, 
1239                     struct command_line *control)
1240 {
1241   struct cleanup *cleanups;
1242   struct commands_info info;
1243
1244   info.from_tty = from_tty;
1245   info.control = control;
1246   info.cmd = NULL;
1247   /* If we read command lines from the user, then `info' will hold an
1248      extra reference to the commands that we must clean up.  */
1249   cleanups = make_cleanup_decref_counted_command_line (&info.cmd);
1250
1251   if (arg == NULL || !*arg)
1252     {
1253       if (breakpoint_count - prev_breakpoint_count > 1)
1254         arg = xstrprintf ("%d-%d", prev_breakpoint_count + 1, 
1255                           breakpoint_count);
1256       else if (breakpoint_count > 0)
1257         arg = xstrprintf ("%d", breakpoint_count);
1258       else
1259         {
1260           /* So that we don't try to free the incoming non-NULL
1261              argument in the cleanup below.  Mapping breakpoint
1262              numbers will fail in this case.  */
1263           arg = NULL;
1264         }
1265     }
1266   else
1267     /* The command loop has some static state, so we need to preserve
1268        our argument.  */
1269     arg = xstrdup (arg);
1270
1271   if (arg != NULL)
1272     make_cleanup (xfree, arg);
1273
1274   info.arg = arg;
1275
1276   map_breakpoint_numbers (arg, do_map_commands_command, &info);
1277
1278   if (info.cmd == NULL)
1279     error (_("No breakpoints specified."));
1280
1281   do_cleanups (cleanups);
1282 }
1283
1284 static void
1285 commands_command (char *arg, int from_tty)
1286 {
1287   commands_command_1 (arg, from_tty, NULL);
1288 }
1289
1290 /* Like commands_command, but instead of reading the commands from
1291    input stream, takes them from an already parsed command structure.
1292
1293    This is used by cli-script.c to DTRT with breakpoint commands
1294    that are part of if and while bodies.  */
1295 enum command_control_type
1296 commands_from_control_command (char *arg, struct command_line *cmd)
1297 {
1298   commands_command_1 (arg, 0, cmd);
1299   return simple_control;
1300 }
1301
1302 /* Return non-zero if BL->TARGET_INFO contains valid information.  */
1303
1304 static int
1305 bp_location_has_shadow (struct bp_location *bl)
1306 {
1307   if (bl->loc_type != bp_loc_software_breakpoint)
1308     return 0;
1309   if (!bl->inserted)
1310     return 0;
1311   if (bl->target_info.shadow_len == 0)
1312     /* BL isn't valid, or doesn't shadow memory.  */
1313     return 0;
1314   return 1;
1315 }
1316
1317 /* Update BUF, which is LEN bytes read from the target address MEMADDR,
1318    by replacing any memory breakpoints with their shadowed contents.
1319
1320    The range of shadowed area by each bp_location is:
1321      bl->address - bp_location_placed_address_before_address_max
1322      up to bl->address + bp_location_shadow_len_after_address_max
1323    The range we were requested to resolve shadows for is:
1324      memaddr ... memaddr + len
1325    Thus the safe cutoff boundaries for performance optimization are
1326      memaddr + len <= (bl->address
1327                        - bp_location_placed_address_before_address_max)
1328    and:
1329      bl->address + bp_location_shadow_len_after_address_max <= memaddr  */
1330
1331 void
1332 breakpoint_xfer_memory (gdb_byte *readbuf, gdb_byte *writebuf,
1333                         const gdb_byte *writebuf_org,
1334                         ULONGEST memaddr, LONGEST len)
1335 {
1336   /* Left boundary, right boundary and median element of our binary
1337      search.  */
1338   unsigned bc_l, bc_r, bc;
1339
1340   /* Find BC_L which is a leftmost element which may affect BUF
1341      content.  It is safe to report lower value but a failure to
1342      report higher one.  */
1343
1344   bc_l = 0;
1345   bc_r = bp_location_count;
1346   while (bc_l + 1 < bc_r)
1347     {
1348       struct bp_location *bl;
1349
1350       bc = (bc_l + bc_r) / 2;
1351       bl = bp_location[bc];
1352
1353       /* Check first BL->ADDRESS will not overflow due to the added
1354          constant.  Then advance the left boundary only if we are sure
1355          the BC element can in no way affect the BUF content (MEMADDR
1356          to MEMADDR + LEN range).
1357
1358          Use the BP_LOCATION_SHADOW_LEN_AFTER_ADDRESS_MAX safety
1359          offset so that we cannot miss a breakpoint with its shadow
1360          range tail still reaching MEMADDR.  */
1361
1362       if ((bl->address + bp_location_shadow_len_after_address_max
1363            >= bl->address)
1364           && (bl->address + bp_location_shadow_len_after_address_max
1365               <= memaddr))
1366         bc_l = bc;
1367       else
1368         bc_r = bc;
1369     }
1370
1371   /* Due to the binary search above, we need to make sure we pick the
1372      first location that's at BC_L's address.  E.g., if there are
1373      multiple locations at the same address, BC_L may end up pointing
1374      at a duplicate location, and miss the "master"/"inserted"
1375      location.  Say, given locations L1, L2 and L3 at addresses A and
1376      B:
1377
1378       L1@A, L2@A, L3@B, ...
1379
1380      BC_L could end up pointing at location L2, while the "master"
1381      location could be L1.  Since the `loc->inserted' flag is only set
1382      on "master" locations, we'd forget to restore the shadow of L1
1383      and L2.  */
1384   while (bc_l > 0
1385          && bp_location[bc_l]->address == bp_location[bc_l - 1]->address)
1386     bc_l--;
1387
1388   /* Now do full processing of the found relevant range of elements.  */
1389
1390   for (bc = bc_l; bc < bp_location_count; bc++)
1391   {
1392     struct bp_location *bl = bp_location[bc];
1393     CORE_ADDR bp_addr = 0;
1394     int bp_size = 0;
1395     int bptoffset = 0;
1396
1397     /* bp_location array has BL->OWNER always non-NULL.  */
1398     if (bl->owner->type == bp_none)
1399       warning (_("reading through apparently deleted breakpoint #%d?"),
1400                bl->owner->number);
1401
1402     /* Performance optimization: any further element can no longer affect BUF
1403        content.  */
1404
1405     if (bl->address >= bp_location_placed_address_before_address_max
1406         && memaddr + len <= (bl->address
1407                              - bp_location_placed_address_before_address_max))
1408       break;
1409
1410     if (!bp_location_has_shadow (bl))
1411       continue;
1412     if (!breakpoint_address_match (bl->target_info.placed_address_space, 0,
1413                                    current_program_space->aspace, 0))
1414       continue;
1415
1416     /* Addresses and length of the part of the breakpoint that
1417        we need to copy.  */
1418     bp_addr = bl->target_info.placed_address;
1419     bp_size = bl->target_info.shadow_len;
1420
1421     if (bp_addr + bp_size <= memaddr)
1422       /* The breakpoint is entirely before the chunk of memory we
1423          are reading.  */
1424       continue;
1425
1426     if (bp_addr >= memaddr + len)
1427       /* The breakpoint is entirely after the chunk of memory we are
1428          reading.  */
1429       continue;
1430
1431     /* Offset within shadow_contents.  */
1432     if (bp_addr < memaddr)
1433       {
1434         /* Only copy the second part of the breakpoint.  */
1435         bp_size -= memaddr - bp_addr;
1436         bptoffset = memaddr - bp_addr;
1437         bp_addr = memaddr;
1438       }
1439
1440     if (bp_addr + bp_size > memaddr + len)
1441       {
1442         /* Only copy the first part of the breakpoint.  */
1443         bp_size -= (bp_addr + bp_size) - (memaddr + len);
1444       }
1445
1446     if (readbuf != NULL)
1447       {
1448         /* Update the read buffer with this inserted breakpoint's
1449            shadow.  */
1450         memcpy (readbuf + bp_addr - memaddr,
1451                 bl->target_info.shadow_contents + bptoffset, bp_size);
1452       }
1453     else
1454       {
1455         struct gdbarch *gdbarch = bl->gdbarch;
1456         const unsigned char *bp;
1457         CORE_ADDR placed_address = bl->target_info.placed_address;
1458         unsigned placed_size = bl->target_info.placed_size;
1459
1460         /* Update the shadow with what we want to write to memory.  */
1461         memcpy (bl->target_info.shadow_contents + bptoffset,
1462                 writebuf_org + bp_addr - memaddr, bp_size);
1463
1464         /* Determine appropriate breakpoint contents and size for this
1465            address.  */
1466         bp = gdbarch_breakpoint_from_pc (gdbarch, &placed_address, &placed_size);
1467
1468         /* Update the final write buffer with this inserted
1469            breakpoint's INSN.  */
1470         memcpy (writebuf + bp_addr - memaddr, bp + bptoffset, bp_size);
1471       }
1472   }
1473 }
1474 \f
1475
1476 /* Return true if BPT is either a software breakpoint or a hardware
1477    breakpoint.  */
1478
1479 int
1480 is_breakpoint (const struct breakpoint *bpt)
1481 {
1482   return (bpt->type == bp_breakpoint
1483           || bpt->type == bp_hardware_breakpoint);
1484 }
1485
1486 /* Return true if BPT is of any hardware watchpoint kind.  */
1487
1488 static int
1489 is_hardware_watchpoint (const struct breakpoint *bpt)
1490 {
1491   return (bpt->type == bp_hardware_watchpoint
1492           || bpt->type == bp_read_watchpoint
1493           || bpt->type == bp_access_watchpoint);
1494 }
1495
1496 /* Return true if BPT is of any watchpoint kind, hardware or
1497    software.  */
1498
1499 int
1500 is_watchpoint (const struct breakpoint *bpt)
1501 {
1502   return (is_hardware_watchpoint (bpt)
1503           || bpt->type == bp_watchpoint);
1504 }
1505
1506 /* Returns true if the current thread and its running state are safe
1507    to evaluate or update watchpoint B.  Watchpoints on local
1508    expressions need to be evaluated in the context of the thread that
1509    was current when the watchpoint was created, and, that thread needs
1510    to be stopped to be able to select the correct frame context.
1511    Watchpoints on global expressions can be evaluated on any thread,
1512    and in any state.  It is presently left to the target allowing
1513    memory accesses when threads are running.  */
1514
1515 static int
1516 watchpoint_in_thread_scope (struct watchpoint *b)
1517 {
1518   return (b->base.pspace == current_program_space
1519           && (ptid_equal (b->watchpoint_thread, null_ptid)
1520               || (ptid_equal (inferior_ptid, b->watchpoint_thread)
1521                   && !is_executing (inferior_ptid))));
1522 }
1523
1524 /* Set watchpoint B to disp_del_at_next_stop, even including its possible
1525    associated bp_watchpoint_scope breakpoint.  */
1526
1527 static void
1528 watchpoint_del_at_next_stop (struct watchpoint *w)
1529 {
1530   struct breakpoint *b = &w->base;
1531
1532   if (b->related_breakpoint != b)
1533     {
1534       gdb_assert (b->related_breakpoint->type == bp_watchpoint_scope);
1535       gdb_assert (b->related_breakpoint->related_breakpoint == b);
1536       b->related_breakpoint->disposition = disp_del_at_next_stop;
1537       b->related_breakpoint->related_breakpoint = b->related_breakpoint;
1538       b->related_breakpoint = b;
1539     }
1540   b->disposition = disp_del_at_next_stop;
1541 }
1542
1543 /* Assuming that B is a watchpoint:
1544    - Reparse watchpoint expression, if REPARSE is non-zero
1545    - Evaluate expression and store the result in B->val
1546    - Evaluate the condition if there is one, and store the result
1547      in b->loc->cond.
1548    - Update the list of values that must be watched in B->loc.
1549
1550    If the watchpoint disposition is disp_del_at_next_stop, then do
1551    nothing.  If this is local watchpoint that is out of scope, delete
1552    it.
1553
1554    Even with `set breakpoint always-inserted on' the watchpoints are
1555    removed + inserted on each stop here.  Normal breakpoints must
1556    never be removed because they might be missed by a running thread
1557    when debugging in non-stop mode.  On the other hand, hardware
1558    watchpoints (is_hardware_watchpoint; processed here) are specific
1559    to each LWP since they are stored in each LWP's hardware debug
1560    registers.  Therefore, such LWP must be stopped first in order to
1561    be able to modify its hardware watchpoints.
1562
1563    Hardware watchpoints must be reset exactly once after being
1564    presented to the user.  It cannot be done sooner, because it would
1565    reset the data used to present the watchpoint hit to the user.  And
1566    it must not be done later because it could display the same single
1567    watchpoint hit during multiple GDB stops.  Note that the latter is
1568    relevant only to the hardware watchpoint types bp_read_watchpoint
1569    and bp_access_watchpoint.  False hit by bp_hardware_watchpoint is
1570    not user-visible - its hit is suppressed if the memory content has
1571    not changed.
1572
1573    The following constraints influence the location where we can reset
1574    hardware watchpoints:
1575
1576    * target_stopped_by_watchpoint and target_stopped_data_address are
1577      called several times when GDB stops.
1578
1579    [linux] 
1580    * Multiple hardware watchpoints can be hit at the same time,
1581      causing GDB to stop.  GDB only presents one hardware watchpoint
1582      hit at a time as the reason for stopping, and all the other hits
1583      are presented later, one after the other, each time the user
1584      requests the execution to be resumed.  Execution is not resumed
1585      for the threads still having pending hit event stored in
1586      LWP_INFO->STATUS.  While the watchpoint is already removed from
1587      the inferior on the first stop the thread hit event is kept being
1588      reported from its cached value by linux_nat_stopped_data_address
1589      until the real thread resume happens after the watchpoint gets
1590      presented and thus its LWP_INFO->STATUS gets reset.
1591
1592    Therefore the hardware watchpoint hit can get safely reset on the
1593    watchpoint removal from inferior.  */
1594
1595 static void
1596 update_watchpoint (struct watchpoint *b, int reparse)
1597 {
1598   int within_current_scope;
1599   struct frame_id saved_frame_id;
1600   int frame_saved;
1601
1602   /* If this is a local watchpoint, we only want to check if the
1603      watchpoint frame is in scope if the current thread is the thread
1604      that was used to create the watchpoint.  */
1605   if (!watchpoint_in_thread_scope (b))
1606     return;
1607
1608   if (b->base.disposition == disp_del_at_next_stop)
1609     return;
1610  
1611   frame_saved = 0;
1612
1613   /* Determine if the watchpoint is within scope.  */
1614   if (b->exp_valid_block == NULL)
1615     within_current_scope = 1;
1616   else
1617     {
1618       struct frame_info *fi = get_current_frame ();
1619       struct gdbarch *frame_arch = get_frame_arch (fi);
1620       CORE_ADDR frame_pc = get_frame_pc (fi);
1621
1622       /* If we're in a function epilogue, unwinding may not work
1623          properly, so do not attempt to recreate locations at this
1624          point.  See similar comments in watchpoint_check.  */
1625       if (gdbarch_in_function_epilogue_p (frame_arch, frame_pc))
1626         return;
1627
1628       /* Save the current frame's ID so we can restore it after
1629          evaluating the watchpoint expression on its own frame.  */
1630       /* FIXME drow/2003-09-09: It would be nice if evaluate_expression
1631          took a frame parameter, so that we didn't have to change the
1632          selected frame.  */
1633       frame_saved = 1;
1634       saved_frame_id = get_frame_id (get_selected_frame (NULL));
1635
1636       fi = frame_find_by_id (b->watchpoint_frame);
1637       within_current_scope = (fi != NULL);
1638       if (within_current_scope)
1639         select_frame (fi);
1640     }
1641
1642   /* We don't free locations.  They are stored in the bp_location array
1643      and update_global_location_list will eventually delete them and
1644      remove breakpoints if needed.  */
1645   b->base.loc = NULL;
1646
1647   if (within_current_scope && reparse)
1648     {
1649       char *s;
1650
1651       if (b->exp)
1652         {
1653           xfree (b->exp);
1654           b->exp = NULL;
1655         }
1656       s = b->exp_string_reparse ? b->exp_string_reparse : b->exp_string;
1657       b->exp = parse_exp_1 (&s, b->exp_valid_block, 0);
1658       /* If the meaning of expression itself changed, the old value is
1659          no longer relevant.  We don't want to report a watchpoint hit
1660          to the user when the old value and the new value may actually
1661          be completely different objects.  */
1662       value_free (b->val);
1663       b->val = NULL;
1664       b->val_valid = 0;
1665
1666       /* Note that unlike with breakpoints, the watchpoint's condition
1667          expression is stored in the breakpoint object, not in the
1668          locations (re)created below.  */
1669       if (b->base.cond_string != NULL)
1670         {
1671           if (b->cond_exp != NULL)
1672             {
1673               xfree (b->cond_exp);
1674               b->cond_exp = NULL;
1675             }
1676
1677           s = b->base.cond_string;
1678           b->cond_exp = parse_exp_1 (&s, b->cond_exp_valid_block, 0);
1679         }
1680     }
1681
1682   /* If we failed to parse the expression, for example because
1683      it refers to a global variable in a not-yet-loaded shared library,
1684      don't try to insert watchpoint.  We don't automatically delete
1685      such watchpoint, though, since failure to parse expression
1686      is different from out-of-scope watchpoint.  */
1687   if ( !target_has_execution)
1688     {
1689       /* Without execution, memory can't change.  No use to try and
1690          set watchpoint locations.  The watchpoint will be reset when
1691          the target gains execution, through breakpoint_re_set.  */
1692     }
1693   else if (within_current_scope && b->exp)
1694     {
1695       int pc = 0;
1696       struct value *val_chain, *v, *result, *next;
1697       struct program_space *frame_pspace;
1698
1699       fetch_subexp_value (b->exp, &pc, &v, &result, &val_chain);
1700
1701       /* Avoid setting b->val if it's already set.  The meaning of
1702          b->val is 'the last value' user saw, and we should update
1703          it only if we reported that last value to user.  As it
1704          happens, the code that reports it updates b->val directly.
1705          We don't keep track of the memory value for masked
1706          watchpoints.  */
1707       if (!b->val_valid && !is_masked_watchpoint (&b->base))
1708         {
1709           b->val = v;
1710           b->val_valid = 1;
1711         }
1712
1713       frame_pspace = get_frame_program_space (get_selected_frame (NULL));
1714
1715       /* Look at each value on the value chain.  */
1716       for (v = val_chain; v; v = value_next (v))
1717         {
1718           /* If it's a memory location, and GDB actually needed
1719              its contents to evaluate the expression, then we
1720              must watch it.  If the first value returned is
1721              still lazy, that means an error occurred reading it;
1722              watch it anyway in case it becomes readable.  */
1723           if (VALUE_LVAL (v) == lval_memory
1724               && (v == val_chain || ! value_lazy (v)))
1725             {
1726               struct type *vtype = check_typedef (value_type (v));
1727
1728               /* We only watch structs and arrays if user asked
1729                  for it explicitly, never if they just happen to
1730                  appear in the middle of some value chain.  */
1731               if (v == result
1732                   || (TYPE_CODE (vtype) != TYPE_CODE_STRUCT
1733                       && TYPE_CODE (vtype) != TYPE_CODE_ARRAY))
1734                 {
1735                   CORE_ADDR addr;
1736                   int len, type;
1737                   struct bp_location *loc, **tmp;
1738
1739                   addr = value_address (v);
1740                   len = TYPE_LENGTH (value_type (v));
1741                   type = hw_write;
1742                   if (b->base.type == bp_read_watchpoint)
1743                     type = hw_read;
1744                   else if (b->base.type == bp_access_watchpoint)
1745                     type = hw_access;
1746
1747                   loc = allocate_bp_location (&b->base);
1748                   for (tmp = &(b->base.loc); *tmp != NULL; tmp = &((*tmp)->next))
1749                     ;
1750                   *tmp = loc;
1751                   loc->gdbarch = get_type_arch (value_type (v));
1752
1753                   loc->pspace = frame_pspace;
1754                   loc->address = addr;
1755                   loc->length = len;
1756                   loc->watchpoint_type = type;
1757                 }
1758             }
1759         }
1760
1761       /* Change the type of breakpoint between hardware assisted or
1762          an ordinary watchpoint depending on the hardware support
1763          and free hardware slots.  REPARSE is set when the inferior
1764          is started.  */
1765       if (reparse)
1766         {
1767           int reg_cnt;
1768           enum bp_loc_type loc_type;
1769           struct bp_location *bl;
1770
1771           reg_cnt = can_use_hardware_watchpoint (val_chain);
1772
1773           if (reg_cnt)
1774             {
1775               int i, target_resources_ok, other_type_used;
1776               enum bptype type;
1777
1778               /* Use an exact watchpoint when there's only one memory region to be
1779                  watched, and only one debug register is needed to watch it.  */
1780               b->exact = target_exact_watchpoints && reg_cnt == 1;
1781
1782               /* We need to determine how many resources are already
1783                  used for all other hardware watchpoints plus this one
1784                  to see if we still have enough resources to also fit
1785                  this watchpoint in as well.  */
1786
1787               /* If this is a software watchpoint, we try to turn it
1788                  to a hardware one -- count resources as if B was of
1789                  hardware watchpoint type.  */
1790               type = b->base.type;
1791               if (type == bp_watchpoint)
1792                 type = bp_hardware_watchpoint;
1793
1794               /* This watchpoint may or may not have been placed on
1795                  the list yet at this point (it won't be in the list
1796                  if we're trying to create it for the first time,
1797                  through watch_command), so always account for it
1798                  manually.  */
1799
1800               /* Count resources used by all watchpoints except B.  */
1801               i = hw_watchpoint_used_count_others (&b->base, type, &other_type_used);
1802
1803               /* Add in the resources needed for B.  */
1804               i += hw_watchpoint_use_count (&b->base);
1805
1806               target_resources_ok
1807                 = target_can_use_hardware_watchpoint (type, i, other_type_used);
1808               if (target_resources_ok <= 0)
1809                 {
1810                   int sw_mode = b->base.ops->works_in_software_mode (&b->base);
1811
1812                   if (target_resources_ok == 0 && !sw_mode)
1813                     error (_("Target does not support this type of "
1814                              "hardware watchpoint."));
1815                   else if (target_resources_ok < 0 && !sw_mode)
1816                     error (_("There are not enough available hardware "
1817                              "resources for this watchpoint."));
1818
1819                   /* Downgrade to software watchpoint.  */
1820                   b->base.type = bp_watchpoint;
1821                 }
1822               else
1823                 {
1824                   /* If this was a software watchpoint, we've just
1825                      found we have enough resources to turn it to a
1826                      hardware watchpoint.  Otherwise, this is a
1827                      nop.  */
1828                   b->base.type = type;
1829                 }
1830             }
1831           else if (!b->base.ops->works_in_software_mode (&b->base))
1832             error (_("Expression cannot be implemented with "
1833                      "read/access watchpoint."));
1834           else
1835             b->base.type = bp_watchpoint;
1836
1837           loc_type = (b->base.type == bp_watchpoint? bp_loc_other
1838                       : bp_loc_hardware_watchpoint);
1839           for (bl = b->base.loc; bl; bl = bl->next)
1840             bl->loc_type = loc_type;
1841         }
1842
1843       for (v = val_chain; v; v = next)
1844         {
1845           next = value_next (v);
1846           if (v != b->val)
1847             value_free (v);
1848         }
1849
1850       /* If a software watchpoint is not watching any memory, then the
1851          above left it without any location set up.  But,
1852          bpstat_stop_status requires a location to be able to report
1853          stops, so make sure there's at least a dummy one.  */
1854       if (b->base.type == bp_watchpoint && b->base.loc == NULL)
1855         {
1856           struct breakpoint *base = &b->base;
1857           base->loc = allocate_bp_location (base);
1858           base->loc->pspace = frame_pspace;
1859           base->loc->address = -1;
1860           base->loc->length = -1;
1861           base->loc->watchpoint_type = -1;
1862         }
1863     }
1864   else if (!within_current_scope)
1865     {
1866       printf_filtered (_("\
1867 Watchpoint %d deleted because the program has left the block\n\
1868 in which its expression is valid.\n"),
1869                        b->base.number);
1870       watchpoint_del_at_next_stop (b);
1871     }
1872
1873   /* Restore the selected frame.  */
1874   if (frame_saved)
1875     select_frame (frame_find_by_id (saved_frame_id));
1876 }
1877
1878
1879 /* Returns 1 iff breakpoint location should be
1880    inserted in the inferior.  We don't differentiate the type of BL's owner
1881    (breakpoint vs. tracepoint), although insert_location in tracepoint's
1882    breakpoint_ops is not defined, because in insert_bp_location,
1883    tracepoint's insert_location will not be called.  */
1884 static int
1885 should_be_inserted (struct bp_location *bl)
1886 {
1887   if (bl->owner == NULL || !breakpoint_enabled (bl->owner))
1888     return 0;
1889
1890   if (bl->owner->disposition == disp_del_at_next_stop)
1891     return 0;
1892
1893   if (!bl->enabled || bl->shlib_disabled || bl->duplicate)
1894     return 0;
1895
1896   if (user_breakpoint_p (bl->owner) && bl->pspace->executing_startup)
1897     return 0;
1898
1899   /* This is set for example, when we're attached to the parent of a
1900      vfork, and have detached from the child.  The child is running
1901      free, and we expect it to do an exec or exit, at which point the
1902      OS makes the parent schedulable again (and the target reports
1903      that the vfork is done).  Until the child is done with the shared
1904      memory region, do not insert breakpoints in the parent, otherwise
1905      the child could still trip on the parent's breakpoints.  Since
1906      the parent is blocked anyway, it won't miss any breakpoint.  */
1907   if (bl->pspace->breakpoints_not_allowed)
1908     return 0;
1909
1910   return 1;
1911 }
1912
1913 /* Same as should_be_inserted but does the check assuming
1914    that the location is not duplicated.  */
1915
1916 static int
1917 unduplicated_should_be_inserted (struct bp_location *bl)
1918 {
1919   int result;
1920   const int save_duplicate = bl->duplicate;
1921
1922   bl->duplicate = 0;
1923   result = should_be_inserted (bl);
1924   bl->duplicate = save_duplicate;
1925   return result;
1926 }
1927
1928 /* Parses a conditional described by an expression COND into an
1929    agent expression bytecode suitable for evaluation
1930    by the bytecode interpreter.  Return NULL if there was
1931    any error during parsing.  */
1932
1933 static struct agent_expr *
1934 parse_cond_to_aexpr (CORE_ADDR scope, struct expression *cond)
1935 {
1936   struct agent_expr *aexpr = NULL;
1937   struct cleanup *old_chain = NULL;
1938   volatile struct gdb_exception ex;
1939
1940   if (!cond)
1941     return NULL;
1942
1943   /* We don't want to stop processing, so catch any errors
1944      that may show up.  */
1945   TRY_CATCH (ex, RETURN_MASK_ERROR)
1946     {
1947       aexpr = gen_eval_for_expr (scope, cond);
1948     }
1949
1950   if (ex.reason < 0)
1951     {
1952       /* If we got here, it means the condition could not be parsed to a valid
1953          bytecode expression and thus can't be evaluated on the target's side.
1954          It's no use iterating through the conditions.  */
1955       return NULL;
1956     }
1957
1958   /* We have a valid agent expression.  */
1959   return aexpr;
1960 }
1961
1962 /* Based on location BL, create a list of breakpoint conditions to be
1963    passed on to the target.  If we have duplicated locations with different
1964    conditions, we will add such conditions to the list.  The idea is that the
1965    target will evaluate the list of conditions and will only notify GDB when
1966    one of them is true.  */
1967
1968 static void
1969 build_target_condition_list (struct bp_location *bl)
1970 {
1971   struct bp_location **locp = NULL, **loc2p;
1972   int null_condition_or_parse_error = 0;
1973   int modified = bl->needs_update;
1974   struct bp_location *loc;
1975
1976   /* This is only meaningful if the target is
1977      evaluating conditions and if the user has
1978      opted for condition evaluation on the target's
1979      side.  */
1980   if (gdb_evaluates_breakpoint_condition_p ()
1981       || !target_supports_evaluation_of_breakpoint_conditions ())
1982     return;
1983
1984   /* Do a first pass to check for locations with no assigned
1985      conditions or conditions that fail to parse to a valid agent expression
1986      bytecode.  If any of these happen, then it's no use to send conditions
1987      to the target since this location will always trigger and generate a
1988      response back to GDB.  */
1989   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
1990     {
1991       loc = (*loc2p);
1992       if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
1993         {
1994           if (modified)
1995             {
1996               struct agent_expr *aexpr;
1997
1998               /* Re-parse the conditions since something changed.  In that
1999                  case we already freed the condition bytecodes (see
2000                  force_breakpoint_reinsertion).  We just
2001                  need to parse the condition to bytecodes again.  */
2002               aexpr = parse_cond_to_aexpr (bl->address, loc->cond);
2003               loc->cond_bytecode = aexpr;
2004
2005               /* Check if we managed to parse the conditional expression
2006                  correctly.  If not, we will not send this condition
2007                  to the target.  */
2008               if (aexpr)
2009                 continue;
2010             }
2011
2012           /* If we have a NULL bytecode expression, it means something
2013              went wrong or we have a null condition expression.  */
2014           if (!loc->cond_bytecode)
2015             {
2016               null_condition_or_parse_error = 1;
2017               break;
2018             }
2019         }
2020     }
2021
2022   /* If any of these happened, it means we will have to evaluate the conditions
2023      for the location's address on gdb's side.  It is no use keeping bytecodes
2024      for all the other duplicate locations, thus we free all of them here.
2025
2026      This is so we have a finer control over which locations' conditions are
2027      being evaluated by GDB or the remote stub.  */
2028   if (null_condition_or_parse_error)
2029     {
2030       ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2031         {
2032           loc = (*loc2p);
2033           if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2034             {
2035               /* Only go as far as the first NULL bytecode is
2036                  located.  */
2037               if (!loc->cond_bytecode)
2038                 return;
2039
2040               free_agent_expr (loc->cond_bytecode);
2041               loc->cond_bytecode = NULL;
2042             }
2043         }
2044     }
2045
2046   /* No NULL conditions or failed bytecode generation.  Build a condition list
2047      for this location's address.  */
2048   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2049     {
2050       loc = (*loc2p);
2051       if (loc->cond
2052           && is_breakpoint (loc->owner)
2053           && loc->pspace->num == bl->pspace->num
2054           && loc->owner->enable_state == bp_enabled
2055           && loc->enabled)
2056         /* Add the condition to the vector.  This will be used later to send the
2057            conditions to the target.  */
2058         VEC_safe_push (agent_expr_p, bl->target_info.conditions,
2059                        loc->cond_bytecode);
2060     }
2061
2062   return;
2063 }
2064
2065 /* Insert a low-level "breakpoint" of some type.  BL is the breakpoint
2066    location.  Any error messages are printed to TMP_ERROR_STREAM; and
2067    DISABLED_BREAKS, and HW_BREAKPOINT_ERROR are used to report problems.
2068    Returns 0 for success, 1 if the bp_location type is not supported or
2069    -1 for failure.
2070
2071    NOTE drow/2003-09-09: This routine could be broken down to an
2072    object-style method for each breakpoint or catchpoint type.  */
2073 static int
2074 insert_bp_location (struct bp_location *bl,
2075                     struct ui_file *tmp_error_stream,
2076                     int *disabled_breaks,
2077                     int *hw_breakpoint_error)
2078 {
2079   int val = 0;
2080
2081   if (!should_be_inserted (bl) || (bl->inserted && !bl->needs_update))
2082     return 0;
2083
2084   /* Initialize the target-specific information.  */
2085   memset (&bl->target_info, 0, sizeof (bl->target_info));
2086   bl->target_info.placed_address = bl->address;
2087   bl->target_info.placed_address_space = bl->pspace->aspace;
2088   bl->target_info.length = bl->length;
2089
2090   /* When working with target-side conditions, we must pass all the conditions
2091      for the same breakpoint address down to the target since GDB will not
2092      insert those locations.  With a list of breakpoint conditions, the target
2093      can decide when to stop and notify GDB.  */
2094
2095   if (is_breakpoint (bl->owner))
2096     {
2097       build_target_condition_list (bl);
2098       /* Reset the condition modification marker.  */
2099       bl->needs_update = 0;
2100     }
2101
2102   if (bl->loc_type == bp_loc_software_breakpoint
2103       || bl->loc_type == bp_loc_hardware_breakpoint)
2104     {
2105       if (bl->owner->type != bp_hardware_breakpoint)
2106         {
2107           /* If the explicitly specified breakpoint type
2108              is not hardware breakpoint, check the memory map to see
2109              if the breakpoint address is in read only memory or not.
2110
2111              Two important cases are:
2112              - location type is not hardware breakpoint, memory
2113              is readonly.  We change the type of the location to
2114              hardware breakpoint.
2115              - location type is hardware breakpoint, memory is
2116              read-write.  This means we've previously made the
2117              location hardware one, but then the memory map changed,
2118              so we undo.
2119              
2120              When breakpoints are removed, remove_breakpoints will use
2121              location types we've just set here, the only possible
2122              problem is that memory map has changed during running
2123              program, but it's not going to work anyway with current
2124              gdb.  */
2125           struct mem_region *mr 
2126             = lookup_mem_region (bl->target_info.placed_address);
2127           
2128           if (mr)
2129             {
2130               if (automatic_hardware_breakpoints)
2131                 {
2132                   enum bp_loc_type new_type;
2133                   
2134                   if (mr->attrib.mode != MEM_RW)
2135                     new_type = bp_loc_hardware_breakpoint;
2136                   else 
2137                     new_type = bp_loc_software_breakpoint;
2138                   
2139                   if (new_type != bl->loc_type)
2140                     {
2141                       static int said = 0;
2142
2143                       bl->loc_type = new_type;
2144                       if (!said)
2145                         {
2146                           fprintf_filtered (gdb_stdout,
2147                                             _("Note: automatically using "
2148                                               "hardware breakpoints for "
2149                                               "read-only addresses.\n"));
2150                           said = 1;
2151                         }
2152                     }
2153                 }
2154               else if (bl->loc_type == bp_loc_software_breakpoint
2155                        && mr->attrib.mode != MEM_RW)        
2156                 warning (_("cannot set software breakpoint "
2157                            "at readonly address %s"),
2158                          paddress (bl->gdbarch, bl->address));
2159             }
2160         }
2161         
2162       /* First check to see if we have to handle an overlay.  */
2163       if (overlay_debugging == ovly_off
2164           || bl->section == NULL
2165           || !(section_is_overlay (bl->section)))
2166         {
2167           /* No overlay handling: just set the breakpoint.  */
2168
2169           val = bl->owner->ops->insert_location (bl);
2170         }
2171       else
2172         {
2173           /* This breakpoint is in an overlay section.
2174              Shall we set a breakpoint at the LMA?  */
2175           if (!overlay_events_enabled)
2176             {
2177               /* Yes -- overlay event support is not active, 
2178                  so we must try to set a breakpoint at the LMA.
2179                  This will not work for a hardware breakpoint.  */
2180               if (bl->loc_type == bp_loc_hardware_breakpoint)
2181                 warning (_("hardware breakpoint %d not supported in overlay!"),
2182                          bl->owner->number);
2183               else
2184                 {
2185                   CORE_ADDR addr = overlay_unmapped_address (bl->address,
2186                                                              bl->section);
2187                   /* Set a software (trap) breakpoint at the LMA.  */
2188                   bl->overlay_target_info = bl->target_info;
2189                   bl->overlay_target_info.placed_address = addr;
2190                   val = target_insert_breakpoint (bl->gdbarch,
2191                                                   &bl->overlay_target_info);
2192                   if (val != 0)
2193                     fprintf_unfiltered (tmp_error_stream,
2194                                         "Overlay breakpoint %d "
2195                                         "failed: in ROM?\n",
2196                                         bl->owner->number);
2197                 }
2198             }
2199           /* Shall we set a breakpoint at the VMA? */
2200           if (section_is_mapped (bl->section))
2201             {
2202               /* Yes.  This overlay section is mapped into memory.  */
2203               val = bl->owner->ops->insert_location (bl);
2204             }
2205           else
2206             {
2207               /* No.  This breakpoint will not be inserted.  
2208                  No error, but do not mark the bp as 'inserted'.  */
2209               return 0;
2210             }
2211         }
2212
2213       if (val)
2214         {
2215           /* Can't set the breakpoint.  */
2216           if (solib_name_from_address (bl->pspace, bl->address))
2217             {
2218               /* See also: disable_breakpoints_in_shlibs.  */
2219               val = 0;
2220               bl->shlib_disabled = 1;
2221               observer_notify_breakpoint_modified (bl->owner);
2222               if (!*disabled_breaks)
2223                 {
2224                   fprintf_unfiltered (tmp_error_stream, 
2225                                       "Cannot insert breakpoint %d.\n", 
2226                                       bl->owner->number);
2227                   fprintf_unfiltered (tmp_error_stream, 
2228                                       "Temporarily disabling shared "
2229                                       "library breakpoints:\n");
2230                 }
2231               *disabled_breaks = 1;
2232               fprintf_unfiltered (tmp_error_stream,
2233                                   "breakpoint #%d\n", bl->owner->number);
2234             }
2235           else
2236             {
2237               if (bl->loc_type == bp_loc_hardware_breakpoint)
2238                 {
2239                   *hw_breakpoint_error = 1;
2240                   fprintf_unfiltered (tmp_error_stream,
2241                                       "Cannot insert hardware "
2242                                       "breakpoint %d.\n",
2243                                       bl->owner->number);
2244                 }
2245               else
2246                 {
2247                   fprintf_unfiltered (tmp_error_stream, 
2248                                       "Cannot insert breakpoint %d.\n", 
2249                                       bl->owner->number);
2250                   fprintf_filtered (tmp_error_stream, 
2251                                     "Error accessing memory address ");
2252                   fputs_filtered (paddress (bl->gdbarch, bl->address),
2253                                   tmp_error_stream);
2254                   fprintf_filtered (tmp_error_stream, ": %s.\n",
2255                                     safe_strerror (val));
2256                 }
2257
2258             }
2259         }
2260       else
2261         bl->inserted = 1;
2262
2263       return val;
2264     }
2265
2266   else if (bl->loc_type == bp_loc_hardware_watchpoint
2267            /* NOTE drow/2003-09-08: This state only exists for removing
2268               watchpoints.  It's not clear that it's necessary...  */
2269            && bl->owner->disposition != disp_del_at_next_stop)
2270     {
2271       gdb_assert (bl->owner->ops != NULL
2272                   && bl->owner->ops->insert_location != NULL);
2273
2274       val = bl->owner->ops->insert_location (bl);
2275
2276       /* If trying to set a read-watchpoint, and it turns out it's not
2277          supported, try emulating one with an access watchpoint.  */
2278       if (val == 1 && bl->watchpoint_type == hw_read)
2279         {
2280           struct bp_location *loc, **loc_temp;
2281
2282           /* But don't try to insert it, if there's already another
2283              hw_access location that would be considered a duplicate
2284              of this one.  */
2285           ALL_BP_LOCATIONS (loc, loc_temp)
2286             if (loc != bl
2287                 && loc->watchpoint_type == hw_access
2288                 && watchpoint_locations_match (bl, loc))
2289               {
2290                 bl->duplicate = 1;
2291                 bl->inserted = 1;
2292                 bl->target_info = loc->target_info;
2293                 bl->watchpoint_type = hw_access;
2294                 val = 0;
2295                 break;
2296               }
2297
2298           if (val == 1)
2299             {
2300               bl->watchpoint_type = hw_access;
2301               val = bl->owner->ops->insert_location (bl);
2302
2303               if (val)
2304                 /* Back to the original value.  */
2305                 bl->watchpoint_type = hw_read;
2306             }
2307         }
2308
2309       bl->inserted = (val == 0);
2310     }
2311
2312   else if (bl->owner->type == bp_catchpoint)
2313     {
2314       gdb_assert (bl->owner->ops != NULL
2315                   && bl->owner->ops->insert_location != NULL);
2316
2317       val = bl->owner->ops->insert_location (bl);
2318       if (val)
2319         {
2320           bl->owner->enable_state = bp_disabled;
2321
2322           if (val == 1)
2323             warning (_("\
2324 Error inserting catchpoint %d: Your system does not support this type\n\
2325 of catchpoint."), bl->owner->number);
2326           else
2327             warning (_("Error inserting catchpoint %d."), bl->owner->number);
2328         }
2329
2330       bl->inserted = (val == 0);
2331
2332       /* We've already printed an error message if there was a problem
2333          inserting this catchpoint, and we've disabled the catchpoint,
2334          so just return success.  */
2335       return 0;
2336     }
2337
2338   return 0;
2339 }
2340
2341 /* This function is called when program space PSPACE is about to be
2342    deleted.  It takes care of updating breakpoints to not reference
2343    PSPACE anymore.  */
2344
2345 void
2346 breakpoint_program_space_exit (struct program_space *pspace)
2347 {
2348   struct breakpoint *b, *b_temp;
2349   struct bp_location *loc, **loc_temp;
2350
2351   /* Remove any breakpoint that was set through this program space.  */
2352   ALL_BREAKPOINTS_SAFE (b, b_temp)
2353     {
2354       if (b->pspace == pspace)
2355         delete_breakpoint (b);
2356     }
2357
2358   /* Breakpoints set through other program spaces could have locations
2359      bound to PSPACE as well.  Remove those.  */
2360   ALL_BP_LOCATIONS (loc, loc_temp)
2361     {
2362       struct bp_location *tmp;
2363
2364       if (loc->pspace == pspace)
2365         {
2366           /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
2367           if (loc->owner->loc == loc)
2368             loc->owner->loc = loc->next;
2369           else
2370             for (tmp = loc->owner->loc; tmp->next != NULL; tmp = tmp->next)
2371               if (tmp->next == loc)
2372                 {
2373                   tmp->next = loc->next;
2374                   break;
2375                 }
2376         }
2377     }
2378
2379   /* Now update the global location list to permanently delete the
2380      removed locations above.  */
2381   update_global_location_list (0);
2382 }
2383
2384 /* Make sure all breakpoints are inserted in inferior.
2385    Throws exception on any error.
2386    A breakpoint that is already inserted won't be inserted
2387    again, so calling this function twice is safe.  */
2388 void
2389 insert_breakpoints (void)
2390 {
2391   struct breakpoint *bpt;
2392
2393   ALL_BREAKPOINTS (bpt)
2394     if (is_hardware_watchpoint (bpt))
2395       {
2396         struct watchpoint *w = (struct watchpoint *) bpt;
2397
2398         update_watchpoint (w, 0 /* don't reparse.  */);
2399       }
2400
2401   update_global_location_list (1);
2402
2403   /* update_global_location_list does not insert breakpoints when
2404      always_inserted_mode is not enabled.  Explicitly insert them
2405      now.  */
2406   if (!breakpoints_always_inserted_mode ())
2407     insert_breakpoint_locations ();
2408 }
2409
2410 /* This is used when we need to synch breakpoint conditions between GDB and the
2411    target.  It is the case with deleting and disabling of breakpoints when using
2412    always-inserted mode.  */
2413
2414 static void
2415 update_inserted_breakpoint_locations (void)
2416 {
2417   struct bp_location *bl, **blp_tmp;
2418   int error_flag = 0;
2419   int val = 0;
2420   int disabled_breaks = 0;
2421   int hw_breakpoint_error = 0;
2422
2423   struct ui_file *tmp_error_stream = mem_fileopen ();
2424   struct cleanup *cleanups = make_cleanup_ui_file_delete (tmp_error_stream);
2425
2426   /* Explicitly mark the warning -- this will only be printed if
2427      there was an error.  */
2428   fprintf_unfiltered (tmp_error_stream, "Warning:\n");
2429
2430   save_current_space_and_thread ();
2431
2432   ALL_BP_LOCATIONS (bl, blp_tmp)
2433     {
2434       /* We only want to update software breakpoints and hardware
2435          breakpoints.  */
2436       if (!is_breakpoint (bl->owner))
2437         continue;
2438
2439       /* We only want to update locations that are already inserted
2440          and need updating.  This is to avoid unwanted insertion during
2441          deletion of breakpoints.  */
2442       if (!bl->inserted || (bl->inserted && !bl->needs_update))
2443         continue;
2444
2445       switch_to_program_space_and_thread (bl->pspace);
2446
2447       /* For targets that support global breakpoints, there's no need
2448          to select an inferior to insert breakpoint to.  In fact, even
2449          if we aren't attached to any process yet, we should still
2450          insert breakpoints.  */
2451       if (!gdbarch_has_global_breakpoints (target_gdbarch)
2452           && ptid_equal (inferior_ptid, null_ptid))
2453         continue;
2454
2455       val = insert_bp_location (bl, tmp_error_stream, &disabled_breaks,
2456                                     &hw_breakpoint_error);
2457       if (val)
2458         error_flag = val;
2459     }
2460
2461   if (error_flag)
2462     {
2463       target_terminal_ours_for_output ();
2464       error_stream (tmp_error_stream);
2465     }
2466
2467   do_cleanups (cleanups);
2468 }
2469
2470 /* Used when starting or continuing the program.  */
2471
2472 static void
2473 insert_breakpoint_locations (void)
2474 {
2475   struct breakpoint *bpt;
2476   struct bp_location *bl, **blp_tmp;
2477   int error_flag = 0;
2478   int val = 0;
2479   int disabled_breaks = 0;
2480   int hw_breakpoint_error = 0;
2481
2482   struct ui_file *tmp_error_stream = mem_fileopen ();
2483   struct cleanup *cleanups = make_cleanup_ui_file_delete (tmp_error_stream);
2484   
2485   /* Explicitly mark the warning -- this will only be printed if
2486      there was an error.  */
2487   fprintf_unfiltered (tmp_error_stream, "Warning:\n");
2488
2489   save_current_space_and_thread ();
2490
2491   ALL_BP_LOCATIONS (bl, blp_tmp)
2492     {
2493       if (!should_be_inserted (bl) || (bl->inserted && !bl->needs_update))
2494         continue;
2495
2496       /* There is no point inserting thread-specific breakpoints if
2497          the thread no longer exists.  ALL_BP_LOCATIONS bp_location
2498          has BL->OWNER always non-NULL.  */
2499       if (bl->owner->thread != -1
2500           && !valid_thread_id (bl->owner->thread))
2501         continue;
2502
2503       switch_to_program_space_and_thread (bl->pspace);
2504
2505       /* For targets that support global breakpoints, there's no need
2506          to select an inferior to insert breakpoint to.  In fact, even
2507          if we aren't attached to any process yet, we should still
2508          insert breakpoints.  */
2509       if (!gdbarch_has_global_breakpoints (target_gdbarch)
2510           && ptid_equal (inferior_ptid, null_ptid))
2511         continue;
2512
2513       val = insert_bp_location (bl, tmp_error_stream, &disabled_breaks,
2514                                     &hw_breakpoint_error);
2515       if (val)
2516         error_flag = val;
2517     }
2518
2519   /* If we failed to insert all locations of a watchpoint, remove
2520      them, as half-inserted watchpoint is of limited use.  */
2521   ALL_BREAKPOINTS (bpt)  
2522     {
2523       int some_failed = 0;
2524       struct bp_location *loc;
2525
2526       if (!is_hardware_watchpoint (bpt))
2527         continue;
2528
2529       if (!breakpoint_enabled (bpt))
2530         continue;
2531
2532       if (bpt->disposition == disp_del_at_next_stop)
2533         continue;
2534       
2535       for (loc = bpt->loc; loc; loc = loc->next)
2536         if (!loc->inserted && should_be_inserted (loc))
2537           {
2538             some_failed = 1;
2539             break;
2540           }
2541       if (some_failed)
2542         {
2543           for (loc = bpt->loc; loc; loc = loc->next)
2544             if (loc->inserted)
2545               remove_breakpoint (loc, mark_uninserted);
2546
2547           hw_breakpoint_error = 1;
2548           fprintf_unfiltered (tmp_error_stream,
2549                               "Could not insert hardware watchpoint %d.\n", 
2550                               bpt->number);
2551           error_flag = -1;
2552         }
2553     }
2554
2555   if (error_flag)
2556     {
2557       /* If a hardware breakpoint or watchpoint was inserted, add a
2558          message about possibly exhausted resources.  */
2559       if (hw_breakpoint_error)
2560         {
2561           fprintf_unfiltered (tmp_error_stream, 
2562                               "Could not insert hardware breakpoints:\n\
2563 You may have requested too many hardware breakpoints/watchpoints.\n");
2564         }
2565       target_terminal_ours_for_output ();
2566       error_stream (tmp_error_stream);
2567     }
2568
2569   do_cleanups (cleanups);
2570 }
2571
2572 /* Used when the program stops.
2573    Returns zero if successful, or non-zero if there was a problem
2574    removing a breakpoint location.  */
2575
2576 int
2577 remove_breakpoints (void)
2578 {
2579   struct bp_location *bl, **blp_tmp;
2580   int val = 0;
2581
2582   ALL_BP_LOCATIONS (bl, blp_tmp)
2583   {
2584     if (bl->inserted && !is_tracepoint (bl->owner))
2585       val |= remove_breakpoint (bl, mark_uninserted);
2586   }
2587   return val;
2588 }
2589
2590 /* Remove breakpoints of process PID.  */
2591
2592 int
2593 remove_breakpoints_pid (int pid)
2594 {
2595   struct bp_location *bl, **blp_tmp;
2596   int val;
2597   struct inferior *inf = find_inferior_pid (pid);
2598
2599   ALL_BP_LOCATIONS (bl, blp_tmp)
2600   {
2601     if (bl->pspace != inf->pspace)
2602       continue;
2603
2604     if (bl->inserted)
2605       {
2606         val = remove_breakpoint (bl, mark_uninserted);
2607         if (val != 0)
2608           return val;
2609       }
2610   }
2611   return 0;
2612 }
2613
2614 int
2615 reattach_breakpoints (int pid)
2616 {
2617   struct cleanup *old_chain;
2618   struct bp_location *bl, **blp_tmp;
2619   int val;
2620   struct ui_file *tmp_error_stream;
2621   int dummy1 = 0, dummy2 = 0;
2622   struct inferior *inf;
2623   struct thread_info *tp;
2624
2625   tp = any_live_thread_of_process (pid);
2626   if (tp == NULL)
2627     return 1;
2628
2629   inf = find_inferior_pid (pid);
2630   old_chain = save_inferior_ptid ();
2631
2632   inferior_ptid = tp->ptid;
2633
2634   tmp_error_stream = mem_fileopen ();
2635   make_cleanup_ui_file_delete (tmp_error_stream);
2636
2637   ALL_BP_LOCATIONS (bl, blp_tmp)
2638   {
2639     if (bl->pspace != inf->pspace)
2640       continue;
2641
2642     if (bl->inserted)
2643       {
2644         bl->inserted = 0;
2645         val = insert_bp_location (bl, tmp_error_stream, &dummy1, &dummy2);
2646         if (val != 0)
2647           {
2648             do_cleanups (old_chain);
2649             return val;
2650           }
2651       }
2652   }
2653   do_cleanups (old_chain);
2654   return 0;
2655 }
2656
2657 static int internal_breakpoint_number = -1;
2658
2659 /* Set the breakpoint number of B, depending on the value of INTERNAL.
2660    If INTERNAL is non-zero, the breakpoint number will be populated
2661    from internal_breakpoint_number and that variable decremented.
2662    Otherwise the breakpoint number will be populated from
2663    breakpoint_count and that value incremented.  Internal breakpoints
2664    do not set the internal var bpnum.  */
2665 static void
2666 set_breakpoint_number (int internal, struct breakpoint *b)
2667 {
2668   if (internal)
2669     b->number = internal_breakpoint_number--;
2670   else
2671     {
2672       set_breakpoint_count (breakpoint_count + 1);
2673       b->number = breakpoint_count;
2674     }
2675 }
2676
2677 static struct breakpoint *
2678 create_internal_breakpoint (struct gdbarch *gdbarch,
2679                             CORE_ADDR address, enum bptype type,
2680                             const struct breakpoint_ops *ops)
2681 {
2682   struct symtab_and_line sal;
2683   struct breakpoint *b;
2684
2685   init_sal (&sal);              /* Initialize to zeroes.  */
2686
2687   sal.pc = address;
2688   sal.section = find_pc_overlay (sal.pc);
2689   sal.pspace = current_program_space;
2690
2691   b = set_raw_breakpoint (gdbarch, sal, type, ops);
2692   b->number = internal_breakpoint_number--;
2693   b->disposition = disp_donttouch;
2694
2695   return b;
2696 }
2697
2698 static const char *const longjmp_names[] =
2699   {
2700     "longjmp", "_longjmp", "siglongjmp", "_siglongjmp"
2701   };
2702 #define NUM_LONGJMP_NAMES ARRAY_SIZE(longjmp_names)
2703
2704 /* Per-objfile data private to breakpoint.c.  */
2705 struct breakpoint_objfile_data
2706 {
2707   /* Minimal symbol for "_ovly_debug_event" (if any).  */
2708   struct minimal_symbol *overlay_msym;
2709
2710   /* Minimal symbol(s) for "longjmp", "siglongjmp", etc. (if any).  */
2711   struct minimal_symbol *longjmp_msym[NUM_LONGJMP_NAMES];
2712
2713   /* Minimal symbol for "std::terminate()" (if any).  */
2714   struct minimal_symbol *terminate_msym;
2715
2716   /* Minimal symbol for "_Unwind_DebugHook" (if any).  */
2717   struct minimal_symbol *exception_msym;
2718 };
2719
2720 static const struct objfile_data *breakpoint_objfile_key;
2721
2722 /* Minimal symbol not found sentinel.  */
2723 static struct minimal_symbol msym_not_found;
2724
2725 /* Returns TRUE if MSYM point to the "not found" sentinel.  */
2726
2727 static int
2728 msym_not_found_p (const struct minimal_symbol *msym)
2729 {
2730   return msym == &msym_not_found;
2731 }
2732
2733 /* Return per-objfile data needed by breakpoint.c.
2734    Allocate the data if necessary.  */
2735
2736 static struct breakpoint_objfile_data *
2737 get_breakpoint_objfile_data (struct objfile *objfile)
2738 {
2739   struct breakpoint_objfile_data *bp_objfile_data;
2740
2741   bp_objfile_data = objfile_data (objfile, breakpoint_objfile_key);
2742   if (bp_objfile_data == NULL)
2743     {
2744       bp_objfile_data = obstack_alloc (&objfile->objfile_obstack,
2745                                        sizeof (*bp_objfile_data));
2746
2747       memset (bp_objfile_data, 0, sizeof (*bp_objfile_data));
2748       set_objfile_data (objfile, breakpoint_objfile_key, bp_objfile_data);
2749     }
2750   return bp_objfile_data;
2751 }
2752
2753 static void
2754 create_overlay_event_breakpoint (void)
2755 {
2756   struct objfile *objfile;
2757   const char *const func_name = "_ovly_debug_event";
2758
2759   ALL_OBJFILES (objfile)
2760     {
2761       struct breakpoint *b;
2762       struct breakpoint_objfile_data *bp_objfile_data;
2763       CORE_ADDR addr;
2764
2765       bp_objfile_data = get_breakpoint_objfile_data (objfile);
2766
2767       if (msym_not_found_p (bp_objfile_data->overlay_msym))
2768         continue;
2769
2770       if (bp_objfile_data->overlay_msym == NULL)
2771         {
2772           struct minimal_symbol *m;
2773
2774           m = lookup_minimal_symbol_text (func_name, objfile);
2775           if (m == NULL)
2776             {
2777               /* Avoid future lookups in this objfile.  */
2778               bp_objfile_data->overlay_msym = &msym_not_found;
2779               continue;
2780             }
2781           bp_objfile_data->overlay_msym = m;
2782         }
2783
2784       addr = SYMBOL_VALUE_ADDRESS (bp_objfile_data->overlay_msym);
2785       b = create_internal_breakpoint (get_objfile_arch (objfile), addr,
2786                                       bp_overlay_event,
2787                                       &internal_breakpoint_ops);
2788       b->addr_string = xstrdup (func_name);
2789
2790       if (overlay_debugging == ovly_auto)
2791         {
2792           b->enable_state = bp_enabled;
2793           overlay_events_enabled = 1;
2794         }
2795       else
2796        {
2797          b->enable_state = bp_disabled;
2798          overlay_events_enabled = 0;
2799        }
2800     }
2801   update_global_location_list (1);
2802 }
2803
2804 static void
2805 create_longjmp_master_breakpoint (void)
2806 {
2807   struct program_space *pspace;
2808   struct cleanup *old_chain;
2809
2810   old_chain = save_current_program_space ();
2811
2812   ALL_PSPACES (pspace)
2813   {
2814     struct objfile *objfile;
2815
2816     set_current_program_space (pspace);
2817
2818     ALL_OBJFILES (objfile)
2819     {
2820       int i;
2821       struct gdbarch *gdbarch;
2822       struct breakpoint_objfile_data *bp_objfile_data;
2823
2824       gdbarch = get_objfile_arch (objfile);
2825       if (!gdbarch_get_longjmp_target_p (gdbarch))
2826         continue;
2827
2828       bp_objfile_data = get_breakpoint_objfile_data (objfile);
2829
2830       for (i = 0; i < NUM_LONGJMP_NAMES; i++)
2831         {
2832           struct breakpoint *b;
2833           const char *func_name;
2834           CORE_ADDR addr;
2835
2836           if (msym_not_found_p (bp_objfile_data->longjmp_msym[i]))
2837             continue;
2838
2839           func_name = longjmp_names[i];
2840           if (bp_objfile_data->longjmp_msym[i] == NULL)
2841             {
2842               struct minimal_symbol *m;
2843
2844               m = lookup_minimal_symbol_text (func_name, objfile);
2845               if (m == NULL)
2846                 {
2847                   /* Prevent future lookups in this objfile.  */
2848                   bp_objfile_data->longjmp_msym[i] = &msym_not_found;
2849                   continue;
2850                 }
2851               bp_objfile_data->longjmp_msym[i] = m;
2852             }
2853
2854           addr = SYMBOL_VALUE_ADDRESS (bp_objfile_data->longjmp_msym[i]);
2855           b = create_internal_breakpoint (gdbarch, addr, bp_longjmp_master,
2856                                           &internal_breakpoint_ops);
2857           b->addr_string = xstrdup (func_name);
2858           b->enable_state = bp_disabled;
2859         }
2860     }
2861   }
2862   update_global_location_list (1);
2863
2864   do_cleanups (old_chain);
2865 }
2866
2867 /* Create a master std::terminate breakpoint.  */
2868 static void
2869 create_std_terminate_master_breakpoint (void)
2870 {
2871   struct program_space *pspace;
2872   struct cleanup *old_chain;
2873   const char *const func_name = "std::terminate()";
2874
2875   old_chain = save_current_program_space ();
2876
2877   ALL_PSPACES (pspace)
2878   {
2879     struct objfile *objfile;
2880     CORE_ADDR addr;
2881
2882     set_current_program_space (pspace);
2883
2884     ALL_OBJFILES (objfile)
2885     {
2886       struct breakpoint *b;
2887       struct breakpoint_objfile_data *bp_objfile_data;
2888
2889       bp_objfile_data = get_breakpoint_objfile_data (objfile);
2890
2891       if (msym_not_found_p (bp_objfile_data->terminate_msym))
2892         continue;
2893
2894       if (bp_objfile_data->terminate_msym == NULL)
2895         {
2896           struct minimal_symbol *m;
2897
2898           m = lookup_minimal_symbol (func_name, NULL, objfile);
2899           if (m == NULL || (MSYMBOL_TYPE (m) != mst_text
2900                             && MSYMBOL_TYPE (m) != mst_file_text))
2901             {
2902               /* Prevent future lookups in this objfile.  */
2903               bp_objfile_data->terminate_msym = &msym_not_found;
2904               continue;
2905             }
2906           bp_objfile_data->terminate_msym = m;
2907         }
2908
2909       addr = SYMBOL_VALUE_ADDRESS (bp_objfile_data->terminate_msym);
2910       b = create_internal_breakpoint (get_objfile_arch (objfile), addr,
2911                                       bp_std_terminate_master,
2912                                       &internal_breakpoint_ops);
2913       b->addr_string = xstrdup (func_name);
2914       b->enable_state = bp_disabled;
2915     }
2916   }
2917
2918   update_global_location_list (1);
2919
2920   do_cleanups (old_chain);
2921 }
2922
2923 /* Install a master breakpoint on the unwinder's debug hook.  */
2924
2925 void
2926 create_exception_master_breakpoint (void)
2927 {
2928   struct objfile *objfile;
2929   const char *const func_name = "_Unwind_DebugHook";
2930
2931   ALL_OBJFILES (objfile)
2932     {
2933       struct breakpoint *b;
2934       struct gdbarch *gdbarch;
2935       struct breakpoint_objfile_data *bp_objfile_data;
2936       CORE_ADDR addr;
2937
2938       bp_objfile_data = get_breakpoint_objfile_data (objfile);
2939
2940       if (msym_not_found_p (bp_objfile_data->exception_msym))
2941         continue;
2942
2943       gdbarch = get_objfile_arch (objfile);
2944
2945       if (bp_objfile_data->exception_msym == NULL)
2946         {
2947           struct minimal_symbol *debug_hook;
2948
2949           debug_hook = lookup_minimal_symbol (func_name, NULL, objfile);
2950           if (debug_hook == NULL)
2951             {
2952               bp_objfile_data->exception_msym = &msym_not_found;
2953               continue;
2954             }
2955
2956           bp_objfile_data->exception_msym = debug_hook;
2957         }
2958
2959       addr = SYMBOL_VALUE_ADDRESS (bp_objfile_data->exception_msym);
2960       addr = gdbarch_convert_from_func_ptr_addr (gdbarch, addr,
2961                                                  &current_target);
2962       b = create_internal_breakpoint (gdbarch, addr, bp_exception_master,
2963                                       &internal_breakpoint_ops);
2964       b->addr_string = xstrdup (func_name);
2965       b->enable_state = bp_disabled;
2966     }
2967
2968   update_global_location_list (1);
2969 }
2970
2971 void
2972 update_breakpoints_after_exec (void)
2973 {
2974   struct breakpoint *b, *b_tmp;
2975   struct bp_location *bploc, **bplocp_tmp;
2976
2977   /* We're about to delete breakpoints from GDB's lists.  If the
2978      INSERTED flag is true, GDB will try to lift the breakpoints by
2979      writing the breakpoints' "shadow contents" back into memory.  The
2980      "shadow contents" are NOT valid after an exec, so GDB should not
2981      do that.  Instead, the target is responsible from marking
2982      breakpoints out as soon as it detects an exec.  We don't do that
2983      here instead, because there may be other attempts to delete
2984      breakpoints after detecting an exec and before reaching here.  */
2985   ALL_BP_LOCATIONS (bploc, bplocp_tmp)
2986     if (bploc->pspace == current_program_space)
2987       gdb_assert (!bploc->inserted);
2988
2989   ALL_BREAKPOINTS_SAFE (b, b_tmp)
2990   {
2991     if (b->pspace != current_program_space)
2992       continue;
2993
2994     /* Solib breakpoints must be explicitly reset after an exec().  */
2995     if (b->type == bp_shlib_event)
2996       {
2997         delete_breakpoint (b);
2998         continue;
2999       }
3000
3001     /* JIT breakpoints must be explicitly reset after an exec().  */
3002     if (b->type == bp_jit_event)
3003       {
3004         delete_breakpoint (b);
3005         continue;
3006       }
3007
3008     /* Thread event breakpoints must be set anew after an exec(),
3009        as must overlay event and longjmp master breakpoints.  */
3010     if (b->type == bp_thread_event || b->type == bp_overlay_event
3011         || b->type == bp_longjmp_master || b->type == bp_std_terminate_master
3012         || b->type == bp_exception_master)
3013       {
3014         delete_breakpoint (b);
3015         continue;
3016       }
3017
3018     /* Step-resume breakpoints are meaningless after an exec().  */
3019     if (b->type == bp_step_resume || b->type == bp_hp_step_resume)
3020       {
3021         delete_breakpoint (b);
3022         continue;
3023       }
3024
3025     /* Longjmp and longjmp-resume breakpoints are also meaningless
3026        after an exec.  */
3027     if (b->type == bp_longjmp || b->type == bp_longjmp_resume
3028         || b->type == bp_exception || b->type == bp_exception_resume)
3029       {
3030         delete_breakpoint (b);
3031         continue;
3032       }
3033
3034     if (b->type == bp_catchpoint)
3035       {
3036         /* For now, none of the bp_catchpoint breakpoints need to
3037            do anything at this point.  In the future, if some of
3038            the catchpoints need to something, we will need to add
3039            a new method, and call this method from here.  */
3040         continue;
3041       }
3042
3043     /* bp_finish is a special case.  The only way we ought to be able
3044        to see one of these when an exec() has happened, is if the user
3045        caught a vfork, and then said "finish".  Ordinarily a finish just
3046        carries them to the call-site of the current callee, by setting
3047        a temporary bp there and resuming.  But in this case, the finish
3048        will carry them entirely through the vfork & exec.
3049
3050        We don't want to allow a bp_finish to remain inserted now.  But
3051        we can't safely delete it, 'cause finish_command has a handle to
3052        the bp on a bpstat, and will later want to delete it.  There's a
3053        chance (and I've seen it happen) that if we delete the bp_finish
3054        here, that its storage will get reused by the time finish_command
3055        gets 'round to deleting the "use to be a bp_finish" breakpoint.
3056        We really must allow finish_command to delete a bp_finish.
3057
3058        In the absence of a general solution for the "how do we know
3059        it's safe to delete something others may have handles to?"
3060        problem, what we'll do here is just uninsert the bp_finish, and
3061        let finish_command delete it.
3062
3063        (We know the bp_finish is "doomed" in the sense that it's
3064        momentary, and will be deleted as soon as finish_command sees
3065        the inferior stopped.  So it doesn't matter that the bp's
3066        address is probably bogus in the new a.out, unlike e.g., the
3067        solib breakpoints.)  */
3068
3069     if (b->type == bp_finish)
3070       {
3071         continue;
3072       }
3073
3074     /* Without a symbolic address, we have little hope of the
3075        pre-exec() address meaning the same thing in the post-exec()
3076        a.out.  */
3077     if (b->addr_string == NULL)
3078       {
3079         delete_breakpoint (b);
3080         continue;
3081       }
3082   }
3083   /* FIXME what about longjmp breakpoints?  Re-create them here?  */
3084   create_overlay_event_breakpoint ();
3085   create_longjmp_master_breakpoint ();
3086   create_std_terminate_master_breakpoint ();
3087   create_exception_master_breakpoint ();
3088 }
3089
3090 int
3091 detach_breakpoints (int pid)
3092 {
3093   struct bp_location *bl, **blp_tmp;
3094   int val = 0;
3095   struct cleanup *old_chain = save_inferior_ptid ();
3096   struct inferior *inf = current_inferior ();
3097
3098   if (pid == PIDGET (inferior_ptid))
3099     error (_("Cannot detach breakpoints of inferior_ptid"));
3100
3101   /* Set inferior_ptid; remove_breakpoint_1 uses this global.  */
3102   inferior_ptid = pid_to_ptid (pid);
3103   ALL_BP_LOCATIONS (bl, blp_tmp)
3104   {
3105     if (bl->pspace != inf->pspace)
3106       continue;
3107
3108     if (bl->inserted)
3109       val |= remove_breakpoint_1 (bl, mark_inserted);
3110   }
3111
3112   /* Detach single-step breakpoints as well.  */
3113   detach_single_step_breakpoints ();
3114
3115   do_cleanups (old_chain);
3116   return val;
3117 }
3118
3119 /* Remove the breakpoint location BL from the current address space.
3120    Note that this is used to detach breakpoints from a child fork.
3121    When we get here, the child isn't in the inferior list, and neither
3122    do we have objects to represent its address space --- we should
3123    *not* look at bl->pspace->aspace here.  */
3124
3125 static int
3126 remove_breakpoint_1 (struct bp_location *bl, insertion_state_t is)
3127 {
3128   int val;
3129
3130   /* BL is never in moribund_locations by our callers.  */
3131   gdb_assert (bl->owner != NULL);
3132
3133   if (bl->owner->enable_state == bp_permanent)
3134     /* Permanent breakpoints cannot be inserted or removed.  */
3135     return 0;
3136
3137   /* The type of none suggests that owner is actually deleted.
3138      This should not ever happen.  */
3139   gdb_assert (bl->owner->type != bp_none);
3140
3141   if (bl->loc_type == bp_loc_software_breakpoint
3142       || bl->loc_type == bp_loc_hardware_breakpoint)
3143     {
3144       /* "Normal" instruction breakpoint: either the standard
3145          trap-instruction bp (bp_breakpoint), or a
3146          bp_hardware_breakpoint.  */
3147
3148       /* First check to see if we have to handle an overlay.  */
3149       if (overlay_debugging == ovly_off
3150           || bl->section == NULL
3151           || !(section_is_overlay (bl->section)))
3152         {
3153           /* No overlay handling: just remove the breakpoint.  */
3154           val = bl->owner->ops->remove_location (bl);
3155         }
3156       else
3157         {
3158           /* This breakpoint is in an overlay section.
3159              Did we set a breakpoint at the LMA?  */
3160           if (!overlay_events_enabled)
3161               {
3162                 /* Yes -- overlay event support is not active, so we
3163                    should have set a breakpoint at the LMA.  Remove it.  
3164                 */
3165                 /* Ignore any failures: if the LMA is in ROM, we will
3166                    have already warned when we failed to insert it.  */
3167                 if (bl->loc_type == bp_loc_hardware_breakpoint)
3168                   target_remove_hw_breakpoint (bl->gdbarch,
3169                                                &bl->overlay_target_info);
3170                 else
3171                   target_remove_breakpoint (bl->gdbarch,
3172                                             &bl->overlay_target_info);
3173               }
3174           /* Did we set a breakpoint at the VMA? 
3175              If so, we will have marked the breakpoint 'inserted'.  */
3176           if (bl->inserted)
3177             {
3178               /* Yes -- remove it.  Previously we did not bother to
3179                  remove the breakpoint if the section had been
3180                  unmapped, but let's not rely on that being safe.  We
3181                  don't know what the overlay manager might do.  */
3182
3183               /* However, we should remove *software* breakpoints only
3184                  if the section is still mapped, or else we overwrite
3185                  wrong code with the saved shadow contents.  */
3186               if (bl->loc_type == bp_loc_hardware_breakpoint
3187                   || section_is_mapped (bl->section))
3188                 val = bl->owner->ops->remove_location (bl);
3189               else
3190                 val = 0;
3191             }
3192           else
3193             {
3194               /* No -- not inserted, so no need to remove.  No error.  */
3195               val = 0;
3196             }
3197         }
3198
3199       /* In some cases, we might not be able to remove a breakpoint
3200          in a shared library that has already been removed, but we
3201          have not yet processed the shlib unload event.  */
3202       if (val && solib_name_from_address (bl->pspace, bl->address))
3203         val = 0;
3204
3205       if (val)
3206         return val;
3207       bl->inserted = (is == mark_inserted);
3208     }
3209   else if (bl->loc_type == bp_loc_hardware_watchpoint)
3210     {
3211       gdb_assert (bl->owner->ops != NULL
3212                   && bl->owner->ops->remove_location != NULL);
3213
3214       bl->inserted = (is == mark_inserted);
3215       bl->owner->ops->remove_location (bl);
3216
3217       /* Failure to remove any of the hardware watchpoints comes here.  */
3218       if ((is == mark_uninserted) && (bl->inserted))
3219         warning (_("Could not remove hardware watchpoint %d."),
3220                  bl->owner->number);
3221     }
3222   else if (bl->owner->type == bp_catchpoint
3223            && breakpoint_enabled (bl->owner)
3224            && !bl->duplicate)
3225     {
3226       gdb_assert (bl->owner->ops != NULL
3227                   && bl->owner->ops->remove_location != NULL);
3228
3229       val = bl->owner->ops->remove_location (bl);
3230       if (val)
3231         return val;
3232
3233       bl->inserted = (is == mark_inserted);
3234     }
3235
3236   return 0;
3237 }
3238
3239 static int
3240 remove_breakpoint (struct bp_location *bl, insertion_state_t is)
3241 {
3242   int ret;
3243   struct cleanup *old_chain;
3244
3245   /* BL is never in moribund_locations by our callers.  */
3246   gdb_assert (bl->owner != NULL);
3247
3248   if (bl->owner->enable_state == bp_permanent)
3249     /* Permanent breakpoints cannot be inserted or removed.  */
3250     return 0;
3251
3252   /* The type of none suggests that owner is actually deleted.
3253      This should not ever happen.  */
3254   gdb_assert (bl->owner->type != bp_none);
3255
3256   old_chain = save_current_space_and_thread ();
3257
3258   switch_to_program_space_and_thread (bl->pspace);
3259
3260   ret = remove_breakpoint_1 (bl, is);
3261
3262   do_cleanups (old_chain);
3263   return ret;
3264 }
3265
3266 /* Clear the "inserted" flag in all breakpoints.  */
3267
3268 void
3269 mark_breakpoints_out (void)
3270 {
3271   struct bp_location *bl, **blp_tmp;
3272
3273   ALL_BP_LOCATIONS (bl, blp_tmp)
3274     if (bl->pspace == current_program_space)
3275       bl->inserted = 0;
3276 }
3277
3278 /* Clear the "inserted" flag in all breakpoints and delete any
3279    breakpoints which should go away between runs of the program.
3280
3281    Plus other such housekeeping that has to be done for breakpoints
3282    between runs.
3283
3284    Note: this function gets called at the end of a run (by
3285    generic_mourn_inferior) and when a run begins (by
3286    init_wait_for_inferior).  */
3287
3288
3289
3290 void
3291 breakpoint_init_inferior (enum inf_context context)
3292 {
3293   struct breakpoint *b, *b_tmp;
3294   struct bp_location *bl, **blp_tmp;
3295   int ix;
3296   struct program_space *pspace = current_program_space;
3297
3298   /* If breakpoint locations are shared across processes, then there's
3299      nothing to do.  */
3300   if (gdbarch_has_global_breakpoints (target_gdbarch))
3301     return;
3302
3303   ALL_BP_LOCATIONS (bl, blp_tmp)
3304   {
3305     /* ALL_BP_LOCATIONS bp_location has BL->OWNER always non-NULL.  */
3306     if (bl->pspace == pspace
3307         && bl->owner->enable_state != bp_permanent)
3308       bl->inserted = 0;
3309   }
3310
3311   ALL_BREAKPOINTS_SAFE (b, b_tmp)
3312   {
3313     if (b->loc && b->loc->pspace != pspace)
3314       continue;
3315
3316     switch (b->type)
3317       {
3318       case bp_call_dummy:
3319
3320         /* If the call dummy breakpoint is at the entry point it will
3321            cause problems when the inferior is rerun, so we better get
3322            rid of it.  */
3323
3324       case bp_watchpoint_scope:
3325
3326         /* Also get rid of scope breakpoints.  */
3327
3328       case bp_shlib_event:
3329
3330         /* Also remove solib event breakpoints.  Their addresses may
3331            have changed since the last time we ran the program.
3332            Actually we may now be debugging against different target;
3333            and so the solib backend that installed this breakpoint may
3334            not be used in by the target.  E.g.,
3335
3336            (gdb) file prog-linux
3337            (gdb) run               # native linux target
3338            ...
3339            (gdb) kill
3340            (gdb) file prog-win.exe
3341            (gdb) tar rem :9999     # remote Windows gdbserver.
3342         */
3343
3344         delete_breakpoint (b);
3345         break;
3346
3347       case bp_watchpoint:
3348       case bp_hardware_watchpoint:
3349       case bp_read_watchpoint:
3350       case bp_access_watchpoint:
3351         {
3352           struct watchpoint *w = (struct watchpoint *) b;
3353
3354           /* Likewise for watchpoints on local expressions.  */
3355           if (w->exp_valid_block != NULL)
3356             delete_breakpoint (b);
3357           else if (context == inf_starting)
3358             {
3359               /* Reset val field to force reread of starting value in
3360                  insert_breakpoints.  */
3361               if (w->val)
3362                 value_free (w->val);
3363               w->val = NULL;
3364               w->val_valid = 0;
3365           }
3366         }
3367         break;
3368       default:
3369         break;
3370       }
3371   }
3372
3373   /* Get rid of the moribund locations.  */
3374   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, bl); ++ix)
3375     decref_bp_location (&bl);
3376   VEC_free (bp_location_p, moribund_locations);
3377 }
3378
3379 /* These functions concern about actual breakpoints inserted in the
3380    target --- to e.g. check if we need to do decr_pc adjustment or if
3381    we need to hop over the bkpt --- so we check for address space
3382    match, not program space.  */
3383
3384 /* breakpoint_here_p (PC) returns non-zero if an enabled breakpoint
3385    exists at PC.  It returns ordinary_breakpoint_here if it's an
3386    ordinary breakpoint, or permanent_breakpoint_here if it's a
3387    permanent breakpoint.
3388    - When continuing from a location with an ordinary breakpoint, we
3389      actually single step once before calling insert_breakpoints.
3390    - When continuing from a location with a permanent breakpoint, we
3391      need to use the `SKIP_PERMANENT_BREAKPOINT' macro, provided by
3392      the target, to advance the PC past the breakpoint.  */
3393
3394 enum breakpoint_here
3395 breakpoint_here_p (struct address_space *aspace, CORE_ADDR pc)
3396 {
3397   struct bp_location *bl, **blp_tmp;
3398   int any_breakpoint_here = 0;
3399
3400   ALL_BP_LOCATIONS (bl, blp_tmp)
3401     {
3402       if (bl->loc_type != bp_loc_software_breakpoint
3403           && bl->loc_type != bp_loc_hardware_breakpoint)
3404         continue;
3405
3406       /* ALL_BP_LOCATIONS bp_location has BL->OWNER always non-NULL.  */
3407       if ((breakpoint_enabled (bl->owner)
3408            || bl->owner->enable_state == bp_permanent)
3409           && breakpoint_location_address_match (bl, aspace, pc))
3410         {
3411           if (overlay_debugging 
3412               && section_is_overlay (bl->section)
3413               && !section_is_mapped (bl->section))
3414             continue;           /* unmapped overlay -- can't be a match */
3415           else if (bl->owner->enable_state == bp_permanent)
3416             return permanent_breakpoint_here;
3417           else
3418             any_breakpoint_here = 1;
3419         }
3420     }
3421
3422   return any_breakpoint_here ? ordinary_breakpoint_here : 0;
3423 }
3424
3425 /* Return true if there's a moribund breakpoint at PC.  */
3426
3427 int
3428 moribund_breakpoint_here_p (struct address_space *aspace, CORE_ADDR pc)
3429 {
3430   struct bp_location *loc;
3431   int ix;
3432
3433   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
3434     if (breakpoint_location_address_match (loc, aspace, pc))
3435       return 1;
3436
3437   return 0;
3438 }
3439
3440 /* Returns non-zero if there's a breakpoint inserted at PC, which is
3441    inserted using regular breakpoint_chain / bp_location array
3442    mechanism.  This does not check for single-step breakpoints, which
3443    are inserted and removed using direct target manipulation.  */
3444
3445 int
3446 regular_breakpoint_inserted_here_p (struct address_space *aspace, 
3447                                     CORE_ADDR pc)
3448 {
3449   struct bp_location *bl, **blp_tmp;
3450
3451   ALL_BP_LOCATIONS (bl, blp_tmp)
3452     {
3453       if (bl->loc_type != bp_loc_software_breakpoint
3454           && bl->loc_type != bp_loc_hardware_breakpoint)
3455         continue;
3456
3457       if (bl->inserted
3458           && breakpoint_location_address_match (bl, aspace, pc))
3459         {
3460           if (overlay_debugging 
3461               && section_is_overlay (bl->section)
3462               && !section_is_mapped (bl->section))
3463             continue;           /* unmapped overlay -- can't be a match */
3464           else
3465             return 1;
3466         }
3467     }
3468   return 0;
3469 }
3470
3471 /* Returns non-zero iff there's either regular breakpoint
3472    or a single step breakpoint inserted at PC.  */
3473
3474 int
3475 breakpoint_inserted_here_p (struct address_space *aspace, CORE_ADDR pc)
3476 {
3477   if (regular_breakpoint_inserted_here_p (aspace, pc))
3478     return 1;
3479
3480   if (single_step_breakpoint_inserted_here_p (aspace, pc))
3481     return 1;
3482
3483   return 0;
3484 }
3485
3486 /* This function returns non-zero iff there is a software breakpoint
3487    inserted at PC.  */
3488
3489 int
3490 software_breakpoint_inserted_here_p (struct address_space *aspace,
3491                                      CORE_ADDR pc)
3492 {
3493   struct bp_location *bl, **blp_tmp;
3494
3495   ALL_BP_LOCATIONS (bl, blp_tmp)
3496     {
3497       if (bl->loc_type != bp_loc_software_breakpoint)
3498         continue;
3499
3500       if (bl->inserted
3501           && breakpoint_address_match (bl->pspace->aspace, bl->address,
3502                                        aspace, pc))
3503         {
3504           if (overlay_debugging 
3505               && section_is_overlay (bl->section)
3506               && !section_is_mapped (bl->section))
3507             continue;           /* unmapped overlay -- can't be a match */
3508           else
3509             return 1;
3510         }
3511     }
3512
3513   /* Also check for software single-step breakpoints.  */
3514   if (single_step_breakpoint_inserted_here_p (aspace, pc))
3515     return 1;
3516
3517   return 0;
3518 }
3519
3520 int
3521 hardware_watchpoint_inserted_in_range (struct address_space *aspace,
3522                                        CORE_ADDR addr, ULONGEST len)
3523 {
3524   struct breakpoint *bpt;
3525
3526   ALL_BREAKPOINTS (bpt)
3527     {
3528       struct bp_location *loc;
3529
3530       if (bpt->type != bp_hardware_watchpoint
3531           && bpt->type != bp_access_watchpoint)
3532         continue;
3533
3534       if (!breakpoint_enabled (bpt))
3535         continue;
3536
3537       for (loc = bpt->loc; loc; loc = loc->next)
3538         if (loc->pspace->aspace == aspace && loc->inserted)
3539           {
3540             CORE_ADDR l, h;
3541
3542             /* Check for intersection.  */
3543             l = max (loc->address, addr);
3544             h = min (loc->address + loc->length, addr + len);
3545             if (l < h)
3546               return 1;
3547           }
3548     }
3549   return 0;
3550 }
3551
3552 /* breakpoint_thread_match (PC, PTID) returns true if the breakpoint at
3553    PC is valid for process/thread PTID.  */
3554
3555 int
3556 breakpoint_thread_match (struct address_space *aspace, CORE_ADDR pc,
3557                          ptid_t ptid)
3558 {
3559   struct bp_location *bl, **blp_tmp;
3560   /* The thread and task IDs associated to PTID, computed lazily.  */
3561   int thread = -1;
3562   int task = 0;
3563   
3564   ALL_BP_LOCATIONS (bl, blp_tmp)
3565     {
3566       if (bl->loc_type != bp_loc_software_breakpoint
3567           && bl->loc_type != bp_loc_hardware_breakpoint)
3568         continue;
3569
3570       /* ALL_BP_LOCATIONS bp_location has bl->OWNER always non-NULL.  */
3571       if (!breakpoint_enabled (bl->owner)
3572           && bl->owner->enable_state != bp_permanent)
3573         continue;
3574
3575       if (!breakpoint_location_address_match (bl, aspace, pc))
3576         continue;
3577
3578       if (bl->owner->thread != -1)
3579         {
3580           /* This is a thread-specific breakpoint.  Check that ptid
3581              matches that thread.  If thread hasn't been computed yet,
3582              it is now time to do so.  */
3583           if (thread == -1)
3584             thread = pid_to_thread_id (ptid);
3585           if (bl->owner->thread != thread)
3586             continue;
3587         }
3588
3589       if (bl->owner->task != 0)
3590         {
3591           /* This is a task-specific breakpoint.  Check that ptid
3592              matches that task.  If task hasn't been computed yet,
3593              it is now time to do so.  */
3594           if (task == 0)
3595             task = ada_get_task_number (ptid);
3596           if (bl->owner->task != task)
3597             continue;
3598         }
3599
3600       if (overlay_debugging 
3601           && section_is_overlay (bl->section)
3602           && !section_is_mapped (bl->section))
3603         continue;           /* unmapped overlay -- can't be a match */
3604
3605       return 1;
3606     }
3607
3608   return 0;
3609 }
3610 \f
3611
3612 /* bpstat stuff.  External routines' interfaces are documented
3613    in breakpoint.h.  */
3614
3615 int
3616 ep_is_catchpoint (struct breakpoint *ep)
3617 {
3618   return (ep->type == bp_catchpoint);
3619 }
3620
3621 /* Frees any storage that is part of a bpstat.  Does not walk the
3622    'next' chain.  */
3623
3624 static void
3625 bpstat_free (bpstat bs)
3626 {
3627   if (bs->old_val != NULL)
3628     value_free (bs->old_val);
3629   decref_counted_command_line (&bs->commands);
3630   decref_bp_location (&bs->bp_location_at);
3631   xfree (bs);
3632 }
3633
3634 /* Clear a bpstat so that it says we are not at any breakpoint.
3635    Also free any storage that is part of a bpstat.  */
3636
3637 void
3638 bpstat_clear (bpstat *bsp)
3639 {
3640   bpstat p;
3641   bpstat q;
3642
3643   if (bsp == 0)
3644     return;
3645   p = *bsp;
3646   while (p != NULL)
3647     {
3648       q = p->next;
3649       bpstat_free (p);
3650       p = q;
3651     }
3652   *bsp = NULL;
3653 }
3654
3655 /* Return a copy of a bpstat.  Like "bs1 = bs2" but all storage that
3656    is part of the bpstat is copied as well.  */
3657
3658 bpstat
3659 bpstat_copy (bpstat bs)
3660 {
3661   bpstat p = NULL;
3662   bpstat tmp;
3663   bpstat retval = NULL;
3664
3665   if (bs == NULL)
3666     return bs;
3667
3668   for (; bs != NULL; bs = bs->next)
3669     {
3670       tmp = (bpstat) xmalloc (sizeof (*tmp));
3671       memcpy (tmp, bs, sizeof (*tmp));
3672       incref_counted_command_line (tmp->commands);
3673       incref_bp_location (tmp->bp_location_at);
3674       if (bs->old_val != NULL)
3675         {
3676           tmp->old_val = value_copy (bs->old_val);
3677           release_value (tmp->old_val);
3678         }
3679
3680       if (p == NULL)
3681         /* This is the first thing in the chain.  */
3682         retval = tmp;
3683       else
3684         p->next = tmp;
3685       p = tmp;
3686     }
3687   p->next = NULL;
3688   return retval;
3689 }
3690
3691 /* Find the bpstat associated with this breakpoint.  */
3692
3693 bpstat
3694 bpstat_find_breakpoint (bpstat bsp, struct breakpoint *breakpoint)
3695 {
3696   if (bsp == NULL)
3697     return NULL;
3698
3699   for (; bsp != NULL; bsp = bsp->next)
3700     {
3701       if (bsp->breakpoint_at == breakpoint)
3702         return bsp;
3703     }
3704   return NULL;
3705 }
3706
3707 /* Put in *NUM the breakpoint number of the first breakpoint we are
3708    stopped at.  *BSP upon return is a bpstat which points to the
3709    remaining breakpoints stopped at (but which is not guaranteed to be
3710    good for anything but further calls to bpstat_num).
3711
3712    Return 0 if passed a bpstat which does not indicate any breakpoints.
3713    Return -1 if stopped at a breakpoint that has been deleted since
3714    we set it.
3715    Return 1 otherwise.  */
3716
3717 int
3718 bpstat_num (bpstat *bsp, int *num)
3719 {
3720   struct breakpoint *b;
3721
3722   if ((*bsp) == NULL)
3723     return 0;                   /* No more breakpoint values */
3724
3725   /* We assume we'll never have several bpstats that correspond to a
3726      single breakpoint -- otherwise, this function might return the
3727      same number more than once and this will look ugly.  */
3728   b = (*bsp)->breakpoint_at;
3729   *bsp = (*bsp)->next;
3730   if (b == NULL)
3731     return -1;                  /* breakpoint that's been deleted since */
3732
3733   *num = b->number;             /* We have its number */
3734   return 1;
3735 }
3736
3737 /* See breakpoint.h.  */
3738
3739 void
3740 bpstat_clear_actions (void)
3741 {
3742   struct thread_info *tp;
3743   bpstat bs;
3744
3745   if (ptid_equal (inferior_ptid, null_ptid))
3746     return;
3747
3748   tp = find_thread_ptid (inferior_ptid);
3749   if (tp == NULL)
3750     return;
3751
3752   for (bs = tp->control.stop_bpstat; bs != NULL; bs = bs->next)
3753     {
3754       decref_counted_command_line (&bs->commands);
3755
3756       if (bs->old_val != NULL)
3757         {
3758           value_free (bs->old_val);
3759           bs->old_val = NULL;
3760         }
3761     }
3762 }
3763
3764 /* Called when a command is about to proceed the inferior.  */
3765
3766 static void
3767 breakpoint_about_to_proceed (void)
3768 {
3769   if (!ptid_equal (inferior_ptid, null_ptid))
3770     {
3771       struct thread_info *tp = inferior_thread ();
3772
3773       /* Allow inferior function calls in breakpoint commands to not
3774          interrupt the command list.  When the call finishes
3775          successfully, the inferior will be standing at the same
3776          breakpoint as if nothing happened.  */
3777       if (tp->control.in_infcall)
3778         return;
3779     }
3780
3781   breakpoint_proceeded = 1;
3782 }
3783
3784 /* Stub for cleaning up our state if we error-out of a breakpoint
3785    command.  */
3786 static void
3787 cleanup_executing_breakpoints (void *ignore)
3788 {
3789   executing_breakpoint_commands = 0;
3790 }
3791
3792 /* Return non-zero iff CMD as the first line of a command sequence is `silent'
3793    or its equivalent.  */
3794
3795 static int
3796 command_line_is_silent (struct command_line *cmd)
3797 {
3798   return cmd && (strcmp ("silent", cmd->line) == 0
3799                  || (xdb_commands && strcmp ("Q", cmd->line) == 0));
3800 }
3801
3802 /* Execute all the commands associated with all the breakpoints at
3803    this location.  Any of these commands could cause the process to
3804    proceed beyond this point, etc.  We look out for such changes by
3805    checking the global "breakpoint_proceeded" after each command.
3806
3807    Returns true if a breakpoint command resumed the inferior.  In that
3808    case, it is the caller's responsibility to recall it again with the
3809    bpstat of the current thread.  */
3810
3811 static int
3812 bpstat_do_actions_1 (bpstat *bsp)
3813 {
3814   bpstat bs;
3815   struct cleanup *old_chain;
3816   int again = 0;
3817
3818   /* Avoid endless recursion if a `source' command is contained
3819      in bs->commands.  */
3820   if (executing_breakpoint_commands)
3821     return 0;
3822
3823   executing_breakpoint_commands = 1;
3824   old_chain = make_cleanup (cleanup_executing_breakpoints, 0);
3825
3826   prevent_dont_repeat ();
3827
3828   /* This pointer will iterate over the list of bpstat's.  */
3829   bs = *bsp;
3830
3831   breakpoint_proceeded = 0;
3832   for (; bs != NULL; bs = bs->next)
3833     {
3834       struct counted_command_line *ccmd;
3835       struct command_line *cmd;
3836       struct cleanup *this_cmd_tree_chain;
3837
3838       /* Take ownership of the BSP's command tree, if it has one.
3839
3840          The command tree could legitimately contain commands like
3841          'step' and 'next', which call clear_proceed_status, which
3842          frees stop_bpstat's command tree.  To make sure this doesn't
3843          free the tree we're executing out from under us, we need to
3844          take ownership of the tree ourselves.  Since a given bpstat's
3845          commands are only executed once, we don't need to copy it; we
3846          can clear the pointer in the bpstat, and make sure we free
3847          the tree when we're done.  */
3848       ccmd = bs->commands;
3849       bs->commands = NULL;
3850       this_cmd_tree_chain = make_cleanup_decref_counted_command_line (&ccmd);
3851       cmd = ccmd ? ccmd->commands : NULL;
3852       if (command_line_is_silent (cmd))
3853         {
3854           /* The action has been already done by bpstat_stop_status.  */
3855           cmd = cmd->next;
3856         }
3857
3858       while (cmd != NULL)
3859         {
3860           execute_control_command (cmd);
3861
3862           if (breakpoint_proceeded)
3863             break;
3864           else
3865             cmd = cmd->next;
3866         }
3867
3868       /* We can free this command tree now.  */
3869       do_cleanups (this_cmd_tree_chain);
3870
3871       if (breakpoint_proceeded)
3872         {
3873           if (target_can_async_p ())
3874             /* If we are in async mode, then the target might be still
3875                running, not stopped at any breakpoint, so nothing for
3876                us to do here -- just return to the event loop.  */
3877             ;
3878           else
3879             /* In sync mode, when execute_control_command returns
3880                we're already standing on the next breakpoint.
3881                Breakpoint commands for that stop were not run, since
3882                execute_command does not run breakpoint commands --
3883                only command_line_handler does, but that one is not
3884                involved in execution of breakpoint commands.  So, we
3885                can now execute breakpoint commands.  It should be
3886                noted that making execute_command do bpstat actions is
3887                not an option -- in this case we'll have recursive
3888                invocation of bpstat for each breakpoint with a
3889                command, and can easily blow up GDB stack.  Instead, we
3890                return true, which will trigger the caller to recall us
3891                with the new stop_bpstat.  */
3892             again = 1;
3893           break;
3894         }
3895     }
3896   do_cleanups (old_chain);
3897   return again;
3898 }
3899
3900 void
3901 bpstat_do_actions (void)
3902 {
3903   struct cleanup *cleanup_if_error = make_bpstat_clear_actions_cleanup ();
3904
3905   /* Do any commands attached to breakpoint we are stopped at.  */
3906   while (!ptid_equal (inferior_ptid, null_ptid)
3907          && target_has_execution
3908          && !is_exited (inferior_ptid)
3909          && !is_executing (inferior_ptid))
3910     /* Since in sync mode, bpstat_do_actions may resume the inferior,
3911        and only return when it is stopped at the next breakpoint, we
3912        keep doing breakpoint actions until it returns false to
3913        indicate the inferior was not resumed.  */
3914     if (!bpstat_do_actions_1 (&inferior_thread ()->control.stop_bpstat))
3915       break;
3916
3917   discard_cleanups (cleanup_if_error);
3918 }
3919
3920 /* Print out the (old or new) value associated with a watchpoint.  */
3921
3922 static void
3923 watchpoint_value_print (struct value *val, struct ui_file *stream)
3924 {
3925   if (val == NULL)
3926     fprintf_unfiltered (stream, _("<unreadable>"));
3927   else
3928     {
3929       struct value_print_options opts;
3930       get_user_print_options (&opts);
3931       value_print (val, stream, &opts);
3932     }
3933 }
3934
3935 /* Generic routine for printing messages indicating why we
3936    stopped.  The behavior of this function depends on the value
3937    'print_it' in the bpstat structure.  Under some circumstances we
3938    may decide not to print anything here and delegate the task to
3939    normal_stop().  */
3940
3941 static enum print_stop_action
3942 print_bp_stop_message (bpstat bs)
3943 {
3944   switch (bs->print_it)
3945     {
3946     case print_it_noop:
3947       /* Nothing should be printed for this bpstat entry.  */
3948       return PRINT_UNKNOWN;
3949       break;
3950
3951     case print_it_done:
3952       /* We still want to print the frame, but we already printed the
3953          relevant messages.  */
3954       return PRINT_SRC_AND_LOC;
3955       break;
3956
3957     case print_it_normal:
3958       {
3959         struct breakpoint *b = bs->breakpoint_at;
3960
3961         /* bs->breakpoint_at can be NULL if it was a momentary breakpoint
3962            which has since been deleted.  */
3963         if (b == NULL)
3964           return PRINT_UNKNOWN;
3965
3966         /* Normal case.  Call the breakpoint's print_it method.  */
3967         return b->ops->print_it (bs);
3968       }
3969       break;
3970
3971     default:
3972       internal_error (__FILE__, __LINE__,
3973                       _("print_bp_stop_message: unrecognized enum value"));
3974       break;
3975     }
3976 }
3977
3978 /* A helper function that prints a shared library stopped event.  */
3979
3980 static void
3981 print_solib_event (int is_catchpoint)
3982 {
3983   int any_deleted
3984     = !VEC_empty (char_ptr, current_program_space->deleted_solibs);
3985   int any_added
3986     = !VEC_empty (so_list_ptr, current_program_space->added_solibs);
3987
3988   if (!is_catchpoint)
3989     {
3990       if (any_added || any_deleted)
3991         ui_out_text (current_uiout,
3992                      _("Stopped due to shared library event:\n"));
3993       else
3994         ui_out_text (current_uiout,
3995                      _("Stopped due to shared library event (no "
3996                        "libraries added or removed)\n"));
3997     }
3998
3999   if (ui_out_is_mi_like_p (current_uiout))
4000     ui_out_field_string (current_uiout, "reason",
4001                          async_reason_lookup (EXEC_ASYNC_SOLIB_EVENT));
4002
4003   if (any_deleted)
4004     {
4005       struct cleanup *cleanup;
4006       char *name;
4007       int ix;
4008
4009       ui_out_text (current_uiout, _("  Inferior unloaded "));
4010       cleanup = make_cleanup_ui_out_list_begin_end (current_uiout,
4011                                                     "removed");
4012       for (ix = 0;
4013            VEC_iterate (char_ptr, current_program_space->deleted_solibs,
4014                         ix, name);
4015            ++ix)
4016         {
4017           if (ix > 0)
4018             ui_out_text (current_uiout, "    ");
4019           ui_out_field_string (current_uiout, "library", name);
4020           ui_out_text (current_uiout, "\n");
4021         }
4022
4023       do_cleanups (cleanup);
4024     }
4025
4026   if (any_added)
4027     {
4028       struct so_list *iter;
4029       int ix;
4030       struct cleanup *cleanup;
4031
4032       ui_out_text (current_uiout, _("  Inferior loaded "));
4033       cleanup = make_cleanup_ui_out_list_begin_end (current_uiout,
4034                                                     "added");
4035       for (ix = 0;
4036            VEC_iterate (so_list_ptr, current_program_space->added_solibs,
4037                         ix, iter);
4038            ++ix)
4039         {
4040           if (ix > 0)
4041             ui_out_text (current_uiout, "    ");
4042           ui_out_field_string (current_uiout, "library", iter->so_name);
4043           ui_out_text (current_uiout, "\n");
4044         }
4045
4046       do_cleanups (cleanup);
4047     }
4048 }
4049
4050 /* Print a message indicating what happened.  This is called from
4051    normal_stop().  The input to this routine is the head of the bpstat
4052    list - a list of the eventpoints that caused this stop.  KIND is
4053    the target_waitkind for the stopping event.  This
4054    routine calls the generic print routine for printing a message
4055    about reasons for stopping.  This will print (for example) the
4056    "Breakpoint n," part of the output.  The return value of this
4057    routine is one of:
4058
4059    PRINT_UNKNOWN: Means we printed nothing.
4060    PRINT_SRC_AND_LOC: Means we printed something, and expect subsequent
4061    code to print the location.  An example is 
4062    "Breakpoint 1, " which should be followed by
4063    the location.
4064    PRINT_SRC_ONLY: Means we printed something, but there is no need
4065    to also print the location part of the message.
4066    An example is the catch/throw messages, which
4067    don't require a location appended to the end.
4068    PRINT_NOTHING: We have done some printing and we don't need any 
4069    further info to be printed.  */
4070
4071 enum print_stop_action
4072 bpstat_print (bpstat bs, int kind)
4073 {
4074   int val;
4075
4076   /* Maybe another breakpoint in the chain caused us to stop.
4077      (Currently all watchpoints go on the bpstat whether hit or not.
4078      That probably could (should) be changed, provided care is taken
4079      with respect to bpstat_explains_signal).  */
4080   for (; bs; bs = bs->next)
4081     {
4082       val = print_bp_stop_message (bs);
4083       if (val == PRINT_SRC_ONLY 
4084           || val == PRINT_SRC_AND_LOC 
4085           || val == PRINT_NOTHING)
4086         return val;
4087     }
4088
4089   /* If we had hit a shared library event breakpoint,
4090      print_bp_stop_message would print out this message.  If we hit an
4091      OS-level shared library event, do the same thing.  */
4092   if (kind == TARGET_WAITKIND_LOADED)
4093     {
4094       print_solib_event (0);
4095       return PRINT_NOTHING;
4096     }
4097
4098   /* We reached the end of the chain, or we got a null BS to start
4099      with and nothing was printed.  */
4100   return PRINT_UNKNOWN;
4101 }
4102
4103 /* Evaluate the expression EXP and return 1 if value is zero.  This is
4104    used inside a catch_errors to evaluate the breakpoint condition.
4105    The argument is a "struct expression *" that has been cast to a
4106    "char *" to make it pass through catch_errors.  */
4107
4108 static int
4109 breakpoint_cond_eval (void *exp)
4110 {
4111   struct value *mark = value_mark ();
4112   int i = !value_true (evaluate_expression ((struct expression *) exp));
4113
4114   value_free_to_mark (mark);
4115   return i;
4116 }
4117
4118 /* Allocate a new bpstat.  Link it to the FIFO list by BS_LINK_POINTER.  */
4119
4120 static bpstat
4121 bpstat_alloc (struct bp_location *bl, bpstat **bs_link_pointer)
4122 {
4123   bpstat bs;
4124
4125   bs = (bpstat) xmalloc (sizeof (*bs));
4126   bs->next = NULL;
4127   **bs_link_pointer = bs;
4128   *bs_link_pointer = &bs->next;
4129   bs->breakpoint_at = bl->owner;
4130   bs->bp_location_at = bl;
4131   incref_bp_location (bl);
4132   /* If the condition is false, etc., don't do the commands.  */
4133   bs->commands = NULL;
4134   bs->old_val = NULL;
4135   bs->print_it = print_it_normal;
4136   return bs;
4137 }
4138 \f
4139 /* The target has stopped with waitstatus WS.  Check if any hardware
4140    watchpoints have triggered, according to the target.  */
4141
4142 int
4143 watchpoints_triggered (struct target_waitstatus *ws)
4144 {
4145   int stopped_by_watchpoint = target_stopped_by_watchpoint ();
4146   CORE_ADDR addr;
4147   struct breakpoint *b;
4148
4149   if (!stopped_by_watchpoint)
4150     {
4151       /* We were not stopped by a watchpoint.  Mark all watchpoints
4152          as not triggered.  */
4153       ALL_BREAKPOINTS (b)
4154         if (is_hardware_watchpoint (b))
4155           {
4156             struct watchpoint *w = (struct watchpoint *) b;
4157
4158             w->watchpoint_triggered = watch_triggered_no;
4159           }
4160
4161       return 0;
4162     }
4163
4164   if (!target_stopped_data_address (&current_target, &addr))
4165     {
4166       /* We were stopped by a watchpoint, but we don't know where.
4167          Mark all watchpoints as unknown.  */
4168       ALL_BREAKPOINTS (b)
4169         if (is_hardware_watchpoint (b))
4170           {
4171             struct watchpoint *w = (struct watchpoint *) b;
4172
4173             w->watchpoint_triggered = watch_triggered_unknown;
4174           }
4175
4176       return stopped_by_watchpoint;
4177     }
4178
4179   /* The target could report the data address.  Mark watchpoints
4180      affected by this data address as triggered, and all others as not
4181      triggered.  */
4182
4183   ALL_BREAKPOINTS (b)
4184     if (is_hardware_watchpoint (b))
4185       {
4186         struct watchpoint *w = (struct watchpoint *) b;
4187         struct bp_location *loc;
4188
4189         w->watchpoint_triggered = watch_triggered_no;
4190         for (loc = b->loc; loc; loc = loc->next)
4191           {
4192             if (is_masked_watchpoint (b))
4193               {
4194                 CORE_ADDR newaddr = addr & w->hw_wp_mask;
4195                 CORE_ADDR start = loc->address & w->hw_wp_mask;
4196
4197                 if (newaddr == start)
4198                   {
4199                     w->watchpoint_triggered = watch_triggered_yes;
4200                     break;
4201                   }
4202               }
4203             /* Exact match not required.  Within range is sufficient.  */
4204             else if (target_watchpoint_addr_within_range (&current_target,
4205                                                          addr, loc->address,
4206                                                          loc->length))
4207               {
4208                 w->watchpoint_triggered = watch_triggered_yes;
4209                 break;
4210               }
4211           }
4212       }
4213
4214   return 1;
4215 }
4216
4217 /* Possible return values for watchpoint_check (this can't be an enum
4218    because of check_errors).  */
4219 /* The watchpoint has been deleted.  */
4220 #define WP_DELETED 1
4221 /* The value has changed.  */
4222 #define WP_VALUE_CHANGED 2
4223 /* The value has not changed.  */
4224 #define WP_VALUE_NOT_CHANGED 3
4225 /* Ignore this watchpoint, no matter if the value changed or not.  */
4226 #define WP_IGNORE 4
4227
4228 #define BP_TEMPFLAG 1
4229 #define BP_HARDWAREFLAG 2
4230
4231 /* Evaluate watchpoint condition expression and check if its value
4232    changed.
4233
4234    P should be a pointer to struct bpstat, but is defined as a void *
4235    in order for this function to be usable with catch_errors.  */
4236
4237 static int
4238 watchpoint_check (void *p)
4239 {
4240   bpstat bs = (bpstat) p;
4241   struct watchpoint *b;
4242   struct frame_info *fr;
4243   int within_current_scope;
4244
4245   /* BS is built from an existing struct breakpoint.  */
4246   gdb_assert (bs->breakpoint_at != NULL);
4247   b = (struct watchpoint *) bs->breakpoint_at;
4248
4249   /* If this is a local watchpoint, we only want to check if the
4250      watchpoint frame is in scope if the current thread is the thread
4251      that was used to create the watchpoint.  */
4252   if (!watchpoint_in_thread_scope (b))
4253     return WP_IGNORE;
4254
4255   if (b->exp_valid_block == NULL)
4256     within_current_scope = 1;
4257   else
4258     {
4259       struct frame_info *frame = get_current_frame ();
4260       struct gdbarch *frame_arch = get_frame_arch (frame);
4261       CORE_ADDR frame_pc = get_frame_pc (frame);
4262
4263       /* in_function_epilogue_p() returns a non-zero value if we're
4264          still in the function but the stack frame has already been
4265          invalidated.  Since we can't rely on the values of local
4266          variables after the stack has been destroyed, we are treating
4267          the watchpoint in that state as `not changed' without further
4268          checking.  Don't mark watchpoints as changed if the current
4269          frame is in an epilogue - even if they are in some other
4270          frame, our view of the stack is likely to be wrong and
4271          frame_find_by_id could error out.  */
4272       if (gdbarch_in_function_epilogue_p (frame_arch, frame_pc))
4273         return WP_IGNORE;
4274
4275       fr = frame_find_by_id (b->watchpoint_frame);
4276       within_current_scope = (fr != NULL);
4277
4278       /* If we've gotten confused in the unwinder, we might have
4279          returned a frame that can't describe this variable.  */
4280       if (within_current_scope)
4281         {
4282           struct symbol *function;
4283
4284           function = get_frame_function (fr);
4285           if (function == NULL
4286               || !contained_in (b->exp_valid_block,
4287                                 SYMBOL_BLOCK_VALUE (function)))
4288             within_current_scope = 0;
4289         }
4290
4291       if (within_current_scope)
4292         /* If we end up stopping, the current frame will get selected
4293            in normal_stop.  So this call to select_frame won't affect
4294            the user.  */
4295         select_frame (fr);
4296     }
4297
4298   if (within_current_scope)
4299     {
4300       /* We use value_{,free_to_}mark because it could be a *long*
4301          time before we return to the command level and call
4302          free_all_values.  We can't call free_all_values because we
4303          might be in the middle of evaluating a function call.  */
4304
4305       int pc = 0;
4306       struct value *mark;
4307       struct value *new_val;
4308
4309       if (is_masked_watchpoint (&b->base))
4310         /* Since we don't know the exact trigger address (from
4311            stopped_data_address), just tell the user we've triggered
4312            a mask watchpoint.  */
4313         return WP_VALUE_CHANGED;
4314
4315       mark = value_mark ();
4316       fetch_subexp_value (b->exp, &pc, &new_val, NULL, NULL);
4317
4318       /* We use value_equal_contents instead of value_equal because
4319          the latter coerces an array to a pointer, thus comparing just
4320          the address of the array instead of its contents.  This is
4321          not what we want.  */
4322       if ((b->val != NULL) != (new_val != NULL)
4323           || (b->val != NULL && !value_equal_contents (b->val, new_val)))
4324         {
4325           if (new_val != NULL)
4326             {
4327               release_value (new_val);
4328               value_free_to_mark (mark);
4329             }
4330           bs->old_val = b->val;
4331           b->val = new_val;
4332           b->val_valid = 1;
4333           return WP_VALUE_CHANGED;
4334         }
4335       else
4336         {
4337           /* Nothing changed.  */
4338           value_free_to_mark (mark);
4339           return WP_VALUE_NOT_CHANGED;
4340         }
4341     }
4342   else
4343     {
4344       struct ui_out *uiout = current_uiout;
4345
4346       /* This seems like the only logical thing to do because
4347          if we temporarily ignored the watchpoint, then when
4348          we reenter the block in which it is valid it contains
4349          garbage (in the case of a function, it may have two
4350          garbage values, one before and one after the prologue).
4351          So we can't even detect the first assignment to it and
4352          watch after that (since the garbage may or may not equal
4353          the first value assigned).  */
4354       /* We print all the stop information in
4355          breakpoint_ops->print_it, but in this case, by the time we
4356          call breakpoint_ops->print_it this bp will be deleted
4357          already.  So we have no choice but print the information
4358          here.  */
4359       if (ui_out_is_mi_like_p (uiout))
4360         ui_out_field_string
4361           (uiout, "reason", async_reason_lookup (EXEC_ASYNC_WATCHPOINT_SCOPE));
4362       ui_out_text (uiout, "\nWatchpoint ");
4363       ui_out_field_int (uiout, "wpnum", b->base.number);
4364       ui_out_text (uiout,
4365                    " deleted because the program has left the block in\n\
4366 which its expression is valid.\n");     
4367
4368       /* Make sure the watchpoint's commands aren't executed.  */
4369       decref_counted_command_line (&b->base.commands);
4370       watchpoint_del_at_next_stop (b);
4371
4372       return WP_DELETED;
4373     }
4374 }
4375
4376 /* Return true if it looks like target has stopped due to hitting
4377    breakpoint location BL.  This function does not check if we should
4378    stop, only if BL explains the stop.  */
4379
4380 static int
4381 bpstat_check_location (const struct bp_location *bl,
4382                        struct address_space *aspace, CORE_ADDR bp_addr,
4383                        const struct target_waitstatus *ws)
4384 {
4385   struct breakpoint *b = bl->owner;
4386
4387   /* BL is from an existing breakpoint.  */
4388   gdb_assert (b != NULL);
4389
4390   return b->ops->breakpoint_hit (bl, aspace, bp_addr, ws);
4391 }
4392
4393 /* Determine if the watched values have actually changed, and we
4394    should stop.  If not, set BS->stop to 0.  */
4395
4396 static void
4397 bpstat_check_watchpoint (bpstat bs)
4398 {
4399   const struct bp_location *bl;
4400   struct watchpoint *b;
4401
4402   /* BS is built for existing struct breakpoint.  */
4403   bl = bs->bp_location_at;
4404   gdb_assert (bl != NULL);
4405   b = (struct watchpoint *) bs->breakpoint_at;
4406   gdb_assert (b != NULL);
4407
4408     {
4409       int must_check_value = 0;
4410       
4411       if (b->base.type == bp_watchpoint)
4412         /* For a software watchpoint, we must always check the
4413            watched value.  */
4414         must_check_value = 1;
4415       else if (b->watchpoint_triggered == watch_triggered_yes)
4416         /* We have a hardware watchpoint (read, write, or access)
4417            and the target earlier reported an address watched by
4418            this watchpoint.  */
4419         must_check_value = 1;
4420       else if (b->watchpoint_triggered == watch_triggered_unknown
4421                && b->base.type == bp_hardware_watchpoint)
4422         /* We were stopped by a hardware watchpoint, but the target could
4423            not report the data address.  We must check the watchpoint's
4424            value.  Access and read watchpoints are out of luck; without
4425            a data address, we can't figure it out.  */
4426         must_check_value = 1;
4427
4428       if (must_check_value)
4429         {
4430           char *message
4431             = xstrprintf ("Error evaluating expression for watchpoint %d\n",
4432                           b->base.number);
4433           struct cleanup *cleanups = make_cleanup (xfree, message);
4434           int e = catch_errors (watchpoint_check, bs, message,
4435                                 RETURN_MASK_ALL);
4436           do_cleanups (cleanups);
4437           switch (e)
4438             {
4439             case WP_DELETED:
4440               /* We've already printed what needs to be printed.  */
4441               bs->print_it = print_it_done;
4442               /* Stop.  */
4443               break;
4444             case WP_IGNORE:
4445               bs->print_it = print_it_noop;
4446               bs->stop = 0;
4447               break;
4448             case WP_VALUE_CHANGED:
4449               if (b->base.type == bp_read_watchpoint)
4450                 {
4451                   /* There are two cases to consider here:
4452
4453                      1. We're watching the triggered memory for reads.
4454                      In that case, trust the target, and always report
4455                      the watchpoint hit to the user.  Even though
4456                      reads don't cause value changes, the value may
4457                      have changed since the last time it was read, and
4458                      since we're not trapping writes, we will not see
4459                      those, and as such we should ignore our notion of
4460                      old value.
4461
4462                      2. We're watching the triggered memory for both
4463                      reads and writes.  There are two ways this may
4464                      happen:
4465
4466                      2.1. This is a target that can't break on data
4467                      reads only, but can break on accesses (reads or
4468                      writes), such as e.g., x86.  We detect this case
4469                      at the time we try to insert read watchpoints.
4470
4471                      2.2. Otherwise, the target supports read
4472                      watchpoints, but, the user set an access or write
4473                      watchpoint watching the same memory as this read
4474                      watchpoint.
4475
4476                      If we're watching memory writes as well as reads,
4477                      ignore watchpoint hits when we find that the
4478                      value hasn't changed, as reads don't cause
4479                      changes.  This still gives false positives when
4480                      the program writes the same value to memory as
4481                      what there was already in memory (we will confuse
4482                      it for a read), but it's much better than
4483                      nothing.  */
4484
4485                   int other_write_watchpoint = 0;
4486
4487                   if (bl->watchpoint_type == hw_read)
4488                     {
4489                       struct breakpoint *other_b;
4490
4491                       ALL_BREAKPOINTS (other_b)
4492                         if (other_b->type == bp_hardware_watchpoint
4493                             || other_b->type == bp_access_watchpoint)
4494                           {
4495                             struct watchpoint *other_w =
4496                               (struct watchpoint *) other_b;
4497
4498                             if (other_w->watchpoint_triggered
4499                                 == watch_triggered_yes)
4500                               {
4501                                 other_write_watchpoint = 1;
4502                                 break;
4503                               }
4504                           }
4505                     }
4506
4507                   if (other_write_watchpoint
4508                       || bl->watchpoint_type == hw_access)
4509                     {
4510                       /* We're watching the same memory for writes,
4511                          and the value changed since the last time we
4512                          updated it, so this trap must be for a write.
4513                          Ignore it.  */
4514                       bs->print_it = print_it_noop;
4515                       bs->stop = 0;
4516                     }
4517                 }
4518               break;
4519             case WP_VALUE_NOT_CHANGED:
4520               if (b->base.type == bp_hardware_watchpoint
4521                   || b->base.type == bp_watchpoint)
4522                 {
4523                   /* Don't stop: write watchpoints shouldn't fire if
4524                      the value hasn't changed.  */
4525                   bs->print_it = print_it_noop;
4526                   bs->stop = 0;
4527                 }
4528               /* Stop.  */
4529               break;
4530             default:
4531               /* Can't happen.  */
4532             case 0:
4533               /* Error from catch_errors.  */
4534               printf_filtered (_("Watchpoint %d deleted.\n"), b->base.number);
4535               watchpoint_del_at_next_stop (b);
4536               /* We've already printed what needs to be printed.  */
4537               bs->print_it = print_it_done;
4538               break;
4539             }
4540         }
4541       else      /* must_check_value == 0 */
4542         {
4543           /* This is a case where some watchpoint(s) triggered, but
4544              not at the address of this watchpoint, or else no
4545              watchpoint triggered after all.  So don't print
4546              anything for this watchpoint.  */
4547           bs->print_it = print_it_noop;
4548           bs->stop = 0;
4549         }
4550     }
4551 }
4552
4553
4554 /* Check conditions (condition proper, frame, thread and ignore count)
4555    of breakpoint referred to by BS.  If we should not stop for this
4556    breakpoint, set BS->stop to 0.  */
4557
4558 static void
4559 bpstat_check_breakpoint_conditions (bpstat bs, ptid_t ptid)
4560 {
4561   int thread_id = pid_to_thread_id (ptid);
4562   const struct bp_location *bl;
4563   struct breakpoint *b;
4564
4565   /* BS is built for existing struct breakpoint.  */
4566   bl = bs->bp_location_at;
4567   gdb_assert (bl != NULL);
4568   b = bs->breakpoint_at;
4569   gdb_assert (b != NULL);
4570
4571   /* Even if the target evaluated the condition on its end and notified GDB, we
4572      need to do so again since GDB does not know if we stopped due to a
4573      breakpoint or a single step breakpoint.  */
4574
4575   if (frame_id_p (b->frame_id)
4576       && !frame_id_eq (b->frame_id, get_stack_frame_id (get_current_frame ())))
4577     bs->stop = 0;
4578   else if (bs->stop)
4579     {
4580       int value_is_zero = 0;
4581       struct expression *cond;
4582
4583       /* Evaluate Python breakpoints that have a "stop"
4584          method implemented.  */
4585       if (b->py_bp_object)
4586         bs->stop = gdbpy_should_stop (b->py_bp_object);
4587
4588       if (is_watchpoint (b))
4589         {
4590           struct watchpoint *w = (struct watchpoint *) b;
4591
4592           cond = w->cond_exp;
4593         }
4594       else
4595         cond = bl->cond;
4596
4597       if (cond && b->disposition != disp_del_at_next_stop)
4598         {
4599           int within_current_scope = 1;
4600           struct watchpoint * w;
4601
4602           /* We use value_mark and value_free_to_mark because it could
4603              be a long time before we return to the command level and
4604              call free_all_values.  We can't call free_all_values
4605              because we might be in the middle of evaluating a
4606              function call.  */
4607           struct value *mark = value_mark ();
4608
4609           if (is_watchpoint (b))
4610             w = (struct watchpoint *) b;
4611           else
4612             w = NULL;
4613
4614           /* Need to select the frame, with all that implies so that
4615              the conditions will have the right context.  Because we
4616              use the frame, we will not see an inlined function's
4617              variables when we arrive at a breakpoint at the start
4618              of the inlined function; the current frame will be the
4619              call site.  */
4620           if (w == NULL || w->cond_exp_valid_block == NULL)
4621             select_frame (get_current_frame ());
4622           else
4623             {
4624               struct frame_info *frame;
4625
4626               /* For local watchpoint expressions, which particular
4627                  instance of a local is being watched matters, so we
4628                  keep track of the frame to evaluate the expression
4629                  in.  To evaluate the condition however, it doesn't
4630                  really matter which instantiation of the function
4631                  where the condition makes sense triggers the
4632                  watchpoint.  This allows an expression like "watch
4633                  global if q > 10" set in `func', catch writes to
4634                  global on all threads that call `func', or catch
4635                  writes on all recursive calls of `func' by a single
4636                  thread.  We simply always evaluate the condition in
4637                  the innermost frame that's executing where it makes
4638                  sense to evaluate the condition.  It seems
4639                  intuitive.  */
4640               frame = block_innermost_frame (w->cond_exp_valid_block);
4641               if (frame != NULL)
4642                 select_frame (frame);
4643               else
4644                 within_current_scope = 0;
4645             }
4646           if (within_current_scope)
4647             value_is_zero
4648               = catch_errors (breakpoint_cond_eval, cond,
4649                               "Error in testing breakpoint condition:\n",
4650                               RETURN_MASK_ALL);
4651           else
4652             {
4653               warning (_("Watchpoint condition cannot be tested "
4654                          "in the current scope"));
4655               /* If we failed to set the right context for this
4656                  watchpoint, unconditionally report it.  */
4657               value_is_zero = 0;
4658             }
4659           /* FIXME-someday, should give breakpoint #.  */
4660           value_free_to_mark (mark);
4661         }
4662
4663       if (cond && value_is_zero)
4664         {
4665           bs->stop = 0;
4666         }
4667       else if (b->thread != -1 && b->thread != thread_id)
4668         {
4669           bs->stop = 0;
4670         }
4671       else if (b->ignore_count > 0)
4672         {
4673           b->ignore_count--;
4674           annotate_ignore_count_change ();
4675           bs->stop = 0;
4676           /* Increase the hit count even though we don't stop.  */
4677           ++(b->hit_count);
4678           observer_notify_breakpoint_modified (b);
4679         }       
4680     }
4681 }
4682
4683
4684 /* Get a bpstat associated with having just stopped at address
4685    BP_ADDR in thread PTID.
4686
4687    Determine whether we stopped at a breakpoint, etc, or whether we
4688    don't understand this stop.  Result is a chain of bpstat's such
4689    that:
4690
4691    if we don't understand the stop, the result is a null pointer.
4692
4693    if we understand why we stopped, the result is not null.
4694
4695    Each element of the chain refers to a particular breakpoint or
4696    watchpoint at which we have stopped.  (We may have stopped for
4697    several reasons concurrently.)
4698
4699    Each element of the chain has valid next, breakpoint_at,
4700    commands, FIXME??? fields.  */
4701
4702 bpstat
4703 bpstat_stop_status (struct address_space *aspace,
4704                     CORE_ADDR bp_addr, ptid_t ptid,
4705                     const struct target_waitstatus *ws)
4706 {
4707   struct breakpoint *b = NULL;
4708   struct bp_location *bl;
4709   struct bp_location *loc;
4710   /* First item of allocated bpstat's.  */
4711   bpstat bs_head = NULL, *bs_link = &bs_head;
4712   /* Pointer to the last thing in the chain currently.  */
4713   bpstat bs;
4714   int ix;
4715   int need_remove_insert;
4716   int removed_any;
4717
4718   /* First, build the bpstat chain with locations that explain a
4719      target stop, while being careful to not set the target running,
4720      as that may invalidate locations (in particular watchpoint
4721      locations are recreated).  Resuming will happen here with
4722      breakpoint conditions or watchpoint expressions that include
4723      inferior function calls.  */
4724
4725   ALL_BREAKPOINTS (b)
4726     {
4727       if (!breakpoint_enabled (b) && b->enable_state != bp_permanent)
4728         continue;
4729
4730       for (bl = b->loc; bl != NULL; bl = bl->next)
4731         {
4732           /* For hardware watchpoints, we look only at the first
4733              location.  The watchpoint_check function will work on the
4734              entire expression, not the individual locations.  For
4735              read watchpoints, the watchpoints_triggered function has
4736              checked all locations already.  */
4737           if (b->type == bp_hardware_watchpoint && bl != b->loc)
4738             break;
4739
4740           if (bl->shlib_disabled)
4741             continue;
4742
4743           if (!bpstat_check_location (bl, aspace, bp_addr, ws))
4744             continue;
4745
4746           /* Come here if it's a watchpoint, or if the break address
4747              matches.  */
4748
4749           bs = bpstat_alloc (bl, &bs_link);     /* Alloc a bpstat to
4750                                                    explain stop.  */
4751
4752           /* Assume we stop.  Should we find a watchpoint that is not
4753              actually triggered, or if the condition of the breakpoint
4754              evaluates as false, we'll reset 'stop' to 0.  */
4755           bs->stop = 1;
4756           bs->print = 1;
4757
4758           /* If this is a scope breakpoint, mark the associated
4759              watchpoint as triggered so that we will handle the
4760              out-of-scope event.  We'll get to the watchpoint next
4761              iteration.  */
4762           if (b->type == bp_watchpoint_scope && b->related_breakpoint != b)
4763             {
4764               struct watchpoint *w = (struct watchpoint *) b->related_breakpoint;
4765
4766               w->watchpoint_triggered = watch_triggered_yes;
4767             }
4768         }
4769     }
4770
4771   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
4772     {
4773       if (breakpoint_location_address_match (loc, aspace, bp_addr))
4774         {
4775           bs = bpstat_alloc (loc, &bs_link);
4776           /* For hits of moribund locations, we should just proceed.  */
4777           bs->stop = 0;
4778           bs->print = 0;
4779           bs->print_it = print_it_noop;
4780         }
4781     }
4782
4783   /* A bit of special processing for shlib breakpoints.  We need to
4784      process solib loading here, so that the lists of loaded and
4785      unloaded libraries are correct before we handle "catch load" and
4786      "catch unload".  */
4787   for (bs = bs_head; bs != NULL; bs = bs->next)
4788     {
4789       if (bs->breakpoint_at && bs->breakpoint_at->type == bp_shlib_event)
4790         {
4791           handle_solib_event ();
4792           break;
4793         }
4794     }
4795
4796   /* Now go through the locations that caused the target to stop, and
4797      check whether we're interested in reporting this stop to higher
4798      layers, or whether we should resume the target transparently.  */
4799
4800   removed_any = 0;
4801
4802   for (bs = bs_head; bs != NULL; bs = bs->next)
4803     {
4804       if (!bs->stop)
4805         continue;
4806
4807       b = bs->breakpoint_at;
4808       b->ops->check_status (bs);
4809       if (bs->stop)
4810         {
4811           bpstat_check_breakpoint_conditions (bs, ptid);
4812
4813           if (bs->stop)
4814             {
4815               ++(b->hit_count);
4816               observer_notify_breakpoint_modified (b);
4817
4818               /* We will stop here.  */
4819               if (b->disposition == disp_disable)
4820                 {
4821                   --(b->enable_count);
4822                   if (b->enable_count <= 0
4823                       && b->enable_state != bp_permanent)
4824                     b->enable_state = bp_disabled;
4825                   removed_any = 1;
4826                 }
4827               if (b->silent)
4828                 bs->print = 0;
4829               bs->commands = b->commands;
4830               incref_counted_command_line (bs->commands);
4831               if (command_line_is_silent (bs->commands
4832                                           ? bs->commands->commands : NULL))
4833                 bs->print = 0;
4834             }
4835
4836         }
4837
4838       /* Print nothing for this entry if we don't stop or don't
4839          print.  */
4840       if (!bs->stop || !bs->print)
4841         bs->print_it = print_it_noop;
4842     }
4843
4844   /* If we aren't stopping, the value of some hardware watchpoint may
4845      not have changed, but the intermediate memory locations we are
4846      watching may have.  Don't bother if we're stopping; this will get
4847      done later.  */
4848   need_remove_insert = 0;
4849   if (! bpstat_causes_stop (bs_head))
4850     for (bs = bs_head; bs != NULL; bs = bs->next)
4851       if (!bs->stop
4852           && bs->breakpoint_at
4853           && is_hardware_watchpoint (bs->breakpoint_at))
4854         {
4855           struct watchpoint *w = (struct watchpoint *) bs->breakpoint_at;
4856
4857           update_watchpoint (w, 0 /* don't reparse.  */);
4858           need_remove_insert = 1;
4859         }
4860
4861   if (need_remove_insert)
4862     update_global_location_list (1);
4863   else if (removed_any)
4864     update_global_location_list (0);
4865
4866   return bs_head;
4867 }
4868
4869 static void
4870 handle_jit_event (void)
4871 {
4872   struct frame_info *frame;
4873   struct gdbarch *gdbarch;
4874
4875   /* Switch terminal for any messages produced by
4876      breakpoint_re_set.  */
4877   target_terminal_ours_for_output ();
4878
4879   frame = get_current_frame ();
4880   gdbarch = get_frame_arch (frame);
4881
4882   jit_event_handler (gdbarch);
4883
4884   target_terminal_inferior ();
4885 }
4886
4887 /* Handle an solib event by calling solib_add.  */
4888
4889 void
4890 handle_solib_event (void)
4891 {
4892   clear_program_space_solib_cache (current_inferior ()->pspace);
4893
4894   /* Check for any newly added shared libraries if we're supposed to
4895      be adding them automatically.  Switch terminal for any messages
4896      produced by breakpoint_re_set.  */
4897   target_terminal_ours_for_output ();
4898 #ifdef SOLIB_ADD
4899   SOLIB_ADD (NULL, 0, &current_target, auto_solib_add);
4900 #else
4901   solib_add (NULL, 0, &current_target, auto_solib_add);
4902 #endif
4903   target_terminal_inferior ();
4904 }
4905
4906 /* Prepare WHAT final decision for infrun.  */
4907
4908 /* Decide what infrun needs to do with this bpstat.  */
4909
4910 struct bpstat_what
4911 bpstat_what (bpstat bs_head)
4912 {
4913   struct bpstat_what retval;
4914   int jit_event = 0;
4915   bpstat bs;
4916
4917   retval.main_action = BPSTAT_WHAT_KEEP_CHECKING;
4918   retval.call_dummy = STOP_NONE;
4919   retval.is_longjmp = 0;
4920
4921   for (bs = bs_head; bs != NULL; bs = bs->next)
4922     {
4923       /* Extract this BS's action.  After processing each BS, we check
4924          if its action overrides all we've seem so far.  */
4925       enum bpstat_what_main_action this_action = BPSTAT_WHAT_KEEP_CHECKING;
4926       enum bptype bptype;
4927
4928       if (bs->breakpoint_at == NULL)
4929         {
4930           /* I suspect this can happen if it was a momentary
4931              breakpoint which has since been deleted.  */
4932           bptype = bp_none;
4933         }
4934       else
4935         bptype = bs->breakpoint_at->type;
4936
4937       switch (bptype)
4938         {
4939         case bp_none:
4940           break;
4941         case bp_breakpoint:
4942         case bp_hardware_breakpoint:
4943         case bp_until:
4944         case bp_finish:
4945         case bp_shlib_event:
4946           if (bs->stop)
4947             {
4948               if (bs->print)
4949                 this_action = BPSTAT_WHAT_STOP_NOISY;
4950               else
4951                 this_action = BPSTAT_WHAT_STOP_SILENT;
4952             }
4953           else
4954             this_action = BPSTAT_WHAT_SINGLE;
4955           break;
4956         case bp_watchpoint:
4957         case bp_hardware_watchpoint:
4958         case bp_read_watchpoint:
4959         case bp_access_watchpoint:
4960           if (bs->stop)
4961             {
4962               if (bs->print)
4963                 this_action = BPSTAT_WHAT_STOP_NOISY;
4964               else
4965                 this_action = BPSTAT_WHAT_STOP_SILENT;
4966             }
4967           else
4968             {
4969               /* There was a watchpoint, but we're not stopping.
4970                  This requires no further action.  */
4971             }
4972           break;
4973         case bp_longjmp:
4974         case bp_exception:
4975           this_action = BPSTAT_WHAT_SET_LONGJMP_RESUME;
4976           retval.is_longjmp = bptype == bp_longjmp;
4977           break;
4978         case bp_longjmp_resume:
4979         case bp_exception_resume:
4980           this_action = BPSTAT_WHAT_CLEAR_LONGJMP_RESUME;
4981           retval.is_longjmp = bptype == bp_longjmp_resume;
4982           break;
4983         case bp_step_resume:
4984           if (bs->stop)
4985             this_action = BPSTAT_WHAT_STEP_RESUME;
4986           else
4987             {
4988               /* It is for the wrong frame.  */
4989               this_action = BPSTAT_WHAT_SINGLE;
4990             }
4991           break;
4992         case bp_hp_step_resume:
4993           if (bs->stop)
4994             this_action = BPSTAT_WHAT_HP_STEP_RESUME;
4995           else
4996             {
4997               /* It is for the wrong frame.  */
4998               this_action = BPSTAT_WHAT_SINGLE;
4999             }
5000           break;
5001         case bp_watchpoint_scope:
5002         case bp_thread_event:
5003         case bp_overlay_event:
5004         case bp_longjmp_master:
5005         case bp_std_terminate_master:
5006         case bp_exception_master:
5007           this_action = BPSTAT_WHAT_SINGLE;
5008           break;
5009         case bp_catchpoint:
5010           if (bs->stop)
5011             {
5012               if (bs->print)
5013                 this_action = BPSTAT_WHAT_STOP_NOISY;
5014               else
5015                 this_action = BPSTAT_WHAT_STOP_SILENT;
5016             }
5017           else
5018             {
5019               /* There was a catchpoint, but we're not stopping.
5020                  This requires no further action.  */
5021             }
5022           break;
5023         case bp_jit_event:
5024           jit_event = 1;
5025           this_action = BPSTAT_WHAT_SINGLE;
5026           break;
5027         case bp_call_dummy:
5028           /* Make sure the action is stop (silent or noisy),
5029              so infrun.c pops the dummy frame.  */
5030           retval.call_dummy = STOP_STACK_DUMMY;
5031           this_action = BPSTAT_WHAT_STOP_SILENT;
5032           break;
5033         case bp_std_terminate:
5034           /* Make sure the action is stop (silent or noisy),
5035              so infrun.c pops the dummy frame.  */
5036           retval.call_dummy = STOP_STD_TERMINATE;
5037           this_action = BPSTAT_WHAT_STOP_SILENT;
5038           break;
5039         case bp_tracepoint:
5040         case bp_fast_tracepoint:
5041         case bp_static_tracepoint:
5042           /* Tracepoint hits should not be reported back to GDB, and
5043              if one got through somehow, it should have been filtered
5044              out already.  */
5045           internal_error (__FILE__, __LINE__,
5046                           _("bpstat_what: tracepoint encountered"));
5047           break;
5048         case bp_gnu_ifunc_resolver:
5049           /* Step over it (and insert bp_gnu_ifunc_resolver_return).  */
5050           this_action = BPSTAT_WHAT_SINGLE;
5051           break;
5052         case bp_gnu_ifunc_resolver_return:
5053           /* The breakpoint will be removed, execution will restart from the
5054              PC of the former breakpoint.  */
5055           this_action = BPSTAT_WHAT_KEEP_CHECKING;
5056           break;
5057         default:
5058           internal_error (__FILE__, __LINE__,
5059                           _("bpstat_what: unhandled bptype %d"), (int) bptype);
5060         }
5061
5062       retval.main_action = max (retval.main_action, this_action);
5063     }
5064
5065   /* These operations may affect the bs->breakpoint_at state so they are
5066      delayed after MAIN_ACTION is decided above.  */
5067
5068   if (jit_event)
5069     {
5070       if (debug_infrun)
5071         fprintf_unfiltered (gdb_stdlog, "bpstat_what: bp_jit_event\n");
5072
5073       handle_jit_event ();
5074     }
5075
5076   for (bs = bs_head; bs != NULL; bs = bs->next)
5077     {
5078       struct breakpoint *b = bs->breakpoint_at;
5079
5080       if (b == NULL)
5081         continue;
5082       switch (b->type)
5083         {
5084         case bp_gnu_ifunc_resolver:
5085           gnu_ifunc_resolver_stop (b);
5086           break;
5087         case bp_gnu_ifunc_resolver_return:
5088           gnu_ifunc_resolver_return_stop (b);
5089           break;
5090         }
5091     }
5092
5093   return retval;
5094 }
5095
5096 /* Nonzero if we should step constantly (e.g. watchpoints on machines
5097    without hardware support).  This isn't related to a specific bpstat,
5098    just to things like whether watchpoints are set.  */
5099
5100 int
5101 bpstat_should_step (void)
5102 {
5103   struct breakpoint *b;
5104
5105   ALL_BREAKPOINTS (b)
5106     if (breakpoint_enabled (b) && b->type == bp_watchpoint && b->loc != NULL)
5107       return 1;
5108   return 0;
5109 }
5110
5111 int
5112 bpstat_causes_stop (bpstat bs)
5113 {
5114   for (; bs != NULL; bs = bs->next)
5115     if (bs->stop)
5116       return 1;
5117
5118   return 0;
5119 }
5120
5121 \f
5122
5123 /* Compute a string of spaces suitable to indent the next line
5124    so it starts at the position corresponding to the table column
5125    named COL_NAME in the currently active table of UIOUT.  */
5126
5127 static char *
5128 wrap_indent_at_field (struct ui_out *uiout, const char *col_name)
5129 {
5130   static char wrap_indent[80];
5131   int i, total_width, width, align;
5132   char *text;
5133
5134   total_width = 0;
5135   for (i = 1; ui_out_query_field (uiout, i, &width, &align, &text); i++)
5136     {
5137       if (strcmp (text, col_name) == 0)
5138         {
5139           gdb_assert (total_width < sizeof wrap_indent);
5140           memset (wrap_indent, ' ', total_width);
5141           wrap_indent[total_width] = 0;
5142
5143           return wrap_indent;
5144         }
5145
5146       total_width += width + 1;
5147     }
5148
5149   return NULL;
5150 }
5151
5152 /* Determine if the locations of this breakpoint will have their conditions
5153    evaluated by the target, host or a mix of both.  Returns the following:
5154
5155     "host": Host evals condition.
5156     "host or target": Host or Target evals condition.
5157     "target": Target evals condition.
5158 */
5159
5160 static const char *
5161 bp_condition_evaluator (struct breakpoint *b)
5162 {
5163   struct bp_location *bl;
5164   char host_evals = 0;
5165   char target_evals = 0;
5166
5167   if (!b)
5168     return NULL;
5169
5170   if (!is_breakpoint (b))
5171     return NULL;
5172
5173   if (gdb_evaluates_breakpoint_condition_p ()
5174       || !target_supports_evaluation_of_breakpoint_conditions ())
5175     return condition_evaluation_host;
5176
5177   for (bl = b->loc; bl; bl = bl->next)
5178     {
5179       if (bl->cond_bytecode)
5180         target_evals++;
5181       else
5182         host_evals++;
5183     }
5184
5185   if (host_evals && target_evals)
5186     return condition_evaluation_both;
5187   else if (target_evals)
5188     return condition_evaluation_target;
5189   else
5190     return condition_evaluation_host;
5191 }
5192
5193 /* Determine the breakpoint location's condition evaluator.  This is
5194    similar to bp_condition_evaluator, but for locations.  */
5195
5196 static const char *
5197 bp_location_condition_evaluator (struct bp_location *bl)
5198 {
5199   if (bl && !is_breakpoint (bl->owner))
5200     return NULL;
5201
5202   if (gdb_evaluates_breakpoint_condition_p ()
5203       || !target_supports_evaluation_of_breakpoint_conditions ())
5204     return condition_evaluation_host;
5205
5206   if (bl && bl->cond_bytecode)
5207     return condition_evaluation_target;
5208   else
5209     return condition_evaluation_host;
5210 }
5211
5212 /* Print the LOC location out of the list of B->LOC locations.  */
5213
5214 static void
5215 print_breakpoint_location (struct breakpoint *b,
5216                            struct bp_location *loc)
5217 {
5218   struct ui_out *uiout = current_uiout;
5219   struct cleanup *old_chain = save_current_program_space ();
5220
5221   if (loc != NULL && loc->shlib_disabled)
5222     loc = NULL;
5223
5224   if (loc != NULL)
5225     set_current_program_space (loc->pspace);
5226
5227   if (b->display_canonical)
5228     ui_out_field_string (uiout, "what", b->addr_string);
5229   else if (loc && loc->source_file)
5230     {
5231       struct symbol *sym 
5232         = find_pc_sect_function (loc->address, loc->section);
5233       if (sym)
5234         {
5235           ui_out_text (uiout, "in ");
5236           ui_out_field_string (uiout, "func",
5237                                SYMBOL_PRINT_NAME (sym));
5238           ui_out_text (uiout, " ");
5239           ui_out_wrap_hint (uiout, wrap_indent_at_field (uiout, "what"));
5240           ui_out_text (uiout, "at ");
5241         }
5242       ui_out_field_string (uiout, "file", loc->source_file);
5243       ui_out_text (uiout, ":");
5244       
5245       if (ui_out_is_mi_like_p (uiout))
5246         {
5247           struct symtab_and_line sal = find_pc_line (loc->address, 0);
5248           char *fullname = symtab_to_fullname (sal.symtab);
5249           
5250           if (fullname)
5251             ui_out_field_string (uiout, "fullname", fullname);
5252         }
5253       
5254       ui_out_field_int (uiout, "line", loc->line_number);
5255     }
5256   else if (loc)
5257     {
5258       struct ui_stream *stb = ui_out_stream_new (uiout);
5259       struct cleanup *stb_chain = make_cleanup_ui_out_stream_delete (stb);
5260
5261       print_address_symbolic (loc->gdbarch, loc->address, stb->stream,
5262                               demangle, "");
5263       ui_out_field_stream (uiout, "at", stb);
5264
5265       do_cleanups (stb_chain);
5266     }
5267   else
5268     ui_out_field_string (uiout, "pending", b->addr_string);
5269
5270   if (loc && is_breakpoint (b)
5271       && breakpoint_condition_evaluation_mode () == condition_evaluation_target
5272       && bp_condition_evaluator (b) == condition_evaluation_both)
5273     {
5274       ui_out_text (uiout, " (");
5275       ui_out_field_string (uiout, "evaluated-by",
5276                            bp_location_condition_evaluator (loc));
5277       ui_out_text (uiout, ")");
5278     }
5279
5280   do_cleanups (old_chain);
5281 }
5282
5283 static const char *
5284 bptype_string (enum bptype type)
5285 {
5286   struct ep_type_description
5287     {
5288       enum bptype type;
5289       char *description;
5290     };
5291   static struct ep_type_description bptypes[] =
5292   {
5293     {bp_none, "?deleted?"},
5294     {bp_breakpoint, "breakpoint"},
5295     {bp_hardware_breakpoint, "hw breakpoint"},
5296     {bp_until, "until"},
5297     {bp_finish, "finish"},
5298     {bp_watchpoint, "watchpoint"},
5299     {bp_hardware_watchpoint, "hw watchpoint"},
5300     {bp_read_watchpoint, "read watchpoint"},
5301     {bp_access_watchpoint, "acc watchpoint"},
5302     {bp_longjmp, "longjmp"},
5303     {bp_longjmp_resume, "longjmp resume"},
5304     {bp_exception, "exception"},
5305     {bp_exception_resume, "exception resume"},
5306     {bp_step_resume, "step resume"},
5307     {bp_hp_step_resume, "high-priority step resume"},
5308     {bp_watchpoint_scope, "watchpoint scope"},
5309     {bp_call_dummy, "call dummy"},
5310     {bp_std_terminate, "std::terminate"},
5311     {bp_shlib_event, "shlib events"},
5312     {bp_thread_event, "thread events"},
5313     {bp_overlay_event, "overlay events"},
5314     {bp_longjmp_master, "longjmp master"},
5315     {bp_std_terminate_master, "std::terminate master"},
5316     {bp_exception_master, "exception master"},
5317     {bp_catchpoint, "catchpoint"},
5318     {bp_tracepoint, "tracepoint"},
5319     {bp_fast_tracepoint, "fast tracepoint"},
5320     {bp_static_tracepoint, "static tracepoint"},
5321     {bp_jit_event, "jit events"},
5322     {bp_gnu_ifunc_resolver, "STT_GNU_IFUNC resolver"},
5323     {bp_gnu_ifunc_resolver_return, "STT_GNU_IFUNC resolver return"},
5324   };
5325
5326   if (((int) type >= (sizeof (bptypes) / sizeof (bptypes[0])))
5327       || ((int) type != bptypes[(int) type].type))
5328     internal_error (__FILE__, __LINE__,
5329                     _("bptypes table does not describe type #%d."),
5330                     (int) type);
5331
5332   return bptypes[(int) type].description;
5333 }
5334
5335 /* Print B to gdb_stdout.  */
5336
5337 static void
5338 print_one_breakpoint_location (struct breakpoint *b,
5339                                struct bp_location *loc,
5340                                int loc_number,
5341                                struct bp_location **last_loc,
5342                                int allflag)
5343 {
5344   struct command_line *l;
5345   static char bpenables[] = "nynny";
5346
5347   struct ui_out *uiout = current_uiout;
5348   int header_of_multiple = 0;
5349   int part_of_multiple = (loc != NULL);
5350   struct value_print_options opts;
5351
5352   get_user_print_options (&opts);
5353
5354   gdb_assert (!loc || loc_number != 0);
5355   /* See comment in print_one_breakpoint concerning treatment of
5356      breakpoints with single disabled location.  */
5357   if (loc == NULL 
5358       && (b->loc != NULL 
5359           && (b->loc->next != NULL || !b->loc->enabled)))
5360     header_of_multiple = 1;
5361   if (loc == NULL)
5362     loc = b->loc;
5363
5364   annotate_record ();
5365
5366   /* 1 */
5367   annotate_field (0);
5368   if (part_of_multiple)
5369     {
5370       char *formatted;
5371       formatted = xstrprintf ("%d.%d", b->number, loc_number);
5372       ui_out_field_string (uiout, "number", formatted);
5373       xfree (formatted);
5374     }
5375   else
5376     {
5377       ui_out_field_int (uiout, "number", b->number);
5378     }
5379
5380   /* 2 */
5381   annotate_field (1);
5382   if (part_of_multiple)
5383     ui_out_field_skip (uiout, "type");
5384   else
5385     ui_out_field_string (uiout, "type", bptype_string (b->type));
5386
5387   /* 3 */
5388   annotate_field (2);
5389   if (part_of_multiple)
5390     ui_out_field_skip (uiout, "disp");
5391   else
5392     ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
5393
5394
5395   /* 4 */
5396   annotate_field (3);
5397   if (part_of_multiple)
5398     ui_out_field_string (uiout, "enabled", loc->enabled ? "y" : "n");
5399   else
5400     ui_out_field_fmt (uiout, "enabled", "%c", 
5401                       bpenables[(int) b->enable_state]);
5402   ui_out_spaces (uiout, 2);
5403
5404   
5405   /* 5 and 6 */
5406   if (b->ops != NULL && b->ops->print_one != NULL)
5407     {
5408       /* Although the print_one can possibly print all locations,
5409          calling it here is not likely to get any nice result.  So,
5410          make sure there's just one location.  */
5411       gdb_assert (b->loc == NULL || b->loc->next == NULL);
5412       b->ops->print_one (b, last_loc);
5413     }
5414   else
5415     switch (b->type)
5416       {
5417       case bp_none:
5418         internal_error (__FILE__, __LINE__,
5419                         _("print_one_breakpoint: bp_none encountered\n"));
5420         break;
5421
5422       case bp_watchpoint:
5423       case bp_hardware_watchpoint:
5424       case bp_read_watchpoint:
5425       case bp_access_watchpoint:
5426         {
5427           struct watchpoint *w = (struct watchpoint *) b;
5428
5429           /* Field 4, the address, is omitted (which makes the columns
5430              not line up too nicely with the headers, but the effect
5431              is relatively readable).  */
5432           if (opts.addressprint)
5433             ui_out_field_skip (uiout, "addr");
5434           annotate_field (5);
5435           ui_out_field_string (uiout, "what", w->exp_string);
5436         }
5437         break;
5438
5439       case bp_breakpoint:
5440       case bp_hardware_breakpoint:
5441       case bp_until:
5442       case bp_finish:
5443       case bp_longjmp:
5444       case bp_longjmp_resume:
5445       case bp_exception:
5446       case bp_exception_resume:
5447       case bp_step_resume:
5448       case bp_hp_step_resume:
5449       case bp_watchpoint_scope:
5450       case bp_call_dummy:
5451       case bp_std_terminate:
5452       case bp_shlib_event:
5453       case bp_thread_event:
5454       case bp_overlay_event:
5455       case bp_longjmp_master:
5456       case bp_std_terminate_master:
5457       case bp_exception_master:
5458       case bp_tracepoint:
5459       case bp_fast_tracepoint:
5460       case bp_static_tracepoint:
5461       case bp_jit_event:
5462       case bp_gnu_ifunc_resolver:
5463       case bp_gnu_ifunc_resolver_return:
5464         if (opts.addressprint)
5465           {
5466             annotate_field (4);
5467             if (header_of_multiple)
5468               ui_out_field_string (uiout, "addr", "<MULTIPLE>");
5469             else if (b->loc == NULL || loc->shlib_disabled)
5470               ui_out_field_string (uiout, "addr", "<PENDING>");
5471             else
5472               ui_out_field_core_addr (uiout, "addr",
5473                                       loc->gdbarch, loc->address);
5474           }
5475         annotate_field (5);
5476         if (!header_of_multiple)
5477           print_breakpoint_location (b, loc);
5478         if (b->loc)
5479           *last_loc = b->loc;
5480         break;
5481       }
5482
5483
5484   /* For backward compatibility, don't display inferiors unless there
5485      are several.  */
5486   if (loc != NULL
5487       && !header_of_multiple
5488       && (allflag
5489           || (!gdbarch_has_global_breakpoints (target_gdbarch)
5490               && (number_of_program_spaces () > 1
5491                   || number_of_inferiors () > 1)
5492               /* LOC is for existing B, it cannot be in
5493                  moribund_locations and thus having NULL OWNER.  */
5494               && loc->owner->type != bp_catchpoint)))
5495     {
5496       struct inferior *inf;
5497       int first = 1;
5498
5499       for (inf = inferior_list; inf != NULL; inf = inf->next)
5500         {
5501           if (inf->pspace == loc->pspace)
5502             {
5503               if (first)
5504                 {
5505                   first = 0;
5506                   ui_out_text (uiout, " inf ");
5507                 }
5508               else
5509                 ui_out_text (uiout, ", ");
5510               ui_out_text (uiout, plongest (inf->num));
5511             }
5512         }
5513     }
5514
5515   if (!part_of_multiple)
5516     {
5517       if (b->thread != -1)
5518         {
5519           /* FIXME: This seems to be redundant and lost here; see the
5520              "stop only in" line a little further down.  */
5521           ui_out_text (uiout, " thread ");
5522           ui_out_field_int (uiout, "thread", b->thread);
5523         }
5524       else if (b->task != 0)
5525         {
5526           ui_out_text (uiout, " task ");
5527           ui_out_field_int (uiout, "task", b->task);
5528         }
5529     }
5530
5531   ui_out_text (uiout, "\n");
5532
5533   if (!part_of_multiple)
5534     b->ops->print_one_detail (b, uiout);
5535
5536   if (part_of_multiple && frame_id_p (b->frame_id))
5537     {
5538       annotate_field (6);
5539       ui_out_text (uiout, "\tstop only in stack frame at ");
5540       /* FIXME: cagney/2002-12-01: Shouldn't be poking around inside
5541          the frame ID.  */
5542       ui_out_field_core_addr (uiout, "frame",
5543                               b->gdbarch, b->frame_id.stack_addr);
5544       ui_out_text (uiout, "\n");
5545     }
5546   
5547   if (!part_of_multiple && b->cond_string)
5548     {
5549       annotate_field (7);
5550       if (is_tracepoint (b))
5551         ui_out_text (uiout, "\ttrace only if ");
5552       else
5553         ui_out_text (uiout, "\tstop only if ");
5554       ui_out_field_string (uiout, "cond", b->cond_string);
5555
5556       /* Print whether the target is doing the breakpoint's condition
5557          evaluation.  If GDB is doing the evaluation, don't print anything.  */
5558       if (is_breakpoint (b)
5559           && breakpoint_condition_evaluation_mode ()
5560           == condition_evaluation_target)
5561         {
5562           ui_out_text (uiout, " (");
5563           ui_out_field_string (uiout, "evaluated-by",
5564                                bp_condition_evaluator (b));
5565           ui_out_text (uiout, " evals)");
5566         }
5567       ui_out_text (uiout, "\n");
5568     }
5569
5570   if (!part_of_multiple && b->thread != -1)
5571     {
5572       /* FIXME should make an annotation for this.  */
5573       ui_out_text (uiout, "\tstop only in thread ");
5574       ui_out_field_int (uiout, "thread", b->thread);
5575       ui_out_text (uiout, "\n");
5576     }
5577   
5578   if (!part_of_multiple && b->hit_count)
5579     {
5580       /* FIXME should make an annotation for this.  */
5581       if (ep_is_catchpoint (b))
5582         ui_out_text (uiout, "\tcatchpoint");
5583       else if (is_tracepoint (b))
5584         ui_out_text (uiout, "\ttracepoint");
5585       else
5586         ui_out_text (uiout, "\tbreakpoint");
5587       ui_out_text (uiout, " already hit ");
5588       ui_out_field_int (uiout, "times", b->hit_count);
5589       if (b->hit_count == 1)
5590         ui_out_text (uiout, " time\n");
5591       else
5592         ui_out_text (uiout, " times\n");
5593     }
5594   
5595   /* Output the count also if it is zero, but only if this is mi.
5596      FIXME: Should have a better test for this.  */
5597   if (ui_out_is_mi_like_p (uiout))
5598     if (!part_of_multiple && b->hit_count == 0)
5599       ui_out_field_int (uiout, "times", b->hit_count);
5600
5601   if (!part_of_multiple && b->ignore_count)
5602     {
5603       annotate_field (8);
5604       ui_out_text (uiout, "\tignore next ");
5605       ui_out_field_int (uiout, "ignore", b->ignore_count);
5606       ui_out_text (uiout, " hits\n");
5607     }
5608
5609   /* Note that an enable count of 1 corresponds to "enable once"
5610      behavior, which is reported by the combination of enablement and
5611      disposition, so we don't need to mention it here.  */
5612   if (!part_of_multiple && b->enable_count > 1)
5613     {
5614       annotate_field (8);
5615       ui_out_text (uiout, "\tdisable after ");
5616       /* Tweak the wording to clarify that ignore and enable counts
5617          are distinct, and have additive effect.  */
5618       if (b->ignore_count)
5619         ui_out_text (uiout, "additional ");
5620       else
5621         ui_out_text (uiout, "next ");
5622       ui_out_field_int (uiout, "enable", b->enable_count);
5623       ui_out_text (uiout, " hits\n");
5624     }
5625
5626   if (!part_of_multiple && is_tracepoint (b))
5627     {
5628       struct tracepoint *tp = (struct tracepoint *) b;
5629
5630       if (tp->traceframe_usage)
5631         {
5632           ui_out_text (uiout, "\ttrace buffer usage ");
5633           ui_out_field_int (uiout, "traceframe-usage", tp->traceframe_usage);
5634           ui_out_text (uiout, " bytes\n");
5635         }
5636     }
5637   
5638   l = b->commands ? b->commands->commands : NULL;
5639   if (!part_of_multiple && l)
5640     {
5641       struct cleanup *script_chain;
5642
5643       annotate_field (9);
5644       script_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "script");
5645       print_command_lines (uiout, l, 4);
5646       do_cleanups (script_chain);
5647     }
5648
5649   if (is_tracepoint (b))
5650     {
5651       struct tracepoint *t = (struct tracepoint *) b;
5652
5653       if (!part_of_multiple && t->pass_count)
5654         {
5655           annotate_field (10);
5656           ui_out_text (uiout, "\tpass count ");
5657           ui_out_field_int (uiout, "pass", t->pass_count);
5658           ui_out_text (uiout, " \n");
5659         }
5660     }
5661
5662   if (ui_out_is_mi_like_p (uiout) && !part_of_multiple)
5663     {
5664       if (is_watchpoint (b))
5665         {
5666           struct watchpoint *w = (struct watchpoint *) b;
5667
5668           ui_out_field_string (uiout, "original-location", w->exp_string);
5669         }
5670       else if (b->addr_string)
5671         ui_out_field_string (uiout, "original-location", b->addr_string);
5672     }
5673 }
5674
5675 static void
5676 print_one_breakpoint (struct breakpoint *b,
5677                       struct bp_location **last_loc, 
5678                       int allflag)
5679 {
5680   struct cleanup *bkpt_chain;
5681   struct ui_out *uiout = current_uiout;
5682
5683   bkpt_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "bkpt");
5684
5685   print_one_breakpoint_location (b, NULL, 0, last_loc, allflag);
5686   do_cleanups (bkpt_chain);
5687
5688   /* If this breakpoint has custom print function,
5689      it's already printed.  Otherwise, print individual
5690      locations, if any.  */
5691   if (b->ops == NULL || b->ops->print_one == NULL)
5692     {
5693       /* If breakpoint has a single location that is disabled, we
5694          print it as if it had several locations, since otherwise it's
5695          hard to represent "breakpoint enabled, location disabled"
5696          situation.
5697
5698          Note that while hardware watchpoints have several locations
5699          internally, that's not a property exposed to user.  */
5700       if (b->loc 
5701           && !is_hardware_watchpoint (b)
5702           && (b->loc->next || !b->loc->enabled))
5703         {
5704           struct bp_location *loc;
5705           int n = 1;
5706
5707           for (loc = b->loc; loc; loc = loc->next, ++n)
5708             {
5709               struct cleanup *inner2 =
5710                 make_cleanup_ui_out_tuple_begin_end (uiout, NULL);
5711               print_one_breakpoint_location (b, loc, n, last_loc, allflag);
5712               do_cleanups (inner2);
5713             }
5714         }
5715     }
5716 }
5717
5718 static int
5719 breakpoint_address_bits (struct breakpoint *b)
5720 {
5721   int print_address_bits = 0;
5722   struct bp_location *loc;
5723
5724   for (loc = b->loc; loc; loc = loc->next)
5725     {
5726       int addr_bit;
5727
5728       /* Software watchpoints that aren't watching memory don't have
5729          an address to print.  */
5730       if (b->type == bp_watchpoint && loc->watchpoint_type == -1)
5731         continue;
5732
5733       addr_bit = gdbarch_addr_bit (loc->gdbarch);
5734       if (addr_bit > print_address_bits)
5735         print_address_bits = addr_bit;
5736     }
5737
5738   return print_address_bits;
5739 }
5740
5741 struct captured_breakpoint_query_args
5742   {
5743     int bnum;
5744   };
5745
5746 static int
5747 do_captured_breakpoint_query (struct ui_out *uiout, void *data)
5748 {
5749   struct captured_breakpoint_query_args *args = data;
5750   struct breakpoint *b;
5751   struct bp_location *dummy_loc = NULL;
5752
5753   ALL_BREAKPOINTS (b)
5754     {
5755       if (args->bnum == b->number)
5756         {
5757           print_one_breakpoint (b, &dummy_loc, 0);
5758           return GDB_RC_OK;
5759         }
5760     }
5761   return GDB_RC_NONE;
5762 }
5763
5764 enum gdb_rc
5765 gdb_breakpoint_query (struct ui_out *uiout, int bnum, 
5766                       char **error_message)
5767 {
5768   struct captured_breakpoint_query_args args;
5769
5770   args.bnum = bnum;
5771   /* For the moment we don't trust print_one_breakpoint() to not throw
5772      an error.  */
5773   if (catch_exceptions_with_msg (uiout, do_captured_breakpoint_query, &args,
5774                                  error_message, RETURN_MASK_ALL) < 0)
5775     return GDB_RC_FAIL;
5776   else
5777     return GDB_RC_OK;
5778 }
5779
5780 /* Return true if this breakpoint was set by the user, false if it is
5781    internal or momentary.  */
5782
5783 int
5784 user_breakpoint_p (struct breakpoint *b)
5785 {
5786   return b->number > 0;
5787 }
5788
5789 /* Print information on user settable breakpoint (watchpoint, etc)
5790    number BNUM.  If BNUM is -1 print all user-settable breakpoints.
5791    If ALLFLAG is non-zero, include non-user-settable breakpoints.  If
5792    FILTER is non-NULL, call it on each breakpoint and only include the
5793    ones for which it returns non-zero.  Return the total number of
5794    breakpoints listed.  */
5795
5796 static int
5797 breakpoint_1 (char *args, int allflag, 
5798               int (*filter) (const struct breakpoint *))
5799 {
5800   struct breakpoint *b;
5801   struct bp_location *last_loc = NULL;
5802   int nr_printable_breakpoints;
5803   struct cleanup *bkpttbl_chain;
5804   struct value_print_options opts;
5805   int print_address_bits = 0;
5806   int print_type_col_width = 14;
5807   struct ui_out *uiout = current_uiout;
5808
5809   get_user_print_options (&opts);
5810
5811   /* Compute the number of rows in the table, as well as the size
5812      required for address fields.  */
5813   nr_printable_breakpoints = 0;
5814   ALL_BREAKPOINTS (b)
5815     {
5816       /* If we have a filter, only list the breakpoints it accepts.  */
5817       if (filter && !filter (b))
5818         continue;
5819
5820       /* If we have an "args" string, it is a list of breakpoints to 
5821          accept.  Skip the others.  */
5822       if (args != NULL && *args != '\0')
5823         {
5824           if (allflag && parse_and_eval_long (args) != b->number)
5825             continue;
5826           if (!allflag && !number_is_in_list (args, b->number))
5827             continue;
5828         }
5829
5830       if (allflag || user_breakpoint_p (b))
5831         {
5832           int addr_bit, type_len;
5833
5834           addr_bit = breakpoint_address_bits (b);
5835           if (addr_bit > print_address_bits)
5836             print_address_bits = addr_bit;
5837
5838           type_len = strlen (bptype_string (b->type));
5839           if (type_len > print_type_col_width)
5840             print_type_col_width = type_len;
5841
5842           nr_printable_breakpoints++;
5843         }
5844     }
5845
5846   if (opts.addressprint)
5847     bkpttbl_chain 
5848       = make_cleanup_ui_out_table_begin_end (uiout, 6,
5849                                              nr_printable_breakpoints,
5850                                              "BreakpointTable");
5851   else
5852     bkpttbl_chain 
5853       = make_cleanup_ui_out_table_begin_end (uiout, 5,
5854                                              nr_printable_breakpoints,
5855                                              "BreakpointTable");
5856
5857   if (nr_printable_breakpoints > 0)
5858     annotate_breakpoints_headers ();
5859   if (nr_printable_breakpoints > 0)
5860     annotate_field (0);
5861   ui_out_table_header (uiout, 7, ui_left, "number", "Num");     /* 1 */
5862   if (nr_printable_breakpoints > 0)
5863     annotate_field (1);
5864   ui_out_table_header (uiout, print_type_col_width, ui_left,
5865                        "type", "Type");                         /* 2 */
5866   if (nr_printable_breakpoints > 0)
5867     annotate_field (2);
5868   ui_out_table_header (uiout, 4, ui_left, "disp", "Disp");      /* 3 */
5869   if (nr_printable_breakpoints > 0)
5870     annotate_field (3);
5871   ui_out_table_header (uiout, 3, ui_left, "enabled", "Enb");    /* 4 */
5872   if (opts.addressprint)
5873     {
5874       if (nr_printable_breakpoints > 0)
5875         annotate_field (4);
5876       if (print_address_bits <= 32)
5877         ui_out_table_header (uiout, 10, ui_left, 
5878                              "addr", "Address");                /* 5 */
5879       else
5880         ui_out_table_header (uiout, 18, ui_left, 
5881                              "addr", "Address");                /* 5 */
5882     }
5883   if (nr_printable_breakpoints > 0)
5884     annotate_field (5);
5885   ui_out_table_header (uiout, 40, ui_noalign, "what", "What");  /* 6 */
5886   ui_out_table_body (uiout);
5887   if (nr_printable_breakpoints > 0)
5888     annotate_breakpoints_table ();
5889
5890   ALL_BREAKPOINTS (b)
5891     {
5892       QUIT;
5893       /* If we have a filter, only list the breakpoints it accepts.  */
5894       if (filter && !filter (b))
5895         continue;
5896
5897       /* If we have an "args" string, it is a list of breakpoints to 
5898          accept.  Skip the others.  */
5899
5900       if (args != NULL && *args != '\0')
5901         {
5902           if (allflag)  /* maintenance info breakpoint */
5903             {
5904               if (parse_and_eval_long (args) != b->number)
5905                 continue;
5906             }
5907           else          /* all others */
5908             {
5909               if (!number_is_in_list (args, b->number))
5910                 continue;
5911             }
5912         }
5913       /* We only print out user settable breakpoints unless the
5914          allflag is set.  */
5915       if (allflag || user_breakpoint_p (b))
5916         print_one_breakpoint (b, &last_loc, allflag);
5917     }
5918
5919   do_cleanups (bkpttbl_chain);
5920
5921   if (nr_printable_breakpoints == 0)
5922     {
5923       /* If there's a filter, let the caller decide how to report
5924          empty list.  */
5925       if (!filter)
5926         {
5927           if (args == NULL || *args == '\0')
5928             ui_out_message (uiout, 0, "No breakpoints or watchpoints.\n");
5929           else
5930             ui_out_message (uiout, 0, 
5931                             "No breakpoint or watchpoint matching '%s'.\n",
5932                             args);
5933         }
5934     }
5935   else
5936     {
5937       if (last_loc && !server_command)
5938         set_next_address (last_loc->gdbarch, last_loc->address);
5939     }
5940
5941   /* FIXME?  Should this be moved up so that it is only called when
5942      there have been breakpoints? */
5943   annotate_breakpoints_table_end ();
5944
5945   return nr_printable_breakpoints;
5946 }
5947
5948 /* Display the value of default-collect in a way that is generally
5949    compatible with the breakpoint list.  */
5950
5951 static void
5952 default_collect_info (void)
5953 {
5954   struct ui_out *uiout = current_uiout;
5955
5956   /* If it has no value (which is frequently the case), say nothing; a
5957      message like "No default-collect." gets in user's face when it's
5958      not wanted.  */
5959   if (!*default_collect)
5960     return;
5961
5962   /* The following phrase lines up nicely with per-tracepoint collect
5963      actions.  */
5964   ui_out_text (uiout, "default collect ");
5965   ui_out_field_string (uiout, "default-collect", default_collect);
5966   ui_out_text (uiout, " \n");
5967 }
5968   
5969 static void
5970 breakpoints_info (char *args, int from_tty)
5971 {
5972   breakpoint_1 (args, 0, NULL);
5973
5974   default_collect_info ();
5975 }
5976
5977 static void
5978 watchpoints_info (char *args, int from_tty)
5979 {
5980   int num_printed = breakpoint_1 (args, 0, is_watchpoint);
5981   struct ui_out *uiout = current_uiout;
5982
5983   if (num_printed == 0)
5984     {
5985       if (args == NULL || *args == '\0')
5986         ui_out_message (uiout, 0, "No watchpoints.\n");
5987       else
5988         ui_out_message (uiout, 0, "No watchpoint matching '%s'.\n", args);
5989     }
5990 }
5991
5992 static void
5993 maintenance_info_breakpoints (char *args, int from_tty)
5994 {
5995   breakpoint_1 (args, 1, NULL);
5996
5997   default_collect_info ();
5998 }
5999
6000 static int
6001 breakpoint_has_pc (struct breakpoint *b,
6002                    struct program_space *pspace,
6003                    CORE_ADDR pc, struct obj_section *section)
6004 {
6005   struct bp_location *bl = b->loc;
6006
6007   for (; bl; bl = bl->next)
6008     {
6009       if (bl->pspace == pspace
6010           && bl->address == pc
6011           && (!overlay_debugging || bl->section == section))
6012         return 1;         
6013     }
6014   return 0;
6015 }
6016
6017 /* Print a message describing any user-breakpoints set at PC.  This
6018    concerns with logical breakpoints, so we match program spaces, not
6019    address spaces.  */
6020
6021 static void
6022 describe_other_breakpoints (struct gdbarch *gdbarch,
6023                             struct program_space *pspace, CORE_ADDR pc,
6024                             struct obj_section *section, int thread)
6025 {
6026   int others = 0;
6027   struct breakpoint *b;
6028
6029   ALL_BREAKPOINTS (b)
6030     others += (user_breakpoint_p (b)
6031                && breakpoint_has_pc (b, pspace, pc, section));
6032   if (others > 0)
6033     {
6034       if (others == 1)
6035         printf_filtered (_("Note: breakpoint "));
6036       else /* if (others == ???) */
6037         printf_filtered (_("Note: breakpoints "));
6038       ALL_BREAKPOINTS (b)
6039         if (user_breakpoint_p (b) && breakpoint_has_pc (b, pspace, pc, section))
6040           {
6041             others--;
6042             printf_filtered ("%d", b->number);
6043             if (b->thread == -1 && thread != -1)
6044               printf_filtered (" (all threads)");
6045             else if (b->thread != -1)
6046               printf_filtered (" (thread %d)", b->thread);
6047             printf_filtered ("%s%s ",
6048                              ((b->enable_state == bp_disabled
6049                                || b->enable_state == bp_call_disabled)
6050                               ? " (disabled)"
6051                               : b->enable_state == bp_permanent 
6052                               ? " (permanent)"
6053                               : ""),
6054                              (others > 1) ? "," 
6055                              : ((others == 1) ? " and" : ""));
6056           }
6057       printf_filtered (_("also set at pc "));
6058       fputs_filtered (paddress (gdbarch, pc), gdb_stdout);
6059       printf_filtered (".\n");
6060     }
6061 }
6062 \f
6063
6064 /* Return true iff it is meaningful to use the address member of
6065    BPT.  For some breakpoint types, the address member is irrelevant
6066    and it makes no sense to attempt to compare it to other addresses
6067    (or use it for any other purpose either).
6068
6069    More specifically, each of the following breakpoint types will
6070    always have a zero valued address and we don't want to mark
6071    breakpoints of any of these types to be a duplicate of an actual
6072    breakpoint at address zero:
6073
6074       bp_watchpoint
6075       bp_catchpoint
6076
6077 */
6078
6079 static int
6080 breakpoint_address_is_meaningful (struct breakpoint *bpt)
6081 {
6082   enum bptype type = bpt->type;
6083
6084   return (type != bp_watchpoint && type != bp_catchpoint);
6085 }
6086
6087 /* Assuming LOC1 and LOC2's owners are hardware watchpoints, returns
6088    true if LOC1 and LOC2 represent the same watchpoint location.  */
6089
6090 static int
6091 watchpoint_locations_match (struct bp_location *loc1, 
6092                             struct bp_location *loc2)
6093 {
6094   struct watchpoint *w1 = (struct watchpoint *) loc1->owner;
6095   struct watchpoint *w2 = (struct watchpoint *) loc2->owner;
6096
6097   /* Both of them must exist.  */
6098   gdb_assert (w1 != NULL);
6099   gdb_assert (w2 != NULL);
6100
6101   /* If the target can evaluate the condition expression in hardware,
6102      then we we need to insert both watchpoints even if they are at
6103      the same place.  Otherwise the watchpoint will only trigger when
6104      the condition of whichever watchpoint was inserted evaluates to
6105      true, not giving a chance for GDB to check the condition of the
6106      other watchpoint.  */
6107   if ((w1->cond_exp
6108        && target_can_accel_watchpoint_condition (loc1->address, 
6109                                                  loc1->length,
6110                                                  loc1->watchpoint_type,
6111                                                  w1->cond_exp))
6112       || (w2->cond_exp
6113           && target_can_accel_watchpoint_condition (loc2->address, 
6114                                                     loc2->length,
6115                                                     loc2->watchpoint_type,
6116                                                     w2->cond_exp)))
6117     return 0;
6118
6119   /* Note that this checks the owner's type, not the location's.  In
6120      case the target does not support read watchpoints, but does
6121      support access watchpoints, we'll have bp_read_watchpoint
6122      watchpoints with hw_access locations.  Those should be considered
6123      duplicates of hw_read locations.  The hw_read locations will
6124      become hw_access locations later.  */
6125   return (loc1->owner->type == loc2->owner->type
6126           && loc1->pspace->aspace == loc2->pspace->aspace
6127           && loc1->address == loc2->address
6128           && loc1->length == loc2->length);
6129 }
6130
6131 /* Returns true if {ASPACE1,ADDR1} and {ASPACE2,ADDR2} represent the
6132    same breakpoint location.  In most targets, this can only be true
6133    if ASPACE1 matches ASPACE2.  On targets that have global
6134    breakpoints, the address space doesn't really matter.  */
6135
6136 static int
6137 breakpoint_address_match (struct address_space *aspace1, CORE_ADDR addr1,
6138                           struct address_space *aspace2, CORE_ADDR addr2)
6139 {
6140   return ((gdbarch_has_global_breakpoints (target_gdbarch)
6141            || aspace1 == aspace2)
6142           && addr1 == addr2);
6143 }
6144
6145 /* Returns true if {ASPACE2,ADDR2} falls within the range determined by
6146    {ASPACE1,ADDR1,LEN1}.  In most targets, this can only be true if ASPACE1
6147    matches ASPACE2.  On targets that have global breakpoints, the address
6148    space doesn't really matter.  */
6149
6150 static int
6151 breakpoint_address_match_range (struct address_space *aspace1, CORE_ADDR addr1,
6152                                 int len1, struct address_space *aspace2,
6153                                 CORE_ADDR addr2)
6154 {
6155   return ((gdbarch_has_global_breakpoints (target_gdbarch)
6156            || aspace1 == aspace2)
6157           && addr2 >= addr1 && addr2 < addr1 + len1);
6158 }
6159
6160 /* Returns true if {ASPACE,ADDR} matches the breakpoint BL.  BL may be
6161    a ranged breakpoint.  In most targets, a match happens only if ASPACE
6162    matches the breakpoint's address space.  On targets that have global
6163    breakpoints, the address space doesn't really matter.  */
6164
6165 static int
6166 breakpoint_location_address_match (struct bp_location *bl,
6167                                    struct address_space *aspace,
6168                                    CORE_ADDR addr)
6169 {
6170   return (breakpoint_address_match (bl->pspace->aspace, bl->address,
6171                                     aspace, addr)
6172           || (bl->length
6173               && breakpoint_address_match_range (bl->pspace->aspace,
6174                                                  bl->address, bl->length,
6175                                                  aspace, addr)));
6176 }
6177
6178 /* If LOC1 and LOC2's owners are not tracepoints, returns false directly.
6179    Then, if LOC1 and LOC2 represent the same tracepoint location, returns
6180    true, otherwise returns false.  */
6181
6182 static int
6183 tracepoint_locations_match (struct bp_location *loc1,
6184                             struct bp_location *loc2)
6185 {
6186   if (is_tracepoint (loc1->owner) && is_tracepoint (loc2->owner))
6187     /* Since tracepoint locations are never duplicated with others', tracepoint
6188        locations at the same address of different tracepoints are regarded as
6189        different locations.  */
6190     return (loc1->address == loc2->address && loc1->owner == loc2->owner);
6191   else
6192     return 0;
6193 }
6194
6195 /* Assuming LOC1 and LOC2's types' have meaningful target addresses
6196    (breakpoint_address_is_meaningful), returns true if LOC1 and LOC2
6197    represent the same location.  */
6198
6199 static int
6200 breakpoint_locations_match (struct bp_location *loc1, 
6201                             struct bp_location *loc2)
6202 {
6203   int hw_point1, hw_point2;
6204
6205   /* Both of them must not be in moribund_locations.  */
6206   gdb_assert (loc1->owner != NULL);
6207   gdb_assert (loc2->owner != NULL);
6208
6209   hw_point1 = is_hardware_watchpoint (loc1->owner);
6210   hw_point2 = is_hardware_watchpoint (loc2->owner);
6211
6212   if (hw_point1 != hw_point2)
6213     return 0;
6214   else if (hw_point1)
6215     return watchpoint_locations_match (loc1, loc2);
6216   else if (is_tracepoint (loc1->owner) || is_tracepoint (loc2->owner))
6217     return tracepoint_locations_match (loc1, loc2);
6218   else
6219     /* We compare bp_location.length in order to cover ranged breakpoints.  */
6220     return (breakpoint_address_match (loc1->pspace->aspace, loc1->address,
6221                                      loc2->pspace->aspace, loc2->address)
6222             && loc1->length == loc2->length);
6223 }
6224
6225 static void
6226 breakpoint_adjustment_warning (CORE_ADDR from_addr, CORE_ADDR to_addr,
6227                                int bnum, int have_bnum)
6228 {
6229   /* The longest string possibly returned by hex_string_custom
6230      is 50 chars.  These must be at least that big for safety.  */
6231   char astr1[64];
6232   char astr2[64];
6233
6234   strcpy (astr1, hex_string_custom ((unsigned long) from_addr, 8));
6235   strcpy (astr2, hex_string_custom ((unsigned long) to_addr, 8));
6236   if (have_bnum)
6237     warning (_("Breakpoint %d address previously adjusted from %s to %s."),
6238              bnum, astr1, astr2);
6239   else
6240     warning (_("Breakpoint address adjusted from %s to %s."), astr1, astr2);
6241 }
6242
6243 /* Adjust a breakpoint's address to account for architectural
6244    constraints on breakpoint placement.  Return the adjusted address.
6245    Note: Very few targets require this kind of adjustment.  For most
6246    targets, this function is simply the identity function.  */
6247
6248 static CORE_ADDR
6249 adjust_breakpoint_address (struct gdbarch *gdbarch,
6250                            CORE_ADDR bpaddr, enum bptype bptype)
6251 {
6252   if (!gdbarch_adjust_breakpoint_address_p (gdbarch))
6253     {
6254       /* Very few targets need any kind of breakpoint adjustment.  */
6255       return bpaddr;
6256     }
6257   else if (bptype == bp_watchpoint
6258            || bptype == bp_hardware_watchpoint
6259            || bptype == bp_read_watchpoint
6260            || bptype == bp_access_watchpoint
6261            || bptype == bp_catchpoint)
6262     {
6263       /* Watchpoints and the various bp_catch_* eventpoints should not
6264          have their addresses modified.  */
6265       return bpaddr;
6266     }
6267   else
6268     {
6269       CORE_ADDR adjusted_bpaddr;
6270
6271       /* Some targets have architectural constraints on the placement
6272          of breakpoint instructions.  Obtain the adjusted address.  */
6273       adjusted_bpaddr = gdbarch_adjust_breakpoint_address (gdbarch, bpaddr);
6274
6275       /* An adjusted breakpoint address can significantly alter
6276          a user's expectations.  Print a warning if an adjustment
6277          is required.  */
6278       if (adjusted_bpaddr != bpaddr)
6279         breakpoint_adjustment_warning (bpaddr, adjusted_bpaddr, 0, 0);
6280
6281       return adjusted_bpaddr;
6282     }
6283 }
6284
6285 void
6286 init_bp_location (struct bp_location *loc, const struct bp_location_ops *ops,
6287                   struct breakpoint *owner)
6288 {
6289   memset (loc, 0, sizeof (*loc));
6290
6291   gdb_assert (ops != NULL);
6292
6293   loc->ops = ops;
6294   loc->owner = owner;
6295   loc->cond = NULL;
6296   loc->cond_bytecode = NULL;
6297   loc->shlib_disabled = 0;
6298   loc->enabled = 1;
6299
6300   switch (owner->type)
6301     {
6302     case bp_breakpoint:
6303     case bp_until:
6304     case bp_finish:
6305     case bp_longjmp:
6306     case bp_longjmp_resume:
6307     case bp_exception:
6308     case bp_exception_resume:
6309     case bp_step_resume:
6310     case bp_hp_step_resume:
6311     case bp_watchpoint_scope:
6312     case bp_call_dummy:
6313     case bp_std_terminate:
6314     case bp_shlib_event:
6315     case bp_thread_event:
6316     case bp_overlay_event:
6317     case bp_jit_event:
6318     case bp_longjmp_master:
6319     case bp_std_terminate_master:
6320     case bp_exception_master:
6321     case bp_gnu_ifunc_resolver:
6322     case bp_gnu_ifunc_resolver_return:
6323       loc->loc_type = bp_loc_software_breakpoint;
6324       mark_breakpoint_location_modified (loc);
6325       break;
6326     case bp_hardware_breakpoint:
6327       loc->loc_type = bp_loc_hardware_breakpoint;
6328       mark_breakpoint_location_modified (loc);
6329       break;
6330     case bp_hardware_watchpoint:
6331     case bp_read_watchpoint:
6332     case bp_access_watchpoint:
6333       loc->loc_type = bp_loc_hardware_watchpoint;
6334       break;
6335     case bp_watchpoint:
6336     case bp_catchpoint:
6337     case bp_tracepoint:
6338     case bp_fast_tracepoint:
6339     case bp_static_tracepoint:
6340       loc->loc_type = bp_loc_other;
6341       break;
6342     default:
6343       internal_error (__FILE__, __LINE__, _("unknown breakpoint type"));
6344     }
6345
6346   loc->refc = 1;
6347 }
6348
6349 /* Allocate a struct bp_location.  */
6350
6351 static struct bp_location *
6352 allocate_bp_location (struct breakpoint *bpt)
6353 {
6354   return bpt->ops->allocate_location (bpt);
6355 }
6356
6357 static void
6358 free_bp_location (struct bp_location *loc)
6359 {
6360   loc->ops->dtor (loc);
6361   xfree (loc);
6362 }
6363
6364 /* Increment reference count.  */
6365
6366 static void
6367 incref_bp_location (struct bp_location *bl)
6368 {
6369   ++bl->refc;
6370 }
6371
6372 /* Decrement reference count.  If the reference count reaches 0,
6373    destroy the bp_location.  Sets *BLP to NULL.  */
6374
6375 static void
6376 decref_bp_location (struct bp_location **blp)
6377 {
6378   gdb_assert ((*blp)->refc > 0);
6379
6380   if (--(*blp)->refc == 0)
6381     free_bp_location (*blp);
6382   *blp = NULL;
6383 }
6384
6385 /* Add breakpoint B at the end of the global breakpoint chain.  */
6386
6387 static void
6388 add_to_breakpoint_chain (struct breakpoint *b)
6389 {
6390   struct breakpoint *b1;
6391
6392   /* Add this breakpoint to the end of the chain so that a list of
6393      breakpoints will come out in order of increasing numbers.  */
6394
6395   b1 = breakpoint_chain;
6396   if (b1 == 0)
6397     breakpoint_chain = b;
6398   else
6399     {
6400       while (b1->next)
6401         b1 = b1->next;
6402       b1->next = b;
6403     }
6404 }
6405
6406 /* Initializes breakpoint B with type BPTYPE and no locations yet.  */
6407
6408 static void
6409 init_raw_breakpoint_without_location (struct breakpoint *b,
6410                                       struct gdbarch *gdbarch,
6411                                       enum bptype bptype,
6412                                       const struct breakpoint_ops *ops)
6413 {
6414   memset (b, 0, sizeof (*b));
6415
6416   gdb_assert (ops != NULL);
6417
6418   b->ops = ops;
6419   b->type = bptype;
6420   b->gdbarch = gdbarch;
6421   b->language = current_language->la_language;
6422   b->input_radix = input_radix;
6423   b->thread = -1;
6424   b->enable_state = bp_enabled;
6425   b->next = 0;
6426   b->silent = 0;
6427   b->ignore_count = 0;
6428   b->commands = NULL;
6429   b->frame_id = null_frame_id;
6430   b->condition_not_parsed = 0;
6431   b->py_bp_object = NULL;
6432   b->related_breakpoint = b;
6433 }
6434
6435 /* Helper to set_raw_breakpoint below.  Creates a breakpoint
6436    that has type BPTYPE and has no locations as yet.  */
6437
6438 static struct breakpoint *
6439 set_raw_breakpoint_without_location (struct gdbarch *gdbarch,
6440                                      enum bptype bptype,
6441                                      const struct breakpoint_ops *ops)
6442 {
6443   struct breakpoint *b = XNEW (struct breakpoint);
6444
6445   init_raw_breakpoint_without_location (b, gdbarch, bptype, ops);
6446   add_to_breakpoint_chain (b);
6447   return b;
6448 }
6449
6450 /* Initialize loc->function_name.  EXPLICIT_LOC says no indirect function
6451    resolutions should be made as the user specified the location explicitly
6452    enough.  */
6453
6454 static void
6455 set_breakpoint_location_function (struct bp_location *loc, int explicit_loc)
6456 {
6457   gdb_assert (loc->owner != NULL);
6458
6459   if (loc->owner->type == bp_breakpoint
6460       || loc->owner->type == bp_hardware_breakpoint
6461       || is_tracepoint (loc->owner))
6462     {
6463       int is_gnu_ifunc;
6464       const char *function_name;
6465
6466       find_pc_partial_function_gnu_ifunc (loc->address, &function_name,
6467                                           NULL, NULL, &is_gnu_ifunc);
6468
6469       if (is_gnu_ifunc && !explicit_loc)
6470         {
6471           struct breakpoint *b = loc->owner;
6472
6473           gdb_assert (loc->pspace == current_program_space);
6474           if (gnu_ifunc_resolve_name (function_name,
6475                                       &loc->requested_address))
6476             {
6477               /* Recalculate ADDRESS based on new REQUESTED_ADDRESS.  */
6478               loc->address = adjust_breakpoint_address (loc->gdbarch,
6479                                                         loc->requested_address,
6480                                                         b->type);
6481             }
6482           else if (b->type == bp_breakpoint && b->loc == loc
6483                    && loc->next == NULL && b->related_breakpoint == b)
6484             {
6485               /* Create only the whole new breakpoint of this type but do not
6486                  mess more complicated breakpoints with multiple locations.  */
6487               b->type = bp_gnu_ifunc_resolver;
6488             }
6489         }
6490
6491       if (function_name)
6492         loc->function_name = xstrdup (function_name);
6493     }
6494 }
6495
6496 /* Attempt to determine architecture of location identified by SAL.  */
6497 struct gdbarch *
6498 get_sal_arch (struct symtab_and_line sal)
6499 {
6500   if (sal.section)
6501     return get_objfile_arch (sal.section->objfile);
6502   if (sal.symtab)
6503     return get_objfile_arch (sal.symtab->objfile);
6504
6505   return NULL;
6506 }
6507
6508 /* Low level routine for partially initializing a breakpoint of type
6509    BPTYPE.  The newly created breakpoint's address, section, source
6510    file name, and line number are provided by SAL.
6511
6512    It is expected that the caller will complete the initialization of
6513    the newly created breakpoint struct as well as output any status
6514    information regarding the creation of a new breakpoint.  */
6515
6516 static void
6517 init_raw_breakpoint (struct breakpoint *b, struct gdbarch *gdbarch,
6518                      struct symtab_and_line sal, enum bptype bptype,
6519                      const struct breakpoint_ops *ops)
6520 {
6521   init_raw_breakpoint_without_location (b, gdbarch, bptype, ops);
6522
6523   add_location_to_breakpoint (b, &sal);
6524
6525   if (bptype != bp_catchpoint)
6526     gdb_assert (sal.pspace != NULL);
6527
6528   /* Store the program space that was used to set the breakpoint,
6529      except for ordinary breakpoints, which are independent of the
6530      program space.  */
6531   if (bptype != bp_breakpoint && bptype != bp_hardware_breakpoint)
6532     b->pspace = sal.pspace;
6533
6534   breakpoints_changed ();
6535 }
6536
6537 /* set_raw_breakpoint is a low level routine for allocating and
6538    partially initializing a breakpoint of type BPTYPE.  The newly
6539    created breakpoint's address, section, source file name, and line
6540    number are provided by SAL.  The newly created and partially
6541    initialized breakpoint is added to the breakpoint chain and
6542    is also returned as the value of this function.
6543
6544    It is expected that the caller will complete the initialization of
6545    the newly created breakpoint struct as well as output any status
6546    information regarding the creation of a new breakpoint.  In
6547    particular, set_raw_breakpoint does NOT set the breakpoint
6548    number!  Care should be taken to not allow an error to occur
6549    prior to completing the initialization of the breakpoint.  If this
6550    should happen, a bogus breakpoint will be left on the chain.  */
6551
6552 struct breakpoint *
6553 set_raw_breakpoint (struct gdbarch *gdbarch,
6554                     struct symtab_and_line sal, enum bptype bptype,
6555                     const struct breakpoint_ops *ops)
6556 {
6557   struct breakpoint *b = XNEW (struct breakpoint);
6558
6559   init_raw_breakpoint (b, gdbarch, sal, bptype, ops);
6560   add_to_breakpoint_chain (b);
6561   return b;
6562 }
6563
6564
6565 /* Note that the breakpoint object B describes a permanent breakpoint
6566    instruction, hard-wired into the inferior's code.  */
6567 void
6568 make_breakpoint_permanent (struct breakpoint *b)
6569 {
6570   struct bp_location *bl;
6571
6572   b->enable_state = bp_permanent;
6573
6574   /* By definition, permanent breakpoints are already present in the
6575      code.  Mark all locations as inserted.  For now,
6576      make_breakpoint_permanent is called in just one place, so it's
6577      hard to say if it's reasonable to have permanent breakpoint with
6578      multiple locations or not, but it's easy to implement.  */
6579   for (bl = b->loc; bl; bl = bl->next)
6580     bl->inserted = 1;
6581 }
6582
6583 /* Call this routine when stepping and nexting to enable a breakpoint
6584    if we do a longjmp() or 'throw' in TP.  FRAME is the frame which
6585    initiated the operation.  */
6586
6587 void
6588 set_longjmp_breakpoint (struct thread_info *tp, struct frame_id frame)
6589 {
6590   struct breakpoint *b, *b_tmp;
6591   int thread = tp->num;
6592
6593   /* To avoid having to rescan all objfile symbols at every step,
6594      we maintain a list of continually-inserted but always disabled
6595      longjmp "master" breakpoints.  Here, we simply create momentary
6596      clones of those and enable them for the requested thread.  */
6597   ALL_BREAKPOINTS_SAFE (b, b_tmp)
6598     if (b->pspace == current_program_space
6599         && (b->type == bp_longjmp_master
6600             || b->type == bp_exception_master))
6601       {
6602         enum bptype type = b->type == bp_longjmp_master ? bp_longjmp : bp_exception;
6603         struct breakpoint *clone;
6604
6605         clone = momentary_breakpoint_from_master (b, type,
6606                                                   &momentary_breakpoint_ops);
6607         clone->thread = thread;
6608       }
6609
6610   tp->initiating_frame = frame;
6611 }
6612
6613 /* Delete all longjmp breakpoints from THREAD.  */
6614 void
6615 delete_longjmp_breakpoint (int thread)
6616 {
6617   struct breakpoint *b, *b_tmp;
6618
6619   ALL_BREAKPOINTS_SAFE (b, b_tmp)
6620     if (b->type == bp_longjmp || b->type == bp_exception)
6621       {
6622         if (b->thread == thread)
6623           delete_breakpoint (b);
6624       }
6625 }
6626
6627 void
6628 enable_overlay_breakpoints (void)
6629 {
6630   struct breakpoint *b;
6631
6632   ALL_BREAKPOINTS (b)
6633     if (b->type == bp_overlay_event)
6634     {
6635       b->enable_state = bp_enabled;
6636       update_global_location_list (1);
6637       overlay_events_enabled = 1;
6638     }
6639 }
6640
6641 void
6642 disable_overlay_breakpoints (void)
6643 {
6644   struct breakpoint *b;
6645
6646   ALL_BREAKPOINTS (b)
6647     if (b->type == bp_overlay_event)
6648     {
6649       b->enable_state = bp_disabled;
6650       update_global_location_list (0);
6651       overlay_events_enabled = 0;
6652     }
6653 }
6654
6655 /* Set an active std::terminate breakpoint for each std::terminate
6656    master breakpoint.  */
6657 void
6658 set_std_terminate_breakpoint (void)
6659 {
6660   struct breakpoint *b, *b_tmp;
6661
6662   ALL_BREAKPOINTS_SAFE (b, b_tmp)
6663     if (b->pspace == current_program_space
6664         && b->type == bp_std_terminate_master)
6665       {
6666         momentary_breakpoint_from_master (b, bp_std_terminate,
6667                                           &momentary_breakpoint_ops);
6668       }
6669 }
6670
6671 /* Delete all the std::terminate breakpoints.  */
6672 void
6673 delete_std_terminate_breakpoint (void)
6674 {
6675   struct breakpoint *b, *b_tmp;
6676
6677   ALL_BREAKPOINTS_SAFE (b, b_tmp)
6678     if (b->type == bp_std_terminate)
6679       delete_breakpoint (b);
6680 }
6681
6682 struct breakpoint *
6683 create_thread_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
6684 {
6685   struct breakpoint *b;
6686
6687   b = create_internal_breakpoint (gdbarch, address, bp_thread_event,
6688                                   &internal_breakpoint_ops);
6689
6690   b->enable_state = bp_enabled;
6691   /* addr_string has to be used or breakpoint_re_set will delete me.  */
6692   b->addr_string
6693     = xstrprintf ("*%s", paddress (b->loc->gdbarch, b->loc->address));
6694
6695   update_global_location_list_nothrow (1);
6696
6697   return b;
6698 }
6699
6700 void
6701 remove_thread_event_breakpoints (void)
6702 {
6703   struct breakpoint *b, *b_tmp;
6704
6705   ALL_BREAKPOINTS_SAFE (b, b_tmp)
6706     if (b->type == bp_thread_event
6707         && b->loc->pspace == current_program_space)
6708       delete_breakpoint (b);
6709 }
6710
6711 struct lang_and_radix
6712   {
6713     enum language lang;
6714     int radix;
6715   };
6716
6717 /* Create a breakpoint for JIT code registration and unregistration.  */
6718
6719 struct breakpoint *
6720 create_jit_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
6721 {
6722   struct breakpoint *b;
6723
6724   b = create_internal_breakpoint (gdbarch, address, bp_jit_event,
6725                                   &internal_breakpoint_ops);
6726   update_global_location_list_nothrow (1);
6727   return b;
6728 }
6729
6730 /* Remove JIT code registration and unregistration breakpoint(s).  */
6731
6732 void
6733 remove_jit_event_breakpoints (void)
6734 {
6735   struct breakpoint *b, *b_tmp;
6736
6737   ALL_BREAKPOINTS_SAFE (b, b_tmp)
6738     if (b->type == bp_jit_event
6739         && b->loc->pspace == current_program_space)
6740       delete_breakpoint (b);
6741 }
6742
6743 void
6744 remove_solib_event_breakpoints (void)
6745 {
6746   struct breakpoint *b, *b_tmp;
6747
6748   ALL_BREAKPOINTS_SAFE (b, b_tmp)
6749     if (b->type == bp_shlib_event
6750         && b->loc->pspace == current_program_space)
6751       delete_breakpoint (b);
6752 }
6753
6754 struct breakpoint *
6755 create_solib_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
6756 {
6757   struct breakpoint *b;
6758
6759   b = create_internal_breakpoint (gdbarch, address, bp_shlib_event,
6760                                   &internal_breakpoint_ops);
6761   update_global_location_list_nothrow (1);
6762   return b;
6763 }
6764
6765 /* Disable any breakpoints that are on code in shared libraries.  Only
6766    apply to enabled breakpoints, disabled ones can just stay disabled.  */
6767
6768 void
6769 disable_breakpoints_in_shlibs (void)
6770 {
6771   struct bp_location *loc, **locp_tmp;
6772
6773   ALL_BP_LOCATIONS (loc, locp_tmp)
6774   {
6775     /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
6776     struct breakpoint *b = loc->owner;
6777
6778     /* We apply the check to all breakpoints, including disabled for
6779        those with loc->duplicate set.  This is so that when breakpoint
6780        becomes enabled, or the duplicate is removed, gdb will try to
6781        insert all breakpoints.  If we don't set shlib_disabled here,
6782        we'll try to insert those breakpoints and fail.  */
6783     if (((b->type == bp_breakpoint)
6784          || (b->type == bp_jit_event)
6785          || (b->type == bp_hardware_breakpoint)
6786          || (is_tracepoint (b)))
6787         && loc->pspace == current_program_space
6788         && !loc->shlib_disabled
6789 #ifdef PC_SOLIB
6790         && PC_SOLIB (loc->address)
6791 #else
6792         && solib_name_from_address (loc->pspace, loc->address)
6793 #endif
6794         )
6795       {
6796         loc->shlib_disabled = 1;
6797       }
6798   }
6799 }
6800
6801 /* Disable any breakpoints and tracepoints that are in an unloaded shared
6802    library.  Only apply to enabled breakpoints, disabled ones can just stay
6803    disabled.  */
6804
6805 static void
6806 disable_breakpoints_in_unloaded_shlib (struct so_list *solib)
6807 {
6808   struct bp_location *loc, **locp_tmp;
6809   int disabled_shlib_breaks = 0;
6810
6811   /* SunOS a.out shared libraries are always mapped, so do not
6812      disable breakpoints; they will only be reported as unloaded
6813      through clear_solib when GDB discards its shared library
6814      list.  See clear_solib for more information.  */
6815   if (exec_bfd != NULL
6816       && bfd_get_flavour (exec_bfd) == bfd_target_aout_flavour)
6817     return;
6818
6819   ALL_BP_LOCATIONS (loc, locp_tmp)
6820   {
6821     /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
6822     struct breakpoint *b = loc->owner;
6823
6824     if (solib->pspace == loc->pspace
6825         && !loc->shlib_disabled
6826         && (((b->type == bp_breakpoint
6827               || b->type == bp_jit_event
6828               || b->type == bp_hardware_breakpoint)
6829              && (loc->loc_type == bp_loc_hardware_breakpoint
6830                  || loc->loc_type == bp_loc_software_breakpoint))
6831             || is_tracepoint (b))
6832         && solib_contains_address_p (solib, loc->address))
6833       {
6834         loc->shlib_disabled = 1;
6835         /* At this point, we cannot rely on remove_breakpoint
6836            succeeding so we must mark the breakpoint as not inserted
6837            to prevent future errors occurring in remove_breakpoints.  */
6838         loc->inserted = 0;
6839
6840         /* This may cause duplicate notifications for the same breakpoint.  */
6841         observer_notify_breakpoint_modified (b);
6842
6843         if (!disabled_shlib_breaks)
6844           {
6845             target_terminal_ours_for_output ();
6846             warning (_("Temporarily disabling breakpoints "
6847                        "for unloaded shared library \"%s\""),
6848                      solib->so_name);
6849           }
6850         disabled_shlib_breaks = 1;
6851       }
6852   }
6853 }
6854
6855 /* FORK & VFORK catchpoints.  */
6856
6857 /* An instance of this type is used to represent a fork or vfork
6858    catchpoint.  It includes a "struct breakpoint" as a kind of base
6859    class; users downcast to "struct breakpoint *" when needed.  A
6860    breakpoint is really of this type iff its ops pointer points to
6861    CATCH_FORK_BREAKPOINT_OPS.  */
6862
6863 struct fork_catchpoint
6864 {
6865   /* The base class.  */
6866   struct breakpoint base;
6867
6868   /* Process id of a child process whose forking triggered this
6869      catchpoint.  This field is only valid immediately after this
6870      catchpoint has triggered.  */
6871   ptid_t forked_inferior_pid;
6872 };
6873
6874 /* Implement the "insert" breakpoint_ops method for fork
6875    catchpoints.  */
6876
6877 static int
6878 insert_catch_fork (struct bp_location *bl)
6879 {
6880   return target_insert_fork_catchpoint (PIDGET (inferior_ptid));
6881 }
6882
6883 /* Implement the "remove" breakpoint_ops method for fork
6884    catchpoints.  */
6885
6886 static int
6887 remove_catch_fork (struct bp_location *bl)
6888 {
6889   return target_remove_fork_catchpoint (PIDGET (inferior_ptid));
6890 }
6891
6892 /* Implement the "breakpoint_hit" breakpoint_ops method for fork
6893    catchpoints.  */
6894
6895 static int
6896 breakpoint_hit_catch_fork (const struct bp_location *bl,
6897                            struct address_space *aspace, CORE_ADDR bp_addr,
6898                            const struct target_waitstatus *ws)
6899 {
6900   struct fork_catchpoint *c = (struct fork_catchpoint *) bl->owner;
6901
6902   if (ws->kind != TARGET_WAITKIND_FORKED)
6903     return 0;
6904
6905   c->forked_inferior_pid = ws->value.related_pid;
6906   return 1;
6907 }
6908
6909 /* Implement the "print_it" breakpoint_ops method for fork
6910    catchpoints.  */
6911
6912 static enum print_stop_action
6913 print_it_catch_fork (bpstat bs)
6914 {
6915   struct ui_out *uiout = current_uiout;
6916   struct breakpoint *b = bs->breakpoint_at;
6917   struct fork_catchpoint *c = (struct fork_catchpoint *) bs->breakpoint_at;
6918
6919   annotate_catchpoint (b->number);
6920   if (b->disposition == disp_del)
6921     ui_out_text (uiout, "\nTemporary catchpoint ");
6922   else
6923     ui_out_text (uiout, "\nCatchpoint ");
6924   if (ui_out_is_mi_like_p (uiout))
6925     {
6926       ui_out_field_string (uiout, "reason",
6927                            async_reason_lookup (EXEC_ASYNC_FORK));
6928       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
6929     }
6930   ui_out_field_int (uiout, "bkptno", b->number);
6931   ui_out_text (uiout, " (forked process ");
6932   ui_out_field_int (uiout, "newpid", ptid_get_pid (c->forked_inferior_pid));
6933   ui_out_text (uiout, "), ");
6934   return PRINT_SRC_AND_LOC;
6935 }
6936
6937 /* Implement the "print_one" breakpoint_ops method for fork
6938    catchpoints.  */
6939
6940 static void
6941 print_one_catch_fork (struct breakpoint *b, struct bp_location **last_loc)
6942 {
6943   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
6944   struct value_print_options opts;
6945   struct ui_out *uiout = current_uiout;
6946
6947   get_user_print_options (&opts);
6948
6949   /* Field 4, the address, is omitted (which makes the columns not
6950      line up too nicely with the headers, but the effect is relatively
6951      readable).  */
6952   if (opts.addressprint)
6953     ui_out_field_skip (uiout, "addr");
6954   annotate_field (5);
6955   ui_out_text (uiout, "fork");
6956   if (!ptid_equal (c->forked_inferior_pid, null_ptid))
6957     {
6958       ui_out_text (uiout, ", process ");
6959       ui_out_field_int (uiout, "what",
6960                         ptid_get_pid (c->forked_inferior_pid));
6961       ui_out_spaces (uiout, 1);
6962     }
6963 }
6964
6965 /* Implement the "print_mention" breakpoint_ops method for fork
6966    catchpoints.  */
6967
6968 static void
6969 print_mention_catch_fork (struct breakpoint *b)
6970 {
6971   printf_filtered (_("Catchpoint %d (fork)"), b->number);
6972 }
6973
6974 /* Implement the "print_recreate" breakpoint_ops method for fork
6975    catchpoints.  */
6976
6977 static void
6978 print_recreate_catch_fork (struct breakpoint *b, struct ui_file *fp)
6979 {
6980   fprintf_unfiltered (fp, "catch fork");
6981   print_recreate_thread (b, fp);
6982 }
6983
6984 /* The breakpoint_ops structure to be used in fork catchpoints.  */
6985
6986 static struct breakpoint_ops catch_fork_breakpoint_ops;
6987
6988 /* Implement the "insert" breakpoint_ops method for vfork
6989    catchpoints.  */
6990
6991 static int
6992 insert_catch_vfork (struct bp_location *bl)
6993 {
6994   return target_insert_vfork_catchpoint (PIDGET (inferior_ptid));
6995 }
6996
6997 /* Implement the "remove" breakpoint_ops method for vfork
6998    catchpoints.  */
6999
7000 static int
7001 remove_catch_vfork (struct bp_location *bl)
7002 {
7003   return target_remove_vfork_catchpoint (PIDGET (inferior_ptid));
7004 }
7005
7006 /* Implement the "breakpoint_hit" breakpoint_ops method for vfork
7007    catchpoints.  */
7008
7009 static int
7010 breakpoint_hit_catch_vfork (const struct bp_location *bl,
7011                             struct address_space *aspace, CORE_ADDR bp_addr,
7012                             const struct target_waitstatus *ws)
7013 {
7014   struct fork_catchpoint *c = (struct fork_catchpoint *) bl->owner;
7015
7016   if (ws->kind != TARGET_WAITKIND_VFORKED)
7017     return 0;
7018
7019   c->forked_inferior_pid = ws->value.related_pid;
7020   return 1;
7021 }
7022
7023 /* Implement the "print_it" breakpoint_ops method for vfork
7024    catchpoints.  */
7025
7026 static enum print_stop_action
7027 print_it_catch_vfork (bpstat bs)
7028 {
7029   struct ui_out *uiout = current_uiout;
7030   struct breakpoint *b = bs->breakpoint_at;
7031   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
7032
7033   annotate_catchpoint (b->number);
7034   if (b->disposition == disp_del)
7035     ui_out_text (uiout, "\nTemporary catchpoint ");
7036   else
7037     ui_out_text (uiout, "\nCatchpoint ");
7038   if (ui_out_is_mi_like_p (uiout))
7039     {
7040       ui_out_field_string (uiout, "reason",
7041                            async_reason_lookup (EXEC_ASYNC_VFORK));
7042       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
7043     }
7044   ui_out_field_int (uiout, "bkptno", b->number);
7045   ui_out_text (uiout, " (vforked process ");
7046   ui_out_field_int (uiout, "newpid", ptid_get_pid (c->forked_inferior_pid));
7047   ui_out_text (uiout, "), ");
7048   return PRINT_SRC_AND_LOC;
7049 }
7050
7051 /* Implement the "print_one" breakpoint_ops method for vfork
7052    catchpoints.  */
7053
7054 static void
7055 print_one_catch_vfork (struct breakpoint *b, struct bp_location **last_loc)
7056 {
7057   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
7058   struct value_print_options opts;
7059   struct ui_out *uiout = current_uiout;
7060
7061   get_user_print_options (&opts);
7062   /* Field 4, the address, is omitted (which makes the columns not
7063      line up too nicely with the headers, but the effect is relatively
7064      readable).  */
7065   if (opts.addressprint)
7066     ui_out_field_skip (uiout, "addr");
7067   annotate_field (5);
7068   ui_out_text (uiout, "vfork");
7069   if (!ptid_equal (c->forked_inferior_pid, null_ptid))
7070     {
7071       ui_out_text (uiout, ", process ");
7072       ui_out_field_int (uiout, "what",
7073                         ptid_get_pid (c->forked_inferior_pid));
7074       ui_out_spaces (uiout, 1);
7075     }
7076 }
7077
7078 /* Implement the "print_mention" breakpoint_ops method for vfork
7079    catchpoints.  */
7080
7081 static void
7082 print_mention_catch_vfork (struct breakpoint *b)
7083 {
7084   printf_filtered (_("Catchpoint %d (vfork)"), b->number);
7085 }
7086
7087 /* Implement the "print_recreate" breakpoint_ops method for vfork
7088    catchpoints.  */
7089
7090 static void
7091 print_recreate_catch_vfork (struct breakpoint *b, struct ui_file *fp)
7092 {
7093   fprintf_unfiltered (fp, "catch vfork");
7094   print_recreate_thread (b, fp);
7095 }
7096
7097 /* The breakpoint_ops structure to be used in vfork catchpoints.  */
7098
7099 static struct breakpoint_ops catch_vfork_breakpoint_ops;
7100
7101 /* An instance of this type is used to represent an solib catchpoint.
7102    It includes a "struct breakpoint" as a kind of base class; users
7103    downcast to "struct breakpoint *" when needed.  A breakpoint is
7104    really of this type iff its ops pointer points to
7105    CATCH_SOLIB_BREAKPOINT_OPS.  */
7106
7107 struct solib_catchpoint
7108 {
7109   /* The base class.  */
7110   struct breakpoint base;
7111
7112   /* True for "catch load", false for "catch unload".  */
7113   unsigned char is_load;
7114
7115   /* Regular expression to match, if any.  COMPILED is only valid when
7116      REGEX is non-NULL.  */
7117   char *regex;
7118   regex_t compiled;
7119 };
7120
7121 static void
7122 dtor_catch_solib (struct breakpoint *b)
7123 {
7124   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
7125
7126   if (self->regex)
7127     regfree (&self->compiled);
7128   xfree (self->regex);
7129
7130   base_breakpoint_ops.dtor (b);
7131 }
7132
7133 static int
7134 insert_catch_solib (struct bp_location *ignore)
7135 {
7136   return 0;
7137 }
7138
7139 static int
7140 remove_catch_solib (struct bp_location *ignore)
7141 {
7142   return 0;
7143 }
7144
7145 static int
7146 breakpoint_hit_catch_solib (const struct bp_location *bl,
7147                             struct address_space *aspace,
7148                             CORE_ADDR bp_addr,
7149                             const struct target_waitstatus *ws)
7150 {
7151   struct solib_catchpoint *self = (struct solib_catchpoint *) bl->owner;
7152   struct breakpoint *other;
7153
7154   if (ws->kind == TARGET_WAITKIND_LOADED)
7155     return 1;
7156
7157   ALL_BREAKPOINTS (other)
7158   {
7159     struct bp_location *other_bl;
7160
7161     if (other == bl->owner)
7162       continue;
7163
7164     if (other->type != bp_shlib_event)
7165       continue;
7166
7167     if (self->base.pspace != NULL && other->pspace != self->base.pspace)
7168       continue;
7169
7170     for (other_bl = other->loc; other_bl != NULL; other_bl = other_bl->next)
7171       {
7172         if (other->ops->breakpoint_hit (other_bl, aspace, bp_addr, ws))
7173           return 1;
7174       }
7175   }
7176
7177   return 0;
7178 }
7179
7180 static void
7181 check_status_catch_solib (struct bpstats *bs)
7182 {
7183   struct solib_catchpoint *self
7184     = (struct solib_catchpoint *) bs->breakpoint_at;
7185   int ix;
7186
7187   if (self->is_load)
7188     {
7189       struct so_list *iter;
7190
7191       for (ix = 0;
7192            VEC_iterate (so_list_ptr, current_program_space->added_solibs,
7193                         ix, iter);
7194            ++ix)
7195         {
7196           if (!self->regex
7197               || regexec (&self->compiled, iter->so_name, 0, NULL, 0) == 0)
7198             return;
7199         }
7200     }
7201   else
7202     {
7203       char *iter;
7204
7205       for (ix = 0;
7206            VEC_iterate (char_ptr, current_program_space->deleted_solibs,
7207                         ix, iter);
7208            ++ix)
7209         {
7210           if (!self->regex
7211               || regexec (&self->compiled, iter, 0, NULL, 0) == 0)
7212             return;
7213         }
7214     }
7215
7216   bs->stop = 0;
7217   bs->print_it = print_it_noop;
7218 }
7219
7220 static enum print_stop_action
7221 print_it_catch_solib (bpstat bs)
7222 {
7223   struct breakpoint *b = bs->breakpoint_at;
7224   struct ui_out *uiout = current_uiout;
7225
7226   annotate_catchpoint (b->number);
7227   if (b->disposition == disp_del)
7228     ui_out_text (uiout, "\nTemporary catchpoint ");
7229   else
7230     ui_out_text (uiout, "\nCatchpoint ");
7231   ui_out_field_int (uiout, "bkptno", b->number);
7232   ui_out_text (uiout, "\n");
7233   if (ui_out_is_mi_like_p (uiout))
7234     ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
7235   print_solib_event (1);
7236   return PRINT_SRC_AND_LOC;
7237 }
7238
7239 static void
7240 print_one_catch_solib (struct breakpoint *b, struct bp_location **locs)
7241 {
7242   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
7243   struct value_print_options opts;
7244   struct ui_out *uiout = current_uiout;
7245   char *msg;
7246
7247   get_user_print_options (&opts);
7248   /* Field 4, the address, is omitted (which makes the columns not
7249      line up too nicely with the headers, but the effect is relatively
7250      readable).  */
7251   if (opts.addressprint)
7252     {
7253       annotate_field (4);
7254       ui_out_field_skip (uiout, "addr");
7255     }
7256
7257   annotate_field (5);
7258   if (self->is_load)
7259     {
7260       if (self->regex)
7261         msg = xstrprintf (_("load of library matching %s"), self->regex);
7262       else
7263         msg = xstrdup (_("load of library"));
7264     }
7265   else
7266     {
7267       if (self->regex)
7268         msg = xstrprintf (_("unload of library matching %s"), self->regex);
7269       else
7270         msg = xstrdup (_("unload of library"));
7271     }
7272   ui_out_field_string (uiout, "what", msg);
7273   xfree (msg);
7274 }
7275
7276 static void
7277 print_mention_catch_solib (struct breakpoint *b)
7278 {
7279   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
7280
7281   printf_filtered (_("Catchpoint %d (%s)"), b->number,
7282                    self->is_load ? "load" : "unload");
7283 }
7284
7285 static void
7286 print_recreate_catch_solib (struct breakpoint *b, struct ui_file *fp)
7287 {
7288   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
7289
7290   fprintf_unfiltered (fp, "%s %s",
7291                       b->disposition == disp_del ? "tcatch" : "catch",
7292                       self->is_load ? "load" : "unload");
7293   if (self->regex)
7294     fprintf_unfiltered (fp, " %s", self->regex);
7295   fprintf_unfiltered (fp, "\n");
7296 }
7297
7298 static struct breakpoint_ops catch_solib_breakpoint_ops;
7299
7300 /* A helper function that does all the work for "catch load" and
7301    "catch unload".  */
7302
7303 static void
7304 catch_load_or_unload (char *arg, int from_tty, int is_load,
7305                       struct cmd_list_element *command)
7306 {
7307   struct solib_catchpoint *c;
7308   struct gdbarch *gdbarch = get_current_arch ();
7309   int tempflag;
7310   regex_t compiled;
7311   struct cleanup *cleanup;
7312
7313   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
7314
7315   if (!arg)
7316     arg = "";
7317   arg = skip_spaces (arg);
7318
7319   c = XCNEW (struct solib_catchpoint);
7320   cleanup = make_cleanup (xfree, c);
7321
7322   if (*arg != '\0')
7323     {
7324       int errcode;
7325
7326       errcode = regcomp (&c->compiled, arg, REG_NOSUB);
7327       if (errcode != 0)
7328         {
7329           char *err = get_regcomp_error (errcode, &c->compiled);
7330
7331           make_cleanup (xfree, err);
7332           error (_("Invalid regexp (%s): %s"), err, arg);
7333         }
7334       c->regex = xstrdup (arg);
7335     }
7336
7337   c->is_load = is_load;
7338   init_catchpoint (&c->base, gdbarch, tempflag, NULL,
7339                    &catch_solib_breakpoint_ops);
7340
7341   discard_cleanups (cleanup);
7342   install_breakpoint (0, &c->base, 1);
7343 }
7344
7345 static void
7346 catch_load_command_1 (char *arg, int from_tty,
7347                       struct cmd_list_element *command)
7348 {
7349   catch_load_or_unload (arg, from_tty, 1, command);
7350 }
7351
7352 static void
7353 catch_unload_command_1 (char *arg, int from_tty,
7354                         struct cmd_list_element *command)
7355 {
7356   catch_load_or_unload (arg, from_tty, 0, command);
7357 }
7358
7359 /* An instance of this type is used to represent a syscall catchpoint.
7360    It includes a "struct breakpoint" as a kind of base class; users
7361    downcast to "struct breakpoint *" when needed.  A breakpoint is
7362    really of this type iff its ops pointer points to
7363    CATCH_SYSCALL_BREAKPOINT_OPS.  */
7364
7365 struct syscall_catchpoint
7366 {
7367   /* The base class.  */
7368   struct breakpoint base;
7369
7370   /* Syscall numbers used for the 'catch syscall' feature.  If no
7371      syscall has been specified for filtering, its value is NULL.
7372      Otherwise, it holds a list of all syscalls to be caught.  The
7373      list elements are allocated with xmalloc.  */
7374   VEC(int) *syscalls_to_be_caught;
7375 };
7376
7377 /* Implement the "dtor" breakpoint_ops method for syscall
7378    catchpoints.  */
7379
7380 static void
7381 dtor_catch_syscall (struct breakpoint *b)
7382 {
7383   struct syscall_catchpoint *c = (struct syscall_catchpoint *) b;
7384
7385   VEC_free (int, c->syscalls_to_be_caught);
7386
7387   base_breakpoint_ops.dtor (b);
7388 }
7389
7390 /* Implement the "insert" breakpoint_ops method for syscall
7391    catchpoints.  */
7392
7393 static int
7394 insert_catch_syscall (struct bp_location *bl)
7395 {
7396   struct syscall_catchpoint *c = (struct syscall_catchpoint *) bl->owner;
7397   struct inferior *inf = current_inferior ();
7398
7399   ++inf->total_syscalls_count;
7400   if (!c->syscalls_to_be_caught)
7401     ++inf->any_syscall_count;
7402   else
7403     {
7404       int i, iter;
7405
7406       for (i = 0;
7407            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
7408            i++)
7409         {
7410           int elem;
7411
7412           if (iter >= VEC_length (int, inf->syscalls_counts))
7413             {
7414               int old_size = VEC_length (int, inf->syscalls_counts);
7415               uintptr_t vec_addr_offset
7416                 = old_size * ((uintptr_t) sizeof (int));
7417               uintptr_t vec_addr;
7418               VEC_safe_grow (int, inf->syscalls_counts, iter + 1);
7419               vec_addr = (uintptr_t) VEC_address (int, inf->syscalls_counts) +
7420                 vec_addr_offset;
7421               memset ((void *) vec_addr, 0,
7422                       (iter + 1 - old_size) * sizeof (int));
7423             }
7424           elem = VEC_index (int, inf->syscalls_counts, iter);
7425           VEC_replace (int, inf->syscalls_counts, iter, ++elem);
7426         }
7427     }
7428
7429   return target_set_syscall_catchpoint (PIDGET (inferior_ptid),
7430                                         inf->total_syscalls_count != 0,
7431                                         inf->any_syscall_count,
7432                                         VEC_length (int, inf->syscalls_counts),
7433                                         VEC_address (int, inf->syscalls_counts));
7434 }
7435
7436 /* Implement the "remove" breakpoint_ops method for syscall
7437    catchpoints.  */
7438
7439 static int
7440 remove_catch_syscall (struct bp_location *bl)
7441 {
7442   struct syscall_catchpoint *c = (struct syscall_catchpoint *) bl->owner;
7443   struct inferior *inf = current_inferior ();
7444
7445   --inf->total_syscalls_count;
7446   if (!c->syscalls_to_be_caught)
7447     --inf->any_syscall_count;
7448   else
7449     {
7450       int i, iter;
7451
7452       for (i = 0;
7453            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
7454            i++)
7455         {
7456           int elem;
7457           if (iter >= VEC_length (int, inf->syscalls_counts))
7458             /* Shouldn't happen.  */
7459             continue;
7460           elem = VEC_index (int, inf->syscalls_counts, iter);
7461           VEC_replace (int, inf->syscalls_counts, iter, --elem);
7462         }
7463     }
7464
7465   return target_set_syscall_catchpoint (PIDGET (inferior_ptid),
7466                                         inf->total_syscalls_count != 0,
7467                                         inf->any_syscall_count,
7468                                         VEC_length (int, inf->syscalls_counts),
7469                                         VEC_address (int,
7470                                                      inf->syscalls_counts));
7471 }
7472
7473 /* Implement the "breakpoint_hit" breakpoint_ops method for syscall
7474    catchpoints.  */
7475
7476 static int
7477 breakpoint_hit_catch_syscall (const struct bp_location *bl,
7478                               struct address_space *aspace, CORE_ADDR bp_addr,
7479                               const struct target_waitstatus *ws)
7480 {
7481   /* We must check if we are catching specific syscalls in this
7482      breakpoint.  If we are, then we must guarantee that the called
7483      syscall is the same syscall we are catching.  */
7484   int syscall_number = 0;
7485   const struct syscall_catchpoint *c
7486     = (const struct syscall_catchpoint *) bl->owner;
7487
7488   if (ws->kind != TARGET_WAITKIND_SYSCALL_ENTRY
7489       && ws->kind != TARGET_WAITKIND_SYSCALL_RETURN)
7490     return 0;
7491
7492   syscall_number = ws->value.syscall_number;
7493
7494   /* Now, checking if the syscall is the same.  */
7495   if (c->syscalls_to_be_caught)
7496     {
7497       int i, iter;
7498
7499       for (i = 0;
7500            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
7501            i++)
7502         if (syscall_number == iter)
7503           break;
7504       /* Not the same.  */
7505       if (!iter)
7506         return 0;
7507     }
7508
7509   return 1;
7510 }
7511
7512 /* Implement the "print_it" breakpoint_ops method for syscall
7513    catchpoints.  */
7514
7515 static enum print_stop_action
7516 print_it_catch_syscall (bpstat bs)
7517 {
7518   struct ui_out *uiout = current_uiout;
7519   struct breakpoint *b = bs->breakpoint_at;
7520   /* These are needed because we want to know in which state a
7521      syscall is.  It can be in the TARGET_WAITKIND_SYSCALL_ENTRY
7522      or TARGET_WAITKIND_SYSCALL_RETURN, and depending on it we
7523      must print "called syscall" or "returned from syscall".  */
7524   ptid_t ptid;
7525   struct target_waitstatus last;
7526   struct syscall s;
7527   char *syscall_id;
7528
7529   get_last_target_status (&ptid, &last);
7530
7531   get_syscall_by_number (last.value.syscall_number, &s);
7532
7533   annotate_catchpoint (b->number);
7534
7535   if (b->disposition == disp_del)
7536     ui_out_text (uiout, "\nTemporary catchpoint ");
7537   else
7538     ui_out_text (uiout, "\nCatchpoint ");
7539   if (ui_out_is_mi_like_p (uiout))
7540     {
7541       ui_out_field_string (uiout, "reason",
7542                            async_reason_lookup (last.kind == TARGET_WAITKIND_SYSCALL_ENTRY
7543                                                 ? EXEC_ASYNC_SYSCALL_ENTRY
7544                                                 : EXEC_ASYNC_SYSCALL_RETURN));
7545       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
7546     }
7547   ui_out_field_int (uiout, "bkptno", b->number);
7548
7549   if (last.kind == TARGET_WAITKIND_SYSCALL_ENTRY)
7550     ui_out_text (uiout, " (call to syscall ");
7551   else
7552     ui_out_text (uiout, " (returned from syscall ");
7553
7554   if (s.name == NULL || ui_out_is_mi_like_p (uiout))
7555     ui_out_field_int (uiout, "syscall-number", last.value.syscall_number);
7556   if (s.name != NULL)
7557     ui_out_field_string (uiout, "syscall-name", s.name);
7558
7559   ui_out_text (uiout, "), ");
7560
7561   return PRINT_SRC_AND_LOC;
7562 }
7563
7564 /* Implement the "print_one" breakpoint_ops method for syscall
7565    catchpoints.  */
7566
7567 static void
7568 print_one_catch_syscall (struct breakpoint *b,
7569                          struct bp_location **last_loc)
7570 {
7571   struct syscall_catchpoint *c = (struct syscall_catchpoint *) b;
7572   struct value_print_options opts;
7573   struct ui_out *uiout = current_uiout;
7574
7575   get_user_print_options (&opts);
7576   /* Field 4, the address, is omitted (which makes the columns not
7577      line up too nicely with the headers, but the effect is relatively
7578      readable).  */
7579   if (opts.addressprint)
7580     ui_out_field_skip (uiout, "addr");
7581   annotate_field (5);
7582
7583   if (c->syscalls_to_be_caught
7584       && VEC_length (int, c->syscalls_to_be_caught) > 1)
7585     ui_out_text (uiout, "syscalls \"");
7586   else
7587     ui_out_text (uiout, "syscall \"");
7588
7589   if (c->syscalls_to_be_caught)
7590     {
7591       int i, iter;
7592       char *text = xstrprintf ("%s", "");
7593
7594       for (i = 0;
7595            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
7596            i++)
7597         {
7598           char *x = text;
7599           struct syscall s;
7600           get_syscall_by_number (iter, &s);
7601
7602           if (s.name != NULL)
7603             text = xstrprintf ("%s%s, ", text, s.name);
7604           else
7605             text = xstrprintf ("%s%d, ", text, iter);
7606
7607           /* We have to xfree the last 'text' (now stored at 'x')
7608              because xstrprintf dynamically allocates new space for it
7609              on every call.  */
7610           xfree (x);
7611         }
7612       /* Remove the last comma.  */
7613       text[strlen (text) - 2] = '\0';
7614       ui_out_field_string (uiout, "what", text);
7615     }
7616   else
7617     ui_out_field_string (uiout, "what", "<any syscall>");
7618   ui_out_text (uiout, "\" ");
7619 }
7620
7621 /* Implement the "print_mention" breakpoint_ops method for syscall
7622    catchpoints.  */
7623
7624 static void
7625 print_mention_catch_syscall (struct breakpoint *b)
7626 {
7627   struct syscall_catchpoint *c = (struct syscall_catchpoint *) b;
7628
7629   if (c->syscalls_to_be_caught)
7630     {
7631       int i, iter;
7632
7633       if (VEC_length (int, c->syscalls_to_be_caught) > 1)
7634         printf_filtered (_("Catchpoint %d (syscalls"), b->number);
7635       else
7636         printf_filtered (_("Catchpoint %d (syscall"), b->number);
7637
7638       for (i = 0;
7639            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
7640            i++)
7641         {
7642           struct syscall s;
7643           get_syscall_by_number (iter, &s);
7644
7645           if (s.name)
7646             printf_filtered (" '%s' [%d]", s.name, s.number);
7647           else
7648             printf_filtered (" %d", s.number);
7649         }
7650       printf_filtered (")");
7651     }
7652   else
7653     printf_filtered (_("Catchpoint %d (any syscall)"),
7654                      b->number);
7655 }
7656
7657 /* Implement the "print_recreate" breakpoint_ops method for syscall
7658    catchpoints.  */
7659
7660 static void
7661 print_recreate_catch_syscall (struct breakpoint *b, struct ui_file *fp)
7662 {
7663   struct syscall_catchpoint *c = (struct syscall_catchpoint *) b;
7664
7665   fprintf_unfiltered (fp, "catch syscall");
7666
7667   if (c->syscalls_to_be_caught)
7668     {
7669       int i, iter;
7670
7671       for (i = 0;
7672            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
7673            i++)
7674         {
7675           struct syscall s;
7676
7677           get_syscall_by_number (iter, &s);
7678           if (s.name)
7679             fprintf_unfiltered (fp, " %s", s.name);
7680           else
7681             fprintf_unfiltered (fp, " %d", s.number);
7682         }
7683     }
7684   print_recreate_thread (b, fp);
7685 }
7686
7687 /* The breakpoint_ops structure to be used in syscall catchpoints.  */
7688
7689 static struct breakpoint_ops catch_syscall_breakpoint_ops;
7690
7691 /* Returns non-zero if 'b' is a syscall catchpoint.  */
7692
7693 static int
7694 syscall_catchpoint_p (struct breakpoint *b)
7695 {
7696   return (b->ops == &catch_syscall_breakpoint_ops);
7697 }
7698
7699 /* Initialize a new breakpoint of the bp_catchpoint kind.  If TEMPFLAG
7700    is non-zero, then make the breakpoint temporary.  If COND_STRING is
7701    not NULL, then store it in the breakpoint.  OPS, if not NULL, is
7702    the breakpoint_ops structure associated to the catchpoint.  */
7703
7704 static void
7705 init_catchpoint (struct breakpoint *b,
7706                  struct gdbarch *gdbarch, int tempflag,
7707                  char *cond_string,
7708                  const struct breakpoint_ops *ops)
7709 {
7710   struct symtab_and_line sal;
7711
7712   init_sal (&sal);
7713   sal.pspace = current_program_space;
7714
7715   init_raw_breakpoint (b, gdbarch, sal, bp_catchpoint, ops);
7716
7717   b->cond_string = (cond_string == NULL) ? NULL : xstrdup (cond_string);
7718   b->disposition = tempflag ? disp_del : disp_donttouch;
7719 }
7720
7721 void
7722 install_breakpoint (int internal, struct breakpoint *b, int update_gll)
7723 {
7724   add_to_breakpoint_chain (b);
7725   set_breakpoint_number (internal, b);
7726   if (!internal)
7727     mention (b);
7728   observer_notify_breakpoint_created (b);
7729
7730   if (update_gll)
7731     update_global_location_list (1);
7732 }
7733
7734 static void
7735 create_fork_vfork_event_catchpoint (struct gdbarch *gdbarch,
7736                                     int tempflag, char *cond_string,
7737                                     const struct breakpoint_ops *ops)
7738 {
7739   struct fork_catchpoint *c = XNEW (struct fork_catchpoint);
7740
7741   init_catchpoint (&c->base, gdbarch, tempflag, cond_string, ops);
7742
7743   c->forked_inferior_pid = null_ptid;
7744
7745   install_breakpoint (0, &c->base, 1);
7746 }
7747
7748 /* Exec catchpoints.  */
7749
7750 /* An instance of this type is used to represent an exec catchpoint.
7751    It includes a "struct breakpoint" as a kind of base class; users
7752    downcast to "struct breakpoint *" when needed.  A breakpoint is
7753    really of this type iff its ops pointer points to
7754    CATCH_EXEC_BREAKPOINT_OPS.  */
7755
7756 struct exec_catchpoint
7757 {
7758   /* The base class.  */
7759   struct breakpoint base;
7760
7761   /* Filename of a program whose exec triggered this catchpoint.
7762      This field is only valid immediately after this catchpoint has
7763      triggered.  */
7764   char *exec_pathname;
7765 };
7766
7767 /* Implement the "dtor" breakpoint_ops method for exec
7768    catchpoints.  */
7769
7770 static void
7771 dtor_catch_exec (struct breakpoint *b)
7772 {
7773   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
7774
7775   xfree (c->exec_pathname);
7776
7777   base_breakpoint_ops.dtor (b);
7778 }
7779
7780 static int
7781 insert_catch_exec (struct bp_location *bl)
7782 {
7783   return target_insert_exec_catchpoint (PIDGET (inferior_ptid));
7784 }
7785
7786 static int
7787 remove_catch_exec (struct bp_location *bl)
7788 {
7789   return target_remove_exec_catchpoint (PIDGET (inferior_ptid));
7790 }
7791
7792 static int
7793 breakpoint_hit_catch_exec (const struct bp_location *bl,
7794                            struct address_space *aspace, CORE_ADDR bp_addr,
7795                            const struct target_waitstatus *ws)
7796 {
7797   struct exec_catchpoint *c = (struct exec_catchpoint *) bl->owner;
7798
7799   if (ws->kind != TARGET_WAITKIND_EXECD)
7800     return 0;
7801
7802   c->exec_pathname = xstrdup (ws->value.execd_pathname);
7803   return 1;
7804 }
7805
7806 static enum print_stop_action
7807 print_it_catch_exec (bpstat bs)
7808 {
7809   struct ui_out *uiout = current_uiout;
7810   struct breakpoint *b = bs->breakpoint_at;
7811   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
7812
7813   annotate_catchpoint (b->number);
7814   if (b->disposition == disp_del)
7815     ui_out_text (uiout, "\nTemporary catchpoint ");
7816   else
7817     ui_out_text (uiout, "\nCatchpoint ");
7818   if (ui_out_is_mi_like_p (uiout))
7819     {
7820       ui_out_field_string (uiout, "reason",
7821                            async_reason_lookup (EXEC_ASYNC_EXEC));
7822       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
7823     }
7824   ui_out_field_int (uiout, "bkptno", b->number);
7825   ui_out_text (uiout, " (exec'd ");
7826   ui_out_field_string (uiout, "new-exec", c->exec_pathname);
7827   ui_out_text (uiout, "), ");
7828
7829   return PRINT_SRC_AND_LOC;
7830 }
7831
7832 static void
7833 print_one_catch_exec (struct breakpoint *b, struct bp_location **last_loc)
7834 {
7835   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
7836   struct value_print_options opts;
7837   struct ui_out *uiout = current_uiout;
7838
7839   get_user_print_options (&opts);
7840
7841   /* Field 4, the address, is omitted (which makes the columns
7842      not line up too nicely with the headers, but the effect
7843      is relatively readable).  */
7844   if (opts.addressprint)
7845     ui_out_field_skip (uiout, "addr");
7846   annotate_field (5);
7847   ui_out_text (uiout, "exec");
7848   if (c->exec_pathname != NULL)
7849     {
7850       ui_out_text (uiout, ", program \"");
7851       ui_out_field_string (uiout, "what", c->exec_pathname);
7852       ui_out_text (uiout, "\" ");
7853     }
7854 }
7855
7856 static void
7857 print_mention_catch_exec (struct breakpoint *b)
7858 {
7859   printf_filtered (_("Catchpoint %d (exec)"), b->number);
7860 }
7861
7862 /* Implement the "print_recreate" breakpoint_ops method for exec
7863    catchpoints.  */
7864
7865 static void
7866 print_recreate_catch_exec (struct breakpoint *b, struct ui_file *fp)
7867 {
7868   fprintf_unfiltered (fp, "catch exec");
7869   print_recreate_thread (b, fp);
7870 }
7871
7872 static struct breakpoint_ops catch_exec_breakpoint_ops;
7873
7874 static void
7875 create_syscall_event_catchpoint (int tempflag, VEC(int) *filter,
7876                                  const struct breakpoint_ops *ops)
7877 {
7878   struct syscall_catchpoint *c;
7879   struct gdbarch *gdbarch = get_current_arch ();
7880
7881   c = XNEW (struct syscall_catchpoint);
7882   init_catchpoint (&c->base, gdbarch, tempflag, NULL, ops);
7883   c->syscalls_to_be_caught = filter;
7884
7885   install_breakpoint (0, &c->base, 1);
7886 }
7887
7888 static int
7889 hw_breakpoint_used_count (void)
7890 {
7891   int i = 0;
7892   struct breakpoint *b;
7893   struct bp_location *bl;
7894
7895   ALL_BREAKPOINTS (b)
7896   {
7897     if (b->type == bp_hardware_breakpoint && breakpoint_enabled (b))
7898       for (bl = b->loc; bl; bl = bl->next)
7899         {
7900           /* Special types of hardware breakpoints may use more than
7901              one register.  */
7902           i += b->ops->resources_needed (bl);
7903         }
7904   }
7905
7906   return i;
7907 }
7908
7909 /* Returns the resources B would use if it were a hardware
7910    watchpoint.  */
7911
7912 static int
7913 hw_watchpoint_use_count (struct breakpoint *b)
7914 {
7915   int i = 0;
7916   struct bp_location *bl;
7917
7918   if (!breakpoint_enabled (b))
7919     return 0;
7920
7921   for (bl = b->loc; bl; bl = bl->next)
7922     {
7923       /* Special types of hardware watchpoints may use more than
7924          one register.  */
7925       i += b->ops->resources_needed (bl);
7926     }
7927
7928   return i;
7929 }
7930
7931 /* Returns the sum the used resources of all hardware watchpoints of
7932    type TYPE in the breakpoints list.  Also returns in OTHER_TYPE_USED
7933    the sum of the used resources of all hardware watchpoints of other
7934    types _not_ TYPE.  */
7935
7936 static int
7937 hw_watchpoint_used_count_others (struct breakpoint *except,
7938                                  enum bptype type, int *other_type_used)
7939 {
7940   int i = 0;
7941   struct breakpoint *b;
7942
7943   *other_type_used = 0;
7944   ALL_BREAKPOINTS (b)
7945     {
7946       if (b == except)
7947         continue;
7948       if (!breakpoint_enabled (b))
7949         continue;
7950
7951       if (b->type == type)
7952         i += hw_watchpoint_use_count (b);
7953       else if (is_hardware_watchpoint (b))
7954         *other_type_used = 1;
7955     }
7956
7957   return i;
7958 }
7959
7960 void
7961 disable_watchpoints_before_interactive_call_start (void)
7962 {
7963   struct breakpoint *b;
7964
7965   ALL_BREAKPOINTS (b)
7966   {
7967     if (is_watchpoint (b) && breakpoint_enabled (b))
7968       {
7969         b->enable_state = bp_call_disabled;
7970         update_global_location_list (0);
7971       }
7972   }
7973 }
7974
7975 void
7976 enable_watchpoints_after_interactive_call_stop (void)
7977 {
7978   struct breakpoint *b;
7979
7980   ALL_BREAKPOINTS (b)
7981   {
7982     if (is_watchpoint (b) && b->enable_state == bp_call_disabled)
7983       {
7984         b->enable_state = bp_enabled;
7985         update_global_location_list (1);
7986       }
7987   }
7988 }
7989
7990 void
7991 disable_breakpoints_before_startup (void)
7992 {
7993   current_program_space->executing_startup = 1;
7994   update_global_location_list (0);
7995 }
7996
7997 void
7998 enable_breakpoints_after_startup (void)
7999 {
8000   current_program_space->executing_startup = 0;
8001   breakpoint_re_set ();
8002 }
8003
8004
8005 /* Set a breakpoint that will evaporate an end of command
8006    at address specified by SAL.
8007    Restrict it to frame FRAME if FRAME is nonzero.  */
8008
8009 struct breakpoint *
8010 set_momentary_breakpoint (struct gdbarch *gdbarch, struct symtab_and_line sal,
8011                           struct frame_id frame_id, enum bptype type)
8012 {
8013   struct breakpoint *b;
8014
8015   /* If FRAME_ID is valid, it should be a real frame, not an inlined
8016      one.  */
8017   gdb_assert (!frame_id_inlined_p (frame_id));
8018
8019   b = set_raw_breakpoint (gdbarch, sal, type, &momentary_breakpoint_ops);
8020   b->enable_state = bp_enabled;
8021   b->disposition = disp_donttouch;
8022   b->frame_id = frame_id;
8023
8024   /* If we're debugging a multi-threaded program, then we want
8025      momentary breakpoints to be active in only a single thread of
8026      control.  */
8027   if (in_thread_list (inferior_ptid))
8028     b->thread = pid_to_thread_id (inferior_ptid);
8029
8030   update_global_location_list_nothrow (1);
8031
8032   return b;
8033 }
8034
8035 /* Make a momentary breakpoint based on the master breakpoint ORIG.
8036    The new breakpoint will have type TYPE, and use OPS as it
8037    breakpoint_ops.  */
8038
8039 static struct breakpoint *
8040 momentary_breakpoint_from_master (struct breakpoint *orig,
8041                                   enum bptype type,
8042                                   const struct breakpoint_ops *ops)
8043 {
8044   struct breakpoint *copy;
8045
8046   copy = set_raw_breakpoint_without_location (orig->gdbarch, type, ops);
8047   copy->loc = allocate_bp_location (copy);
8048   set_breakpoint_location_function (copy->loc, 1);
8049
8050   copy->loc->gdbarch = orig->loc->gdbarch;
8051   copy->loc->requested_address = orig->loc->requested_address;
8052   copy->loc->address = orig->loc->address;
8053   copy->loc->section = orig->loc->section;
8054   copy->loc->pspace = orig->loc->pspace;
8055
8056   if (orig->loc->source_file != NULL)
8057     copy->loc->source_file = xstrdup (orig->loc->source_file);
8058
8059   copy->loc->line_number = orig->loc->line_number;
8060   copy->frame_id = orig->frame_id;
8061   copy->thread = orig->thread;
8062   copy->pspace = orig->pspace;
8063
8064   copy->enable_state = bp_enabled;
8065   copy->disposition = disp_donttouch;
8066   copy->number = internal_breakpoint_number--;
8067
8068   update_global_location_list_nothrow (0);
8069   return copy;
8070 }
8071
8072 /* Make a deep copy of momentary breakpoint ORIG.  Returns NULL if
8073    ORIG is NULL.  */
8074
8075 struct breakpoint *
8076 clone_momentary_breakpoint (struct breakpoint *orig)
8077 {
8078   /* If there's nothing to clone, then return nothing.  */
8079   if (orig == NULL)
8080     return NULL;
8081
8082   return momentary_breakpoint_from_master (orig, orig->type, orig->ops);
8083 }
8084
8085 struct breakpoint *
8086 set_momentary_breakpoint_at_pc (struct gdbarch *gdbarch, CORE_ADDR pc,
8087                                 enum bptype type)
8088 {
8089   struct symtab_and_line sal;
8090
8091   sal = find_pc_line (pc, 0);
8092   sal.pc = pc;
8093   sal.section = find_pc_overlay (pc);
8094   sal.explicit_pc = 1;
8095
8096   return set_momentary_breakpoint (gdbarch, sal, null_frame_id, type);
8097 }
8098 \f
8099
8100 /* Tell the user we have just set a breakpoint B.  */
8101
8102 static void
8103 mention (struct breakpoint *b)
8104 {
8105   b->ops->print_mention (b);
8106   if (ui_out_is_mi_like_p (current_uiout))
8107     return;
8108   printf_filtered ("\n");
8109 }
8110 \f
8111
8112 static struct bp_location *
8113 add_location_to_breakpoint (struct breakpoint *b,
8114                             const struct symtab_and_line *sal)
8115 {
8116   struct bp_location *loc, **tmp;
8117   CORE_ADDR adjusted_address;
8118   struct gdbarch *loc_gdbarch = get_sal_arch (*sal);
8119
8120   if (loc_gdbarch == NULL)
8121     loc_gdbarch = b->gdbarch;
8122
8123   /* Adjust the breakpoint's address prior to allocating a location.
8124      Once we call allocate_bp_location(), that mostly uninitialized
8125      location will be placed on the location chain.  Adjustment of the
8126      breakpoint may cause target_read_memory() to be called and we do
8127      not want its scan of the location chain to find a breakpoint and
8128      location that's only been partially initialized.  */
8129   adjusted_address = adjust_breakpoint_address (loc_gdbarch,
8130                                                 sal->pc, b->type);
8131
8132   loc = allocate_bp_location (b);
8133   for (tmp = &(b->loc); *tmp != NULL; tmp = &((*tmp)->next))
8134     ;
8135   *tmp = loc;
8136
8137   loc->requested_address = sal->pc;
8138   loc->address = adjusted_address;
8139   loc->pspace = sal->pspace;
8140   gdb_assert (loc->pspace != NULL);
8141   loc->section = sal->section;
8142   loc->gdbarch = loc_gdbarch;
8143
8144   if (sal->symtab != NULL)
8145     loc->source_file = xstrdup (sal->symtab->filename);
8146   loc->line_number = sal->line;
8147
8148   set_breakpoint_location_function (loc,
8149                                     sal->explicit_pc || sal->explicit_line);
8150   return loc;
8151 }
8152 \f
8153
8154 /* Return 1 if LOC is pointing to a permanent breakpoint, 
8155    return 0 otherwise.  */
8156
8157 static int
8158 bp_loc_is_permanent (struct bp_location *loc)
8159 {
8160   int len;
8161   CORE_ADDR addr;
8162   const gdb_byte *bpoint;
8163   gdb_byte *target_mem;
8164   struct cleanup *cleanup;
8165   int retval = 0;
8166
8167   gdb_assert (loc != NULL);
8168
8169   addr = loc->address;
8170   bpoint = gdbarch_breakpoint_from_pc (loc->gdbarch, &addr, &len);
8171
8172   /* Software breakpoints unsupported?  */
8173   if (bpoint == NULL)
8174     return 0;
8175
8176   target_mem = alloca (len);
8177
8178   /* Enable the automatic memory restoration from breakpoints while
8179      we read the memory.  Otherwise we could say about our temporary
8180      breakpoints they are permanent.  */
8181   cleanup = save_current_space_and_thread ();
8182
8183   switch_to_program_space_and_thread (loc->pspace);
8184   make_show_memory_breakpoints_cleanup (0);
8185
8186   if (target_read_memory (loc->address, target_mem, len) == 0
8187       && memcmp (target_mem, bpoint, len) == 0)
8188     retval = 1;
8189
8190   do_cleanups (cleanup);
8191
8192   return retval;
8193 }
8194
8195
8196
8197 /* Create a breakpoint with SAL as location.  Use ADDR_STRING
8198    as textual description of the location, and COND_STRING
8199    as condition expression.  */
8200
8201 static void
8202 init_breakpoint_sal (struct breakpoint *b, struct gdbarch *gdbarch,
8203                      struct symtabs_and_lines sals, char *addr_string,
8204                      char *filter, char *cond_string,
8205                      enum bptype type, enum bpdisp disposition,
8206                      int thread, int task, int ignore_count,
8207                      const struct breakpoint_ops *ops, int from_tty,
8208                      int enabled, int internal, int display_canonical)
8209 {
8210   int i;
8211
8212   if (type == bp_hardware_breakpoint)
8213     {
8214       int target_resources_ok;
8215
8216       i = hw_breakpoint_used_count ();
8217       target_resources_ok =
8218         target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
8219                                             i + 1, 0);
8220       if (target_resources_ok == 0)
8221         error (_("No hardware breakpoint support in the target."));
8222       else if (target_resources_ok < 0)
8223         error (_("Hardware breakpoints used exceeds limit."));
8224     }
8225
8226   gdb_assert (sals.nelts > 0);
8227
8228   for (i = 0; i < sals.nelts; ++i)
8229     {
8230       struct symtab_and_line sal = sals.sals[i];
8231       struct bp_location *loc;
8232
8233       if (from_tty)
8234         {
8235           struct gdbarch *loc_gdbarch = get_sal_arch (sal);
8236           if (!loc_gdbarch)
8237             loc_gdbarch = gdbarch;
8238
8239           describe_other_breakpoints (loc_gdbarch,
8240                                       sal.pspace, sal.pc, sal.section, thread);
8241         }
8242
8243       if (i == 0)
8244         {
8245           init_raw_breakpoint (b, gdbarch, sal, type, ops);
8246           b->thread = thread;
8247           b->task = task;
8248   
8249           b->cond_string = cond_string;
8250           b->ignore_count = ignore_count;
8251           b->enable_state = enabled ? bp_enabled : bp_disabled;
8252           b->disposition = disposition;
8253
8254           if (type == bp_static_tracepoint)
8255             {
8256               struct tracepoint *t = (struct tracepoint *) b;
8257               struct static_tracepoint_marker marker;
8258
8259               if (strace_marker_p (b))
8260                 {
8261                   /* We already know the marker exists, otherwise, we
8262                      wouldn't see a sal for it.  */
8263                   char *p = &addr_string[3];
8264                   char *endp;
8265                   char *marker_str;
8266
8267                   p = skip_spaces (p);
8268
8269                   endp = skip_to_space (p);
8270
8271                   marker_str = savestring (p, endp - p);
8272                   t->static_trace_marker_id = marker_str;
8273
8274                   printf_filtered (_("Probed static tracepoint "
8275                                      "marker \"%s\"\n"),
8276                                    t->static_trace_marker_id);
8277                 }
8278               else if (target_static_tracepoint_marker_at (sal.pc, &marker))
8279                 {
8280                   t->static_trace_marker_id = xstrdup (marker.str_id);
8281                   release_static_tracepoint_marker (&marker);
8282
8283                   printf_filtered (_("Probed static tracepoint "
8284                                      "marker \"%s\"\n"),
8285                                    t->static_trace_marker_id);
8286                 }
8287               else
8288                 warning (_("Couldn't determine the static "
8289                            "tracepoint marker to probe"));
8290             }
8291
8292           loc = b->loc;
8293         }
8294       else
8295         {
8296           loc = add_location_to_breakpoint (b, &sal);
8297         }
8298
8299       if (bp_loc_is_permanent (loc))
8300         make_breakpoint_permanent (b);
8301
8302       if (b->cond_string)
8303         {
8304           char *arg = b->cond_string;
8305           loc->cond = parse_exp_1 (&arg, block_for_pc (loc->address), 0);
8306           if (*arg)
8307               error (_("Garbage %s follows condition"), arg);
8308         }
8309     }   
8310
8311   b->display_canonical = display_canonical;
8312   if (addr_string)
8313     b->addr_string = addr_string;
8314   else
8315     /* addr_string has to be used or breakpoint_re_set will delete
8316        me.  */
8317     b->addr_string
8318       = xstrprintf ("*%s", paddress (b->loc->gdbarch, b->loc->address));
8319   b->filter = filter;
8320 }
8321
8322 static void
8323 create_breakpoint_sal (struct gdbarch *gdbarch,
8324                        struct symtabs_and_lines sals, char *addr_string,
8325                        char *filter, char *cond_string,
8326                        enum bptype type, enum bpdisp disposition,
8327                        int thread, int task, int ignore_count,
8328                        const struct breakpoint_ops *ops, int from_tty,
8329                        int enabled, int internal, int display_canonical)
8330 {
8331   struct breakpoint *b;
8332   struct cleanup *old_chain;
8333
8334   if (is_tracepoint_type (type))
8335     {
8336       struct tracepoint *t;
8337
8338       t = XCNEW (struct tracepoint);
8339       b = &t->base;
8340     }
8341   else
8342     b = XNEW (struct breakpoint);
8343
8344   old_chain = make_cleanup (xfree, b);
8345
8346   init_breakpoint_sal (b, gdbarch,
8347                        sals, addr_string,
8348                        filter, cond_string,
8349                        type, disposition,
8350                        thread, task, ignore_count,
8351                        ops, from_tty,
8352                        enabled, internal, display_canonical);
8353   discard_cleanups (old_chain);
8354
8355   install_breakpoint (internal, b, 0);
8356 }
8357
8358 /* Add SALS.nelts breakpoints to the breakpoint table.  For each
8359    SALS.sal[i] breakpoint, include the corresponding ADDR_STRING[i]
8360    value.  COND_STRING, if not NULL, specified the condition to be
8361    used for all breakpoints.  Essentially the only case where
8362    SALS.nelts is not 1 is when we set a breakpoint on an overloaded
8363    function.  In that case, it's still not possible to specify
8364    separate conditions for different overloaded functions, so
8365    we take just a single condition string.
8366    
8367    NOTE: If the function succeeds, the caller is expected to cleanup
8368    the arrays ADDR_STRING, COND_STRING, and SALS (but not the
8369    array contents).  If the function fails (error() is called), the
8370    caller is expected to cleanups both the ADDR_STRING, COND_STRING,
8371    COND and SALS arrays and each of those arrays contents.  */
8372
8373 static void
8374 create_breakpoints_sal (struct gdbarch *gdbarch,
8375                         struct linespec_result *canonical,
8376                         char *cond_string,
8377                         enum bptype type, enum bpdisp disposition,
8378                         int thread, int task, int ignore_count,
8379                         const struct breakpoint_ops *ops, int from_tty,
8380                         int enabled, int internal)
8381 {
8382   int i;
8383   struct linespec_sals *lsal;
8384
8385   if (canonical->pre_expanded)
8386     gdb_assert (VEC_length (linespec_sals, canonical->sals) == 1);
8387
8388   for (i = 0; VEC_iterate (linespec_sals, canonical->sals, i, lsal); ++i)
8389     {
8390       /* Note that 'addr_string' can be NULL in the case of a plain
8391          'break', without arguments.  */
8392       char *addr_string = (canonical->addr_string
8393                            ? xstrdup (canonical->addr_string)
8394                            : NULL);
8395       char *filter_string = lsal->canonical ? xstrdup (lsal->canonical) : NULL;
8396       struct cleanup *inner = make_cleanup (xfree, addr_string);
8397
8398       make_cleanup (xfree, filter_string);
8399       create_breakpoint_sal (gdbarch, lsal->sals,
8400                              addr_string,
8401                              filter_string,
8402                              cond_string, type, disposition,
8403                              thread, task, ignore_count, ops,
8404                              from_tty, enabled, internal,
8405                              canonical->special_display);
8406       discard_cleanups (inner);
8407     }
8408 }
8409
8410 /* Parse ADDRESS which is assumed to be a SAL specification possibly
8411    followed by conditionals.  On return, SALS contains an array of SAL
8412    addresses found.  ADDR_STRING contains a vector of (canonical)
8413    address strings.  ADDRESS points to the end of the SAL.
8414
8415    The array and the line spec strings are allocated on the heap, it is
8416    the caller's responsibility to free them.  */
8417
8418 static void
8419 parse_breakpoint_sals (char **address,
8420                        struct linespec_result *canonical)
8421 {
8422   char *addr_start = *address;
8423
8424   /* If no arg given, or if first arg is 'if ', use the default
8425      breakpoint.  */
8426   if ((*address) == NULL
8427       || (strncmp ((*address), "if", 2) == 0 && isspace ((*address)[2])))
8428     {
8429       /* The last displayed codepoint, if it's valid, is our default breakpoint
8430          address.  */
8431       if (last_displayed_sal_is_valid ())
8432         {
8433           struct linespec_sals lsal;
8434           struct symtab_and_line sal;
8435
8436           init_sal (&sal);              /* Initialize to zeroes.  */
8437           lsal.sals.sals = (struct symtab_and_line *)
8438             xmalloc (sizeof (struct symtab_and_line));
8439
8440           /* Set sal's pspace, pc, symtab, and line to the values
8441              corresponding to the last call to print_frame_info.  */
8442           get_last_displayed_sal (&sal);
8443           sal.section = find_pc_overlay (sal.pc);
8444
8445           /* "break" without arguments is equivalent to "break *PC"
8446              where PC is the last displayed codepoint's address.  So
8447              make sure to set sal.explicit_pc to prevent GDB from
8448              trying to expand the list of sals to include all other
8449              instances with the same symtab and line.  */
8450           sal.explicit_pc = 1;
8451
8452           lsal.sals.sals[0] = sal;
8453           lsal.sals.nelts = 1;
8454           lsal.canonical = NULL;
8455
8456           VEC_safe_push (linespec_sals, canonical->sals, &lsal);
8457         }
8458       else
8459         error (_("No default breakpoint address now."));
8460     }
8461   else
8462     {
8463       /* Force almost all breakpoints to be in terms of the
8464          current_source_symtab (which is decode_line_1's default).
8465          This should produce the results we want almost all of the
8466          time while leaving default_breakpoint_* alone.  */
8467       if (last_displayed_sal_is_valid ())
8468         decode_line_full (address, DECODE_LINE_FUNFIRSTLINE,
8469                           get_last_displayed_symtab (),
8470                           get_last_displayed_line (),
8471                           canonical, NULL, NULL);
8472       else
8473         decode_line_full (address, DECODE_LINE_FUNFIRSTLINE,
8474                           (struct symtab *) NULL, 0,
8475                           canonical, NULL, NULL);
8476     }
8477 }
8478
8479
8480 /* Convert each SAL into a real PC.  Verify that the PC can be
8481    inserted as a breakpoint.  If it can't throw an error.  */
8482
8483 static void
8484 breakpoint_sals_to_pc (struct symtabs_and_lines *sals)
8485 {    
8486   int i;
8487
8488   for (i = 0; i < sals->nelts; i++)
8489     resolve_sal_pc (&sals->sals[i]);
8490 }
8491
8492 /* Fast tracepoints may have restrictions on valid locations.  For
8493    instance, a fast tracepoint using a jump instead of a trap will
8494    likely have to overwrite more bytes than a trap would, and so can
8495    only be placed where the instruction is longer than the jump, or a
8496    multi-instruction sequence does not have a jump into the middle of
8497    it, etc.  */
8498
8499 static void
8500 check_fast_tracepoint_sals (struct gdbarch *gdbarch,
8501                             struct symtabs_and_lines *sals)
8502 {
8503   int i, rslt;
8504   struct symtab_and_line *sal;
8505   char *msg;
8506   struct cleanup *old_chain;
8507
8508   for (i = 0; i < sals->nelts; i++)
8509     {
8510       struct gdbarch *sarch;
8511
8512       sal = &sals->sals[i];
8513
8514       sarch = get_sal_arch (*sal);
8515       /* We fall back to GDBARCH if there is no architecture
8516          associated with SAL.  */
8517       if (sarch == NULL)
8518         sarch = gdbarch;
8519       rslt = gdbarch_fast_tracepoint_valid_at (sarch, sal->pc,
8520                                                NULL, &msg);
8521       old_chain = make_cleanup (xfree, msg);
8522
8523       if (!rslt)
8524         error (_("May not have a fast tracepoint at 0x%s%s"),
8525                paddress (sarch, sal->pc), (msg ? msg : ""));
8526
8527       do_cleanups (old_chain);
8528     }
8529 }
8530
8531 /* Given TOK, a string specification of condition and thread, as
8532    accepted by the 'break' command, extract the condition
8533    string and thread number and set *COND_STRING and *THREAD.
8534    PC identifies the context at which the condition should be parsed.
8535    If no condition is found, *COND_STRING is set to NULL.
8536    If no thread is found, *THREAD is set to -1.  */
8537 static void 
8538 find_condition_and_thread (char *tok, CORE_ADDR pc, 
8539                            char **cond_string, int *thread, int *task)
8540 {
8541   *cond_string = NULL;
8542   *thread = -1;
8543   while (tok && *tok)
8544     {
8545       char *end_tok;
8546       int toklen;
8547       char *cond_start = NULL;
8548       char *cond_end = NULL;
8549
8550       tok = skip_spaces (tok);
8551       
8552       end_tok = skip_to_space (tok);
8553       
8554       toklen = end_tok - tok;
8555       
8556       if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
8557         {
8558           struct expression *expr;
8559
8560           tok = cond_start = end_tok + 1;
8561           expr = parse_exp_1 (&tok, block_for_pc (pc), 0);
8562           xfree (expr);
8563           cond_end = tok;
8564           *cond_string = savestring (cond_start, 
8565                                      cond_end - cond_start);
8566         }
8567       else if (toklen >= 1 && strncmp (tok, "thread", toklen) == 0)
8568         {
8569           char *tmptok;
8570           
8571           tok = end_tok + 1;
8572           tmptok = tok;
8573           *thread = strtol (tok, &tok, 0);
8574           if (tok == tmptok)
8575             error (_("Junk after thread keyword."));
8576           if (!valid_thread_id (*thread))
8577             error (_("Unknown thread %d."), *thread);
8578         }
8579       else if (toklen >= 1 && strncmp (tok, "task", toklen) == 0)
8580         {
8581           char *tmptok;
8582
8583           tok = end_tok + 1;
8584           tmptok = tok;
8585           *task = strtol (tok, &tok, 0);
8586           if (tok == tmptok)
8587             error (_("Junk after task keyword."));
8588           if (!valid_task_id (*task))
8589             error (_("Unknown task %d."), *task);
8590         }
8591       else
8592         error (_("Junk at end of arguments."));
8593     }
8594 }
8595
8596 /* Decode a static tracepoint marker spec.  */
8597
8598 static struct symtabs_and_lines
8599 decode_static_tracepoint_spec (char **arg_p)
8600 {
8601   VEC(static_tracepoint_marker_p) *markers = NULL;
8602   struct symtabs_and_lines sals;
8603   struct symtab_and_line sal;
8604   struct symbol *sym;
8605   struct cleanup *old_chain;
8606   char *p = &(*arg_p)[3];
8607   char *endp;
8608   char *marker_str;
8609   int i;
8610
8611   p = skip_spaces (p);
8612
8613   endp = skip_to_space (p);
8614
8615   marker_str = savestring (p, endp - p);
8616   old_chain = make_cleanup (xfree, marker_str);
8617
8618   markers = target_static_tracepoint_markers_by_strid (marker_str);
8619   if (VEC_empty(static_tracepoint_marker_p, markers))
8620     error (_("No known static tracepoint marker named %s"), marker_str);
8621
8622   sals.nelts = VEC_length(static_tracepoint_marker_p, markers);
8623   sals.sals = xmalloc (sizeof *sals.sals * sals.nelts);
8624
8625   for (i = 0; i < sals.nelts; i++)
8626     {
8627       struct static_tracepoint_marker *marker;
8628
8629       marker = VEC_index (static_tracepoint_marker_p, markers, i);
8630
8631       init_sal (&sals.sals[i]);
8632
8633       sals.sals[i] = find_pc_line (marker->address, 0);
8634       sals.sals[i].pc = marker->address;
8635
8636       release_static_tracepoint_marker (marker);
8637     }
8638
8639   do_cleanups (old_chain);
8640
8641   *arg_p = endp;
8642   return sals;
8643 }
8644
8645 /* Set a breakpoint.  This function is shared between CLI and MI
8646    functions for setting a breakpoint.  This function has two major
8647    modes of operations, selected by the PARSE_CONDITION_AND_THREAD
8648    parameter.  If non-zero, the function will parse arg, extracting
8649    breakpoint location, address and thread.  Otherwise, ARG is just
8650    the location of breakpoint, with condition and thread specified by
8651    the COND_STRING and THREAD parameters.  If INTERNAL is non-zero,
8652    the breakpoint number will be allocated from the internal
8653    breakpoint count.  Returns true if any breakpoint was created;
8654    false otherwise.  */
8655
8656 int
8657 create_breakpoint (struct gdbarch *gdbarch,
8658                    char *arg, char *cond_string, int thread,
8659                    int parse_condition_and_thread,
8660                    int tempflag, enum bptype type_wanted,
8661                    int ignore_count,
8662                    enum auto_boolean pending_break_support,
8663                    const struct breakpoint_ops *ops,
8664                    int from_tty, int enabled, int internal)
8665 {
8666   volatile struct gdb_exception e;
8667   char *copy_arg = NULL;
8668   char *addr_start = arg;
8669   struct linespec_result canonical;
8670   struct cleanup *old_chain;
8671   struct cleanup *bkpt_chain = NULL;
8672   int i;
8673   int pending = 0;
8674   int task = 0;
8675   int prev_bkpt_count = breakpoint_count;
8676
8677   gdb_assert (ops != NULL);
8678
8679   init_linespec_result (&canonical);
8680
8681   TRY_CATCH (e, RETURN_MASK_ALL)
8682     {
8683       ops->create_sals_from_address (&arg, &canonical, type_wanted,
8684                                      addr_start, &copy_arg);
8685     }
8686
8687   /* If caller is interested in rc value from parse, set value.  */
8688   switch (e.reason)
8689     {
8690     case GDB_NO_ERROR:
8691       if (VEC_empty (linespec_sals, canonical.sals))
8692         return 0;
8693       break;
8694     case RETURN_ERROR:
8695       switch (e.error)
8696         {
8697         case NOT_FOUND_ERROR:
8698
8699           /* If pending breakpoint support is turned off, throw
8700              error.  */
8701
8702           if (pending_break_support == AUTO_BOOLEAN_FALSE)
8703             throw_exception (e);
8704
8705           exception_print (gdb_stderr, e);
8706
8707           /* If pending breakpoint support is auto query and the user
8708              selects no, then simply return the error code.  */
8709           if (pending_break_support == AUTO_BOOLEAN_AUTO
8710               && !nquery (_("Make %s pending on future shared library load? "),
8711                           bptype_string (type_wanted)))
8712             return 0;
8713
8714           /* At this point, either the user was queried about setting
8715              a pending breakpoint and selected yes, or pending
8716              breakpoint behavior is on and thus a pending breakpoint
8717              is defaulted on behalf of the user.  */
8718           {
8719             struct linespec_sals lsal;
8720
8721             copy_arg = xstrdup (addr_start);
8722             lsal.canonical = xstrdup (copy_arg);
8723             lsal.sals.nelts = 1;
8724             lsal.sals.sals = XNEW (struct symtab_and_line);
8725             init_sal (&lsal.sals.sals[0]);
8726             pending = 1;
8727             VEC_safe_push (linespec_sals, canonical.sals, &lsal);
8728           }
8729           break;
8730         default:
8731           throw_exception (e);
8732         }
8733       break;
8734     default:
8735       throw_exception (e);
8736     }
8737
8738   /* Create a chain of things that always need to be cleaned up.  */
8739   old_chain = make_cleanup_destroy_linespec_result (&canonical);
8740
8741   /* ----------------------------- SNIP -----------------------------
8742      Anything added to the cleanup chain beyond this point is assumed
8743      to be part of a breakpoint.  If the breakpoint create succeeds
8744      then the memory is not reclaimed.  */
8745   bkpt_chain = make_cleanup (null_cleanup, 0);
8746
8747   /* Resolve all line numbers to PC's and verify that the addresses
8748      are ok for the target.  */
8749   if (!pending)
8750     {
8751       int ix;
8752       struct linespec_sals *iter;
8753
8754       for (ix = 0; VEC_iterate (linespec_sals, canonical.sals, ix, iter); ++ix)
8755         breakpoint_sals_to_pc (&iter->sals);
8756     }
8757
8758   /* Fast tracepoints may have additional restrictions on location.  */
8759   if (!pending && type_wanted == bp_fast_tracepoint)
8760     {
8761       int ix;
8762       struct linespec_sals *iter;
8763
8764       for (ix = 0; VEC_iterate (linespec_sals, canonical.sals, ix, iter); ++ix)
8765         check_fast_tracepoint_sals (gdbarch, &iter->sals);
8766     }
8767
8768   /* Verify that condition can be parsed, before setting any
8769      breakpoints.  Allocate a separate condition expression for each
8770      breakpoint.  */
8771   if (!pending)
8772     {
8773       struct linespec_sals *lsal;
8774
8775       lsal = VEC_index (linespec_sals, canonical.sals, 0);
8776
8777       if (parse_condition_and_thread)
8778         {
8779             /* Here we only parse 'arg' to separate condition
8780                from thread number, so parsing in context of first
8781                sal is OK.  When setting the breakpoint we'll 
8782                re-parse it in context of each sal.  */
8783             cond_string = NULL;
8784             thread = -1;
8785             find_condition_and_thread (arg, lsal->sals.sals[0].pc, &cond_string,
8786                                        &thread, &task);
8787             if (cond_string)
8788                 make_cleanup (xfree, cond_string);
8789         }
8790       else
8791         {
8792             /* Create a private copy of condition string.  */
8793             if (cond_string)
8794             {
8795                 cond_string = xstrdup (cond_string);
8796                 make_cleanup (xfree, cond_string);
8797             }
8798         }
8799
8800       ops->create_breakpoints_sal (gdbarch, &canonical, lsal,
8801                                    cond_string, type_wanted,
8802                                    tempflag ? disp_del : disp_donttouch,
8803                                    thread, task, ignore_count, ops,
8804                                    from_tty, enabled, internal);
8805     }
8806   else
8807     {
8808       struct breakpoint *b;
8809
8810       make_cleanup (xfree, copy_arg);
8811
8812       if (is_tracepoint_type (type_wanted))
8813         {
8814           struct tracepoint *t;
8815
8816           t = XCNEW (struct tracepoint);
8817           b = &t->base;
8818         }
8819       else
8820         b = XNEW (struct breakpoint);
8821
8822       init_raw_breakpoint_without_location (b, gdbarch, type_wanted, ops);
8823
8824       b->addr_string = copy_arg;
8825       b->cond_string = NULL;
8826       b->ignore_count = ignore_count;
8827       b->disposition = tempflag ? disp_del : disp_donttouch;
8828       b->condition_not_parsed = 1;
8829       b->enable_state = enabled ? bp_enabled : bp_disabled;
8830       if ((type_wanted != bp_breakpoint
8831            && type_wanted != bp_hardware_breakpoint) || thread != -1)
8832         b->pspace = current_program_space;
8833
8834       install_breakpoint (internal, b, 0);
8835     }
8836   
8837   if (VEC_length (linespec_sals, canonical.sals) > 1)
8838     {
8839       warning (_("Multiple breakpoints were set.\nUse the "
8840                  "\"delete\" command to delete unwanted breakpoints."));
8841       prev_breakpoint_count = prev_bkpt_count;
8842     }
8843
8844   /* That's it.  Discard the cleanups for data inserted into the
8845      breakpoint.  */
8846   discard_cleanups (bkpt_chain);
8847   /* But cleanup everything else.  */
8848   do_cleanups (old_chain);
8849
8850   /* error call may happen here - have BKPT_CHAIN already discarded.  */
8851   update_global_location_list (1);
8852
8853   return 1;
8854 }
8855
8856 /* Set a breakpoint.
8857    ARG is a string describing breakpoint address,
8858    condition, and thread.
8859    FLAG specifies if a breakpoint is hardware on,
8860    and if breakpoint is temporary, using BP_HARDWARE_FLAG
8861    and BP_TEMPFLAG.  */
8862
8863 static void
8864 break_command_1 (char *arg, int flag, int from_tty)
8865 {
8866   int tempflag = flag & BP_TEMPFLAG;
8867   enum bptype type_wanted = (flag & BP_HARDWAREFLAG
8868                              ? bp_hardware_breakpoint
8869                              : bp_breakpoint);
8870
8871   create_breakpoint (get_current_arch (),
8872                      arg,
8873                      NULL, 0, 1 /* parse arg */,
8874                      tempflag, type_wanted,
8875                      0 /* Ignore count */,
8876                      pending_break_support,
8877                      &bkpt_breakpoint_ops,
8878                      from_tty,
8879                      1 /* enabled */,
8880                      0 /* internal */);
8881 }
8882
8883 /* Helper function for break_command_1 and disassemble_command.  */
8884
8885 void
8886 resolve_sal_pc (struct symtab_and_line *sal)
8887 {
8888   CORE_ADDR pc;
8889
8890   if (sal->pc == 0 && sal->symtab != NULL)
8891     {
8892       if (!find_line_pc (sal->symtab, sal->line, &pc))
8893         error (_("No line %d in file \"%s\"."),
8894                sal->line, sal->symtab->filename);
8895       sal->pc = pc;
8896
8897       /* If this SAL corresponds to a breakpoint inserted using a line
8898          number, then skip the function prologue if necessary.  */
8899       if (sal->explicit_line)
8900         skip_prologue_sal (sal);
8901     }
8902
8903   if (sal->section == 0 && sal->symtab != NULL)
8904     {
8905       struct blockvector *bv;
8906       struct block *b;
8907       struct symbol *sym;
8908
8909       bv = blockvector_for_pc_sect (sal->pc, 0, &b, sal->symtab);
8910       if (bv != NULL)
8911         {
8912           sym = block_linkage_function (b);
8913           if (sym != NULL)
8914             {
8915               fixup_symbol_section (sym, sal->symtab->objfile);
8916               sal->section = SYMBOL_OBJ_SECTION (sym);
8917             }
8918           else
8919             {
8920               /* It really is worthwhile to have the section, so we'll
8921                  just have to look harder. This case can be executed
8922                  if we have line numbers but no functions (as can
8923                  happen in assembly source).  */
8924
8925               struct minimal_symbol *msym;
8926               struct cleanup *old_chain = save_current_space_and_thread ();
8927
8928               switch_to_program_space_and_thread (sal->pspace);
8929
8930               msym = lookup_minimal_symbol_by_pc (sal->pc);
8931               if (msym)
8932                 sal->section = SYMBOL_OBJ_SECTION (msym);
8933
8934               do_cleanups (old_chain);
8935             }
8936         }
8937     }
8938 }
8939
8940 void
8941 break_command (char *arg, int from_tty)
8942 {
8943   break_command_1 (arg, 0, from_tty);
8944 }
8945
8946 void
8947 tbreak_command (char *arg, int from_tty)
8948 {
8949   break_command_1 (arg, BP_TEMPFLAG, from_tty);
8950 }
8951
8952 static void
8953 hbreak_command (char *arg, int from_tty)
8954 {
8955   break_command_1 (arg, BP_HARDWAREFLAG, from_tty);
8956 }
8957
8958 static void
8959 thbreak_command (char *arg, int from_tty)
8960 {
8961   break_command_1 (arg, (BP_TEMPFLAG | BP_HARDWAREFLAG), from_tty);
8962 }
8963
8964 static void
8965 stop_command (char *arg, int from_tty)
8966 {
8967   printf_filtered (_("Specify the type of breakpoint to set.\n\
8968 Usage: stop in <function | address>\n\
8969        stop at <line>\n"));
8970 }
8971
8972 static void
8973 stopin_command (char *arg, int from_tty)
8974 {
8975   int badInput = 0;
8976
8977   if (arg == (char *) NULL)
8978     badInput = 1;
8979   else if (*arg != '*')
8980     {
8981       char *argptr = arg;
8982       int hasColon = 0;
8983
8984       /* Look for a ':'.  If this is a line number specification, then
8985          say it is bad, otherwise, it should be an address or
8986          function/method name.  */
8987       while (*argptr && !hasColon)
8988         {
8989           hasColon = (*argptr == ':');
8990           argptr++;
8991         }
8992
8993       if (hasColon)
8994         badInput = (*argptr != ':');    /* Not a class::method */
8995       else
8996         badInput = isdigit (*arg);      /* a simple line number */
8997     }
8998
8999   if (badInput)
9000     printf_filtered (_("Usage: stop in <function | address>\n"));
9001   else
9002     break_command_1 (arg, 0, from_tty);
9003 }
9004
9005 static void
9006 stopat_command (char *arg, int from_tty)
9007 {
9008   int badInput = 0;
9009
9010   if (arg == (char *) NULL || *arg == '*')      /* no line number */
9011     badInput = 1;
9012   else
9013     {
9014       char *argptr = arg;
9015       int hasColon = 0;
9016
9017       /* Look for a ':'.  If there is a '::' then get out, otherwise
9018          it is probably a line number.  */
9019       while (*argptr && !hasColon)
9020         {
9021           hasColon = (*argptr == ':');
9022           argptr++;
9023         }
9024
9025       if (hasColon)
9026         badInput = (*argptr == ':');    /* we have class::method */
9027       else
9028         badInput = !isdigit (*arg);     /* not a line number */
9029     }
9030
9031   if (badInput)
9032     printf_filtered (_("Usage: stop at <line>\n"));
9033   else
9034     break_command_1 (arg, 0, from_tty);
9035 }
9036
9037 /* Implement the "breakpoint_hit" breakpoint_ops method for
9038    ranged breakpoints.  */
9039
9040 static int
9041 breakpoint_hit_ranged_breakpoint (const struct bp_location *bl,
9042                                   struct address_space *aspace,
9043                                   CORE_ADDR bp_addr,
9044                                   const struct target_waitstatus *ws)
9045 {
9046   if (ws->kind != TARGET_WAITKIND_STOPPED
9047       || ws->value.sig != TARGET_SIGNAL_TRAP)
9048     return 0;
9049
9050   return breakpoint_address_match_range (bl->pspace->aspace, bl->address,
9051                                          bl->length, aspace, bp_addr);
9052 }
9053
9054 /* Implement the "resources_needed" breakpoint_ops method for
9055    ranged breakpoints.  */
9056
9057 static int
9058 resources_needed_ranged_breakpoint (const struct bp_location *bl)
9059 {
9060   return target_ranged_break_num_registers ();
9061 }
9062
9063 /* Implement the "print_it" breakpoint_ops method for
9064    ranged breakpoints.  */
9065
9066 static enum print_stop_action
9067 print_it_ranged_breakpoint (bpstat bs)
9068 {
9069   struct breakpoint *b = bs->breakpoint_at;
9070   struct bp_location *bl = b->loc;
9071   struct ui_out *uiout = current_uiout;
9072
9073   gdb_assert (b->type == bp_hardware_breakpoint);
9074
9075   /* Ranged breakpoints have only one location.  */
9076   gdb_assert (bl && bl->next == NULL);
9077
9078   annotate_breakpoint (b->number);
9079   if (b->disposition == disp_del)
9080     ui_out_text (uiout, "\nTemporary ranged breakpoint ");
9081   else
9082     ui_out_text (uiout, "\nRanged breakpoint ");
9083   if (ui_out_is_mi_like_p (uiout))
9084     {
9085       ui_out_field_string (uiout, "reason",
9086                       async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
9087       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
9088     }
9089   ui_out_field_int (uiout, "bkptno", b->number);
9090   ui_out_text (uiout, ", ");
9091
9092   return PRINT_SRC_AND_LOC;
9093 }
9094
9095 /* Implement the "print_one" breakpoint_ops method for
9096    ranged breakpoints.  */
9097
9098 static void
9099 print_one_ranged_breakpoint (struct breakpoint *b,
9100                              struct bp_location **last_loc)
9101 {
9102   struct bp_location *bl = b->loc;
9103   struct value_print_options opts;
9104   struct ui_out *uiout = current_uiout;
9105
9106   /* Ranged breakpoints have only one location.  */
9107   gdb_assert (bl && bl->next == NULL);
9108
9109   get_user_print_options (&opts);
9110
9111   if (opts.addressprint)
9112     /* We don't print the address range here, it will be printed later
9113        by print_one_detail_ranged_breakpoint.  */
9114     ui_out_field_skip (uiout, "addr");
9115   annotate_field (5);
9116   print_breakpoint_location (b, bl);
9117   *last_loc = bl;
9118 }
9119
9120 /* Implement the "print_one_detail" breakpoint_ops method for
9121    ranged breakpoints.  */
9122
9123 static void
9124 print_one_detail_ranged_breakpoint (const struct breakpoint *b,
9125                                     struct ui_out *uiout)
9126 {
9127   CORE_ADDR address_start, address_end;
9128   struct bp_location *bl = b->loc;
9129   struct ui_stream *stb = ui_out_stream_new (uiout);
9130   struct cleanup *cleanup = make_cleanup_ui_out_stream_delete (stb);
9131
9132   gdb_assert (bl);
9133
9134   address_start = bl->address;
9135   address_end = address_start + bl->length - 1;
9136
9137   ui_out_text (uiout, "\taddress range: ");
9138   fprintf_unfiltered (stb->stream, "[%s, %s]",
9139                       print_core_address (bl->gdbarch, address_start),
9140                       print_core_address (bl->gdbarch, address_end));
9141   ui_out_field_stream (uiout, "addr", stb);
9142   ui_out_text (uiout, "\n");
9143
9144   do_cleanups (cleanup);
9145 }
9146
9147 /* Implement the "print_mention" breakpoint_ops method for
9148    ranged breakpoints.  */
9149
9150 static void
9151 print_mention_ranged_breakpoint (struct breakpoint *b)
9152 {
9153   struct bp_location *bl = b->loc;
9154   struct ui_out *uiout = current_uiout;
9155
9156   gdb_assert (bl);
9157   gdb_assert (b->type == bp_hardware_breakpoint);
9158
9159   if (ui_out_is_mi_like_p (uiout))
9160     return;
9161
9162   printf_filtered (_("Hardware assisted ranged breakpoint %d from %s to %s."),
9163                    b->number, paddress (bl->gdbarch, bl->address),
9164                    paddress (bl->gdbarch, bl->address + bl->length - 1));
9165 }
9166
9167 /* Implement the "print_recreate" breakpoint_ops method for
9168    ranged breakpoints.  */
9169
9170 static void
9171 print_recreate_ranged_breakpoint (struct breakpoint *b, struct ui_file *fp)
9172 {
9173   fprintf_unfiltered (fp, "break-range %s, %s", b->addr_string,
9174                       b->addr_string_range_end);
9175   print_recreate_thread (b, fp);
9176 }
9177
9178 /* The breakpoint_ops structure to be used in ranged breakpoints.  */
9179
9180 static struct breakpoint_ops ranged_breakpoint_ops;
9181
9182 /* Find the address where the end of the breakpoint range should be
9183    placed, given the SAL of the end of the range.  This is so that if
9184    the user provides a line number, the end of the range is set to the
9185    last instruction of the given line.  */
9186
9187 static CORE_ADDR
9188 find_breakpoint_range_end (struct symtab_and_line sal)
9189 {
9190   CORE_ADDR end;
9191
9192   /* If the user provided a PC value, use it.  Otherwise,
9193      find the address of the end of the given location.  */
9194   if (sal.explicit_pc)
9195     end = sal.pc;
9196   else
9197     {
9198       int ret;
9199       CORE_ADDR start;
9200
9201       ret = find_line_pc_range (sal, &start, &end);
9202       if (!ret)
9203         error (_("Could not find location of the end of the range."));
9204
9205       /* find_line_pc_range returns the start of the next line.  */
9206       end--;
9207     }
9208
9209   return end;
9210 }
9211
9212 /* Implement the "break-range" CLI command.  */
9213
9214 static void
9215 break_range_command (char *arg, int from_tty)
9216 {
9217   char *arg_start, *addr_string_start, *addr_string_end;
9218   struct linespec_result canonical_start, canonical_end;
9219   int bp_count, can_use_bp, length;
9220   CORE_ADDR end;
9221   struct breakpoint *b;
9222   struct symtab_and_line sal_start, sal_end;
9223   struct cleanup *cleanup_bkpt;
9224   struct linespec_sals *lsal_start, *lsal_end;
9225
9226   /* We don't support software ranged breakpoints.  */
9227   if (target_ranged_break_num_registers () < 0)
9228     error (_("This target does not support hardware ranged breakpoints."));
9229
9230   bp_count = hw_breakpoint_used_count ();
9231   bp_count += target_ranged_break_num_registers ();
9232   can_use_bp = target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
9233                                                    bp_count, 0);
9234   if (can_use_bp < 0)
9235     error (_("Hardware breakpoints used exceeds limit."));
9236
9237   arg = skip_spaces (arg);
9238   if (arg == NULL || arg[0] == '\0')
9239     error(_("No address range specified."));
9240
9241   init_linespec_result (&canonical_start);
9242
9243   arg_start = arg;
9244   parse_breakpoint_sals (&arg, &canonical_start);
9245
9246   cleanup_bkpt = make_cleanup_destroy_linespec_result (&canonical_start);
9247
9248   if (arg[0] != ',')
9249     error (_("Too few arguments."));
9250   else if (VEC_empty (linespec_sals, canonical_start.sals))
9251     error (_("Could not find location of the beginning of the range."));
9252
9253   lsal_start = VEC_index (linespec_sals, canonical_start.sals, 0);
9254
9255   if (VEC_length (linespec_sals, canonical_start.sals) > 1
9256       || lsal_start->sals.nelts != 1)
9257     error (_("Cannot create a ranged breakpoint with multiple locations."));
9258
9259   sal_start = lsal_start->sals.sals[0];
9260   addr_string_start = savestring (arg_start, arg - arg_start);
9261   make_cleanup (xfree, addr_string_start);
9262
9263   arg++;        /* Skip the comma.  */
9264   arg = skip_spaces (arg);
9265
9266   /* Parse the end location.  */
9267
9268   init_linespec_result (&canonical_end);
9269   arg_start = arg;
9270
9271   /* We call decode_line_full directly here instead of using
9272      parse_breakpoint_sals because we need to specify the start location's
9273      symtab and line as the default symtab and line for the end of the
9274      range.  This makes it possible to have ranges like "foo.c:27, +14",
9275      where +14 means 14 lines from the start location.  */
9276   decode_line_full (&arg, DECODE_LINE_FUNFIRSTLINE,
9277                     sal_start.symtab, sal_start.line,
9278                     &canonical_end, NULL, NULL);
9279
9280   make_cleanup_destroy_linespec_result (&canonical_end);
9281
9282   if (VEC_empty (linespec_sals, canonical_end.sals))
9283     error (_("Could not find location of the end of the range."));
9284
9285   lsal_end = VEC_index (linespec_sals, canonical_end.sals, 0);
9286   if (VEC_length (linespec_sals, canonical_end.sals) > 1
9287       || lsal_end->sals.nelts != 1)
9288     error (_("Cannot create a ranged breakpoint with multiple locations."));
9289
9290   sal_end = lsal_end->sals.sals[0];
9291   addr_string_end = savestring (arg_start, arg - arg_start);
9292   make_cleanup (xfree, addr_string_end);
9293
9294   end = find_breakpoint_range_end (sal_end);
9295   if (sal_start.pc > end)
9296     error (_("Invalid address range, end precedes start."));
9297
9298   length = end - sal_start.pc + 1;
9299   if (length < 0)
9300     /* Length overflowed.  */
9301     error (_("Address range too large."));
9302   else if (length == 1)
9303     {
9304       /* This range is simple enough to be handled by
9305          the `hbreak' command.  */
9306       hbreak_command (addr_string_start, 1);
9307
9308       do_cleanups (cleanup_bkpt);
9309
9310       return;
9311     }
9312
9313   /* Now set up the breakpoint.  */
9314   b = set_raw_breakpoint (get_current_arch (), sal_start,
9315                           bp_hardware_breakpoint, &ranged_breakpoint_ops);
9316   set_breakpoint_count (breakpoint_count + 1);
9317   b->number = breakpoint_count;
9318   b->disposition = disp_donttouch;
9319   b->addr_string = xstrdup (addr_string_start);
9320   b->addr_string_range_end = xstrdup (addr_string_end);
9321   b->loc->length = length;
9322
9323   do_cleanups (cleanup_bkpt);
9324
9325   mention (b);
9326   observer_notify_breakpoint_created (b);
9327   update_global_location_list (1);
9328 }
9329
9330 /*  Return non-zero if EXP is verified as constant.  Returned zero
9331     means EXP is variable.  Also the constant detection may fail for
9332     some constant expressions and in such case still falsely return
9333     zero.  */
9334
9335 static int
9336 watchpoint_exp_is_const (const struct expression *exp)
9337 {
9338   int i = exp->nelts;
9339
9340   while (i > 0)
9341     {
9342       int oplenp, argsp;
9343
9344       /* We are only interested in the descriptor of each element.  */
9345       operator_length (exp, i, &oplenp, &argsp);
9346       i -= oplenp;
9347
9348       switch (exp->elts[i].opcode)
9349         {
9350         case BINOP_ADD:
9351         case BINOP_SUB:
9352         case BINOP_MUL:
9353         case BINOP_DIV:
9354         case BINOP_REM:
9355         case BINOP_MOD:
9356         case BINOP_LSH:
9357         case BINOP_RSH:
9358         case BINOP_LOGICAL_AND:
9359         case BINOP_LOGICAL_OR:
9360         case BINOP_BITWISE_AND:
9361         case BINOP_BITWISE_IOR:
9362         case BINOP_BITWISE_XOR:
9363         case BINOP_EQUAL:
9364         case BINOP_NOTEQUAL:
9365         case BINOP_LESS:
9366         case BINOP_GTR:
9367         case BINOP_LEQ:
9368         case BINOP_GEQ:
9369         case BINOP_REPEAT:
9370         case BINOP_COMMA:
9371         case BINOP_EXP:
9372         case BINOP_MIN:
9373         case BINOP_MAX:
9374         case BINOP_INTDIV:
9375         case BINOP_CONCAT:
9376         case BINOP_IN:
9377         case BINOP_RANGE:
9378         case TERNOP_COND:
9379         case TERNOP_SLICE:
9380         case TERNOP_SLICE_COUNT:
9381
9382         case OP_LONG:
9383         case OP_DOUBLE:
9384         case OP_DECFLOAT:
9385         case OP_LAST:
9386         case OP_COMPLEX:
9387         case OP_STRING:
9388         case OP_BITSTRING:
9389         case OP_ARRAY:
9390         case OP_TYPE:
9391         case OP_NAME:
9392         case OP_OBJC_NSSTRING:
9393
9394         case UNOP_NEG:
9395         case UNOP_LOGICAL_NOT:
9396         case UNOP_COMPLEMENT:
9397         case UNOP_ADDR:
9398         case UNOP_HIGH:
9399         case UNOP_CAST:
9400           /* Unary, binary and ternary operators: We have to check
9401              their operands.  If they are constant, then so is the
9402              result of that operation.  For instance, if A and B are
9403              determined to be constants, then so is "A + B".
9404
9405              UNOP_IND is one exception to the rule above, because the
9406              value of *ADDR is not necessarily a constant, even when
9407              ADDR is.  */
9408           break;
9409
9410         case OP_VAR_VALUE:
9411           /* Check whether the associated symbol is a constant.
9412
9413              We use SYMBOL_CLASS rather than TYPE_CONST because it's
9414              possible that a buggy compiler could mark a variable as
9415              constant even when it is not, and TYPE_CONST would return
9416              true in this case, while SYMBOL_CLASS wouldn't.
9417
9418              We also have to check for function symbols because they
9419              are always constant.  */
9420           {
9421             struct symbol *s = exp->elts[i + 2].symbol;
9422
9423             if (SYMBOL_CLASS (s) != LOC_BLOCK
9424                 && SYMBOL_CLASS (s) != LOC_CONST
9425                 && SYMBOL_CLASS (s) != LOC_CONST_BYTES)
9426               return 0;
9427             break;
9428           }
9429
9430         /* The default action is to return 0 because we are using
9431            the optimistic approach here: If we don't know something,
9432            then it is not a constant.  */
9433         default:
9434           return 0;
9435         }
9436     }
9437
9438   return 1;
9439 }
9440
9441 /* Implement the "dtor" breakpoint_ops method for watchpoints.  */
9442
9443 static void
9444 dtor_watchpoint (struct breakpoint *self)
9445 {
9446   struct watchpoint *w = (struct watchpoint *) self;
9447
9448   xfree (w->cond_exp);
9449   xfree (w->exp);
9450   xfree (w->exp_string);
9451   xfree (w->exp_string_reparse);
9452   value_free (w->val);
9453
9454   base_breakpoint_ops.dtor (self);
9455 }
9456
9457 /* Implement the "re_set" breakpoint_ops method for watchpoints.  */
9458
9459 static void
9460 re_set_watchpoint (struct breakpoint *b)
9461 {
9462   struct watchpoint *w = (struct watchpoint *) b;
9463
9464   /* Watchpoint can be either on expression using entirely global
9465      variables, or it can be on local variables.
9466
9467      Watchpoints of the first kind are never auto-deleted, and even
9468      persist across program restarts.  Since they can use variables
9469      from shared libraries, we need to reparse expression as libraries
9470      are loaded and unloaded.
9471
9472      Watchpoints on local variables can also change meaning as result
9473      of solib event.  For example, if a watchpoint uses both a local
9474      and a global variables in expression, it's a local watchpoint,
9475      but unloading of a shared library will make the expression
9476      invalid.  This is not a very common use case, but we still
9477      re-evaluate expression, to avoid surprises to the user.
9478
9479      Note that for local watchpoints, we re-evaluate it only if
9480      watchpoints frame id is still valid.  If it's not, it means the
9481      watchpoint is out of scope and will be deleted soon.  In fact,
9482      I'm not sure we'll ever be called in this case.
9483
9484      If a local watchpoint's frame id is still valid, then
9485      w->exp_valid_block is likewise valid, and we can safely use it.
9486
9487      Don't do anything about disabled watchpoints, since they will be
9488      reevaluated again when enabled.  */
9489   update_watchpoint (w, 1 /* reparse */);
9490 }
9491
9492 /* Implement the "insert" breakpoint_ops method for hardware watchpoints.  */
9493
9494 static int
9495 insert_watchpoint (struct bp_location *bl)
9496 {
9497   struct watchpoint *w = (struct watchpoint *) bl->owner;
9498   int length = w->exact ? 1 : bl->length;
9499
9500   return target_insert_watchpoint (bl->address, length, bl->watchpoint_type,
9501                                    w->cond_exp);
9502 }
9503
9504 /* Implement the "remove" breakpoint_ops method for hardware watchpoints.  */
9505
9506 static int
9507 remove_watchpoint (struct bp_location *bl)
9508 {
9509   struct watchpoint *w = (struct watchpoint *) bl->owner;
9510   int length = w->exact ? 1 : bl->length;
9511
9512   return target_remove_watchpoint (bl->address, length, bl->watchpoint_type,
9513                                    w->cond_exp);
9514 }
9515
9516 static int
9517 breakpoint_hit_watchpoint (const struct bp_location *bl,
9518                            struct address_space *aspace, CORE_ADDR bp_addr,
9519                            const struct target_waitstatus *ws)
9520 {
9521   struct breakpoint *b = bl->owner;
9522   struct watchpoint *w = (struct watchpoint *) b;
9523
9524   /* Continuable hardware watchpoints are treated as non-existent if the
9525      reason we stopped wasn't a hardware watchpoint (we didn't stop on
9526      some data address).  Otherwise gdb won't stop on a break instruction
9527      in the code (not from a breakpoint) when a hardware watchpoint has
9528      been defined.  Also skip watchpoints which we know did not trigger
9529      (did not match the data address).  */
9530   if (is_hardware_watchpoint (b)
9531       && w->watchpoint_triggered == watch_triggered_no)
9532     return 0;
9533
9534   return 1;
9535 }
9536
9537 static void
9538 check_status_watchpoint (bpstat bs)
9539 {
9540   gdb_assert (is_watchpoint (bs->breakpoint_at));
9541
9542   bpstat_check_watchpoint (bs);
9543 }
9544
9545 /* Implement the "resources_needed" breakpoint_ops method for
9546    hardware watchpoints.  */
9547
9548 static int
9549 resources_needed_watchpoint (const struct bp_location *bl)
9550 {
9551   struct watchpoint *w = (struct watchpoint *) bl->owner;
9552   int length = w->exact? 1 : bl->length;
9553
9554   return target_region_ok_for_hw_watchpoint (bl->address, length);
9555 }
9556
9557 /* Implement the "works_in_software_mode" breakpoint_ops method for
9558    hardware watchpoints.  */
9559
9560 static int
9561 works_in_software_mode_watchpoint (const struct breakpoint *b)
9562 {
9563   /* Read and access watchpoints only work with hardware support.  */
9564   return b->type == bp_watchpoint || b->type == bp_hardware_watchpoint;
9565 }
9566
9567 static enum print_stop_action
9568 print_it_watchpoint (bpstat bs)
9569 {
9570   struct cleanup *old_chain;
9571   struct breakpoint *b;
9572   const struct bp_location *bl;
9573   struct ui_stream *stb;
9574   enum print_stop_action result;
9575   struct watchpoint *w;
9576   struct ui_out *uiout = current_uiout;
9577
9578   gdb_assert (bs->bp_location_at != NULL);
9579
9580   bl = bs->bp_location_at;
9581   b = bs->breakpoint_at;
9582   w = (struct watchpoint *) b;
9583
9584   stb = ui_out_stream_new (uiout);
9585   old_chain = make_cleanup_ui_out_stream_delete (stb);
9586
9587   switch (b->type)
9588     {
9589     case bp_watchpoint:
9590     case bp_hardware_watchpoint:
9591       annotate_watchpoint (b->number);
9592       if (ui_out_is_mi_like_p (uiout))
9593         ui_out_field_string
9594           (uiout, "reason",
9595            async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
9596       mention (b);
9597       make_cleanup_ui_out_tuple_begin_end (uiout, "value");
9598       ui_out_text (uiout, "\nOld value = ");
9599       watchpoint_value_print (bs->old_val, stb->stream);
9600       ui_out_field_stream (uiout, "old", stb);
9601       ui_out_text (uiout, "\nNew value = ");
9602       watchpoint_value_print (w->val, stb->stream);
9603       ui_out_field_stream (uiout, "new", stb);
9604       ui_out_text (uiout, "\n");
9605       /* More than one watchpoint may have been triggered.  */
9606       result = PRINT_UNKNOWN;
9607       break;
9608
9609     case bp_read_watchpoint:
9610       if (ui_out_is_mi_like_p (uiout))
9611         ui_out_field_string
9612           (uiout, "reason",
9613            async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
9614       mention (b);
9615       make_cleanup_ui_out_tuple_begin_end (uiout, "value");
9616       ui_out_text (uiout, "\nValue = ");
9617       watchpoint_value_print (w->val, stb->stream);
9618       ui_out_field_stream (uiout, "value", stb);
9619       ui_out_text (uiout, "\n");
9620       result = PRINT_UNKNOWN;
9621       break;
9622
9623     case bp_access_watchpoint:
9624       if (bs->old_val != NULL)
9625         {
9626           annotate_watchpoint (b->number);
9627           if (ui_out_is_mi_like_p (uiout))
9628             ui_out_field_string
9629               (uiout, "reason",
9630                async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
9631           mention (b);
9632           make_cleanup_ui_out_tuple_begin_end (uiout, "value");
9633           ui_out_text (uiout, "\nOld value = ");
9634           watchpoint_value_print (bs->old_val, stb->stream);
9635           ui_out_field_stream (uiout, "old", stb);
9636           ui_out_text (uiout, "\nNew value = ");
9637         }
9638       else
9639         {
9640           mention (b);
9641           if (ui_out_is_mi_like_p (uiout))
9642             ui_out_field_string
9643               (uiout, "reason",
9644                async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
9645           make_cleanup_ui_out_tuple_begin_end (uiout, "value");
9646           ui_out_text (uiout, "\nValue = ");
9647         }
9648       watchpoint_value_print (w->val, stb->stream);
9649       ui_out_field_stream (uiout, "new", stb);
9650       ui_out_text (uiout, "\n");
9651       result = PRINT_UNKNOWN;
9652       break;
9653     default:
9654       result = PRINT_UNKNOWN;
9655     }
9656
9657   do_cleanups (old_chain);
9658   return result;
9659 }
9660
9661 /* Implement the "print_mention" breakpoint_ops method for hardware
9662    watchpoints.  */
9663
9664 static void
9665 print_mention_watchpoint (struct breakpoint *b)
9666 {
9667   struct cleanup *ui_out_chain;
9668   struct watchpoint *w = (struct watchpoint *) b;
9669   struct ui_out *uiout = current_uiout;
9670
9671   switch (b->type)
9672     {
9673     case bp_watchpoint:
9674       ui_out_text (uiout, "Watchpoint ");
9675       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "wpt");
9676       break;
9677     case bp_hardware_watchpoint:
9678       ui_out_text (uiout, "Hardware watchpoint ");
9679       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "wpt");
9680       break;
9681     case bp_read_watchpoint:
9682       ui_out_text (uiout, "Hardware read watchpoint ");
9683       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-rwpt");
9684       break;
9685     case bp_access_watchpoint:
9686       ui_out_text (uiout, "Hardware access (read/write) watchpoint ");
9687       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-awpt");
9688       break;
9689     default:
9690       internal_error (__FILE__, __LINE__,
9691                       _("Invalid hardware watchpoint type."));
9692     }
9693
9694   ui_out_field_int (uiout, "number", b->number);
9695   ui_out_text (uiout, ": ");
9696   ui_out_field_string (uiout, "exp", w->exp_string);
9697   do_cleanups (ui_out_chain);
9698 }
9699
9700 /* Implement the "print_recreate" breakpoint_ops method for
9701    watchpoints.  */
9702
9703 static void
9704 print_recreate_watchpoint (struct breakpoint *b, struct ui_file *fp)
9705 {
9706   struct watchpoint *w = (struct watchpoint *) b;
9707
9708   switch (b->type)
9709     {
9710     case bp_watchpoint:
9711     case bp_hardware_watchpoint:
9712       fprintf_unfiltered (fp, "watch");
9713       break;
9714     case bp_read_watchpoint:
9715       fprintf_unfiltered (fp, "rwatch");
9716       break;
9717     case bp_access_watchpoint:
9718       fprintf_unfiltered (fp, "awatch");
9719       break;
9720     default:
9721       internal_error (__FILE__, __LINE__,
9722                       _("Invalid watchpoint type."));
9723     }
9724
9725   fprintf_unfiltered (fp, " %s", w->exp_string);
9726   print_recreate_thread (b, fp);
9727 }
9728
9729 /* The breakpoint_ops structure to be used in hardware watchpoints.  */
9730
9731 static struct breakpoint_ops watchpoint_breakpoint_ops;
9732
9733 /* Implement the "insert" breakpoint_ops method for
9734    masked hardware watchpoints.  */
9735
9736 static int
9737 insert_masked_watchpoint (struct bp_location *bl)
9738 {
9739   struct watchpoint *w = (struct watchpoint *) bl->owner;
9740
9741   return target_insert_mask_watchpoint (bl->address, w->hw_wp_mask,
9742                                         bl->watchpoint_type);
9743 }
9744
9745 /* Implement the "remove" breakpoint_ops method for
9746    masked hardware watchpoints.  */
9747
9748 static int
9749 remove_masked_watchpoint (struct bp_location *bl)
9750 {
9751   struct watchpoint *w = (struct watchpoint *) bl->owner;
9752
9753   return target_remove_mask_watchpoint (bl->address, w->hw_wp_mask,
9754                                         bl->watchpoint_type);
9755 }
9756
9757 /* Implement the "resources_needed" breakpoint_ops method for
9758    masked hardware watchpoints.  */
9759
9760 static int
9761 resources_needed_masked_watchpoint (const struct bp_location *bl)
9762 {
9763   struct watchpoint *w = (struct watchpoint *) bl->owner;
9764
9765   return target_masked_watch_num_registers (bl->address, w->hw_wp_mask);
9766 }
9767
9768 /* Implement the "works_in_software_mode" breakpoint_ops method for
9769    masked hardware watchpoints.  */
9770
9771 static int
9772 works_in_software_mode_masked_watchpoint (const struct breakpoint *b)
9773 {
9774   return 0;
9775 }
9776
9777 /* Implement the "print_it" breakpoint_ops method for
9778    masked hardware watchpoints.  */
9779
9780 static enum print_stop_action
9781 print_it_masked_watchpoint (bpstat bs)
9782 {
9783   struct breakpoint *b = bs->breakpoint_at;
9784   struct ui_out *uiout = current_uiout;
9785
9786   /* Masked watchpoints have only one location.  */
9787   gdb_assert (b->loc && b->loc->next == NULL);
9788
9789   switch (b->type)
9790     {
9791     case bp_hardware_watchpoint:
9792       annotate_watchpoint (b->number);
9793       if (ui_out_is_mi_like_p (uiout))
9794         ui_out_field_string
9795           (uiout, "reason",
9796            async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
9797       break;
9798
9799     case bp_read_watchpoint:
9800       if (ui_out_is_mi_like_p (uiout))
9801         ui_out_field_string
9802           (uiout, "reason",
9803            async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
9804       break;
9805
9806     case bp_access_watchpoint:
9807       if (ui_out_is_mi_like_p (uiout))
9808         ui_out_field_string
9809           (uiout, "reason",
9810            async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
9811       break;
9812     default:
9813       internal_error (__FILE__, __LINE__,
9814                       _("Invalid hardware watchpoint type."));
9815     }
9816
9817   mention (b);
9818   ui_out_text (uiout, _("\n\
9819 Check the underlying instruction at PC for the memory\n\
9820 address and value which triggered this watchpoint.\n"));
9821   ui_out_text (uiout, "\n");
9822
9823   /* More than one watchpoint may have been triggered.  */
9824   return PRINT_UNKNOWN;
9825 }
9826
9827 /* Implement the "print_one_detail" breakpoint_ops method for
9828    masked hardware watchpoints.  */
9829
9830 static void
9831 print_one_detail_masked_watchpoint (const struct breakpoint *b,
9832                                     struct ui_out *uiout)
9833 {
9834   struct watchpoint *w = (struct watchpoint *) b;
9835
9836   /* Masked watchpoints have only one location.  */
9837   gdb_assert (b->loc && b->loc->next == NULL);
9838
9839   ui_out_text (uiout, "\tmask ");
9840   ui_out_field_core_addr (uiout, "mask", b->loc->gdbarch, w->hw_wp_mask);
9841   ui_out_text (uiout, "\n");
9842 }
9843
9844 /* Implement the "print_mention" breakpoint_ops method for
9845    masked hardware watchpoints.  */
9846
9847 static void
9848 print_mention_masked_watchpoint (struct breakpoint *b)
9849 {
9850   struct watchpoint *w = (struct watchpoint *) b;
9851   struct ui_out *uiout = current_uiout;
9852   struct cleanup *ui_out_chain;
9853
9854   switch (b->type)
9855     {
9856     case bp_hardware_watchpoint:
9857       ui_out_text (uiout, "Masked hardware watchpoint ");
9858       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "wpt");
9859       break;
9860     case bp_read_watchpoint:
9861       ui_out_text (uiout, "Masked hardware read watchpoint ");
9862       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-rwpt");
9863       break;
9864     case bp_access_watchpoint:
9865       ui_out_text (uiout, "Masked hardware access (read/write) watchpoint ");
9866       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-awpt");
9867       break;
9868     default:
9869       internal_error (__FILE__, __LINE__,
9870                       _("Invalid hardware watchpoint type."));
9871     }
9872
9873   ui_out_field_int (uiout, "number", b->number);
9874   ui_out_text (uiout, ": ");
9875   ui_out_field_string (uiout, "exp", w->exp_string);
9876   do_cleanups (ui_out_chain);
9877 }
9878
9879 /* Implement the "print_recreate" breakpoint_ops method for
9880    masked hardware watchpoints.  */
9881
9882 static void
9883 print_recreate_masked_watchpoint (struct breakpoint *b, struct ui_file *fp)
9884 {
9885   struct watchpoint *w = (struct watchpoint *) b;
9886   char tmp[40];
9887
9888   switch (b->type)
9889     {
9890     case bp_hardware_watchpoint:
9891       fprintf_unfiltered (fp, "watch");
9892       break;
9893     case bp_read_watchpoint:
9894       fprintf_unfiltered (fp, "rwatch");
9895       break;
9896     case bp_access_watchpoint:
9897       fprintf_unfiltered (fp, "awatch");
9898       break;
9899     default:
9900       internal_error (__FILE__, __LINE__,
9901                       _("Invalid hardware watchpoint type."));
9902     }
9903
9904   sprintf_vma (tmp, w->hw_wp_mask);
9905   fprintf_unfiltered (fp, " %s mask 0x%s", w->exp_string, tmp);
9906   print_recreate_thread (b, fp);
9907 }
9908
9909 /* The breakpoint_ops structure to be used in masked hardware watchpoints.  */
9910
9911 static struct breakpoint_ops masked_watchpoint_breakpoint_ops;
9912
9913 /* Tell whether the given watchpoint is a masked hardware watchpoint.  */
9914
9915 static int
9916 is_masked_watchpoint (const struct breakpoint *b)
9917 {
9918   return b->ops == &masked_watchpoint_breakpoint_ops;
9919 }
9920
9921 /* accessflag:  hw_write:  watch write, 
9922                 hw_read:   watch read, 
9923                 hw_access: watch access (read or write) */
9924 static void
9925 watch_command_1 (char *arg, int accessflag, int from_tty,
9926                  int just_location, int internal)
9927 {
9928   volatile struct gdb_exception e;
9929   struct breakpoint *b, *scope_breakpoint = NULL;
9930   struct expression *exp;
9931   struct block *exp_valid_block = NULL, *cond_exp_valid_block = NULL;
9932   struct value *val, *mark, *result;
9933   struct frame_info *frame;
9934   char *exp_start = NULL;
9935   char *exp_end = NULL;
9936   char *tok, *end_tok;
9937   int toklen = -1;
9938   char *cond_start = NULL;
9939   char *cond_end = NULL;
9940   enum bptype bp_type;
9941   int thread = -1;
9942   int pc = 0;
9943   /* Flag to indicate whether we are going to use masks for
9944      the hardware watchpoint.  */
9945   int use_mask = 0;
9946   CORE_ADDR mask = 0;
9947   struct watchpoint *w;
9948
9949   /* Make sure that we actually have parameters to parse.  */
9950   if (arg != NULL && arg[0] != '\0')
9951     {
9952       char *value_start;
9953
9954       /* Look for "parameter value" pairs at the end
9955          of the arguments string.  */
9956       for (tok = arg + strlen (arg) - 1; tok > arg; tok--)
9957         {
9958           /* Skip whitespace at the end of the argument list.  */
9959           while (tok > arg && (*tok == ' ' || *tok == '\t'))
9960             tok--;
9961
9962           /* Find the beginning of the last token.
9963              This is the value of the parameter.  */
9964           while (tok > arg && (*tok != ' ' && *tok != '\t'))
9965             tok--;
9966           value_start = tok + 1;
9967
9968           /* Skip whitespace.  */
9969           while (tok > arg && (*tok == ' ' || *tok == '\t'))
9970             tok--;
9971
9972           end_tok = tok;
9973
9974           /* Find the beginning of the second to last token.
9975              This is the parameter itself.  */
9976           while (tok > arg && (*tok != ' ' && *tok != '\t'))
9977             tok--;
9978           tok++;
9979           toklen = end_tok - tok + 1;
9980
9981           if (toklen == 6 && !strncmp (tok, "thread", 6))
9982             {
9983               /* At this point we've found a "thread" token, which means
9984                  the user is trying to set a watchpoint that triggers
9985                  only in a specific thread.  */
9986               char *endp;
9987
9988               if (thread != -1)
9989                 error(_("You can specify only one thread."));
9990
9991               /* Extract the thread ID from the next token.  */
9992               thread = strtol (value_start, &endp, 0);
9993
9994               /* Check if the user provided a valid numeric value for the
9995                  thread ID.  */
9996               if (*endp != ' ' && *endp != '\t' && *endp != '\0')
9997                 error (_("Invalid thread ID specification %s."), value_start);
9998
9999               /* Check if the thread actually exists.  */
10000               if (!valid_thread_id (thread))
10001                 error (_("Unknown thread %d."), thread);
10002             }
10003           else if (toklen == 4 && !strncmp (tok, "mask", 4))
10004             {
10005               /* We've found a "mask" token, which means the user wants to
10006                  create a hardware watchpoint that is going to have the mask
10007                  facility.  */
10008               struct value *mask_value, *mark;
10009
10010               if (use_mask)
10011                 error(_("You can specify only one mask."));
10012
10013               use_mask = just_location = 1;
10014
10015               mark = value_mark ();
10016               mask_value = parse_to_comma_and_eval (&value_start);
10017               mask = value_as_address (mask_value);
10018               value_free_to_mark (mark);
10019             }
10020           else
10021             /* We didn't recognize what we found.  We should stop here.  */
10022             break;
10023
10024           /* Truncate the string and get rid of the "parameter value" pair before
10025              the arguments string is parsed by the parse_exp_1 function.  */
10026           *tok = '\0';
10027         }
10028     }
10029
10030   /* Parse the rest of the arguments.  */
10031   innermost_block = NULL;
10032   exp_start = arg;
10033   exp = parse_exp_1 (&arg, 0, 0);
10034   exp_end = arg;
10035   /* Remove trailing whitespace from the expression before saving it.
10036      This makes the eventual display of the expression string a bit
10037      prettier.  */
10038   while (exp_end > exp_start && (exp_end[-1] == ' ' || exp_end[-1] == '\t'))
10039     --exp_end;
10040
10041   /* Checking if the expression is not constant.  */
10042   if (watchpoint_exp_is_const (exp))
10043     {
10044       int len;
10045
10046       len = exp_end - exp_start;
10047       while (len > 0 && isspace (exp_start[len - 1]))
10048         len--;
10049       error (_("Cannot watch constant value `%.*s'."), len, exp_start);
10050     }
10051
10052   exp_valid_block = innermost_block;
10053   mark = value_mark ();
10054   fetch_subexp_value (exp, &pc, &val, &result, NULL);
10055
10056   if (just_location)
10057     {
10058       int ret;
10059
10060       exp_valid_block = NULL;
10061       val = value_addr (result);
10062       release_value (val);
10063       value_free_to_mark (mark);
10064
10065       if (use_mask)
10066         {
10067           ret = target_masked_watch_num_registers (value_as_address (val),
10068                                                    mask);
10069           if (ret == -1)
10070             error (_("This target does not support masked watchpoints."));
10071           else if (ret == -2)
10072             error (_("Invalid mask or memory region."));
10073         }
10074     }
10075   else if (val != NULL)
10076     release_value (val);
10077
10078   tok = skip_spaces (arg);
10079   end_tok = skip_to_space (tok);
10080
10081   toklen = end_tok - tok;
10082   if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
10083     {
10084       struct expression *cond;
10085
10086       innermost_block = NULL;
10087       tok = cond_start = end_tok + 1;
10088       cond = parse_exp_1 (&tok, 0, 0);
10089
10090       /* The watchpoint expression may not be local, but the condition
10091          may still be.  E.g.: `watch global if local > 0'.  */
10092       cond_exp_valid_block = innermost_block;
10093
10094       xfree (cond);
10095       cond_end = tok;
10096     }
10097   if (*tok)
10098     error (_("Junk at end of command."));
10099
10100   if (accessflag == hw_read)
10101     bp_type = bp_read_watchpoint;
10102   else if (accessflag == hw_access)
10103     bp_type = bp_access_watchpoint;
10104   else
10105     bp_type = bp_hardware_watchpoint;
10106
10107   frame = block_innermost_frame (exp_valid_block);
10108
10109   /* If the expression is "local", then set up a "watchpoint scope"
10110      breakpoint at the point where we've left the scope of the watchpoint
10111      expression.  Create the scope breakpoint before the watchpoint, so
10112      that we will encounter it first in bpstat_stop_status.  */
10113   if (exp_valid_block && frame)
10114     {
10115       if (frame_id_p (frame_unwind_caller_id (frame)))
10116         {
10117           scope_breakpoint
10118             = create_internal_breakpoint (frame_unwind_caller_arch (frame),
10119                                           frame_unwind_caller_pc (frame),
10120                                           bp_watchpoint_scope,
10121                                           &momentary_breakpoint_ops);
10122
10123           scope_breakpoint->enable_state = bp_enabled;
10124
10125           /* Automatically delete the breakpoint when it hits.  */
10126           scope_breakpoint->disposition = disp_del;
10127
10128           /* Only break in the proper frame (help with recursion).  */
10129           scope_breakpoint->frame_id = frame_unwind_caller_id (frame);
10130
10131           /* Set the address at which we will stop.  */
10132           scope_breakpoint->loc->gdbarch
10133             = frame_unwind_caller_arch (frame);
10134           scope_breakpoint->loc->requested_address
10135             = frame_unwind_caller_pc (frame);
10136           scope_breakpoint->loc->address
10137             = adjust_breakpoint_address (scope_breakpoint->loc->gdbarch,
10138                                          scope_breakpoint->loc->requested_address,
10139                                          scope_breakpoint->type);
10140         }
10141     }
10142
10143   /* Now set up the breakpoint.  */
10144
10145   w = XCNEW (struct watchpoint);
10146   b = &w->base;
10147   if (use_mask)
10148     init_raw_breakpoint_without_location (b, NULL, bp_type,
10149                                           &masked_watchpoint_breakpoint_ops);
10150   else
10151     init_raw_breakpoint_without_location (b, NULL, bp_type,
10152                                           &watchpoint_breakpoint_ops);
10153   b->thread = thread;
10154   b->disposition = disp_donttouch;
10155   b->pspace = current_program_space;
10156   w->exp = exp;
10157   w->exp_valid_block = exp_valid_block;
10158   w->cond_exp_valid_block = cond_exp_valid_block;
10159   if (just_location)
10160     {
10161       struct type *t = value_type (val);
10162       CORE_ADDR addr = value_as_address (val);
10163       char *name;
10164
10165       t = check_typedef (TYPE_TARGET_TYPE (check_typedef (t)));
10166       name = type_to_string (t);
10167
10168       w->exp_string_reparse = xstrprintf ("* (%s *) %s", name,
10169                                           core_addr_to_string (addr));
10170       xfree (name);
10171
10172       w->exp_string = xstrprintf ("-location %.*s",
10173                                   (int) (exp_end - exp_start), exp_start);
10174
10175       /* The above expression is in C.  */
10176       b->language = language_c;
10177     }
10178   else
10179     w->exp_string = savestring (exp_start, exp_end - exp_start);
10180
10181   if (use_mask)
10182     {
10183       w->hw_wp_mask = mask;
10184     }
10185   else
10186     {
10187       w->val = val;
10188       w->val_valid = 1;
10189     }
10190
10191   if (cond_start)
10192     b->cond_string = savestring (cond_start, cond_end - cond_start);
10193   else
10194     b->cond_string = 0;
10195
10196   if (frame)
10197     {
10198       w->watchpoint_frame = get_frame_id (frame);
10199       w->watchpoint_thread = inferior_ptid;
10200     }
10201   else
10202     {
10203       w->watchpoint_frame = null_frame_id;
10204       w->watchpoint_thread = null_ptid;
10205     }
10206
10207   if (scope_breakpoint != NULL)
10208     {
10209       /* The scope breakpoint is related to the watchpoint.  We will
10210          need to act on them together.  */
10211       b->related_breakpoint = scope_breakpoint;
10212       scope_breakpoint->related_breakpoint = b;
10213     }
10214
10215   if (!just_location)
10216     value_free_to_mark (mark);
10217
10218   TRY_CATCH (e, RETURN_MASK_ALL)
10219     {
10220       /* Finally update the new watchpoint.  This creates the locations
10221          that should be inserted.  */
10222       update_watchpoint (w, 1);
10223     }
10224   if (e.reason < 0)
10225     {
10226       delete_breakpoint (b);
10227       throw_exception (e);
10228     }
10229
10230   install_breakpoint (internal, b, 1);
10231 }
10232
10233 /* Return count of debug registers needed to watch the given expression.
10234    If the watchpoint cannot be handled in hardware return zero.  */
10235
10236 static int
10237 can_use_hardware_watchpoint (struct value *v)
10238 {
10239   int found_memory_cnt = 0;
10240   struct value *head = v;
10241
10242   /* Did the user specifically forbid us to use hardware watchpoints? */
10243   if (!can_use_hw_watchpoints)
10244     return 0;
10245
10246   /* Make sure that the value of the expression depends only upon
10247      memory contents, and values computed from them within GDB.  If we
10248      find any register references or function calls, we can't use a
10249      hardware watchpoint.
10250
10251      The idea here is that evaluating an expression generates a series
10252      of values, one holding the value of every subexpression.  (The
10253      expression a*b+c has five subexpressions: a, b, a*b, c, and
10254      a*b+c.)  GDB's values hold almost enough information to establish
10255      the criteria given above --- they identify memory lvalues,
10256      register lvalues, computed values, etcetera.  So we can evaluate
10257      the expression, and then scan the chain of values that leaves
10258      behind to decide whether we can detect any possible change to the
10259      expression's final value using only hardware watchpoints.
10260
10261      However, I don't think that the values returned by inferior
10262      function calls are special in any way.  So this function may not
10263      notice that an expression involving an inferior function call
10264      can't be watched with hardware watchpoints.  FIXME.  */
10265   for (; v; v = value_next (v))
10266     {
10267       if (VALUE_LVAL (v) == lval_memory)
10268         {
10269           if (v != head && value_lazy (v))
10270             /* A lazy memory lvalue in the chain is one that GDB never
10271                needed to fetch; we either just used its address (e.g.,
10272                `a' in `a.b') or we never needed it at all (e.g., `a'
10273                in `a,b').  This doesn't apply to HEAD; if that is
10274                lazy then it was not readable, but watch it anyway.  */
10275             ;
10276           else
10277             {
10278               /* Ahh, memory we actually used!  Check if we can cover
10279                  it with hardware watchpoints.  */
10280               struct type *vtype = check_typedef (value_type (v));
10281
10282               /* We only watch structs and arrays if user asked for it
10283                  explicitly, never if they just happen to appear in a
10284                  middle of some value chain.  */
10285               if (v == head
10286                   || (TYPE_CODE (vtype) != TYPE_CODE_STRUCT
10287                       && TYPE_CODE (vtype) != TYPE_CODE_ARRAY))
10288                 {
10289                   CORE_ADDR vaddr = value_address (v);
10290                   int len;
10291                   int num_regs;
10292
10293                   len = (target_exact_watchpoints
10294                          && is_scalar_type_recursive (vtype))?
10295                     1 : TYPE_LENGTH (value_type (v));
10296
10297                   num_regs = target_region_ok_for_hw_watchpoint (vaddr, len);
10298                   if (!num_regs)
10299                     return 0;
10300                   else
10301                     found_memory_cnt += num_regs;
10302                 }
10303             }
10304         }
10305       else if (VALUE_LVAL (v) != not_lval
10306                && deprecated_value_modifiable (v) == 0)
10307         return 0;       /* These are values from the history (e.g., $1).  */
10308       else if (VALUE_LVAL (v) == lval_register)
10309         return 0;       /* Cannot watch a register with a HW watchpoint.  */
10310     }
10311
10312   /* The expression itself looks suitable for using a hardware
10313      watchpoint, but give the target machine a chance to reject it.  */
10314   return found_memory_cnt;
10315 }
10316
10317 void
10318 watch_command_wrapper (char *arg, int from_tty, int internal)
10319 {
10320   watch_command_1 (arg, hw_write, from_tty, 0, internal);
10321 }
10322
10323 /* A helper function that looks for an argument at the start of a
10324    string.  The argument must also either be at the end of the string,
10325    or be followed by whitespace.  Returns 1 if it finds the argument,
10326    0 otherwise.  If the argument is found, it updates *STR.  */
10327
10328 static int
10329 check_for_argument (char **str, char *arg, int arg_len)
10330 {
10331   if (strncmp (*str, arg, arg_len) == 0
10332       && ((*str)[arg_len] == '\0' || isspace ((*str)[arg_len])))
10333     {
10334       *str += arg_len;
10335       return 1;
10336     }
10337   return 0;
10338 }
10339
10340 /* A helper function that looks for the "-location" argument and then
10341    calls watch_command_1.  */
10342
10343 static void
10344 watch_maybe_just_location (char *arg, int accessflag, int from_tty)
10345 {
10346   int just_location = 0;
10347
10348   if (arg
10349       && (check_for_argument (&arg, "-location", sizeof ("-location") - 1)
10350           || check_for_argument (&arg, "-l", sizeof ("-l") - 1)))
10351     {
10352       arg = skip_spaces (arg);
10353       just_location = 1;
10354     }
10355
10356   watch_command_1 (arg, accessflag, from_tty, just_location, 0);
10357 }
10358
10359 static void
10360 watch_command (char *arg, int from_tty)
10361 {
10362   watch_maybe_just_location (arg, hw_write, from_tty);
10363 }
10364
10365 void
10366 rwatch_command_wrapper (char *arg, int from_tty, int internal)
10367 {
10368   watch_command_1 (arg, hw_read, from_tty, 0, internal);
10369 }
10370
10371 static void
10372 rwatch_command (char *arg, int from_tty)
10373 {
10374   watch_maybe_just_location (arg, hw_read, from_tty);
10375 }
10376
10377 void
10378 awatch_command_wrapper (char *arg, int from_tty, int internal)
10379 {
10380   watch_command_1 (arg, hw_access, from_tty, 0, internal);
10381 }
10382
10383 static void
10384 awatch_command (char *arg, int from_tty)
10385 {
10386   watch_maybe_just_location (arg, hw_access, from_tty);
10387 }
10388 \f
10389
10390 /* Helper routines for the until_command routine in infcmd.c.  Here
10391    because it uses the mechanisms of breakpoints.  */
10392
10393 struct until_break_command_continuation_args
10394 {
10395   struct breakpoint *breakpoint;
10396   struct breakpoint *breakpoint2;
10397   int thread_num;
10398 };
10399
10400 /* This function is called by fetch_inferior_event via the
10401    cmd_continuation pointer, to complete the until command.  It takes
10402    care of cleaning up the temporary breakpoints set up by the until
10403    command.  */
10404 static void
10405 until_break_command_continuation (void *arg, int err)
10406 {
10407   struct until_break_command_continuation_args *a = arg;
10408
10409   delete_breakpoint (a->breakpoint);
10410   if (a->breakpoint2)
10411     delete_breakpoint (a->breakpoint2);
10412   delete_longjmp_breakpoint (a->thread_num);
10413 }
10414
10415 void
10416 until_break_command (char *arg, int from_tty, int anywhere)
10417 {
10418   struct symtabs_and_lines sals;
10419   struct symtab_and_line sal;
10420   struct frame_info *frame = get_selected_frame (NULL);
10421   struct gdbarch *frame_gdbarch = get_frame_arch (frame);
10422   struct frame_id stack_frame_id = get_stack_frame_id (frame);
10423   struct frame_id caller_frame_id = frame_unwind_caller_id (frame);
10424   struct breakpoint *breakpoint;
10425   struct breakpoint *breakpoint2 = NULL;
10426   struct cleanup *old_chain;
10427   int thread;
10428   struct thread_info *tp;
10429
10430   clear_proceed_status ();
10431
10432   /* Set a breakpoint where the user wants it and at return from
10433      this function.  */
10434
10435   if (last_displayed_sal_is_valid ())
10436     sals = decode_line_1 (&arg, DECODE_LINE_FUNFIRSTLINE,
10437                           get_last_displayed_symtab (),
10438                           get_last_displayed_line ());
10439   else
10440     sals = decode_line_1 (&arg, DECODE_LINE_FUNFIRSTLINE,
10441                           (struct symtab *) NULL, 0);
10442
10443   if (sals.nelts != 1)
10444     error (_("Couldn't get information on specified line."));
10445
10446   sal = sals.sals[0];
10447   xfree (sals.sals);    /* malloc'd, so freed.  */
10448
10449   if (*arg)
10450     error (_("Junk at end of arguments."));
10451
10452   resolve_sal_pc (&sal);
10453
10454   tp = inferior_thread ();
10455   thread = tp->num;
10456
10457   old_chain = make_cleanup (null_cleanup, NULL);
10458
10459   /* Installing a breakpoint invalidates the frame chain (as it may
10460      need to switch threads), so do any frame handling first.  */
10461
10462   /* Keep within the current frame, or in frames called by the current
10463      one.  */
10464
10465   if (frame_id_p (caller_frame_id))
10466     {
10467       struct symtab_and_line sal2;
10468
10469       sal2 = find_pc_line (frame_unwind_caller_pc (frame), 0);
10470       sal2.pc = frame_unwind_caller_pc (frame);
10471       breakpoint2 = set_momentary_breakpoint (frame_unwind_caller_arch (frame),
10472                                               sal2,
10473                                               caller_frame_id,
10474                                               bp_until);
10475       make_cleanup_delete_breakpoint (breakpoint2);
10476
10477       set_longjmp_breakpoint (tp, caller_frame_id);
10478       make_cleanup (delete_longjmp_breakpoint_cleanup, &thread);
10479     }
10480
10481   if (anywhere)
10482     /* If the user told us to continue until a specified location,
10483        we don't specify a frame at which we need to stop.  */
10484     breakpoint = set_momentary_breakpoint (frame_gdbarch, sal,
10485                                            null_frame_id, bp_until);
10486   else
10487     /* Otherwise, specify the selected frame, because we want to stop
10488        only at the very same frame.  */
10489     breakpoint = set_momentary_breakpoint (frame_gdbarch, sal,
10490                                            stack_frame_id, bp_until);
10491   make_cleanup_delete_breakpoint (breakpoint);
10492
10493   proceed (-1, TARGET_SIGNAL_DEFAULT, 0);
10494
10495   /* If we are running asynchronously, and proceed call above has
10496      actually managed to start the target, arrange for breakpoints to
10497      be deleted when the target stops.  Otherwise, we're already
10498      stopped and delete breakpoints via cleanup chain.  */
10499
10500   if (target_can_async_p () && is_running (inferior_ptid))
10501     {
10502       struct until_break_command_continuation_args *args;
10503       args = xmalloc (sizeof (*args));
10504
10505       args->breakpoint = breakpoint;
10506       args->breakpoint2 = breakpoint2;
10507       args->thread_num = thread;
10508
10509       discard_cleanups (old_chain);
10510       add_continuation (inferior_thread (),
10511                         until_break_command_continuation, args,
10512                         xfree);
10513     }
10514   else
10515     do_cleanups (old_chain);
10516 }
10517
10518 /* This function attempts to parse an optional "if <cond>" clause
10519    from the arg string.  If one is not found, it returns NULL.
10520
10521    Else, it returns a pointer to the condition string.  (It does not
10522    attempt to evaluate the string against a particular block.)  And,
10523    it updates arg to point to the first character following the parsed
10524    if clause in the arg string.  */
10525
10526 static char *
10527 ep_parse_optional_if_clause (char **arg)
10528 {
10529   char *cond_string;
10530
10531   if (((*arg)[0] != 'i') || ((*arg)[1] != 'f') || !isspace ((*arg)[2]))
10532     return NULL;
10533
10534   /* Skip the "if" keyword.  */
10535   (*arg) += 2;
10536
10537   /* Skip any extra leading whitespace, and record the start of the
10538      condition string.  */
10539   *arg = skip_spaces (*arg);
10540   cond_string = *arg;
10541
10542   /* Assume that the condition occupies the remainder of the arg
10543      string.  */
10544   (*arg) += strlen (cond_string);
10545
10546   return cond_string;
10547 }
10548
10549 /* Commands to deal with catching events, such as signals, exceptions,
10550    process start/exit, etc.  */
10551
10552 typedef enum
10553 {
10554   catch_fork_temporary, catch_vfork_temporary,
10555   catch_fork_permanent, catch_vfork_permanent
10556 }
10557 catch_fork_kind;
10558
10559 static void
10560 catch_fork_command_1 (char *arg, int from_tty, 
10561                       struct cmd_list_element *command)
10562 {
10563   struct gdbarch *gdbarch = get_current_arch ();
10564   char *cond_string = NULL;
10565   catch_fork_kind fork_kind;
10566   int tempflag;
10567
10568   fork_kind = (catch_fork_kind) (uintptr_t) get_cmd_context (command);
10569   tempflag = (fork_kind == catch_fork_temporary
10570               || fork_kind == catch_vfork_temporary);
10571
10572   if (!arg)
10573     arg = "";
10574   arg = skip_spaces (arg);
10575
10576   /* The allowed syntax is:
10577      catch [v]fork
10578      catch [v]fork if <cond>
10579
10580      First, check if there's an if clause.  */
10581   cond_string = ep_parse_optional_if_clause (&arg);
10582
10583   if ((*arg != '\0') && !isspace (*arg))
10584     error (_("Junk at end of arguments."));
10585
10586   /* If this target supports it, create a fork or vfork catchpoint
10587      and enable reporting of such events.  */
10588   switch (fork_kind)
10589     {
10590     case catch_fork_temporary:
10591     case catch_fork_permanent:
10592       create_fork_vfork_event_catchpoint (gdbarch, tempflag, cond_string,
10593                                           &catch_fork_breakpoint_ops);
10594       break;
10595     case catch_vfork_temporary:
10596     case catch_vfork_permanent:
10597       create_fork_vfork_event_catchpoint (gdbarch, tempflag, cond_string,
10598                                           &catch_vfork_breakpoint_ops);
10599       break;
10600     default:
10601       error (_("unsupported or unknown fork kind; cannot catch it"));
10602       break;
10603     }
10604 }
10605
10606 static void
10607 catch_exec_command_1 (char *arg, int from_tty, 
10608                       struct cmd_list_element *command)
10609 {
10610   struct exec_catchpoint *c;
10611   struct gdbarch *gdbarch = get_current_arch ();
10612   int tempflag;
10613   char *cond_string = NULL;
10614
10615   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
10616
10617   if (!arg)
10618     arg = "";
10619   arg = skip_spaces (arg);
10620
10621   /* The allowed syntax is:
10622      catch exec
10623      catch exec if <cond>
10624
10625      First, check if there's an if clause.  */
10626   cond_string = ep_parse_optional_if_clause (&arg);
10627
10628   if ((*arg != '\0') && !isspace (*arg))
10629     error (_("Junk at end of arguments."));
10630
10631   c = XNEW (struct exec_catchpoint);
10632   init_catchpoint (&c->base, gdbarch, tempflag, cond_string,
10633                    &catch_exec_breakpoint_ops);
10634   c->exec_pathname = NULL;
10635
10636   install_breakpoint (0, &c->base, 1);
10637 }
10638
10639 static enum print_stop_action
10640 print_it_exception_catchpoint (bpstat bs)
10641 {
10642   struct ui_out *uiout = current_uiout;
10643   struct breakpoint *b = bs->breakpoint_at;
10644   int bp_temp, bp_throw;
10645
10646   annotate_catchpoint (b->number);
10647
10648   bp_throw = strstr (b->addr_string, "throw") != NULL;
10649   if (b->loc->address != b->loc->requested_address)
10650     breakpoint_adjustment_warning (b->loc->requested_address,
10651                                    b->loc->address,
10652                                    b->number, 1);
10653   bp_temp = b->disposition == disp_del;
10654   ui_out_text (uiout, 
10655                bp_temp ? "Temporary catchpoint "
10656                        : "Catchpoint ");
10657   if (!ui_out_is_mi_like_p (uiout))
10658     ui_out_field_int (uiout, "bkptno", b->number);
10659   ui_out_text (uiout,
10660                bp_throw ? " (exception thrown), "
10661                         : " (exception caught), ");
10662   if (ui_out_is_mi_like_p (uiout))
10663     {
10664       ui_out_field_string (uiout, "reason", 
10665                            async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
10666       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
10667       ui_out_field_int (uiout, "bkptno", b->number);
10668     }
10669   return PRINT_SRC_AND_LOC;
10670 }
10671
10672 static void
10673 print_one_exception_catchpoint (struct breakpoint *b, 
10674                                 struct bp_location **last_loc)
10675 {
10676   struct value_print_options opts;
10677   struct ui_out *uiout = current_uiout;
10678
10679   get_user_print_options (&opts);
10680   if (opts.addressprint)
10681     {
10682       annotate_field (4);
10683       if (b->loc == NULL || b->loc->shlib_disabled)
10684         ui_out_field_string (uiout, "addr", "<PENDING>");
10685       else
10686         ui_out_field_core_addr (uiout, "addr",
10687                                 b->loc->gdbarch, b->loc->address);
10688     }
10689   annotate_field (5);
10690   if (b->loc)
10691     *last_loc = b->loc;
10692   if (strstr (b->addr_string, "throw") != NULL)
10693     ui_out_field_string (uiout, "what", "exception throw");
10694   else
10695     ui_out_field_string (uiout, "what", "exception catch");
10696 }
10697
10698 static void
10699 print_mention_exception_catchpoint (struct breakpoint *b)
10700 {
10701   struct ui_out *uiout = current_uiout;
10702   int bp_temp;
10703   int bp_throw;
10704
10705   bp_temp = b->disposition == disp_del;
10706   bp_throw = strstr (b->addr_string, "throw") != NULL;
10707   ui_out_text (uiout, bp_temp ? _("Temporary catchpoint ")
10708                               : _("Catchpoint "));
10709   ui_out_field_int (uiout, "bkptno", b->number);
10710   ui_out_text (uiout, bp_throw ? _(" (throw)")
10711                                : _(" (catch)"));
10712 }
10713
10714 /* Implement the "print_recreate" breakpoint_ops method for throw and
10715    catch catchpoints.  */
10716
10717 static void
10718 print_recreate_exception_catchpoint (struct breakpoint *b, 
10719                                      struct ui_file *fp)
10720 {
10721   int bp_temp;
10722   int bp_throw;
10723
10724   bp_temp = b->disposition == disp_del;
10725   bp_throw = strstr (b->addr_string, "throw") != NULL;
10726   fprintf_unfiltered (fp, bp_temp ? "tcatch " : "catch ");
10727   fprintf_unfiltered (fp, bp_throw ? "throw" : "catch");
10728   print_recreate_thread (b, fp);
10729 }
10730
10731 static struct breakpoint_ops gnu_v3_exception_catchpoint_ops;
10732
10733 static int
10734 handle_gnu_v3_exceptions (int tempflag, char *cond_string,
10735                           enum exception_event_kind ex_event, int from_tty)
10736 {
10737   char *trigger_func_name;
10738  
10739   if (ex_event == EX_EVENT_CATCH)
10740     trigger_func_name = "__cxa_begin_catch";
10741   else
10742     trigger_func_name = "__cxa_throw";
10743
10744   create_breakpoint (get_current_arch (),
10745                      trigger_func_name, cond_string, -1,
10746                      0 /* condition and thread are valid.  */,
10747                      tempflag, bp_breakpoint,
10748                      0,
10749                      AUTO_BOOLEAN_TRUE /* pending */,
10750                      &gnu_v3_exception_catchpoint_ops, from_tty,
10751                      1 /* enabled */,
10752                      0 /* internal */);
10753
10754   return 1;
10755 }
10756
10757 /* Deal with "catch catch" and "catch throw" commands.  */
10758
10759 static void
10760 catch_exception_command_1 (enum exception_event_kind ex_event, char *arg,
10761                            int tempflag, int from_tty)
10762 {
10763   char *cond_string = NULL;
10764
10765   if (!arg)
10766     arg = "";
10767   arg = skip_spaces (arg);
10768
10769   cond_string = ep_parse_optional_if_clause (&arg);
10770
10771   if ((*arg != '\0') && !isspace (*arg))
10772     error (_("Junk at end of arguments."));
10773
10774   if (ex_event != EX_EVENT_THROW
10775       && ex_event != EX_EVENT_CATCH)
10776     error (_("Unsupported or unknown exception event; cannot catch it"));
10777
10778   if (handle_gnu_v3_exceptions (tempflag, cond_string, ex_event, from_tty))
10779     return;
10780
10781   warning (_("Unsupported with this platform/compiler combination."));
10782 }
10783
10784 /* Implementation of "catch catch" command.  */
10785
10786 static void
10787 catch_catch_command (char *arg, int from_tty, struct cmd_list_element *command)
10788 {
10789   int tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
10790
10791   catch_exception_command_1 (EX_EVENT_CATCH, arg, tempflag, from_tty);
10792 }
10793
10794 /* Implementation of "catch throw" command.  */
10795
10796 static void
10797 catch_throw_command (char *arg, int from_tty, struct cmd_list_element *command)
10798 {
10799   int tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
10800
10801   catch_exception_command_1 (EX_EVENT_THROW, arg, tempflag, from_tty);
10802 }
10803
10804 void
10805 init_ada_exception_breakpoint (struct breakpoint *b,
10806                                struct gdbarch *gdbarch,
10807                                struct symtab_and_line sal,
10808                                char *addr_string,
10809                                const struct breakpoint_ops *ops,
10810                                int tempflag,
10811                                int from_tty)
10812 {
10813   if (from_tty)
10814     {
10815       struct gdbarch *loc_gdbarch = get_sal_arch (sal);
10816       if (!loc_gdbarch)
10817         loc_gdbarch = gdbarch;
10818
10819       describe_other_breakpoints (loc_gdbarch,
10820                                   sal.pspace, sal.pc, sal.section, -1);
10821       /* FIXME: brobecker/2006-12-28: Actually, re-implement a special
10822          version for exception catchpoints, because two catchpoints
10823          used for different exception names will use the same address.
10824          In this case, a "breakpoint ... also set at..." warning is
10825          unproductive.  Besides, the warning phrasing is also a bit
10826          inappropriate, we should use the word catchpoint, and tell
10827          the user what type of catchpoint it is.  The above is good
10828          enough for now, though.  */
10829     }
10830
10831   init_raw_breakpoint (b, gdbarch, sal, bp_breakpoint, ops);
10832
10833   b->enable_state = bp_enabled;
10834   b->disposition = tempflag ? disp_del : disp_donttouch;
10835   b->addr_string = addr_string;
10836   b->language = language_ada;
10837 }
10838
10839 /* Splits the argument using space as delimiter.  Returns an xmalloc'd
10840    filter list, or NULL if no filtering is required.  */
10841 static VEC(int) *
10842 catch_syscall_split_args (char *arg)
10843 {
10844   VEC(int) *result = NULL;
10845   struct cleanup *cleanup = make_cleanup (VEC_cleanup (int), &result);
10846
10847   while (*arg != '\0')
10848     {
10849       int i, syscall_number;
10850       char *endptr;
10851       char cur_name[128];
10852       struct syscall s;
10853
10854       /* Skip whitespace.  */
10855       while (isspace (*arg))
10856         arg++;
10857
10858       for (i = 0; i < 127 && arg[i] && !isspace (arg[i]); ++i)
10859         cur_name[i] = arg[i];
10860       cur_name[i] = '\0';
10861       arg += i;
10862
10863       /* Check if the user provided a syscall name or a number.  */
10864       syscall_number = (int) strtol (cur_name, &endptr, 0);
10865       if (*endptr == '\0')
10866         get_syscall_by_number (syscall_number, &s);
10867       else
10868         {
10869           /* We have a name.  Let's check if it's valid and convert it
10870              to a number.  */
10871           get_syscall_by_name (cur_name, &s);
10872
10873           if (s.number == UNKNOWN_SYSCALL)
10874             /* Here we have to issue an error instead of a warning,
10875                because GDB cannot do anything useful if there's no
10876                syscall number to be caught.  */
10877             error (_("Unknown syscall name '%s'."), cur_name);
10878         }
10879
10880       /* Ok, it's valid.  */
10881       VEC_safe_push (int, result, s.number);
10882     }
10883
10884   discard_cleanups (cleanup);
10885   return result;
10886 }
10887
10888 /* Implement the "catch syscall" command.  */
10889
10890 static void
10891 catch_syscall_command_1 (char *arg, int from_tty, 
10892                          struct cmd_list_element *command)
10893 {
10894   int tempflag;
10895   VEC(int) *filter;
10896   struct syscall s;
10897   struct gdbarch *gdbarch = get_current_arch ();
10898
10899   /* Checking if the feature if supported.  */
10900   if (gdbarch_get_syscall_number_p (gdbarch) == 0)
10901     error (_("The feature 'catch syscall' is not supported on \
10902 this architecture yet."));
10903
10904   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
10905
10906   arg = skip_spaces (arg);
10907
10908   /* We need to do this first "dummy" translation in order
10909      to get the syscall XML file loaded or, most important,
10910      to display a warning to the user if there's no XML file
10911      for his/her architecture.  */
10912   get_syscall_by_number (0, &s);
10913
10914   /* The allowed syntax is:
10915      catch syscall
10916      catch syscall <name | number> [<name | number> ... <name | number>]
10917
10918      Let's check if there's a syscall name.  */
10919
10920   if (arg != NULL)
10921     filter = catch_syscall_split_args (arg);
10922   else
10923     filter = NULL;
10924
10925   create_syscall_event_catchpoint (tempflag, filter,
10926                                    &catch_syscall_breakpoint_ops);
10927 }
10928
10929 static void
10930 catch_command (char *arg, int from_tty)
10931 {
10932   error (_("Catch requires an event name."));
10933 }
10934 \f
10935
10936 static void
10937 tcatch_command (char *arg, int from_tty)
10938 {
10939   error (_("Catch requires an event name."));
10940 }
10941
10942 /* A qsort comparison function that sorts breakpoints in order.  */
10943
10944 static int
10945 compare_breakpoints (const void *a, const void *b)
10946 {
10947   const breakpoint_p *ba = a;
10948   uintptr_t ua = (uintptr_t) *ba;
10949   const breakpoint_p *bb = b;
10950   uintptr_t ub = (uintptr_t) *bb;
10951
10952   if ((*ba)->number < (*bb)->number)
10953     return -1;
10954   else if ((*ba)->number > (*bb)->number)
10955     return 1;
10956
10957   /* Now sort by address, in case we see, e..g, two breakpoints with
10958      the number 0.  */
10959   if (ua < ub)
10960     return -1;
10961   return ub > ub ? 1 : 0;
10962 }
10963
10964 /* Delete breakpoints by address or line.  */
10965
10966 static void
10967 clear_command (char *arg, int from_tty)
10968 {
10969   struct breakpoint *b, *prev;
10970   VEC(breakpoint_p) *found = 0;
10971   int ix;
10972   int default_match;
10973   struct symtabs_and_lines sals;
10974   struct symtab_and_line sal;
10975   int i;
10976   struct cleanup *cleanups = make_cleanup (null_cleanup, NULL);
10977
10978   if (arg)
10979     {
10980       sals = decode_line_spec (arg, (DECODE_LINE_FUNFIRSTLINE
10981                                      | DECODE_LINE_LIST_MODE));
10982       default_match = 0;
10983     }
10984   else
10985     {
10986       sals.sals = (struct symtab_and_line *)
10987         xmalloc (sizeof (struct symtab_and_line));
10988       make_cleanup (xfree, sals.sals);
10989       init_sal (&sal);          /* Initialize to zeroes.  */
10990
10991       /* Set sal's line, symtab, pc, and pspace to the values
10992          corresponding to the last call to print_frame_info.  If the
10993          codepoint is not valid, this will set all the fields to 0.  */
10994       get_last_displayed_sal (&sal);
10995       if (sal.symtab == 0)
10996         error (_("No source file specified."));
10997
10998       sals.sals[0] = sal;
10999       sals.nelts = 1;
11000
11001       default_match = 1;
11002     }
11003
11004   /* We don't call resolve_sal_pc here.  That's not as bad as it
11005      seems, because all existing breakpoints typically have both
11006      file/line and pc set.  So, if clear is given file/line, we can
11007      match this to existing breakpoint without obtaining pc at all.
11008
11009      We only support clearing given the address explicitly 
11010      present in breakpoint table.  Say, we've set breakpoint 
11011      at file:line.  There were several PC values for that file:line,
11012      due to optimization, all in one block.
11013
11014      We've picked one PC value.  If "clear" is issued with another
11015      PC corresponding to the same file:line, the breakpoint won't
11016      be cleared.  We probably can still clear the breakpoint, but 
11017      since the other PC value is never presented to user, user
11018      can only find it by guessing, and it does not seem important
11019      to support that.  */
11020
11021   /* For each line spec given, delete bps which correspond to it.  Do
11022      it in two passes, solely to preserve the current behavior that
11023      from_tty is forced true if we delete more than one
11024      breakpoint.  */
11025
11026   found = NULL;
11027   make_cleanup (VEC_cleanup (breakpoint_p), &found);
11028   for (i = 0; i < sals.nelts; i++)
11029     {
11030       int is_abs, sal_name_len;
11031
11032       /* If exact pc given, clear bpts at that pc.
11033          If line given (pc == 0), clear all bpts on specified line.
11034          If defaulting, clear all bpts on default line
11035          or at default pc.
11036
11037          defaulting    sal.pc != 0    tests to do
11038
11039          0              1             pc
11040          1              1             pc _and_ line
11041          0              0             line
11042          1              0             <can't happen> */
11043
11044       sal = sals.sals[i];
11045       is_abs = sal.symtab == NULL ? 1 : IS_ABSOLUTE_PATH (sal.symtab->filename);
11046       sal_name_len = is_abs ? 0 : strlen (sal.symtab->filename);
11047
11048       /* Find all matching breakpoints and add them to 'found'.  */
11049       ALL_BREAKPOINTS (b)
11050         {
11051           int match = 0;
11052           /* Are we going to delete b?  */
11053           if (b->type != bp_none && !is_watchpoint (b))
11054             {
11055               struct bp_location *loc = b->loc;
11056               for (; loc; loc = loc->next)
11057                 {
11058                   /* If the user specified file:line, don't allow a PC
11059                      match.  This matches historical gdb behavior.  */
11060                   int pc_match = (!sal.explicit_line
11061                                   && sal.pc
11062                                   && (loc->pspace == sal.pspace)
11063                                   && (loc->address == sal.pc)
11064                                   && (!section_is_overlay (loc->section)
11065                                       || loc->section == sal.section));
11066                   int line_match = 0;
11067
11068                   if ((default_match || sal.explicit_line)
11069                       && loc->source_file != NULL
11070                       && sal.symtab != NULL
11071                       && sal.pspace == loc->pspace
11072                       && loc->line_number == sal.line)
11073                     {
11074                       if (filename_cmp (loc->source_file,
11075                                         sal.symtab->filename) == 0)
11076                         line_match = 1;
11077                       else if (!IS_ABSOLUTE_PATH (sal.symtab->filename)
11078                                && compare_filenames_for_search (loc->source_file,
11079                                                                 sal.symtab->filename,
11080                                                                 sal_name_len))
11081                         line_match = 1;
11082                     }
11083
11084                   if (pc_match || line_match)
11085                     {
11086                       match = 1;
11087                       break;
11088                     }
11089                 }
11090             }
11091
11092           if (match)
11093             VEC_safe_push(breakpoint_p, found, b);
11094         }
11095     }
11096
11097   /* Now go thru the 'found' chain and delete them.  */
11098   if (VEC_empty(breakpoint_p, found))
11099     {
11100       if (arg)
11101         error (_("No breakpoint at %s."), arg);
11102       else
11103         error (_("No breakpoint at this line."));
11104     }
11105
11106   /* Remove duplicates from the vec.  */
11107   qsort (VEC_address (breakpoint_p, found),
11108          VEC_length (breakpoint_p, found),
11109          sizeof (breakpoint_p),
11110          compare_breakpoints);
11111   prev = VEC_index (breakpoint_p, found, 0);
11112   for (ix = 1; VEC_iterate (breakpoint_p, found, ix, b); ++ix)
11113     {
11114       if (b == prev)
11115         {
11116           VEC_ordered_remove (breakpoint_p, found, ix);
11117           --ix;
11118         }
11119     }
11120
11121   if (VEC_length(breakpoint_p, found) > 1)
11122     from_tty = 1;       /* Always report if deleted more than one.  */
11123   if (from_tty)
11124     {
11125       if (VEC_length(breakpoint_p, found) == 1)
11126         printf_unfiltered (_("Deleted breakpoint "));
11127       else
11128         printf_unfiltered (_("Deleted breakpoints "));
11129     }
11130   breakpoints_changed ();
11131
11132   for (ix = 0; VEC_iterate(breakpoint_p, found, ix, b); ix++)
11133     {
11134       if (from_tty)
11135         printf_unfiltered ("%d ", b->number);
11136       delete_breakpoint (b);
11137     }
11138   if (from_tty)
11139     putchar_unfiltered ('\n');
11140
11141   do_cleanups (cleanups);
11142 }
11143 \f
11144 /* Delete breakpoint in BS if they are `delete' breakpoints and
11145    all breakpoints that are marked for deletion, whether hit or not.
11146    This is called after any breakpoint is hit, or after errors.  */
11147
11148 void
11149 breakpoint_auto_delete (bpstat bs)
11150 {
11151   struct breakpoint *b, *b_tmp;
11152
11153   for (; bs; bs = bs->next)
11154     if (bs->breakpoint_at
11155         && bs->breakpoint_at->disposition == disp_del
11156         && bs->stop)
11157       delete_breakpoint (bs->breakpoint_at);
11158
11159   ALL_BREAKPOINTS_SAFE (b, b_tmp)
11160   {
11161     if (b->disposition == disp_del_at_next_stop)
11162       delete_breakpoint (b);
11163   }
11164 }
11165
11166 /* A comparison function for bp_location AP and BP being interfaced to
11167    qsort.  Sort elements primarily by their ADDRESS (no matter what
11168    does breakpoint_address_is_meaningful say for its OWNER),
11169    secondarily by ordering first bp_permanent OWNERed elements and
11170    terciarily just ensuring the array is sorted stable way despite
11171    qsort being an unstable algorithm.  */
11172
11173 static int
11174 bp_location_compare (const void *ap, const void *bp)
11175 {
11176   struct bp_location *a = *(void **) ap;
11177   struct bp_location *b = *(void **) bp;
11178   /* A and B come from existing breakpoints having non-NULL OWNER.  */
11179   int a_perm = a->owner->enable_state == bp_permanent;
11180   int b_perm = b->owner->enable_state == bp_permanent;
11181
11182   if (a->address != b->address)
11183     return (a->address > b->address) - (a->address < b->address);
11184
11185   /* Sort locations at the same address by their pspace number, keeping
11186      locations of the same inferior (in a multi-inferior environment)
11187      grouped.  */
11188
11189   if (a->pspace->num != b->pspace->num)
11190     return ((a->pspace->num > b->pspace->num)
11191             - (a->pspace->num < b->pspace->num));
11192
11193   /* Sort permanent breakpoints first.  */
11194   if (a_perm != b_perm)
11195     return (a_perm < b_perm) - (a_perm > b_perm);
11196
11197   /* Make the internal GDB representation stable across GDB runs
11198      where A and B memory inside GDB can differ.  Breakpoint locations of
11199      the same type at the same address can be sorted in arbitrary order.  */
11200
11201   if (a->owner->number != b->owner->number)
11202     return ((a->owner->number > b->owner->number)
11203             - (a->owner->number < b->owner->number));
11204
11205   return (a > b) - (a < b);
11206 }
11207
11208 /* Set bp_location_placed_address_before_address_max and
11209    bp_location_shadow_len_after_address_max according to the current
11210    content of the bp_location array.  */
11211
11212 static void
11213 bp_location_target_extensions_update (void)
11214 {
11215   struct bp_location *bl, **blp_tmp;
11216
11217   bp_location_placed_address_before_address_max = 0;
11218   bp_location_shadow_len_after_address_max = 0;
11219
11220   ALL_BP_LOCATIONS (bl, blp_tmp)
11221     {
11222       CORE_ADDR start, end, addr;
11223
11224       if (!bp_location_has_shadow (bl))
11225         continue;
11226
11227       start = bl->target_info.placed_address;
11228       end = start + bl->target_info.shadow_len;
11229
11230       gdb_assert (bl->address >= start);
11231       addr = bl->address - start;
11232       if (addr > bp_location_placed_address_before_address_max)
11233         bp_location_placed_address_before_address_max = addr;
11234
11235       /* Zero SHADOW_LEN would not pass bp_location_has_shadow.  */
11236
11237       gdb_assert (bl->address < end);
11238       addr = end - bl->address;
11239       if (addr > bp_location_shadow_len_after_address_max)
11240         bp_location_shadow_len_after_address_max = addr;
11241     }
11242 }
11243
11244 /* Download tracepoint locations if they haven't been.  */
11245
11246 static void
11247 download_tracepoint_locations (void)
11248 {
11249   struct bp_location *bl, **blp_tmp;
11250   struct cleanup *old_chain;
11251
11252   if (!target_can_download_tracepoint ())
11253     return;
11254
11255   old_chain = save_current_space_and_thread ();
11256
11257   ALL_BP_LOCATIONS (bl, blp_tmp)
11258     {
11259       struct tracepoint *t;
11260
11261       if (!is_tracepoint (bl->owner))
11262         continue;
11263
11264       if ((bl->owner->type == bp_fast_tracepoint
11265            ? !may_insert_fast_tracepoints
11266            : !may_insert_tracepoints))
11267         continue;
11268
11269       /* In tracepoint, locations are _never_ duplicated, so
11270          should_be_inserted is equivalent to
11271          unduplicated_should_be_inserted.  */
11272       if (!should_be_inserted (bl) || bl->inserted)
11273         continue;
11274
11275       switch_to_program_space_and_thread (bl->pspace);
11276
11277       target_download_tracepoint (bl);
11278
11279       bl->inserted = 1;
11280       t = (struct tracepoint *) bl->owner;
11281       t->number_on_target = bl->owner->number;
11282     }
11283
11284   do_cleanups (old_chain);
11285 }
11286
11287 /* Swap the insertion/duplication state between two locations.  */
11288
11289 static void
11290 swap_insertion (struct bp_location *left, struct bp_location *right)
11291 {
11292   const int left_inserted = left->inserted;
11293   const int left_duplicate = left->duplicate;
11294   const int left_needs_update = left->needs_update;
11295   const struct bp_target_info left_target_info = left->target_info;
11296
11297   /* Locations of tracepoints can never be duplicated.  */
11298   if (is_tracepoint (left->owner))
11299     gdb_assert (!left->duplicate);
11300   if (is_tracepoint (right->owner))
11301     gdb_assert (!right->duplicate);
11302
11303   left->inserted = right->inserted;
11304   left->duplicate = right->duplicate;
11305   left->needs_update = right->needs_update;
11306   left->target_info = right->target_info;
11307   right->inserted = left_inserted;
11308   right->duplicate = left_duplicate;
11309   right->needs_update = left_needs_update;
11310   right->target_info = left_target_info;
11311 }
11312
11313 /* Force the re-insertion of the locations at ADDRESS.  This is called
11314    once a new/deleted/modified duplicate location is found and we are evaluating
11315    conditions on the target's side.  Such conditions need to be updated on
11316    the target.  */
11317
11318 static void
11319 force_breakpoint_reinsertion (struct bp_location *bl)
11320 {
11321   struct bp_location **locp = NULL, **loc2p;
11322   struct bp_location *loc;
11323   CORE_ADDR address = 0;
11324   int pspace_num;
11325
11326   address = bl->address;
11327   pspace_num = bl->pspace->num;
11328
11329   /* This is only meaningful if the target is
11330      evaluating conditions and if the user has
11331      opted for condition evaluation on the target's
11332      side.  */
11333   if (gdb_evaluates_breakpoint_condition_p ()
11334       || !target_supports_evaluation_of_breakpoint_conditions ())
11335     return;
11336
11337   /* Flag all breakpoint locations with this address and
11338      the same program space as the location
11339      as "its condition has changed".  We need to
11340      update the conditions on the target's side.  */
11341   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, address)
11342     {
11343       loc = *loc2p;
11344
11345       if (!is_breakpoint (loc->owner)
11346           || pspace_num != loc->pspace->num)
11347         continue;
11348
11349       /* Flag the location appropriately.  We use a different state to
11350          let everyone know that we already updated the set of locations
11351          with addr bl->address and program space bl->pspace.  This is so
11352          we don't have to keep calling these functions just to mark locations
11353          that have already been marked.  */
11354       loc->condition_changed = condition_updated;
11355
11356       /* Free the agent expression bytecode as well.  We will compute
11357          it later on.  */
11358       if (loc->cond_bytecode)
11359         {
11360           free_agent_expr (loc->cond_bytecode);
11361           loc->cond_bytecode = NULL;
11362         }
11363     }
11364 }
11365
11366 /* If SHOULD_INSERT is false, do not insert any breakpoint locations
11367    into the inferior, only remove already-inserted locations that no
11368    longer should be inserted.  Functions that delete a breakpoint or
11369    breakpoints should pass false, so that deleting a breakpoint
11370    doesn't have the side effect of inserting the locations of other
11371    breakpoints that are marked not-inserted, but should_be_inserted
11372    returns true on them.
11373
11374    This behaviour is useful is situations close to tear-down -- e.g.,
11375    after an exec, while the target still has execution, but breakpoint
11376    shadows of the previous executable image should *NOT* be restored
11377    to the new image; or before detaching, where the target still has
11378    execution and wants to delete breakpoints from GDB's lists, and all
11379    breakpoints had already been removed from the inferior.  */
11380
11381 static void
11382 update_global_location_list (int should_insert)
11383 {
11384   struct breakpoint *b;
11385   struct bp_location **locp, *loc;
11386   struct cleanup *cleanups;
11387   /* Last breakpoint location address that was marked for update.  */
11388   CORE_ADDR last_addr = 0;
11389   /* Last breakpoint location program space that was marked for update.  */
11390   int last_pspace_num = -1;
11391
11392   /* Used in the duplicates detection below.  When iterating over all
11393      bp_locations, points to the first bp_location of a given address.
11394      Breakpoints and watchpoints of different types are never
11395      duplicates of each other.  Keep one pointer for each type of
11396      breakpoint/watchpoint, so we only need to loop over all locations
11397      once.  */
11398   struct bp_location *bp_loc_first;  /* breakpoint */
11399   struct bp_location *wp_loc_first;  /* hardware watchpoint */
11400   struct bp_location *awp_loc_first; /* access watchpoint */
11401   struct bp_location *rwp_loc_first; /* read watchpoint */
11402
11403   /* Saved former bp_location array which we compare against the newly
11404      built bp_location from the current state of ALL_BREAKPOINTS.  */
11405   struct bp_location **old_location, **old_locp;
11406   unsigned old_location_count;
11407
11408   old_location = bp_location;
11409   old_location_count = bp_location_count;
11410   bp_location = NULL;
11411   bp_location_count = 0;
11412   cleanups = make_cleanup (xfree, old_location);
11413
11414   ALL_BREAKPOINTS (b)
11415     for (loc = b->loc; loc; loc = loc->next)
11416       bp_location_count++;
11417
11418   bp_location = xmalloc (sizeof (*bp_location) * bp_location_count);
11419   locp = bp_location;
11420   ALL_BREAKPOINTS (b)
11421     for (loc = b->loc; loc; loc = loc->next)
11422       *locp++ = loc;
11423   qsort (bp_location, bp_location_count, sizeof (*bp_location),
11424          bp_location_compare);
11425
11426   bp_location_target_extensions_update ();
11427
11428   /* Identify bp_location instances that are no longer present in the
11429      new list, and therefore should be freed.  Note that it's not
11430      necessary that those locations should be removed from inferior --
11431      if there's another location at the same address (previously
11432      marked as duplicate), we don't need to remove/insert the
11433      location.
11434      
11435      LOCP is kept in sync with OLD_LOCP, each pointing to the current
11436      and former bp_location array state respectively.  */
11437
11438   locp = bp_location;
11439   for (old_locp = old_location; old_locp < old_location + old_location_count;
11440        old_locp++)
11441     {
11442       struct bp_location *old_loc = *old_locp;
11443       struct bp_location **loc2p;
11444
11445       /* Tells if 'old_loc' is found among the new locations.  If
11446          not, we have to free it.  */
11447       int found_object = 0;
11448       /* Tells if the location should remain inserted in the target.  */
11449       int keep_in_target = 0;
11450       int removed = 0;
11451
11452       /* Skip LOCP entries which will definitely never be needed.
11453          Stop either at or being the one matching OLD_LOC.  */
11454       while (locp < bp_location + bp_location_count
11455              && (*locp)->address < old_loc->address)
11456         locp++;
11457
11458       for (loc2p = locp;
11459            (loc2p < bp_location + bp_location_count
11460             && (*loc2p)->address == old_loc->address);
11461            loc2p++)
11462         {
11463           /* Check if this is a new/duplicated location or a duplicated
11464              location that had its condition modified.  If so, we want to send
11465              its condition to the target if evaluation of conditions is taking
11466              place there.  */
11467           if ((*loc2p)->condition_changed == condition_modified
11468               && (last_addr != old_loc->address
11469                   || last_pspace_num != old_loc->pspace->num))
11470             {
11471               force_breakpoint_reinsertion (*loc2p);
11472               last_pspace_num = old_loc->pspace->num;
11473             }
11474
11475           if (*loc2p == old_loc)
11476             found_object = 1;
11477         }
11478
11479       /* We have already handled this address, update it so that we don't
11480          have to go through updates again.  */
11481       last_addr = old_loc->address;
11482
11483       /* Target-side condition evaluation: Handle deleted locations.  */
11484       if (!found_object)
11485         force_breakpoint_reinsertion (old_loc);
11486
11487       /* If this location is no longer present, and inserted, look if
11488          there's maybe a new location at the same address.  If so,
11489          mark that one inserted, and don't remove this one.  This is
11490          needed so that we don't have a time window where a breakpoint
11491          at certain location is not inserted.  */
11492
11493       if (old_loc->inserted)
11494         {
11495           /* If the location is inserted now, we might have to remove
11496              it.  */
11497
11498           if (found_object && should_be_inserted (old_loc))
11499             {
11500               /* The location is still present in the location list,
11501                  and still should be inserted.  Don't do anything.  */
11502               keep_in_target = 1;
11503             }
11504           else
11505             {
11506               /* This location still exists, but it won't be kept in the
11507                  target since it may have been disabled.  We proceed to
11508                  remove its target-side condition.  */
11509
11510               /* The location is either no longer present, or got
11511                  disabled.  See if there's another location at the
11512                  same address, in which case we don't need to remove
11513                  this one from the target.  */
11514
11515               /* OLD_LOC comes from existing struct breakpoint.  */
11516               if (breakpoint_address_is_meaningful (old_loc->owner))
11517                 {
11518                   for (loc2p = locp;
11519                        (loc2p < bp_location + bp_location_count
11520                         && (*loc2p)->address == old_loc->address);
11521                        loc2p++)
11522                     {
11523                       struct bp_location *loc2 = *loc2p;
11524
11525                       if (breakpoint_locations_match (loc2, old_loc))
11526                         {
11527                           /* Read watchpoint locations are switched to
11528                              access watchpoints, if the former are not
11529                              supported, but the latter are.  */
11530                           if (is_hardware_watchpoint (old_loc->owner))
11531                             {
11532                               gdb_assert (is_hardware_watchpoint (loc2->owner));
11533                               loc2->watchpoint_type = old_loc->watchpoint_type;
11534                             }
11535
11536                           /* loc2 is a duplicated location. We need to check
11537                              if it should be inserted in case it will be
11538                              unduplicated.  */
11539                           if (loc2 != old_loc
11540                               && unduplicated_should_be_inserted (loc2))
11541                             {
11542                               swap_insertion (old_loc, loc2);
11543                               keep_in_target = 1;
11544                               break;
11545                             }
11546                         }
11547                     }
11548                 }
11549             }
11550
11551           if (!keep_in_target)
11552             {
11553               if (remove_breakpoint (old_loc, mark_uninserted))
11554                 {
11555                   /* This is just about all we can do.  We could keep
11556                      this location on the global list, and try to
11557                      remove it next time, but there's no particular
11558                      reason why we will succeed next time.
11559                      
11560                      Note that at this point, old_loc->owner is still
11561                      valid, as delete_breakpoint frees the breakpoint
11562                      only after calling us.  */
11563                   printf_filtered (_("warning: Error removing "
11564                                      "breakpoint %d\n"), 
11565                                    old_loc->owner->number);
11566                 }
11567               removed = 1;
11568             }
11569         }
11570
11571       if (!found_object)
11572         {
11573           if (removed && non_stop
11574               && breakpoint_address_is_meaningful (old_loc->owner)
11575               && !is_hardware_watchpoint (old_loc->owner))
11576             {
11577               /* This location was removed from the target.  In
11578                  non-stop mode, a race condition is possible where
11579                  we've removed a breakpoint, but stop events for that
11580                  breakpoint are already queued and will arrive later.
11581                  We apply an heuristic to be able to distinguish such
11582                  SIGTRAPs from other random SIGTRAPs: we keep this
11583                  breakpoint location for a bit, and will retire it
11584                  after we see some number of events.  The theory here
11585                  is that reporting of events should, "on the average",
11586                  be fair, so after a while we'll see events from all
11587                  threads that have anything of interest, and no longer
11588                  need to keep this breakpoint location around.  We
11589                  don't hold locations forever so to reduce chances of
11590                  mistaking a non-breakpoint SIGTRAP for a breakpoint
11591                  SIGTRAP.
11592
11593                  The heuristic failing can be disastrous on
11594                  decr_pc_after_break targets.
11595
11596                  On decr_pc_after_break targets, like e.g., x86-linux,
11597                  if we fail to recognize a late breakpoint SIGTRAP,
11598                  because events_till_retirement has reached 0 too
11599                  soon, we'll fail to do the PC adjustment, and report
11600                  a random SIGTRAP to the user.  When the user resumes
11601                  the inferior, it will most likely immediately crash
11602                  with SIGILL/SIGBUS/SIGSEGV, or worse, get silently
11603                  corrupted, because of being resumed e.g., in the
11604                  middle of a multi-byte instruction, or skipped a
11605                  one-byte instruction.  This was actually seen happen
11606                  on native x86-linux, and should be less rare on
11607                  targets that do not support new thread events, like
11608                  remote, due to the heuristic depending on
11609                  thread_count.
11610
11611                  Mistaking a random SIGTRAP for a breakpoint trap
11612                  causes similar symptoms (PC adjustment applied when
11613                  it shouldn't), but then again, playing with SIGTRAPs
11614                  behind the debugger's back is asking for trouble.
11615
11616                  Since hardware watchpoint traps are always
11617                  distinguishable from other traps, so we don't need to
11618                  apply keep hardware watchpoint moribund locations
11619                  around.  We simply always ignore hardware watchpoint
11620                  traps we can no longer explain.  */
11621
11622               old_loc->events_till_retirement = 3 * (thread_count () + 1);
11623               old_loc->owner = NULL;
11624
11625               VEC_safe_push (bp_location_p, moribund_locations, old_loc);
11626             }
11627           else
11628             {
11629               old_loc->owner = NULL;
11630               decref_bp_location (&old_loc);
11631             }
11632         }
11633     }
11634
11635   /* Rescan breakpoints at the same address and section, marking the
11636      first one as "first" and any others as "duplicates".  This is so
11637      that the bpt instruction is only inserted once.  If we have a
11638      permanent breakpoint at the same place as BPT, make that one the
11639      official one, and the rest as duplicates.  Permanent breakpoints
11640      are sorted first for the same address.
11641
11642      Do the same for hardware watchpoints, but also considering the
11643      watchpoint's type (regular/access/read) and length.  */
11644
11645   bp_loc_first = NULL;
11646   wp_loc_first = NULL;
11647   awp_loc_first = NULL;
11648   rwp_loc_first = NULL;
11649   ALL_BP_LOCATIONS (loc, locp)
11650     {
11651       /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always
11652          non-NULL.  */
11653       struct bp_location **loc_first_p;
11654       b = loc->owner;
11655
11656       if (!should_be_inserted (loc)
11657           || !breakpoint_address_is_meaningful (b)
11658           /* Don't detect duplicate for tracepoint locations because they are
11659            never duplicated.  See the comments in field `duplicate' of
11660            `struct bp_location'.  */
11661           || is_tracepoint (b))
11662         {
11663           /* Clear the condition modification flag.  */
11664           loc->condition_changed = condition_unchanged;
11665           continue;
11666         }
11667
11668       /* Permanent breakpoint should always be inserted.  */
11669       if (b->enable_state == bp_permanent && ! loc->inserted)
11670         internal_error (__FILE__, __LINE__,
11671                         _("allegedly permanent breakpoint is not "
11672                         "actually inserted"));
11673
11674       if (b->type == bp_hardware_watchpoint)
11675         loc_first_p = &wp_loc_first;
11676       else if (b->type == bp_read_watchpoint)
11677         loc_first_p = &rwp_loc_first;
11678       else if (b->type == bp_access_watchpoint)
11679         loc_first_p = &awp_loc_first;
11680       else
11681         loc_first_p = &bp_loc_first;
11682
11683       if (*loc_first_p == NULL
11684           || (overlay_debugging && loc->section != (*loc_first_p)->section)
11685           || !breakpoint_locations_match (loc, *loc_first_p))
11686         {
11687           *loc_first_p = loc;
11688           loc->duplicate = 0;
11689
11690           if (is_breakpoint (loc->owner) && loc->condition_changed)
11691             {
11692               loc->needs_update = 1;
11693               /* Clear the condition modification flag.  */
11694               loc->condition_changed = condition_unchanged;
11695             }
11696           continue;
11697         }
11698
11699
11700       /* This and the above ensure the invariant that the first location
11701          is not duplicated, and is the inserted one.
11702          All following are marked as duplicated, and are not inserted.  */
11703       if (loc->inserted)
11704         swap_insertion (loc, *loc_first_p);
11705       loc->duplicate = 1;
11706
11707       /* Clear the condition modification flag.  */
11708       loc->condition_changed = condition_unchanged;
11709
11710       if ((*loc_first_p)->owner->enable_state == bp_permanent && loc->inserted
11711           && b->enable_state != bp_permanent)
11712         internal_error (__FILE__, __LINE__,
11713                         _("another breakpoint was inserted on top of "
11714                         "a permanent breakpoint"));
11715     }
11716
11717   if (breakpoints_always_inserted_mode ()
11718       && (have_live_inferiors ()
11719           || (gdbarch_has_global_breakpoints (target_gdbarch))))
11720     {
11721       if (should_insert)
11722         insert_breakpoint_locations ();
11723       else
11724         {
11725           /* Though should_insert is false, we may need to update conditions
11726              on the target's side if it is evaluating such conditions.  We
11727              only update conditions for locations that are marked
11728              "needs_update".  */
11729           update_inserted_breakpoint_locations ();
11730         }
11731     }
11732
11733   if (should_insert)
11734     download_tracepoint_locations ();
11735
11736   do_cleanups (cleanups);
11737 }
11738
11739 void
11740 breakpoint_retire_moribund (void)
11741 {
11742   struct bp_location *loc;
11743   int ix;
11744
11745   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
11746     if (--(loc->events_till_retirement) == 0)
11747       {
11748         decref_bp_location (&loc);
11749         VEC_unordered_remove (bp_location_p, moribund_locations, ix);
11750         --ix;
11751       }
11752 }
11753
11754 static void
11755 update_global_location_list_nothrow (int inserting)
11756 {
11757   volatile struct gdb_exception e;
11758
11759   TRY_CATCH (e, RETURN_MASK_ERROR)
11760     update_global_location_list (inserting);
11761 }
11762
11763 /* Clear BKP from a BPS.  */
11764
11765 static void
11766 bpstat_remove_bp_location (bpstat bps, struct breakpoint *bpt)
11767 {
11768   bpstat bs;
11769
11770   for (bs = bps; bs; bs = bs->next)
11771     if (bs->breakpoint_at == bpt)
11772       {
11773         bs->breakpoint_at = NULL;
11774         bs->old_val = NULL;
11775         /* bs->commands will be freed later.  */
11776       }
11777 }
11778
11779 /* Callback for iterate_over_threads.  */
11780 static int
11781 bpstat_remove_breakpoint_callback (struct thread_info *th, void *data)
11782 {
11783   struct breakpoint *bpt = data;
11784
11785   bpstat_remove_bp_location (th->control.stop_bpstat, bpt);
11786   return 0;
11787 }
11788
11789 /* Helper for breakpoint and tracepoint breakpoint_ops->mention
11790    callbacks.  */
11791
11792 static void
11793 say_where (struct breakpoint *b)
11794 {
11795   struct ui_out *uiout = current_uiout;
11796   struct value_print_options opts;
11797
11798   get_user_print_options (&opts);
11799
11800   /* i18n: cagney/2005-02-11: Below needs to be merged into a
11801      single string.  */
11802   if (b->loc == NULL)
11803     {
11804       printf_filtered (_(" (%s) pending."), b->addr_string);
11805     }
11806   else
11807     {
11808       if (opts.addressprint || b->loc->source_file == NULL)
11809         {
11810           printf_filtered (" at ");
11811           fputs_filtered (paddress (b->loc->gdbarch, b->loc->address),
11812                           gdb_stdout);
11813         }
11814       if (b->loc->source_file)
11815         {
11816           /* If there is a single location, we can print the location
11817              more nicely.  */
11818           if (b->loc->next == NULL)
11819             printf_filtered (": file %s, line %d.",
11820                              b->loc->source_file, b->loc->line_number);
11821           else
11822             /* This is not ideal, but each location may have a
11823                different file name, and this at least reflects the
11824                real situation somewhat.  */
11825             printf_filtered (": %s.", b->addr_string);
11826         }
11827
11828       if (b->loc->next)
11829         {
11830           struct bp_location *loc = b->loc;
11831           int n = 0;
11832           for (; loc; loc = loc->next)
11833             ++n;
11834           printf_filtered (" (%d locations)", n);
11835         }
11836     }
11837 }
11838
11839 /* Default bp_location_ops methods.  */
11840
11841 static void
11842 bp_location_dtor (struct bp_location *self)
11843 {
11844   xfree (self->cond);
11845   if (self->cond_bytecode)
11846     free_agent_expr (self->cond_bytecode);
11847   xfree (self->function_name);
11848   xfree (self->source_file);
11849 }
11850
11851 static const struct bp_location_ops bp_location_ops =
11852 {
11853   bp_location_dtor
11854 };
11855
11856 /* Default breakpoint_ops methods all breakpoint_ops ultimately
11857    inherit from.  */
11858
11859 static void
11860 base_breakpoint_dtor (struct breakpoint *self)
11861 {
11862   decref_counted_command_line (&self->commands);
11863   xfree (self->cond_string);
11864   xfree (self->addr_string);
11865   xfree (self->filter);
11866   xfree (self->addr_string_range_end);
11867 }
11868
11869 static struct bp_location *
11870 base_breakpoint_allocate_location (struct breakpoint *self)
11871 {
11872   struct bp_location *loc;
11873
11874   loc = XNEW (struct bp_location);
11875   init_bp_location (loc, &bp_location_ops, self);
11876   return loc;
11877 }
11878
11879 static void
11880 base_breakpoint_re_set (struct breakpoint *b)
11881 {
11882   /* Nothing to re-set. */
11883 }
11884
11885 #define internal_error_pure_virtual_called() \
11886   gdb_assert_not_reached ("pure virtual function called")
11887
11888 static int
11889 base_breakpoint_insert_location (struct bp_location *bl)
11890 {
11891   internal_error_pure_virtual_called ();
11892 }
11893
11894 static int
11895 base_breakpoint_remove_location (struct bp_location *bl)
11896 {
11897   internal_error_pure_virtual_called ();
11898 }
11899
11900 static int
11901 base_breakpoint_breakpoint_hit (const struct bp_location *bl,
11902                                 struct address_space *aspace,
11903                                 CORE_ADDR bp_addr,
11904                                 const struct target_waitstatus *ws)
11905 {
11906   internal_error_pure_virtual_called ();
11907 }
11908
11909 static void
11910 base_breakpoint_check_status (bpstat bs)
11911 {
11912   /* Always stop.   */
11913 }
11914
11915 /* A "works_in_software_mode" breakpoint_ops method that just internal
11916    errors.  */
11917
11918 static int
11919 base_breakpoint_works_in_software_mode (const struct breakpoint *b)
11920 {
11921   internal_error_pure_virtual_called ();
11922 }
11923
11924 /* A "resources_needed" breakpoint_ops method that just internal
11925    errors.  */
11926
11927 static int
11928 base_breakpoint_resources_needed (const struct bp_location *bl)
11929 {
11930   internal_error_pure_virtual_called ();
11931 }
11932
11933 static enum print_stop_action
11934 base_breakpoint_print_it (bpstat bs)
11935 {
11936   internal_error_pure_virtual_called ();
11937 }
11938
11939 static void
11940 base_breakpoint_print_one_detail (const struct breakpoint *self,
11941                                   struct ui_out *uiout)
11942 {
11943   /* nothing */
11944 }
11945
11946 static void
11947 base_breakpoint_print_mention (struct breakpoint *b)
11948 {
11949   internal_error_pure_virtual_called ();
11950 }
11951
11952 static void
11953 base_breakpoint_print_recreate (struct breakpoint *b, struct ui_file *fp)
11954 {
11955   internal_error_pure_virtual_called ();
11956 }
11957
11958 static void
11959 base_breakpoint_create_sals_from_address (char **arg,
11960                                           struct linespec_result *canonical,
11961                                           enum bptype type_wanted,
11962                                           char *addr_start,
11963                                           char **copy_arg)
11964 {
11965   internal_error_pure_virtual_called ();
11966 }
11967
11968 static void
11969 base_breakpoint_create_breakpoints_sal (struct gdbarch *gdbarch,
11970                                         struct linespec_result *c,
11971                                         struct linespec_sals *lsal,
11972                                         char *cond_string,
11973                                         enum bptype type_wanted,
11974                                         enum bpdisp disposition,
11975                                         int thread,
11976                                         int task, int ignore_count,
11977                                         const struct breakpoint_ops *o,
11978                                         int from_tty, int enabled,
11979                                         int internal)
11980 {
11981   internal_error_pure_virtual_called ();
11982 }
11983
11984 static void
11985 base_breakpoint_decode_linespec (struct breakpoint *b, char **s,
11986                                  struct symtabs_and_lines *sals)
11987 {
11988   internal_error_pure_virtual_called ();
11989 }
11990
11991 static struct breakpoint_ops base_breakpoint_ops =
11992 {
11993   base_breakpoint_dtor,
11994   base_breakpoint_allocate_location,
11995   base_breakpoint_re_set,
11996   base_breakpoint_insert_location,
11997   base_breakpoint_remove_location,
11998   base_breakpoint_breakpoint_hit,
11999   base_breakpoint_check_status,
12000   base_breakpoint_resources_needed,
12001   base_breakpoint_works_in_software_mode,
12002   base_breakpoint_print_it,
12003   NULL,
12004   base_breakpoint_print_one_detail,
12005   base_breakpoint_print_mention,
12006   base_breakpoint_print_recreate,
12007   base_breakpoint_create_sals_from_address,
12008   base_breakpoint_create_breakpoints_sal,
12009   base_breakpoint_decode_linespec,
12010 };
12011
12012 /* Default breakpoint_ops methods.  */
12013
12014 static void
12015 bkpt_re_set (struct breakpoint *b)
12016 {
12017   /* FIXME: is this still reachable?  */
12018   if (b->addr_string == NULL)
12019     {
12020       /* Anything without a string can't be re-set.  */
12021       delete_breakpoint (b);
12022       return;
12023     }
12024
12025   breakpoint_re_set_default (b);
12026 }
12027
12028 static int
12029 bkpt_insert_location (struct bp_location *bl)
12030 {
12031   if (bl->loc_type == bp_loc_hardware_breakpoint)
12032     return target_insert_hw_breakpoint (bl->gdbarch,
12033                                         &bl->target_info);
12034   else
12035     return target_insert_breakpoint (bl->gdbarch,
12036                                      &bl->target_info);
12037 }
12038
12039 static int
12040 bkpt_remove_location (struct bp_location *bl)
12041 {
12042   if (bl->loc_type == bp_loc_hardware_breakpoint)
12043     return target_remove_hw_breakpoint (bl->gdbarch, &bl->target_info);
12044   else
12045     return target_remove_breakpoint (bl->gdbarch, &bl->target_info);
12046 }
12047
12048 static int
12049 bkpt_breakpoint_hit (const struct bp_location *bl,
12050                      struct address_space *aspace, CORE_ADDR bp_addr,
12051                      const struct target_waitstatus *ws)
12052 {
12053   struct breakpoint *b = bl->owner;
12054
12055   if (ws->kind != TARGET_WAITKIND_STOPPED
12056       || ws->value.sig != TARGET_SIGNAL_TRAP)
12057     return 0;
12058
12059   if (!breakpoint_address_match (bl->pspace->aspace, bl->address,
12060                                  aspace, bp_addr))
12061     return 0;
12062
12063   if (overlay_debugging         /* unmapped overlay section */
12064       && section_is_overlay (bl->section)
12065       && !section_is_mapped (bl->section))
12066     return 0;
12067
12068   return 1;
12069 }
12070
12071 static int
12072 bkpt_resources_needed (const struct bp_location *bl)
12073 {
12074   gdb_assert (bl->owner->type == bp_hardware_breakpoint);
12075
12076   return 1;
12077 }
12078
12079 static enum print_stop_action
12080 bkpt_print_it (bpstat bs)
12081 {
12082   struct breakpoint *b;
12083   const struct bp_location *bl;
12084   int bp_temp;
12085   struct ui_out *uiout = current_uiout;
12086
12087   gdb_assert (bs->bp_location_at != NULL);
12088
12089   bl = bs->bp_location_at;
12090   b = bs->breakpoint_at;
12091
12092   bp_temp = b->disposition == disp_del;
12093   if (bl->address != bl->requested_address)
12094     breakpoint_adjustment_warning (bl->requested_address,
12095                                    bl->address,
12096                                    b->number, 1);
12097   annotate_breakpoint (b->number);
12098   if (bp_temp)
12099     ui_out_text (uiout, "\nTemporary breakpoint ");
12100   else
12101     ui_out_text (uiout, "\nBreakpoint ");
12102   if (ui_out_is_mi_like_p (uiout))
12103     {
12104       ui_out_field_string (uiout, "reason",
12105                            async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
12106       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
12107     }
12108   ui_out_field_int (uiout, "bkptno", b->number);
12109   ui_out_text (uiout, ", ");
12110
12111   return PRINT_SRC_AND_LOC;
12112 }
12113
12114 static void
12115 bkpt_print_mention (struct breakpoint *b)
12116 {
12117   if (ui_out_is_mi_like_p (current_uiout))
12118     return;
12119
12120   switch (b->type)
12121     {
12122     case bp_breakpoint:
12123     case bp_gnu_ifunc_resolver:
12124       if (b->disposition == disp_del)
12125         printf_filtered (_("Temporary breakpoint"));
12126       else
12127         printf_filtered (_("Breakpoint"));
12128       printf_filtered (_(" %d"), b->number);
12129       if (b->type == bp_gnu_ifunc_resolver)
12130         printf_filtered (_(" at gnu-indirect-function resolver"));
12131       break;
12132     case bp_hardware_breakpoint:
12133       printf_filtered (_("Hardware assisted breakpoint %d"), b->number);
12134       break;
12135     }
12136
12137   say_where (b);
12138 }
12139
12140 static void
12141 bkpt_print_recreate (struct breakpoint *tp, struct ui_file *fp)
12142 {
12143   if (tp->type == bp_breakpoint && tp->disposition == disp_del)
12144     fprintf_unfiltered (fp, "tbreak");
12145   else if (tp->type == bp_breakpoint)
12146     fprintf_unfiltered (fp, "break");
12147   else if (tp->type == bp_hardware_breakpoint
12148            && tp->disposition == disp_del)
12149     fprintf_unfiltered (fp, "thbreak");
12150   else if (tp->type == bp_hardware_breakpoint)
12151     fprintf_unfiltered (fp, "hbreak");
12152   else
12153     internal_error (__FILE__, __LINE__,
12154                     _("unhandled breakpoint type %d"), (int) tp->type);
12155
12156   fprintf_unfiltered (fp, " %s", tp->addr_string);
12157   print_recreate_thread (tp, fp);
12158 }
12159
12160 static void
12161 bkpt_create_sals_from_address (char **arg,
12162                                struct linespec_result *canonical,
12163                                enum bptype type_wanted,
12164                                char *addr_start, char **copy_arg)
12165 {
12166   create_sals_from_address_default (arg, canonical, type_wanted,
12167                                     addr_start, copy_arg);
12168 }
12169
12170 static void
12171 bkpt_create_breakpoints_sal (struct gdbarch *gdbarch,
12172                              struct linespec_result *canonical,
12173                              struct linespec_sals *lsal,
12174                              char *cond_string,
12175                              enum bptype type_wanted,
12176                              enum bpdisp disposition,
12177                              int thread,
12178                              int task, int ignore_count,
12179                              const struct breakpoint_ops *ops,
12180                              int from_tty, int enabled,
12181                              int internal)
12182 {
12183   create_breakpoints_sal_default (gdbarch, canonical, lsal,
12184                                   cond_string, type_wanted,
12185                                   disposition, thread, task,
12186                                   ignore_count, ops, from_tty,
12187                                   enabled, internal);
12188 }
12189
12190 static void
12191 bkpt_decode_linespec (struct breakpoint *b, char **s,
12192                       struct symtabs_and_lines *sals)
12193 {
12194   decode_linespec_default (b, s, sals);
12195 }
12196
12197 /* Virtual table for internal breakpoints.  */
12198
12199 static void
12200 internal_bkpt_re_set (struct breakpoint *b)
12201 {
12202   switch (b->type)
12203     {
12204       /* Delete overlay event and longjmp master breakpoints; they
12205          will be reset later by breakpoint_re_set.  */
12206     case bp_overlay_event:
12207     case bp_longjmp_master:
12208     case bp_std_terminate_master:
12209     case bp_exception_master:
12210       delete_breakpoint (b);
12211       break;
12212
12213       /* This breakpoint is special, it's set up when the inferior
12214          starts and we really don't want to touch it.  */
12215     case bp_shlib_event:
12216
12217       /* Like bp_shlib_event, this breakpoint type is special.  Once
12218          it is set up, we do not want to touch it.  */
12219     case bp_thread_event:
12220       break;
12221     }
12222 }
12223
12224 static void
12225 internal_bkpt_check_status (bpstat bs)
12226 {
12227   if (bs->breakpoint_at->type == bp_shlib_event)
12228     {
12229       /* If requested, stop when the dynamic linker notifies GDB of
12230          events.  This allows the user to get control and place
12231          breakpoints in initializer routines for dynamically loaded
12232          objects (among other things).  */
12233       bs->stop = stop_on_solib_events;
12234       bs->print = stop_on_solib_events;
12235     }
12236   else
12237     bs->stop = 0;
12238 }
12239
12240 static enum print_stop_action
12241 internal_bkpt_print_it (bpstat bs)
12242 {
12243   struct ui_out *uiout = current_uiout;
12244   struct breakpoint *b;
12245
12246   b = bs->breakpoint_at;
12247
12248   switch (b->type)
12249     {
12250     case bp_shlib_event:
12251       /* Did we stop because the user set the stop_on_solib_events
12252          variable?  (If so, we report this as a generic, "Stopped due
12253          to shlib event" message.) */
12254       print_solib_event (0);
12255       break;
12256
12257     case bp_thread_event:
12258       /* Not sure how we will get here.
12259          GDB should not stop for these breakpoints.  */
12260       printf_filtered (_("Thread Event Breakpoint: gdb should not stop!\n"));
12261       break;
12262
12263     case bp_overlay_event:
12264       /* By analogy with the thread event, GDB should not stop for these.  */
12265       printf_filtered (_("Overlay Event Breakpoint: gdb should not stop!\n"));
12266       break;
12267
12268     case bp_longjmp_master:
12269       /* These should never be enabled.  */
12270       printf_filtered (_("Longjmp Master Breakpoint: gdb should not stop!\n"));
12271       break;
12272
12273     case bp_std_terminate_master:
12274       /* These should never be enabled.  */
12275       printf_filtered (_("std::terminate Master Breakpoint: "
12276                          "gdb should not stop!\n"));
12277       break;
12278
12279     case bp_exception_master:
12280       /* These should never be enabled.  */
12281       printf_filtered (_("Exception Master Breakpoint: "
12282                          "gdb should not stop!\n"));
12283       break;
12284     }
12285
12286   return PRINT_NOTHING;
12287 }
12288
12289 static void
12290 internal_bkpt_print_mention (struct breakpoint *b)
12291 {
12292   /* Nothing to mention.  These breakpoints are internal.  */
12293 }
12294
12295 /* Virtual table for momentary breakpoints  */
12296
12297 static void
12298 momentary_bkpt_re_set (struct breakpoint *b)
12299 {
12300   /* Keep temporary breakpoints, which can be encountered when we step
12301      over a dlopen call and SOLIB_ADD is resetting the breakpoints.
12302      Otherwise these should have been blown away via the cleanup chain
12303      or by breakpoint_init_inferior when we rerun the executable.  */
12304 }
12305
12306 static void
12307 momentary_bkpt_check_status (bpstat bs)
12308 {
12309   /* Nothing.  The point of these breakpoints is causing a stop.  */
12310 }
12311
12312 static enum print_stop_action
12313 momentary_bkpt_print_it (bpstat bs)
12314 {
12315   struct ui_out *uiout = current_uiout;
12316
12317   if (ui_out_is_mi_like_p (uiout))
12318     {
12319       struct breakpoint *b = bs->breakpoint_at;
12320
12321       switch (b->type)
12322         {
12323         case bp_finish:
12324           ui_out_field_string
12325             (uiout, "reason",
12326              async_reason_lookup (EXEC_ASYNC_FUNCTION_FINISHED));
12327           break;
12328
12329         case bp_until:
12330           ui_out_field_string
12331             (uiout, "reason",
12332              async_reason_lookup (EXEC_ASYNC_LOCATION_REACHED));
12333           break;
12334         }
12335     }
12336
12337   return PRINT_UNKNOWN;
12338 }
12339
12340 static void
12341 momentary_bkpt_print_mention (struct breakpoint *b)
12342 {
12343   /* Nothing to mention.  These breakpoints are internal.  */
12344 }
12345
12346 /* The breakpoint_ops structure to be used in tracepoints.  */
12347
12348 static void
12349 tracepoint_re_set (struct breakpoint *b)
12350 {
12351   breakpoint_re_set_default (b);
12352 }
12353
12354 static int
12355 tracepoint_breakpoint_hit (const struct bp_location *bl,
12356                            struct address_space *aspace, CORE_ADDR bp_addr,
12357                            const struct target_waitstatus *ws)
12358 {
12359   /* By definition, the inferior does not report stops at
12360      tracepoints.  */
12361   return 0;
12362 }
12363
12364 static void
12365 tracepoint_print_one_detail (const struct breakpoint *self,
12366                              struct ui_out *uiout)
12367 {
12368   struct tracepoint *tp = (struct tracepoint *) self;
12369   if (tp->static_trace_marker_id)
12370     {
12371       gdb_assert (self->type == bp_static_tracepoint);
12372
12373       ui_out_text (uiout, "\tmarker id is ");
12374       ui_out_field_string (uiout, "static-tracepoint-marker-string-id",
12375                            tp->static_trace_marker_id);
12376       ui_out_text (uiout, "\n");
12377     }
12378 }
12379
12380 static void
12381 tracepoint_print_mention (struct breakpoint *b)
12382 {
12383   if (ui_out_is_mi_like_p (current_uiout))
12384     return;
12385
12386   switch (b->type)
12387     {
12388     case bp_tracepoint:
12389       printf_filtered (_("Tracepoint"));
12390       printf_filtered (_(" %d"), b->number);
12391       break;
12392     case bp_fast_tracepoint:
12393       printf_filtered (_("Fast tracepoint"));
12394       printf_filtered (_(" %d"), b->number);
12395       break;
12396     case bp_static_tracepoint:
12397       printf_filtered (_("Static tracepoint"));
12398       printf_filtered (_(" %d"), b->number);
12399       break;
12400     default:
12401       internal_error (__FILE__, __LINE__,
12402                       _("unhandled tracepoint type %d"), (int) b->type);
12403     }
12404
12405   say_where (b);
12406 }
12407
12408 static void
12409 tracepoint_print_recreate (struct breakpoint *self, struct ui_file *fp)
12410 {
12411   struct tracepoint *tp = (struct tracepoint *) self;
12412
12413   if (self->type == bp_fast_tracepoint)
12414     fprintf_unfiltered (fp, "ftrace");
12415   if (self->type == bp_static_tracepoint)
12416     fprintf_unfiltered (fp, "strace");
12417   else if (self->type == bp_tracepoint)
12418     fprintf_unfiltered (fp, "trace");
12419   else
12420     internal_error (__FILE__, __LINE__,
12421                     _("unhandled tracepoint type %d"), (int) self->type);
12422
12423   fprintf_unfiltered (fp, " %s", self->addr_string);
12424   print_recreate_thread (self, fp);
12425
12426   if (tp->pass_count)
12427     fprintf_unfiltered (fp, "  passcount %d\n", tp->pass_count);
12428 }
12429
12430 static void
12431 tracepoint_create_sals_from_address (char **arg,
12432                                      struct linespec_result *canonical,
12433                                      enum bptype type_wanted,
12434                                      char *addr_start, char **copy_arg)
12435 {
12436   create_sals_from_address_default (arg, canonical, type_wanted,
12437                                     addr_start, copy_arg);
12438 }
12439
12440 static void
12441 tracepoint_create_breakpoints_sal (struct gdbarch *gdbarch,
12442                                    struct linespec_result *canonical,
12443                                    struct linespec_sals *lsal,
12444                                    char *cond_string,
12445                                    enum bptype type_wanted,
12446                                    enum bpdisp disposition,
12447                                    int thread,
12448                                    int task, int ignore_count,
12449                                    const struct breakpoint_ops *ops,
12450                                    int from_tty, int enabled,
12451                                    int internal)
12452 {
12453   create_breakpoints_sal_default (gdbarch, canonical, lsal,
12454                                   cond_string, type_wanted,
12455                                   disposition, thread, task,
12456                                   ignore_count, ops, from_tty,
12457                                   enabled, internal);
12458 }
12459
12460 static void
12461 tracepoint_decode_linespec (struct breakpoint *b, char **s,
12462                             struct symtabs_and_lines *sals)
12463 {
12464   decode_linespec_default (b, s, sals);
12465 }
12466
12467 struct breakpoint_ops tracepoint_breakpoint_ops;
12468
12469 /* The breakpoint_ops structure to be used on static tracepoints with
12470    markers (`-m').  */
12471
12472 static void
12473 strace_marker_create_sals_from_address (char **arg,
12474                                         struct linespec_result *canonical,
12475                                         enum bptype type_wanted,
12476                                         char *addr_start, char **copy_arg)
12477 {
12478   struct linespec_sals lsal;
12479
12480   lsal.sals = decode_static_tracepoint_spec (arg);
12481
12482   *copy_arg = savestring (addr_start, *arg - addr_start);
12483
12484   canonical->addr_string = xstrdup (*copy_arg);
12485   lsal.canonical = xstrdup (*copy_arg);
12486   VEC_safe_push (linespec_sals, canonical->sals, &lsal);
12487 }
12488
12489 static void
12490 strace_marker_create_breakpoints_sal (struct gdbarch *gdbarch,
12491                                       struct linespec_result *canonical,
12492                                       struct linespec_sals *lsal,
12493                                       char *cond_string,
12494                                       enum bptype type_wanted,
12495                                       enum bpdisp disposition,
12496                                       int thread,
12497                                       int task, int ignore_count,
12498                                       const struct breakpoint_ops *ops,
12499                                       int from_tty, int enabled,
12500                                       int internal)
12501 {
12502   int i;
12503
12504   /* If the user is creating a static tracepoint by marker id
12505      (strace -m MARKER_ID), then store the sals index, so that
12506      breakpoint_re_set can try to match up which of the newly
12507      found markers corresponds to this one, and, don't try to
12508      expand multiple locations for each sal, given than SALS
12509      already should contain all sals for MARKER_ID.  */
12510
12511   for (i = 0; i < lsal->sals.nelts; ++i)
12512     {
12513       struct symtabs_and_lines expanded;
12514       struct tracepoint *tp;
12515       struct cleanup *old_chain;
12516       char *addr_string;
12517
12518       expanded.nelts = 1;
12519       expanded.sals = &lsal->sals.sals[i];
12520
12521       addr_string = xstrdup (canonical->addr_string);
12522       old_chain = make_cleanup (xfree, addr_string);
12523
12524       tp = XCNEW (struct tracepoint);
12525       init_breakpoint_sal (&tp->base, gdbarch, expanded,
12526                            addr_string, NULL,
12527                            cond_string, type_wanted, disposition,
12528                            thread, task, ignore_count, ops,
12529                            from_tty, enabled, internal,
12530                            canonical->special_display);
12531       /* Given that its possible to have multiple markers with
12532          the same string id, if the user is creating a static
12533          tracepoint by marker id ("strace -m MARKER_ID"), then
12534          store the sals index, so that breakpoint_re_set can
12535          try to match up which of the newly found markers
12536          corresponds to this one  */
12537       tp->static_trace_marker_id_idx = i;
12538
12539       install_breakpoint (internal, &tp->base, 0);
12540
12541       discard_cleanups (old_chain);
12542     }
12543 }
12544
12545 static void
12546 strace_marker_decode_linespec (struct breakpoint *b, char **s,
12547                                struct symtabs_and_lines *sals)
12548 {
12549   struct tracepoint *tp = (struct tracepoint *) b;
12550
12551   *sals = decode_static_tracepoint_spec (s);
12552   if (sals->nelts > tp->static_trace_marker_id_idx)
12553     {
12554       sals->sals[0] = sals->sals[tp->static_trace_marker_id_idx];
12555       sals->nelts = 1;
12556     }
12557   else
12558     error (_("marker %s not found"), tp->static_trace_marker_id);
12559 }
12560
12561 static struct breakpoint_ops strace_marker_breakpoint_ops;
12562
12563 static int
12564 strace_marker_p (struct breakpoint *b)
12565 {
12566   return b->ops == &strace_marker_breakpoint_ops;
12567 }
12568
12569 /* Delete a breakpoint and clean up all traces of it in the data
12570    structures.  */
12571
12572 void
12573 delete_breakpoint (struct breakpoint *bpt)
12574 {
12575   struct breakpoint *b;
12576
12577   gdb_assert (bpt != NULL);
12578
12579   /* Has this bp already been deleted?  This can happen because
12580      multiple lists can hold pointers to bp's.  bpstat lists are
12581      especial culprits.
12582
12583      One example of this happening is a watchpoint's scope bp.  When
12584      the scope bp triggers, we notice that the watchpoint is out of
12585      scope, and delete it.  We also delete its scope bp.  But the
12586      scope bp is marked "auto-deleting", and is already on a bpstat.
12587      That bpstat is then checked for auto-deleting bp's, which are
12588      deleted.
12589
12590      A real solution to this problem might involve reference counts in
12591      bp's, and/or giving them pointers back to their referencing
12592      bpstat's, and teaching delete_breakpoint to only free a bp's
12593      storage when no more references were extent.  A cheaper bandaid
12594      was chosen.  */
12595   if (bpt->type == bp_none)
12596     return;
12597
12598   /* At least avoid this stale reference until the reference counting
12599      of breakpoints gets resolved.  */
12600   if (bpt->related_breakpoint != bpt)
12601     {
12602       struct breakpoint *related;
12603       struct watchpoint *w;
12604
12605       if (bpt->type == bp_watchpoint_scope)
12606         w = (struct watchpoint *) bpt->related_breakpoint;
12607       else if (bpt->related_breakpoint->type == bp_watchpoint_scope)
12608         w = (struct watchpoint *) bpt;
12609       else
12610         w = NULL;
12611       if (w != NULL)
12612         watchpoint_del_at_next_stop (w);
12613
12614       /* Unlink bpt from the bpt->related_breakpoint ring.  */
12615       for (related = bpt; related->related_breakpoint != bpt;
12616            related = related->related_breakpoint);
12617       related->related_breakpoint = bpt->related_breakpoint;
12618       bpt->related_breakpoint = bpt;
12619     }
12620
12621   /* watch_command_1 creates a watchpoint but only sets its number if
12622      update_watchpoint succeeds in creating its bp_locations.  If there's
12623      a problem in that process, we'll be asked to delete the half-created
12624      watchpoint.  In that case, don't announce the deletion.  */
12625   if (bpt->number)
12626     observer_notify_breakpoint_deleted (bpt);
12627
12628   if (breakpoint_chain == bpt)
12629     breakpoint_chain = bpt->next;
12630
12631   ALL_BREAKPOINTS (b)
12632     if (b->next == bpt)
12633     {
12634       b->next = bpt->next;
12635       break;
12636     }
12637
12638   /* Be sure no bpstat's are pointing at the breakpoint after it's
12639      been freed.  */
12640   /* FIXME, how can we find all bpstat's?  We just check stop_bpstat
12641      in all threads for now.  Note that we cannot just remove bpstats
12642      pointing at bpt from the stop_bpstat list entirely, as breakpoint
12643      commands are associated with the bpstat; if we remove it here,
12644      then the later call to bpstat_do_actions (&stop_bpstat); in
12645      event-top.c won't do anything, and temporary breakpoints with
12646      commands won't work.  */
12647
12648   iterate_over_threads (bpstat_remove_breakpoint_callback, bpt);
12649
12650   /* Now that breakpoint is removed from breakpoint list, update the
12651      global location list.  This will remove locations that used to
12652      belong to this breakpoint.  Do this before freeing the breakpoint
12653      itself, since remove_breakpoint looks at location's owner.  It
12654      might be better design to have location completely
12655      self-contained, but it's not the case now.  */
12656   update_global_location_list (0);
12657
12658   bpt->ops->dtor (bpt);
12659   /* On the chance that someone will soon try again to delete this
12660      same bp, we mark it as deleted before freeing its storage.  */
12661   bpt->type = bp_none;
12662   xfree (bpt);
12663 }
12664
12665 static void
12666 do_delete_breakpoint_cleanup (void *b)
12667 {
12668   delete_breakpoint (b);
12669 }
12670
12671 struct cleanup *
12672 make_cleanup_delete_breakpoint (struct breakpoint *b)
12673 {
12674   return make_cleanup (do_delete_breakpoint_cleanup, b);
12675 }
12676
12677 /* Iterator function to call a user-provided callback function once
12678    for each of B and its related breakpoints.  */
12679
12680 static void
12681 iterate_over_related_breakpoints (struct breakpoint *b,
12682                                   void (*function) (struct breakpoint *,
12683                                                     void *),
12684                                   void *data)
12685 {
12686   struct breakpoint *related;
12687
12688   related = b;
12689   do
12690     {
12691       struct breakpoint *next;
12692
12693       /* FUNCTION may delete RELATED.  */
12694       next = related->related_breakpoint;
12695
12696       if (next == related)
12697         {
12698           /* RELATED is the last ring entry.  */
12699           function (related, data);
12700
12701           /* FUNCTION may have deleted it, so we'd never reach back to
12702              B.  There's nothing left to do anyway, so just break
12703              out.  */
12704           break;
12705         }
12706       else
12707         function (related, data);
12708
12709       related = next;
12710     }
12711   while (related != b);
12712 }
12713
12714 static void
12715 do_delete_breakpoint (struct breakpoint *b, void *ignore)
12716 {
12717   delete_breakpoint (b);
12718 }
12719
12720 /* A callback for map_breakpoint_numbers that calls
12721    delete_breakpoint.  */
12722
12723 static void
12724 do_map_delete_breakpoint (struct breakpoint *b, void *ignore)
12725 {
12726   iterate_over_related_breakpoints (b, do_delete_breakpoint, NULL);
12727 }
12728
12729 void
12730 delete_command (char *arg, int from_tty)
12731 {
12732   struct breakpoint *b, *b_tmp;
12733
12734   dont_repeat ();
12735
12736   if (arg == 0)
12737     {
12738       int breaks_to_delete = 0;
12739
12740       /* Delete all breakpoints if no argument.  Do not delete
12741          internal breakpoints, these have to be deleted with an
12742          explicit breakpoint number argument.  */
12743       ALL_BREAKPOINTS (b)
12744         if (user_breakpoint_p (b))
12745           {
12746             breaks_to_delete = 1;
12747             break;
12748           }
12749
12750       /* Ask user only if there are some breakpoints to delete.  */
12751       if (!from_tty
12752           || (breaks_to_delete && query (_("Delete all breakpoints? "))))
12753         {
12754           ALL_BREAKPOINTS_SAFE (b, b_tmp)
12755             if (user_breakpoint_p (b))
12756               delete_breakpoint (b);
12757         }
12758     }
12759   else
12760     map_breakpoint_numbers (arg, do_map_delete_breakpoint, NULL);
12761 }
12762
12763 static int
12764 all_locations_are_pending (struct bp_location *loc)
12765 {
12766   for (; loc; loc = loc->next)
12767     if (!loc->shlib_disabled
12768         && !loc->pspace->executing_startup)
12769       return 0;
12770   return 1;
12771 }
12772
12773 /* Subroutine of update_breakpoint_locations to simplify it.
12774    Return non-zero if multiple fns in list LOC have the same name.
12775    Null names are ignored.  */
12776
12777 static int
12778 ambiguous_names_p (struct bp_location *loc)
12779 {
12780   struct bp_location *l;
12781   htab_t htab = htab_create_alloc (13, htab_hash_string,
12782                                    (int (*) (const void *, 
12783                                              const void *)) streq,
12784                                    NULL, xcalloc, xfree);
12785
12786   for (l = loc; l != NULL; l = l->next)
12787     {
12788       const char **slot;
12789       const char *name = l->function_name;
12790
12791       /* Allow for some names to be NULL, ignore them.  */
12792       if (name == NULL)
12793         continue;
12794
12795       slot = (const char **) htab_find_slot (htab, (const void *) name,
12796                                              INSERT);
12797       /* NOTE: We can assume slot != NULL here because xcalloc never
12798          returns NULL.  */
12799       if (*slot != NULL)
12800         {
12801           htab_delete (htab);
12802           return 1;
12803         }
12804       *slot = name;
12805     }
12806
12807   htab_delete (htab);
12808   return 0;
12809 }
12810
12811 /* When symbols change, it probably means the sources changed as well,
12812    and it might mean the static tracepoint markers are no longer at
12813    the same address or line numbers they used to be at last we
12814    checked.  Losing your static tracepoints whenever you rebuild is
12815    undesirable.  This function tries to resync/rematch gdb static
12816    tracepoints with the markers on the target, for static tracepoints
12817    that have not been set by marker id.  Static tracepoint that have
12818    been set by marker id are reset by marker id in breakpoint_re_set.
12819    The heuristic is:
12820
12821    1) For a tracepoint set at a specific address, look for a marker at
12822    the old PC.  If one is found there, assume to be the same marker.
12823    If the name / string id of the marker found is different from the
12824    previous known name, assume that means the user renamed the marker
12825    in the sources, and output a warning.
12826
12827    2) For a tracepoint set at a given line number, look for a marker
12828    at the new address of the old line number.  If one is found there,
12829    assume to be the same marker.  If the name / string id of the
12830    marker found is different from the previous known name, assume that
12831    means the user renamed the marker in the sources, and output a
12832    warning.
12833
12834    3) If a marker is no longer found at the same address or line, it
12835    may mean the marker no longer exists.  But it may also just mean
12836    the code changed a bit.  Maybe the user added a few lines of code
12837    that made the marker move up or down (in line number terms).  Ask
12838    the target for info about the marker with the string id as we knew
12839    it.  If found, update line number and address in the matching
12840    static tracepoint.  This will get confused if there's more than one
12841    marker with the same ID (possible in UST, although unadvised
12842    precisely because it confuses tools).  */
12843
12844 static struct symtab_and_line
12845 update_static_tracepoint (struct breakpoint *b, struct symtab_and_line sal)
12846 {
12847   struct tracepoint *tp = (struct tracepoint *) b;
12848   struct static_tracepoint_marker marker;
12849   CORE_ADDR pc;
12850   int i;
12851
12852   pc = sal.pc;
12853   if (sal.line)
12854     find_line_pc (sal.symtab, sal.line, &pc);
12855
12856   if (target_static_tracepoint_marker_at (pc, &marker))
12857     {
12858       if (strcmp (tp->static_trace_marker_id, marker.str_id) != 0)
12859         warning (_("static tracepoint %d changed probed marker from %s to %s"),
12860                  b->number,
12861                  tp->static_trace_marker_id, marker.str_id);
12862
12863       xfree (tp->static_trace_marker_id);
12864       tp->static_trace_marker_id = xstrdup (marker.str_id);
12865       release_static_tracepoint_marker (&marker);
12866
12867       return sal;
12868     }
12869
12870   /* Old marker wasn't found on target at lineno.  Try looking it up
12871      by string ID.  */
12872   if (!sal.explicit_pc
12873       && sal.line != 0
12874       && sal.symtab != NULL
12875       && tp->static_trace_marker_id != NULL)
12876     {
12877       VEC(static_tracepoint_marker_p) *markers;
12878
12879       markers
12880         = target_static_tracepoint_markers_by_strid (tp->static_trace_marker_id);
12881
12882       if (!VEC_empty(static_tracepoint_marker_p, markers))
12883         {
12884           struct symtab_and_line sal2;
12885           struct symbol *sym;
12886           struct static_tracepoint_marker *tpmarker;
12887           struct ui_out *uiout = current_uiout;
12888
12889           tpmarker = VEC_index (static_tracepoint_marker_p, markers, 0);
12890
12891           xfree (tp->static_trace_marker_id);
12892           tp->static_trace_marker_id = xstrdup (tpmarker->str_id);
12893
12894           warning (_("marker for static tracepoint %d (%s) not "
12895                      "found at previous line number"),
12896                    b->number, tp->static_trace_marker_id);
12897
12898           init_sal (&sal2);
12899
12900           sal2.pc = tpmarker->address;
12901
12902           sal2 = find_pc_line (tpmarker->address, 0);
12903           sym = find_pc_sect_function (tpmarker->address, NULL);
12904           ui_out_text (uiout, "Now in ");
12905           if (sym)
12906             {
12907               ui_out_field_string (uiout, "func",
12908                                    SYMBOL_PRINT_NAME (sym));
12909               ui_out_text (uiout, " at ");
12910             }
12911           ui_out_field_string (uiout, "file", sal2.symtab->filename);
12912           ui_out_text (uiout, ":");
12913
12914           if (ui_out_is_mi_like_p (uiout))
12915             {
12916               char *fullname = symtab_to_fullname (sal2.symtab);
12917
12918               if (fullname)
12919                 ui_out_field_string (uiout, "fullname", fullname);
12920             }
12921
12922           ui_out_field_int (uiout, "line", sal2.line);
12923           ui_out_text (uiout, "\n");
12924
12925           b->loc->line_number = sal2.line;
12926
12927           xfree (b->loc->source_file);
12928           if (sym)
12929             b->loc->source_file = xstrdup (sal2.symtab->filename);
12930           else
12931             b->loc->source_file = NULL;
12932
12933           xfree (b->addr_string);
12934           b->addr_string = xstrprintf ("%s:%d",
12935                                        sal2.symtab->filename,
12936                                        b->loc->line_number);
12937
12938           /* Might be nice to check if function changed, and warn if
12939              so.  */
12940
12941           release_static_tracepoint_marker (tpmarker);
12942         }
12943     }
12944   return sal;
12945 }
12946
12947 /* Returns 1 iff locations A and B are sufficiently same that
12948    we don't need to report breakpoint as changed.  */
12949
12950 static int
12951 locations_are_equal (struct bp_location *a, struct bp_location *b)
12952 {
12953   while (a && b)
12954     {
12955       if (a->address != b->address)
12956         return 0;
12957
12958       if (a->shlib_disabled != b->shlib_disabled)
12959         return 0;
12960
12961       if (a->enabled != b->enabled)
12962         return 0;
12963
12964       a = a->next;
12965       b = b->next;
12966     }
12967
12968   if ((a == NULL) != (b == NULL))
12969     return 0;
12970
12971   return 1;
12972 }
12973
12974 /* Create new breakpoint locations for B (a hardware or software breakpoint)
12975    based on SALS and SALS_END.  If SALS_END.NELTS is not zero, then B is
12976    a ranged breakpoint.  */
12977
12978 void
12979 update_breakpoint_locations (struct breakpoint *b,
12980                              struct symtabs_and_lines sals,
12981                              struct symtabs_and_lines sals_end)
12982 {
12983   int i;
12984   struct bp_location *existing_locations = b->loc;
12985
12986   if (sals_end.nelts != 0 && (sals.nelts != 1 || sals_end.nelts != 1))
12987     {
12988       /* Ranged breakpoints have only one start location and one end
12989          location.  */
12990       b->enable_state = bp_disabled;
12991       update_global_location_list (1);
12992       printf_unfiltered (_("Could not reset ranged breakpoint %d: "
12993                            "multiple locations found\n"),
12994                          b->number);
12995       return;
12996     }
12997
12998   /* If there's no new locations, and all existing locations are
12999      pending, don't do anything.  This optimizes the common case where
13000      all locations are in the same shared library, that was unloaded.
13001      We'd like to retain the location, so that when the library is
13002      loaded again, we don't loose the enabled/disabled status of the
13003      individual locations.  */
13004   if (all_locations_are_pending (existing_locations) && sals.nelts == 0)
13005     return;
13006
13007   b->loc = NULL;
13008
13009   for (i = 0; i < sals.nelts; ++i)
13010     {
13011       struct bp_location *new_loc;
13012
13013       switch_to_program_space_and_thread (sals.sals[i].pspace);
13014
13015       new_loc = add_location_to_breakpoint (b, &(sals.sals[i]));
13016
13017       /* Reparse conditions, they might contain references to the
13018          old symtab.  */
13019       if (b->cond_string != NULL)
13020         {
13021           char *s;
13022           volatile struct gdb_exception e;
13023
13024           s = b->cond_string;
13025           TRY_CATCH (e, RETURN_MASK_ERROR)
13026             {
13027               new_loc->cond = parse_exp_1 (&s, block_for_pc (sals.sals[i].pc), 
13028                                            0);
13029             }
13030           if (e.reason < 0)
13031             {
13032               warning (_("failed to reevaluate condition "
13033                          "for breakpoint %d: %s"), 
13034                        b->number, e.message);
13035               new_loc->enabled = 0;
13036             }
13037         }
13038
13039       if (sals_end.nelts)
13040         {
13041           CORE_ADDR end = find_breakpoint_range_end (sals_end.sals[0]);
13042
13043           new_loc->length = end - sals.sals[0].pc + 1;
13044         }
13045     }
13046
13047   /* Update locations of permanent breakpoints.  */
13048   if (b->enable_state == bp_permanent)
13049     make_breakpoint_permanent (b);
13050
13051   /* If possible, carry over 'disable' status from existing
13052      breakpoints.  */
13053   {
13054     struct bp_location *e = existing_locations;
13055     /* If there are multiple breakpoints with the same function name,
13056        e.g. for inline functions, comparing function names won't work.
13057        Instead compare pc addresses; this is just a heuristic as things
13058        may have moved, but in practice it gives the correct answer
13059        often enough until a better solution is found.  */
13060     int have_ambiguous_names = ambiguous_names_p (b->loc);
13061
13062     for (; e; e = e->next)
13063       {
13064         if (!e->enabled && e->function_name)
13065           {
13066             struct bp_location *l = b->loc;
13067             if (have_ambiguous_names)
13068               {
13069                 for (; l; l = l->next)
13070                   if (breakpoint_locations_match (e, l))
13071                     {
13072                       l->enabled = 0;
13073                       break;
13074                     }
13075               }
13076             else
13077               {
13078                 for (; l; l = l->next)
13079                   if (l->function_name
13080                       && strcmp (e->function_name, l->function_name) == 0)
13081                     {
13082                       l->enabled = 0;
13083                       break;
13084                     }
13085               }
13086           }
13087       }
13088   }
13089
13090   if (!locations_are_equal (existing_locations, b->loc))
13091     observer_notify_breakpoint_modified (b);
13092
13093   update_global_location_list (1);
13094 }
13095
13096 /* Find the SaL locations corresponding to the given ADDR_STRING.
13097    On return, FOUND will be 1 if any SaL was found, zero otherwise.  */
13098
13099 static struct symtabs_and_lines
13100 addr_string_to_sals (struct breakpoint *b, char *addr_string, int *found)
13101 {
13102   char *s;
13103   struct symtabs_and_lines sals = {0};
13104   volatile struct gdb_exception e;
13105
13106   gdb_assert (b->ops != NULL);
13107   s = addr_string;
13108
13109   TRY_CATCH (e, RETURN_MASK_ERROR)
13110     {
13111       b->ops->decode_linespec (b, &s, &sals);
13112     }
13113   if (e.reason < 0)
13114     {
13115       int not_found_and_ok = 0;
13116       /* For pending breakpoints, it's expected that parsing will
13117          fail until the right shared library is loaded.  User has
13118          already told to create pending breakpoints and don't need
13119          extra messages.  If breakpoint is in bp_shlib_disabled
13120          state, then user already saw the message about that
13121          breakpoint being disabled, and don't want to see more
13122          errors.  */
13123       if (e.error == NOT_FOUND_ERROR
13124           && (b->condition_not_parsed 
13125               || (b->loc && b->loc->shlib_disabled)
13126               || (b->loc && b->loc->pspace->executing_startup)
13127               || b->enable_state == bp_disabled))
13128         not_found_and_ok = 1;
13129
13130       if (!not_found_and_ok)
13131         {
13132           /* We surely don't want to warn about the same breakpoint
13133              10 times.  One solution, implemented here, is disable
13134              the breakpoint on error.  Another solution would be to
13135              have separate 'warning emitted' flag.  Since this
13136              happens only when a binary has changed, I don't know
13137              which approach is better.  */
13138           b->enable_state = bp_disabled;
13139           throw_exception (e);
13140         }
13141     }
13142
13143   if (e.reason == 0 || e.error != NOT_FOUND_ERROR)
13144     {
13145       int i;
13146
13147       for (i = 0; i < sals.nelts; ++i)
13148         resolve_sal_pc (&sals.sals[i]);
13149       if (b->condition_not_parsed && s && s[0])
13150         {
13151           char *cond_string = 0;
13152           int thread = -1;
13153           int task = 0;
13154
13155           find_condition_and_thread (s, sals.sals[0].pc,
13156                                      &cond_string, &thread, &task);
13157           if (cond_string)
13158             b->cond_string = cond_string;
13159           b->thread = thread;
13160           b->task = task;
13161           b->condition_not_parsed = 0;
13162         }
13163
13164       if (b->type == bp_static_tracepoint && !strace_marker_p (b))
13165         sals.sals[0] = update_static_tracepoint (b, sals.sals[0]);
13166
13167       *found = 1;
13168     }
13169   else
13170     *found = 0;
13171
13172   return sals;
13173 }
13174
13175 /* The default re_set method, for typical hardware or software
13176    breakpoints.  Reevaluate the breakpoint and recreate its
13177    locations.  */
13178
13179 static void
13180 breakpoint_re_set_default (struct breakpoint *b)
13181 {
13182   int found;
13183   struct symtabs_and_lines sals, sals_end;
13184   struct symtabs_and_lines expanded = {0};
13185   struct symtabs_and_lines expanded_end = {0};
13186
13187   sals = addr_string_to_sals (b, b->addr_string, &found);
13188   if (found)
13189     {
13190       make_cleanup (xfree, sals.sals);
13191       expanded = sals;
13192     }
13193
13194   if (b->addr_string_range_end)
13195     {
13196       sals_end = addr_string_to_sals (b, b->addr_string_range_end, &found);
13197       if (found)
13198         {
13199           make_cleanup (xfree, sals_end.sals);
13200           expanded_end = sals_end;
13201         }
13202     }
13203
13204   update_breakpoint_locations (b, expanded, expanded_end);
13205 }
13206
13207 /* Default method for creating SALs from an address string.  It basically
13208    calls parse_breakpoint_sals.  Return 1 for success, zero for failure.  */
13209
13210 static void
13211 create_sals_from_address_default (char **arg,
13212                                   struct linespec_result *canonical,
13213                                   enum bptype type_wanted,
13214                                   char *addr_start, char **copy_arg)
13215 {
13216   parse_breakpoint_sals (arg, canonical);
13217 }
13218
13219 /* Call create_breakpoints_sal for the given arguments.  This is the default
13220    function for the `create_breakpoints_sal' method of
13221    breakpoint_ops.  */
13222
13223 static void
13224 create_breakpoints_sal_default (struct gdbarch *gdbarch,
13225                                 struct linespec_result *canonical,
13226                                 struct linespec_sals *lsal,
13227                                 char *cond_string,
13228                                 enum bptype type_wanted,
13229                                 enum bpdisp disposition,
13230                                 int thread,
13231                                 int task, int ignore_count,
13232                                 const struct breakpoint_ops *ops,
13233                                 int from_tty, int enabled,
13234                                 int internal)
13235 {
13236   create_breakpoints_sal (gdbarch, canonical, cond_string,
13237                           type_wanted, disposition,
13238                           thread, task, ignore_count, ops, from_tty,
13239                           enabled, internal);
13240 }
13241
13242 /* Decode the line represented by S by calling decode_line_full.  This is the
13243    default function for the `decode_linespec' method of breakpoint_ops.  */
13244
13245 static void
13246 decode_linespec_default (struct breakpoint *b, char **s,
13247                          struct symtabs_and_lines *sals)
13248 {
13249   struct linespec_result canonical;
13250
13251   init_linespec_result (&canonical);
13252   decode_line_full (s, DECODE_LINE_FUNFIRSTLINE,
13253                     (struct symtab *) NULL, 0,
13254                     &canonical, multiple_symbols_all,
13255                     b->filter);
13256
13257   /* We should get 0 or 1 resulting SALs.  */
13258   gdb_assert (VEC_length (linespec_sals, canonical.sals) < 2);
13259
13260   if (VEC_length (linespec_sals, canonical.sals) > 0)
13261     {
13262       struct linespec_sals *lsal;
13263
13264       lsal = VEC_index (linespec_sals, canonical.sals, 0);
13265       *sals = lsal->sals;
13266       /* Arrange it so the destructor does not free the
13267          contents.  */
13268       lsal->sals.sals = NULL;
13269     }
13270
13271   destroy_linespec_result (&canonical);
13272 }
13273
13274 /* Prepare the global context for a re-set of breakpoint B.  */
13275
13276 static struct cleanup *
13277 prepare_re_set_context (struct breakpoint *b)
13278 {
13279   struct cleanup *cleanups;
13280
13281   input_radix = b->input_radix;
13282   cleanups = save_current_space_and_thread ();
13283   if (b->pspace != NULL)
13284     switch_to_program_space_and_thread (b->pspace);
13285   set_language (b->language);
13286
13287   return cleanups;
13288 }
13289
13290 /* Reset a breakpoint given it's struct breakpoint * BINT.
13291    The value we return ends up being the return value from catch_errors.
13292    Unused in this case.  */
13293
13294 static int
13295 breakpoint_re_set_one (void *bint)
13296 {
13297   /* Get past catch_errs.  */
13298   struct breakpoint *b = (struct breakpoint *) bint;
13299   struct cleanup *cleanups;
13300
13301   cleanups = prepare_re_set_context (b);
13302   b->ops->re_set (b);
13303   do_cleanups (cleanups);
13304   return 0;
13305 }
13306
13307 /* Re-set all breakpoints after symbols have been re-loaded.  */
13308 void
13309 breakpoint_re_set (void)
13310 {
13311   struct breakpoint *b, *b_tmp;
13312   enum language save_language;
13313   int save_input_radix;
13314   struct cleanup *old_chain;
13315
13316   save_language = current_language->la_language;
13317   save_input_radix = input_radix;
13318   old_chain = save_current_program_space ();
13319
13320   ALL_BREAKPOINTS_SAFE (b, b_tmp)
13321   {
13322     /* Format possible error msg.  */
13323     char *message = xstrprintf ("Error in re-setting breakpoint %d: ",
13324                                 b->number);
13325     struct cleanup *cleanups = make_cleanup (xfree, message);
13326     catch_errors (breakpoint_re_set_one, b, message, RETURN_MASK_ALL);
13327     do_cleanups (cleanups);
13328   }
13329   set_language (save_language);
13330   input_radix = save_input_radix;
13331
13332   jit_breakpoint_re_set ();
13333
13334   do_cleanups (old_chain);
13335
13336   create_overlay_event_breakpoint ();
13337   create_longjmp_master_breakpoint ();
13338   create_std_terminate_master_breakpoint ();
13339   create_exception_master_breakpoint ();
13340
13341   /* While we're at it, reset the skip list too.  */
13342   skip_re_set ();
13343 }
13344 \f
13345 /* Reset the thread number of this breakpoint:
13346
13347    - If the breakpoint is for all threads, leave it as-is.
13348    - Else, reset it to the current thread for inferior_ptid.  */
13349 void
13350 breakpoint_re_set_thread (struct breakpoint *b)
13351 {
13352   if (b->thread != -1)
13353     {
13354       if (in_thread_list (inferior_ptid))
13355         b->thread = pid_to_thread_id (inferior_ptid);
13356
13357       /* We're being called after following a fork.  The new fork is
13358          selected as current, and unless this was a vfork will have a
13359          different program space from the original thread.  Reset that
13360          as well.  */
13361       b->loc->pspace = current_program_space;
13362     }
13363 }
13364
13365 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
13366    If from_tty is nonzero, it prints a message to that effect,
13367    which ends with a period (no newline).  */
13368
13369 void
13370 set_ignore_count (int bptnum, int count, int from_tty)
13371 {
13372   struct breakpoint *b;
13373
13374   if (count < 0)
13375     count = 0;
13376
13377   ALL_BREAKPOINTS (b)
13378     if (b->number == bptnum)
13379     {
13380       if (is_tracepoint (b))
13381         {
13382           if (from_tty && count != 0)
13383             printf_filtered (_("Ignore count ignored for tracepoint %d."),
13384                              bptnum);
13385           return;
13386         }
13387       
13388       b->ignore_count = count;
13389       if (from_tty)
13390         {
13391           if (count == 0)
13392             printf_filtered (_("Will stop next time "
13393                                "breakpoint %d is reached."),
13394                              bptnum);
13395           else if (count == 1)
13396             printf_filtered (_("Will ignore next crossing of breakpoint %d."),
13397                              bptnum);
13398           else
13399             printf_filtered (_("Will ignore next %d "
13400                                "crossings of breakpoint %d."),
13401                              count, bptnum);
13402         }
13403       breakpoints_changed ();
13404       observer_notify_breakpoint_modified (b);
13405       return;
13406     }
13407
13408   error (_("No breakpoint number %d."), bptnum);
13409 }
13410
13411 /* Command to set ignore-count of breakpoint N to COUNT.  */
13412
13413 static void
13414 ignore_command (char *args, int from_tty)
13415 {
13416   char *p = args;
13417   int num;
13418
13419   if (p == 0)
13420     error_no_arg (_("a breakpoint number"));
13421
13422   num = get_number (&p);
13423   if (num == 0)
13424     error (_("bad breakpoint number: '%s'"), args);
13425   if (*p == 0)
13426     error (_("Second argument (specified ignore-count) is missing."));
13427
13428   set_ignore_count (num,
13429                     longest_to_int (value_as_long (parse_and_eval (p))),
13430                     from_tty);
13431   if (from_tty)
13432     printf_filtered ("\n");
13433 }
13434 \f
13435 /* Call FUNCTION on each of the breakpoints
13436    whose numbers are given in ARGS.  */
13437
13438 static void
13439 map_breakpoint_numbers (char *args, void (*function) (struct breakpoint *,
13440                                                       void *),
13441                         void *data)
13442 {
13443   int num;
13444   struct breakpoint *b, *tmp;
13445   int match;
13446   struct get_number_or_range_state state;
13447
13448   if (args == 0)
13449     error_no_arg (_("one or more breakpoint numbers"));
13450
13451   init_number_or_range (&state, args);
13452
13453   while (!state.finished)
13454     {
13455       char *p = state.string;
13456
13457       match = 0;
13458
13459       num = get_number_or_range (&state);
13460       if (num == 0)
13461         {
13462           warning (_("bad breakpoint number at or near '%s'"), p);
13463         }
13464       else
13465         {
13466           ALL_BREAKPOINTS_SAFE (b, tmp)
13467             if (b->number == num)
13468               {
13469                 match = 1;
13470                 function (b, data);
13471                 break;
13472               }
13473           if (match == 0)
13474             printf_unfiltered (_("No breakpoint number %d.\n"), num);
13475         }
13476     }
13477 }
13478
13479 static struct bp_location *
13480 find_location_by_number (char *number)
13481 {
13482   char *dot = strchr (number, '.');
13483   char *p1;
13484   int bp_num;
13485   int loc_num;
13486   struct breakpoint *b;
13487   struct bp_location *loc;  
13488
13489   *dot = '\0';
13490
13491   p1 = number;
13492   bp_num = get_number (&p1);
13493   if (bp_num == 0)
13494     error (_("Bad breakpoint number '%s'"), number);
13495
13496   ALL_BREAKPOINTS (b)
13497     if (b->number == bp_num)
13498       {
13499         break;
13500       }
13501
13502   if (!b || b->number != bp_num)
13503     error (_("Bad breakpoint number '%s'"), number);
13504   
13505   p1 = dot+1;
13506   loc_num = get_number (&p1);
13507   if (loc_num == 0)
13508     error (_("Bad breakpoint location number '%s'"), number);
13509
13510   --loc_num;
13511   loc = b->loc;
13512   for (;loc_num && loc; --loc_num, loc = loc->next)
13513     ;
13514   if (!loc)
13515     error (_("Bad breakpoint location number '%s'"), dot+1);
13516     
13517   return loc;  
13518 }
13519
13520
13521 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
13522    If from_tty is nonzero, it prints a message to that effect,
13523    which ends with a period (no newline).  */
13524
13525 void
13526 disable_breakpoint (struct breakpoint *bpt)
13527 {
13528   /* Never disable a watchpoint scope breakpoint; we want to
13529      hit them when we leave scope so we can delete both the
13530      watchpoint and its scope breakpoint at that time.  */
13531   if (bpt->type == bp_watchpoint_scope)
13532     return;
13533
13534   /* You can't disable permanent breakpoints.  */
13535   if (bpt->enable_state == bp_permanent)
13536     return;
13537
13538   bpt->enable_state = bp_disabled;
13539
13540   /* Mark breakpoint locations modified.  */
13541   mark_breakpoint_modified (bpt);
13542
13543   if (target_supports_enable_disable_tracepoint ()
13544       && current_trace_status ()->running && is_tracepoint (bpt))
13545     {
13546       struct bp_location *location;
13547      
13548       for (location = bpt->loc; location; location = location->next)
13549         target_disable_tracepoint (location);
13550     }
13551
13552   update_global_location_list (0);
13553
13554   observer_notify_breakpoint_modified (bpt);
13555 }
13556
13557 /* A callback for iterate_over_related_breakpoints.  */
13558
13559 static void
13560 do_disable_breakpoint (struct breakpoint *b, void *ignore)
13561 {
13562   disable_breakpoint (b);
13563 }
13564
13565 /* A callback for map_breakpoint_numbers that calls
13566    disable_breakpoint.  */
13567
13568 static void
13569 do_map_disable_breakpoint (struct breakpoint *b, void *ignore)
13570 {
13571   iterate_over_related_breakpoints (b, do_disable_breakpoint, NULL);
13572 }
13573
13574 static void
13575 disable_command (char *args, int from_tty)
13576 {
13577   if (args == 0)
13578     {
13579       struct breakpoint *bpt;
13580
13581       ALL_BREAKPOINTS (bpt)
13582         if (user_breakpoint_p (bpt))
13583           disable_breakpoint (bpt);
13584     }
13585   else if (strchr (args, '.'))
13586     {
13587       struct bp_location *loc = find_location_by_number (args);
13588       if (loc)
13589         {
13590           if (loc->enabled)
13591             {
13592               loc->enabled = 0;
13593               mark_breakpoint_location_modified (loc);
13594             }
13595           if (target_supports_enable_disable_tracepoint ()
13596               && current_trace_status ()->running && loc->owner
13597               && is_tracepoint (loc->owner))
13598             target_disable_tracepoint (loc);
13599         }
13600       update_global_location_list (0);
13601     }
13602   else
13603     map_breakpoint_numbers (args, do_map_disable_breakpoint, NULL);
13604 }
13605
13606 static void
13607 enable_breakpoint_disp (struct breakpoint *bpt, enum bpdisp disposition,
13608                         int count)
13609 {
13610   int target_resources_ok;
13611
13612   if (bpt->type == bp_hardware_breakpoint)
13613     {
13614       int i;
13615       i = hw_breakpoint_used_count ();
13616       target_resources_ok = 
13617         target_can_use_hardware_watchpoint (bp_hardware_breakpoint, 
13618                                             i + 1, 0);
13619       if (target_resources_ok == 0)
13620         error (_("No hardware breakpoint support in the target."));
13621       else if (target_resources_ok < 0)
13622         error (_("Hardware breakpoints used exceeds limit."));
13623     }
13624
13625   if (is_watchpoint (bpt))
13626     {
13627       /* Initialize it just to avoid a GCC false warning.  */
13628       enum enable_state orig_enable_state = 0;
13629       volatile struct gdb_exception e;
13630
13631       TRY_CATCH (e, RETURN_MASK_ALL)
13632         {
13633           struct watchpoint *w = (struct watchpoint *) bpt;
13634
13635           orig_enable_state = bpt->enable_state;
13636           bpt->enable_state = bp_enabled;
13637           update_watchpoint (w, 1 /* reparse */);
13638         }
13639       if (e.reason < 0)
13640         {
13641           bpt->enable_state = orig_enable_state;
13642           exception_fprintf (gdb_stderr, e, _("Cannot enable watchpoint %d: "),
13643                              bpt->number);
13644           return;
13645         }
13646     }
13647
13648   if (bpt->enable_state != bp_permanent)
13649     bpt->enable_state = bp_enabled;
13650
13651   bpt->enable_state = bp_enabled;
13652
13653   /* Mark breakpoint locations modified.  */
13654   mark_breakpoint_modified (bpt);
13655
13656   if (target_supports_enable_disable_tracepoint ()
13657       && current_trace_status ()->running && is_tracepoint (bpt))
13658     {
13659       struct bp_location *location;
13660
13661       for (location = bpt->loc; location; location = location->next)
13662         target_enable_tracepoint (location);
13663     }
13664
13665   bpt->disposition = disposition;
13666   bpt->enable_count = count;
13667   update_global_location_list (1);
13668   breakpoints_changed ();
13669   
13670   observer_notify_breakpoint_modified (bpt);
13671 }
13672
13673
13674 void
13675 enable_breakpoint (struct breakpoint *bpt)
13676 {
13677   enable_breakpoint_disp (bpt, bpt->disposition, 0);
13678 }
13679
13680 static void
13681 do_enable_breakpoint (struct breakpoint *bpt, void *arg)
13682 {
13683   enable_breakpoint (bpt);
13684 }
13685
13686 /* A callback for map_breakpoint_numbers that calls
13687    enable_breakpoint.  */
13688
13689 static void
13690 do_map_enable_breakpoint (struct breakpoint *b, void *ignore)
13691 {
13692   iterate_over_related_breakpoints (b, do_enable_breakpoint, NULL);
13693 }
13694
13695 /* The enable command enables the specified breakpoints (or all defined
13696    breakpoints) so they once again become (or continue to be) effective
13697    in stopping the inferior.  */
13698
13699 static void
13700 enable_command (char *args, int from_tty)
13701 {
13702   if (args == 0)
13703     {
13704       struct breakpoint *bpt;
13705
13706       ALL_BREAKPOINTS (bpt)
13707         if (user_breakpoint_p (bpt))
13708           enable_breakpoint (bpt);
13709     }
13710   else if (strchr (args, '.'))
13711     {
13712       struct bp_location *loc = find_location_by_number (args);
13713       if (loc)
13714         {
13715           if (!loc->enabled)
13716             {
13717               loc->enabled = 1;
13718               mark_breakpoint_location_modified (loc);
13719             }
13720           if (target_supports_enable_disable_tracepoint ()
13721               && current_trace_status ()->running && loc->owner
13722               && is_tracepoint (loc->owner))
13723             target_enable_tracepoint (loc);
13724         }
13725       update_global_location_list (1);
13726     }
13727   else
13728     map_breakpoint_numbers (args, do_map_enable_breakpoint, NULL);
13729 }
13730
13731 /* This struct packages up disposition data for application to multiple
13732    breakpoints.  */
13733
13734 struct disp_data
13735 {
13736   enum bpdisp disp;
13737   int count;
13738 };
13739
13740 static void
13741 do_enable_breakpoint_disp (struct breakpoint *bpt, void *arg)
13742 {
13743   struct disp_data disp_data = *(struct disp_data *) arg;
13744
13745   enable_breakpoint_disp (bpt, disp_data.disp, disp_data.count);
13746 }
13747
13748 static void
13749 do_map_enable_once_breakpoint (struct breakpoint *bpt, void *ignore)
13750 {
13751   struct disp_data disp = { disp_disable, 1 };
13752
13753   iterate_over_related_breakpoints (bpt, do_enable_breakpoint_disp, &disp);
13754 }
13755
13756 static void
13757 enable_once_command (char *args, int from_tty)
13758 {
13759   map_breakpoint_numbers (args, do_map_enable_once_breakpoint, NULL);
13760 }
13761
13762 static void
13763 do_map_enable_count_breakpoint (struct breakpoint *bpt, void *countptr)
13764 {
13765   struct disp_data disp = { disp_disable, *(int *) countptr };
13766
13767   iterate_over_related_breakpoints (bpt, do_enable_breakpoint_disp, &disp);
13768 }
13769
13770 static void
13771 enable_count_command (char *args, int from_tty)
13772 {
13773   int count = get_number (&args);
13774
13775   map_breakpoint_numbers (args, do_map_enable_count_breakpoint, &count);
13776 }
13777
13778 static void
13779 do_map_enable_delete_breakpoint (struct breakpoint *bpt, void *ignore)
13780 {
13781   struct disp_data disp = { disp_del, 1 };
13782
13783   iterate_over_related_breakpoints (bpt, do_enable_breakpoint_disp, &disp);
13784 }
13785
13786 static void
13787 enable_delete_command (char *args, int from_tty)
13788 {
13789   map_breakpoint_numbers (args, do_map_enable_delete_breakpoint, NULL);
13790 }
13791 \f
13792 static void
13793 set_breakpoint_cmd (char *args, int from_tty)
13794 {
13795 }
13796
13797 static void
13798 show_breakpoint_cmd (char *args, int from_tty)
13799 {
13800 }
13801
13802 /* Invalidate last known value of any hardware watchpoint if
13803    the memory which that value represents has been written to by
13804    GDB itself.  */
13805
13806 static void
13807 invalidate_bp_value_on_memory_change (CORE_ADDR addr, int len,
13808                                       const bfd_byte *data)
13809 {
13810   struct breakpoint *bp;
13811
13812   ALL_BREAKPOINTS (bp)
13813     if (bp->enable_state == bp_enabled
13814         && bp->type == bp_hardware_watchpoint)
13815       {
13816         struct watchpoint *wp = (struct watchpoint *) bp;
13817
13818         if (wp->val_valid && wp->val)
13819           {
13820             struct bp_location *loc;
13821
13822             for (loc = bp->loc; loc != NULL; loc = loc->next)
13823               if (loc->loc_type == bp_loc_hardware_watchpoint
13824                   && loc->address + loc->length > addr
13825                   && addr + len > loc->address)
13826                 {
13827                   value_free (wp->val);
13828                   wp->val = NULL;
13829                   wp->val_valid = 0;
13830                 }
13831           }
13832       }
13833 }
13834
13835 /* Use the last displayed codepoint's values, or nothing
13836    if they aren't valid.  */
13837
13838 struct symtabs_and_lines
13839 decode_line_spec_1 (char *string, int flags)
13840 {
13841   struct symtabs_and_lines sals;
13842
13843   if (string == 0)
13844     error (_("Empty line specification."));
13845   if (last_displayed_sal_is_valid ())
13846     sals = decode_line_1 (&string, flags,
13847                           get_last_displayed_symtab (),
13848                           get_last_displayed_line ());
13849   else
13850     sals = decode_line_1 (&string, flags, (struct symtab *) NULL, 0);
13851   if (*string)
13852     error (_("Junk at end of line specification: %s"), string);
13853   return sals;
13854 }
13855
13856 /* Create and insert a raw software breakpoint at PC.  Return an
13857    identifier, which should be used to remove the breakpoint later.
13858    In general, places which call this should be using something on the
13859    breakpoint chain instead; this function should be eliminated
13860    someday.  */
13861
13862 void *
13863 deprecated_insert_raw_breakpoint (struct gdbarch *gdbarch,
13864                                   struct address_space *aspace, CORE_ADDR pc)
13865 {
13866   struct bp_target_info *bp_tgt;
13867
13868   bp_tgt = XZALLOC (struct bp_target_info);
13869
13870   bp_tgt->placed_address_space = aspace;
13871   bp_tgt->placed_address = pc;
13872
13873   if (target_insert_breakpoint (gdbarch, bp_tgt) != 0)
13874     {
13875       /* Could not insert the breakpoint.  */
13876       xfree (bp_tgt);
13877       return NULL;
13878     }
13879
13880   return bp_tgt;
13881 }
13882
13883 /* Remove a breakpoint BP inserted by
13884    deprecated_insert_raw_breakpoint.  */
13885
13886 int
13887 deprecated_remove_raw_breakpoint (struct gdbarch *gdbarch, void *bp)
13888 {
13889   struct bp_target_info *bp_tgt = bp;
13890   int ret;
13891
13892   ret = target_remove_breakpoint (gdbarch, bp_tgt);
13893   xfree (bp_tgt);
13894
13895   return ret;
13896 }
13897
13898 /* One (or perhaps two) breakpoints used for software single
13899    stepping.  */
13900
13901 static void *single_step_breakpoints[2];
13902 static struct gdbarch *single_step_gdbarch[2];
13903
13904 /* Create and insert a breakpoint for software single step.  */
13905
13906 void
13907 insert_single_step_breakpoint (struct gdbarch *gdbarch,
13908                                struct address_space *aspace, 
13909                                CORE_ADDR next_pc)
13910 {
13911   void **bpt_p;
13912
13913   if (single_step_breakpoints[0] == NULL)
13914     {
13915       bpt_p = &single_step_breakpoints[0];
13916       single_step_gdbarch[0] = gdbarch;
13917     }
13918   else
13919     {
13920       gdb_assert (single_step_breakpoints[1] == NULL);
13921       bpt_p = &single_step_breakpoints[1];
13922       single_step_gdbarch[1] = gdbarch;
13923     }
13924
13925   /* NOTE drow/2006-04-11: A future improvement to this function would
13926      be to only create the breakpoints once, and actually put them on
13927      the breakpoint chain.  That would let us use set_raw_breakpoint.
13928      We could adjust the addresses each time they were needed.  Doing
13929      this requires corresponding changes elsewhere where single step
13930      breakpoints are handled, however.  So, for now, we use this.  */
13931
13932   *bpt_p = deprecated_insert_raw_breakpoint (gdbarch, aspace, next_pc);
13933   if (*bpt_p == NULL)
13934     error (_("Could not insert single-step breakpoint at %s"),
13935              paddress (gdbarch, next_pc));
13936 }
13937
13938 /* Check if the breakpoints used for software single stepping
13939    were inserted or not.  */
13940
13941 int
13942 single_step_breakpoints_inserted (void)
13943 {
13944   return (single_step_breakpoints[0] != NULL
13945           || single_step_breakpoints[1] != NULL);
13946 }
13947
13948 /* Remove and delete any breakpoints used for software single step.  */
13949
13950 void
13951 remove_single_step_breakpoints (void)
13952 {
13953   gdb_assert (single_step_breakpoints[0] != NULL);
13954
13955   /* See insert_single_step_breakpoint for more about this deprecated
13956      call.  */
13957   deprecated_remove_raw_breakpoint (single_step_gdbarch[0],
13958                                     single_step_breakpoints[0]);
13959   single_step_gdbarch[0] = NULL;
13960   single_step_breakpoints[0] = NULL;
13961
13962   if (single_step_breakpoints[1] != NULL)
13963     {
13964       deprecated_remove_raw_breakpoint (single_step_gdbarch[1],
13965                                         single_step_breakpoints[1]);
13966       single_step_gdbarch[1] = NULL;
13967       single_step_breakpoints[1] = NULL;
13968     }
13969 }
13970
13971 /* Delete software single step breakpoints without removing them from
13972    the inferior.  This is intended to be used if the inferior's address
13973    space where they were inserted is already gone, e.g. after exit or
13974    exec.  */
13975
13976 void
13977 cancel_single_step_breakpoints (void)
13978 {
13979   int i;
13980
13981   for (i = 0; i < 2; i++)
13982     if (single_step_breakpoints[i])
13983       {
13984         xfree (single_step_breakpoints[i]);
13985         single_step_breakpoints[i] = NULL;
13986         single_step_gdbarch[i] = NULL;
13987       }
13988 }
13989
13990 /* Detach software single-step breakpoints from INFERIOR_PTID without
13991    removing them.  */
13992
13993 static void
13994 detach_single_step_breakpoints (void)
13995 {
13996   int i;
13997
13998   for (i = 0; i < 2; i++)
13999     if (single_step_breakpoints[i])
14000       target_remove_breakpoint (single_step_gdbarch[i],
14001                                 single_step_breakpoints[i]);
14002 }
14003
14004 /* Check whether a software single-step breakpoint is inserted at
14005    PC.  */
14006
14007 static int
14008 single_step_breakpoint_inserted_here_p (struct address_space *aspace, 
14009                                         CORE_ADDR pc)
14010 {
14011   int i;
14012
14013   for (i = 0; i < 2; i++)
14014     {
14015       struct bp_target_info *bp_tgt = single_step_breakpoints[i];
14016       if (bp_tgt
14017           && breakpoint_address_match (bp_tgt->placed_address_space,
14018                                        bp_tgt->placed_address,
14019                                        aspace, pc))
14020         return 1;
14021     }
14022
14023   return 0;
14024 }
14025
14026 /* Returns 0 if 'bp' is NOT a syscall catchpoint,
14027    non-zero otherwise.  */
14028 static int
14029 is_syscall_catchpoint_enabled (struct breakpoint *bp)
14030 {
14031   if (syscall_catchpoint_p (bp)
14032       && bp->enable_state != bp_disabled
14033       && bp->enable_state != bp_call_disabled)
14034     return 1;
14035   else
14036     return 0;
14037 }
14038
14039 int
14040 catch_syscall_enabled (void)
14041 {
14042   struct inferior *inf = current_inferior ();
14043
14044   return inf->total_syscalls_count != 0;
14045 }
14046
14047 int
14048 catching_syscall_number (int syscall_number)
14049 {
14050   struct breakpoint *bp;
14051
14052   ALL_BREAKPOINTS (bp)
14053     if (is_syscall_catchpoint_enabled (bp))
14054       {
14055         struct syscall_catchpoint *c = (struct syscall_catchpoint *) bp;
14056
14057         if (c->syscalls_to_be_caught)
14058           {
14059             int i, iter;
14060             for (i = 0;
14061                  VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
14062                  i++)
14063               if (syscall_number == iter)
14064                 return 1;
14065           }
14066         else
14067           return 1;
14068       }
14069
14070   return 0;
14071 }
14072
14073 /* Complete syscall names.  Used by "catch syscall".  */
14074 static char **
14075 catch_syscall_completer (struct cmd_list_element *cmd,
14076                          char *text, char *word)
14077 {
14078   const char **list = get_syscall_names ();
14079   char **retlist
14080     = (list == NULL) ? NULL : complete_on_enum (list, text, word);
14081
14082   xfree (list);
14083   return retlist;
14084 }
14085
14086 /* Tracepoint-specific operations.  */
14087
14088 /* Set tracepoint count to NUM.  */
14089 static void
14090 set_tracepoint_count (int num)
14091 {
14092   tracepoint_count = num;
14093   set_internalvar_integer (lookup_internalvar ("tpnum"), num);
14094 }
14095
14096 void
14097 trace_command (char *arg, int from_tty)
14098 {
14099   if (create_breakpoint (get_current_arch (),
14100                          arg,
14101                          NULL, 0, 1 /* parse arg */,
14102                          0 /* tempflag */,
14103                          bp_tracepoint /* type_wanted */,
14104                          0 /* Ignore count */,
14105                          pending_break_support,
14106                          &tracepoint_breakpoint_ops,
14107                          from_tty,
14108                          1 /* enabled */,
14109                          0 /* internal */))
14110     set_tracepoint_count (breakpoint_count);
14111 }
14112
14113 void
14114 ftrace_command (char *arg, int from_tty)
14115 {
14116   if (create_breakpoint (get_current_arch (),
14117                          arg,
14118                          NULL, 0, 1 /* parse arg */,
14119                          0 /* tempflag */,
14120                          bp_fast_tracepoint /* type_wanted */,
14121                          0 /* Ignore count */,
14122                          pending_break_support,
14123                          &tracepoint_breakpoint_ops,
14124                          from_tty,
14125                          1 /* enabled */,
14126                          0 /* internal */))
14127     set_tracepoint_count (breakpoint_count);
14128 }
14129
14130 /* strace command implementation.  Creates a static tracepoint.  */
14131
14132 void
14133 strace_command (char *arg, int from_tty)
14134 {
14135   struct breakpoint_ops *ops;
14136
14137   /* Decide if we are dealing with a static tracepoint marker (`-m'),
14138      or with a normal static tracepoint.  */
14139   if (arg && strncmp (arg, "-m", 2) == 0 && isspace (arg[2]))
14140     ops = &strace_marker_breakpoint_ops;
14141   else
14142     ops = &tracepoint_breakpoint_ops;
14143
14144   if (create_breakpoint (get_current_arch (),
14145                          arg,
14146                          NULL, 0, 1 /* parse arg */,
14147                          0 /* tempflag */,
14148                          bp_static_tracepoint /* type_wanted */,
14149                          0 /* Ignore count */,
14150                          pending_break_support,
14151                          ops,
14152                          from_tty,
14153                          1 /* enabled */,
14154                          0 /* internal */))
14155     set_tracepoint_count (breakpoint_count);
14156 }
14157
14158 /* Set up a fake reader function that gets command lines from a linked
14159    list that was acquired during tracepoint uploading.  */
14160
14161 static struct uploaded_tp *this_utp;
14162 static int next_cmd;
14163
14164 static char *
14165 read_uploaded_action (void)
14166 {
14167   char *rslt;
14168
14169   VEC_iterate (char_ptr, this_utp->cmd_strings, next_cmd, rslt);
14170
14171   next_cmd++;
14172
14173   return rslt;
14174 }
14175
14176 /* Given information about a tracepoint as recorded on a target (which
14177    can be either a live system or a trace file), attempt to create an
14178    equivalent GDB tracepoint.  This is not a reliable process, since
14179    the target does not necessarily have all the information used when
14180    the tracepoint was originally defined.  */
14181   
14182 struct tracepoint *
14183 create_tracepoint_from_upload (struct uploaded_tp *utp)
14184 {
14185   char *addr_str, small_buf[100];
14186   struct tracepoint *tp;
14187
14188   if (utp->at_string)
14189     addr_str = utp->at_string;
14190   else
14191     {
14192       /* In the absence of a source location, fall back to raw
14193          address.  Since there is no way to confirm that the address
14194          means the same thing as when the trace was started, warn the
14195          user.  */
14196       warning (_("Uploaded tracepoint %d has no "
14197                  "source location, using raw address"),
14198                utp->number);
14199       sprintf (small_buf, "*%s", hex_string (utp->addr));
14200       addr_str = small_buf;
14201     }
14202
14203   /* There's not much we can do with a sequence of bytecodes.  */
14204   if (utp->cond && !utp->cond_string)
14205     warning (_("Uploaded tracepoint %d condition "
14206                "has no source form, ignoring it"),
14207              utp->number);
14208
14209   if (!create_breakpoint (get_current_arch (),
14210                           addr_str,
14211                           utp->cond_string, -1, 0 /* parse cond/thread */,
14212                           0 /* tempflag */,
14213                           utp->type /* type_wanted */,
14214                           0 /* Ignore count */,
14215                           pending_break_support,
14216                           &tracepoint_breakpoint_ops,
14217                           0 /* from_tty */,
14218                           utp->enabled /* enabled */,
14219                           0 /* internal */))
14220     return NULL;
14221
14222   set_tracepoint_count (breakpoint_count);
14223   
14224   /* Get the tracepoint we just created.  */
14225   tp = get_tracepoint (tracepoint_count);
14226   gdb_assert (tp != NULL);
14227
14228   if (utp->pass > 0)
14229     {
14230       sprintf (small_buf, "%d %d", utp->pass, tp->base.number);
14231
14232       trace_pass_command (small_buf, 0);
14233     }
14234
14235   /* If we have uploaded versions of the original commands, set up a
14236      special-purpose "reader" function and call the usual command line
14237      reader, then pass the result to the breakpoint command-setting
14238      function.  */
14239   if (!VEC_empty (char_ptr, utp->cmd_strings))
14240     {
14241       struct command_line *cmd_list;
14242
14243       this_utp = utp;
14244       next_cmd = 0;
14245
14246       cmd_list = read_command_lines_1 (read_uploaded_action, 1, NULL, NULL);
14247
14248       breakpoint_set_commands (&tp->base, cmd_list);
14249     }
14250   else if (!VEC_empty (char_ptr, utp->actions)
14251            || !VEC_empty (char_ptr, utp->step_actions))
14252     warning (_("Uploaded tracepoint %d actions "
14253                "have no source form, ignoring them"),
14254              utp->number);
14255
14256   /* Copy any status information that might be available.  */
14257   tp->base.hit_count = utp->hit_count;
14258   tp->traceframe_usage = utp->traceframe_usage;
14259
14260   return tp;
14261 }
14262   
14263 /* Print information on tracepoint number TPNUM_EXP, or all if
14264    omitted.  */
14265
14266 static void
14267 tracepoints_info (char *args, int from_tty)
14268 {
14269   struct ui_out *uiout = current_uiout;
14270   int num_printed;
14271
14272   num_printed = breakpoint_1 (args, 0, is_tracepoint);
14273
14274   if (num_printed == 0)
14275     {
14276       if (args == NULL || *args == '\0')
14277         ui_out_message (uiout, 0, "No tracepoints.\n");
14278       else
14279         ui_out_message (uiout, 0, "No tracepoint matching '%s'.\n", args);
14280     }
14281
14282   default_collect_info ();
14283 }
14284
14285 /* The 'enable trace' command enables tracepoints.
14286    Not supported by all targets.  */
14287 static void
14288 enable_trace_command (char *args, int from_tty)
14289 {
14290   enable_command (args, from_tty);
14291 }
14292
14293 /* The 'disable trace' command disables tracepoints.
14294    Not supported by all targets.  */
14295 static void
14296 disable_trace_command (char *args, int from_tty)
14297 {
14298   disable_command (args, from_tty);
14299 }
14300
14301 /* Remove a tracepoint (or all if no argument).  */
14302 static void
14303 delete_trace_command (char *arg, int from_tty)
14304 {
14305   struct breakpoint *b, *b_tmp;
14306
14307   dont_repeat ();
14308
14309   if (arg == 0)
14310     {
14311       int breaks_to_delete = 0;
14312
14313       /* Delete all breakpoints if no argument.
14314          Do not delete internal or call-dummy breakpoints, these
14315          have to be deleted with an explicit breakpoint number 
14316          argument.  */
14317       ALL_TRACEPOINTS (b)
14318         if (is_tracepoint (b) && user_breakpoint_p (b))
14319           {
14320             breaks_to_delete = 1;
14321             break;
14322           }
14323
14324       /* Ask user only if there are some breakpoints to delete.  */
14325       if (!from_tty
14326           || (breaks_to_delete && query (_("Delete all tracepoints? "))))
14327         {
14328           ALL_BREAKPOINTS_SAFE (b, b_tmp)
14329             if (is_tracepoint (b) && user_breakpoint_p (b))
14330               delete_breakpoint (b);
14331         }
14332     }
14333   else
14334     map_breakpoint_numbers (arg, do_map_delete_breakpoint, NULL);
14335 }
14336
14337 /* Helper function for trace_pass_command.  */
14338
14339 static void
14340 trace_pass_set_count (struct tracepoint *tp, int count, int from_tty)
14341 {
14342   tp->pass_count = count;
14343   observer_notify_tracepoint_modified (tp->base.number);
14344   if (from_tty)
14345     printf_filtered (_("Setting tracepoint %d's passcount to %d\n"),
14346                      tp->base.number, count);
14347 }
14348
14349 /* Set passcount for tracepoint.
14350
14351    First command argument is passcount, second is tracepoint number.
14352    If tracepoint number omitted, apply to most recently defined.
14353    Also accepts special argument "all".  */
14354
14355 static void
14356 trace_pass_command (char *args, int from_tty)
14357 {
14358   struct tracepoint *t1;
14359   unsigned int count;
14360
14361   if (args == 0 || *args == 0)
14362     error (_("passcount command requires an "
14363              "argument (count + optional TP num)"));
14364
14365   count = strtoul (args, &args, 10);    /* Count comes first, then TP num.  */
14366
14367   while (*args && isspace ((int) *args))
14368     args++;
14369
14370   if (*args && strncasecmp (args, "all", 3) == 0)
14371     {
14372       struct breakpoint *b;
14373
14374       args += 3;                        /* Skip special argument "all".  */
14375       if (*args)
14376         error (_("Junk at end of arguments."));
14377
14378       ALL_TRACEPOINTS (b)
14379       {
14380         t1 = (struct tracepoint *) b;
14381         trace_pass_set_count (t1, count, from_tty);
14382       }
14383     }
14384   else if (*args == '\0')
14385     {
14386       t1 = get_tracepoint_by_number (&args, NULL, 1);
14387       if (t1)
14388         trace_pass_set_count (t1, count, from_tty);
14389     }
14390   else
14391     {
14392       struct get_number_or_range_state state;
14393
14394       init_number_or_range (&state, args);
14395       while (!state.finished)
14396         {
14397           t1 = get_tracepoint_by_number (&args, &state, 1);
14398           if (t1)
14399             trace_pass_set_count (t1, count, from_tty);
14400         }
14401     }
14402 }
14403
14404 struct tracepoint *
14405 get_tracepoint (int num)
14406 {
14407   struct breakpoint *t;
14408
14409   ALL_TRACEPOINTS (t)
14410     if (t->number == num)
14411       return (struct tracepoint *) t;
14412
14413   return NULL;
14414 }
14415
14416 /* Find the tracepoint with the given target-side number (which may be
14417    different from the tracepoint number after disconnecting and
14418    reconnecting).  */
14419
14420 struct tracepoint *
14421 get_tracepoint_by_number_on_target (int num)
14422 {
14423   struct breakpoint *b;
14424
14425   ALL_TRACEPOINTS (b)
14426     {
14427       struct tracepoint *t = (struct tracepoint *) b;
14428
14429       if (t->number_on_target == num)
14430         return t;
14431     }
14432
14433   return NULL;
14434 }
14435
14436 /* Utility: parse a tracepoint number and look it up in the list.
14437    If STATE is not NULL, use, get_number_or_range_state and ignore ARG.
14438    If OPTIONAL_P is true, then if the argument is missing, the most
14439    recent tracepoint (tracepoint_count) is returned.  */
14440 struct tracepoint *
14441 get_tracepoint_by_number (char **arg,
14442                           struct get_number_or_range_state *state,
14443                           int optional_p)
14444 {
14445   extern int tracepoint_count;
14446   struct breakpoint *t;
14447   int tpnum;
14448   char *instring = arg == NULL ? NULL : *arg;
14449
14450   if (state)
14451     {
14452       gdb_assert (!state->finished);
14453       tpnum = get_number_or_range (state);
14454     }
14455   else if (arg == NULL || *arg == NULL || ! **arg)
14456     {
14457       if (optional_p)
14458         tpnum = tracepoint_count;
14459       else
14460         error_no_arg (_("tracepoint number"));
14461     }
14462   else
14463     tpnum = get_number (arg);
14464
14465   if (tpnum <= 0)
14466     {
14467       if (instring && *instring)
14468         printf_filtered (_("bad tracepoint number at or near '%s'\n"), 
14469                          instring);
14470       else
14471         printf_filtered (_("Tracepoint argument missing "
14472                            "and no previous tracepoint\n"));
14473       return NULL;
14474     }
14475
14476   ALL_TRACEPOINTS (t)
14477     if (t->number == tpnum)
14478     {
14479       return (struct tracepoint *) t;
14480     }
14481
14482   printf_unfiltered ("No tracepoint number %d.\n", tpnum);
14483   return NULL;
14484 }
14485
14486 void
14487 print_recreate_thread (struct breakpoint *b, struct ui_file *fp)
14488 {
14489   if (b->thread != -1)
14490     fprintf_unfiltered (fp, " thread %d", b->thread);
14491
14492   if (b->task != 0)
14493     fprintf_unfiltered (fp, " task %d", b->task);
14494
14495   fprintf_unfiltered (fp, "\n");
14496 }
14497
14498 /* Save information on user settable breakpoints (watchpoints, etc) to
14499    a new script file named FILENAME.  If FILTER is non-NULL, call it
14500    on each breakpoint and only include the ones for which it returns
14501    non-zero.  */
14502
14503 static void
14504 save_breakpoints (char *filename, int from_tty,
14505                   int (*filter) (const struct breakpoint *))
14506 {
14507   struct breakpoint *tp;
14508   int any = 0;
14509   char *pathname;
14510   struct cleanup *cleanup;
14511   struct ui_file *fp;
14512   int extra_trace_bits = 0;
14513
14514   if (filename == 0 || *filename == 0)
14515     error (_("Argument required (file name in which to save)"));
14516
14517   /* See if we have anything to save.  */
14518   ALL_BREAKPOINTS (tp)
14519   {
14520     /* Skip internal and momentary breakpoints.  */
14521     if (!user_breakpoint_p (tp))
14522       continue;
14523
14524     /* If we have a filter, only save the breakpoints it accepts.  */
14525     if (filter && !filter (tp))
14526       continue;
14527
14528     any = 1;
14529
14530     if (is_tracepoint (tp))
14531       {
14532         extra_trace_bits = 1;
14533
14534         /* We can stop searching.  */
14535         break;
14536       }
14537   }
14538
14539   if (!any)
14540     {
14541       warning (_("Nothing to save."));
14542       return;
14543     }
14544
14545   pathname = tilde_expand (filename);
14546   cleanup = make_cleanup (xfree, pathname);
14547   fp = gdb_fopen (pathname, "w");
14548   if (!fp)
14549     error (_("Unable to open file '%s' for saving (%s)"),
14550            filename, safe_strerror (errno));
14551   make_cleanup_ui_file_delete (fp);
14552
14553   if (extra_trace_bits)
14554     save_trace_state_variables (fp);
14555
14556   ALL_BREAKPOINTS (tp)
14557   {
14558     /* Skip internal and momentary breakpoints.  */
14559     if (!user_breakpoint_p (tp))
14560       continue;
14561
14562     /* If we have a filter, only save the breakpoints it accepts.  */
14563     if (filter && !filter (tp))
14564       continue;
14565
14566     tp->ops->print_recreate (tp, fp);
14567
14568     /* Note, we can't rely on tp->number for anything, as we can't
14569        assume the recreated breakpoint numbers will match.  Use $bpnum
14570        instead.  */
14571
14572     if (tp->cond_string)
14573       fprintf_unfiltered (fp, "  condition $bpnum %s\n", tp->cond_string);
14574
14575     if (tp->ignore_count)
14576       fprintf_unfiltered (fp, "  ignore $bpnum %d\n", tp->ignore_count);
14577
14578     if (tp->commands)
14579       {
14580         volatile struct gdb_exception ex;       
14581
14582         fprintf_unfiltered (fp, "  commands\n");
14583         
14584         ui_out_redirect (current_uiout, fp);
14585         TRY_CATCH (ex, RETURN_MASK_ALL)
14586           {
14587             print_command_lines (current_uiout, tp->commands->commands, 2);
14588           }
14589         ui_out_redirect (current_uiout, NULL);
14590
14591         if (ex.reason < 0)
14592           throw_exception (ex);
14593
14594         fprintf_unfiltered (fp, "  end\n");
14595       }
14596
14597     if (tp->enable_state == bp_disabled)
14598       fprintf_unfiltered (fp, "disable\n");
14599
14600     /* If this is a multi-location breakpoint, check if the locations
14601        should be individually disabled.  Watchpoint locations are
14602        special, and not user visible.  */
14603     if (!is_watchpoint (tp) && tp->loc && tp->loc->next)
14604       {
14605         struct bp_location *loc;
14606         int n = 1;
14607
14608         for (loc = tp->loc; loc != NULL; loc = loc->next, n++)
14609           if (!loc->enabled)
14610             fprintf_unfiltered (fp, "disable $bpnum.%d\n", n);
14611       }
14612   }
14613
14614   if (extra_trace_bits && *default_collect)
14615     fprintf_unfiltered (fp, "set default-collect %s\n", default_collect);
14616
14617   do_cleanups (cleanup);
14618   if (from_tty)
14619     printf_filtered (_("Saved to file '%s'.\n"), filename);
14620 }
14621
14622 /* The `save breakpoints' command.  */
14623
14624 static void
14625 save_breakpoints_command (char *args, int from_tty)
14626 {
14627   save_breakpoints (args, from_tty, NULL);
14628 }
14629
14630 /* The `save tracepoints' command.  */
14631
14632 static void
14633 save_tracepoints_command (char *args, int from_tty)
14634 {
14635   save_breakpoints (args, from_tty, is_tracepoint);
14636 }
14637
14638 /* Create a vector of all tracepoints.  */
14639
14640 VEC(breakpoint_p) *
14641 all_tracepoints (void)
14642 {
14643   VEC(breakpoint_p) *tp_vec = 0;
14644   struct breakpoint *tp;
14645
14646   ALL_TRACEPOINTS (tp)
14647   {
14648     VEC_safe_push (breakpoint_p, tp_vec, tp);
14649   }
14650
14651   return tp_vec;
14652 }
14653
14654 \f
14655 /* This help string is used for the break, hbreak, tbreak and thbreak
14656    commands.  It is defined as a macro to prevent duplication.
14657    COMMAND should be a string constant containing the name of the
14658    command.  */
14659 #define BREAK_ARGS_HELP(command) \
14660 command" [LOCATION] [thread THREADNUM] [if CONDITION]\n\
14661 LOCATION may be a line number, function name, or \"*\" and an address.\n\
14662 If a line number is specified, break at start of code for that line.\n\
14663 If a function is specified, break at start of code for that function.\n\
14664 If an address is specified, break at that exact address.\n\
14665 With no LOCATION, uses current execution address of the selected\n\
14666 stack frame.  This is useful for breaking on return to a stack frame.\n\
14667 \n\
14668 THREADNUM is the number from \"info threads\".\n\
14669 CONDITION is a boolean expression.\n\
14670 \n\
14671 Multiple breakpoints at one place are permitted, and useful if their\n\
14672 conditions are different.\n\
14673 \n\
14674 Do \"help breakpoints\" for info on other commands dealing with breakpoints."
14675
14676 /* List of subcommands for "catch".  */
14677 static struct cmd_list_element *catch_cmdlist;
14678
14679 /* List of subcommands for "tcatch".  */
14680 static struct cmd_list_element *tcatch_cmdlist;
14681
14682 void
14683 add_catch_command (char *name, char *docstring,
14684                    void (*sfunc) (char *args, int from_tty,
14685                                   struct cmd_list_element *command),
14686                    char **(*completer) (struct cmd_list_element *cmd,
14687                                          char *text, char *word),
14688                    void *user_data_catch,
14689                    void *user_data_tcatch)
14690 {
14691   struct cmd_list_element *command;
14692
14693   command = add_cmd (name, class_breakpoint, NULL, docstring,
14694                      &catch_cmdlist);
14695   set_cmd_sfunc (command, sfunc);
14696   set_cmd_context (command, user_data_catch);
14697   set_cmd_completer (command, completer);
14698
14699   command = add_cmd (name, class_breakpoint, NULL, docstring,
14700                      &tcatch_cmdlist);
14701   set_cmd_sfunc (command, sfunc);
14702   set_cmd_context (command, user_data_tcatch);
14703   set_cmd_completer (command, completer);
14704 }
14705
14706 static void
14707 clear_syscall_counts (struct inferior *inf)
14708 {
14709   inf->total_syscalls_count = 0;
14710   inf->any_syscall_count = 0;
14711   VEC_free (int, inf->syscalls_counts);
14712 }
14713
14714 static void
14715 save_command (char *arg, int from_tty)
14716 {
14717   printf_unfiltered (_("\"save\" must be followed by "
14718                        "the name of a save subcommand.\n"));
14719   help_list (save_cmdlist, "save ", -1, gdb_stdout);
14720 }
14721
14722 struct breakpoint *
14723 iterate_over_breakpoints (int (*callback) (struct breakpoint *, void *),
14724                           void *data)
14725 {
14726   struct breakpoint *b, *b_tmp;
14727
14728   ALL_BREAKPOINTS_SAFE (b, b_tmp)
14729     {
14730       if ((*callback) (b, data))
14731         return b;
14732     }
14733
14734   return NULL;
14735 }
14736
14737 /* Zero if any of the breakpoint's locations could be a location where
14738    functions have been inlined, nonzero otherwise.  */
14739
14740 static int
14741 is_non_inline_function (struct breakpoint *b)
14742 {
14743   /* The shared library event breakpoint is set on the address of a
14744      non-inline function.  */
14745   if (b->type == bp_shlib_event)
14746     return 1;
14747
14748   return 0;
14749 }
14750
14751 /* Nonzero if the specified PC cannot be a location where functions
14752    have been inlined.  */
14753
14754 int
14755 pc_at_non_inline_function (struct address_space *aspace, CORE_ADDR pc,
14756                            const struct target_waitstatus *ws)
14757 {
14758   struct breakpoint *b;
14759   struct bp_location *bl;
14760
14761   ALL_BREAKPOINTS (b)
14762     {
14763       if (!is_non_inline_function (b))
14764         continue;
14765
14766       for (bl = b->loc; bl != NULL; bl = bl->next)
14767         {
14768           if (!bl->shlib_disabled
14769               && bpstat_check_location (bl, aspace, pc, ws))
14770             return 1;
14771         }
14772     }
14773
14774   return 0;
14775 }
14776
14777 void
14778 initialize_breakpoint_ops (void)
14779 {
14780   static int initialized = 0;
14781
14782   struct breakpoint_ops *ops;
14783
14784   if (initialized)
14785     return;
14786   initialized = 1;
14787
14788   /* The breakpoint_ops structure to be inherit by all kinds of
14789      breakpoints (real breakpoints, i.e., user "break" breakpoints,
14790      internal and momentary breakpoints, etc.).  */
14791   ops = &bkpt_base_breakpoint_ops;
14792   *ops = base_breakpoint_ops;
14793   ops->re_set = bkpt_re_set;
14794   ops->insert_location = bkpt_insert_location;
14795   ops->remove_location = bkpt_remove_location;
14796   ops->breakpoint_hit = bkpt_breakpoint_hit;
14797   ops->create_sals_from_address = bkpt_create_sals_from_address;
14798   ops->create_breakpoints_sal = bkpt_create_breakpoints_sal;
14799   ops->decode_linespec = bkpt_decode_linespec;
14800
14801   /* The breakpoint_ops structure to be used in regular breakpoints.  */
14802   ops = &bkpt_breakpoint_ops;
14803   *ops = bkpt_base_breakpoint_ops;
14804   ops->re_set = bkpt_re_set;
14805   ops->resources_needed = bkpt_resources_needed;
14806   ops->print_it = bkpt_print_it;
14807   ops->print_mention = bkpt_print_mention;
14808   ops->print_recreate = bkpt_print_recreate;
14809
14810   /* Ranged breakpoints.  */
14811   ops = &ranged_breakpoint_ops;
14812   *ops = bkpt_breakpoint_ops;
14813   ops->breakpoint_hit = breakpoint_hit_ranged_breakpoint;
14814   ops->resources_needed = resources_needed_ranged_breakpoint;
14815   ops->print_it = print_it_ranged_breakpoint;
14816   ops->print_one = print_one_ranged_breakpoint;
14817   ops->print_one_detail = print_one_detail_ranged_breakpoint;
14818   ops->print_mention = print_mention_ranged_breakpoint;
14819   ops->print_recreate = print_recreate_ranged_breakpoint;
14820
14821   /* Internal breakpoints.  */
14822   ops = &internal_breakpoint_ops;
14823   *ops = bkpt_base_breakpoint_ops;
14824   ops->re_set = internal_bkpt_re_set;
14825   ops->check_status = internal_bkpt_check_status;
14826   ops->print_it = internal_bkpt_print_it;
14827   ops->print_mention = internal_bkpt_print_mention;
14828
14829   /* Momentary breakpoints.  */
14830   ops = &momentary_breakpoint_ops;
14831   *ops = bkpt_base_breakpoint_ops;
14832   ops->re_set = momentary_bkpt_re_set;
14833   ops->check_status = momentary_bkpt_check_status;
14834   ops->print_it = momentary_bkpt_print_it;
14835   ops->print_mention = momentary_bkpt_print_mention;
14836
14837   /* GNU v3 exception catchpoints.  */
14838   ops = &gnu_v3_exception_catchpoint_ops;
14839   *ops = bkpt_breakpoint_ops;
14840   ops->print_it = print_it_exception_catchpoint;
14841   ops->print_one = print_one_exception_catchpoint;
14842   ops->print_mention = print_mention_exception_catchpoint;
14843   ops->print_recreate = print_recreate_exception_catchpoint;
14844
14845   /* Watchpoints.  */
14846   ops = &watchpoint_breakpoint_ops;
14847   *ops = base_breakpoint_ops;
14848   ops->dtor = dtor_watchpoint;
14849   ops->re_set = re_set_watchpoint;
14850   ops->insert_location = insert_watchpoint;
14851   ops->remove_location = remove_watchpoint;
14852   ops->breakpoint_hit = breakpoint_hit_watchpoint;
14853   ops->check_status = check_status_watchpoint;
14854   ops->resources_needed = resources_needed_watchpoint;
14855   ops->works_in_software_mode = works_in_software_mode_watchpoint;
14856   ops->print_it = print_it_watchpoint;
14857   ops->print_mention = print_mention_watchpoint;
14858   ops->print_recreate = print_recreate_watchpoint;
14859
14860   /* Masked watchpoints.  */
14861   ops = &masked_watchpoint_breakpoint_ops;
14862   *ops = watchpoint_breakpoint_ops;
14863   ops->insert_location = insert_masked_watchpoint;
14864   ops->remove_location = remove_masked_watchpoint;
14865   ops->resources_needed = resources_needed_masked_watchpoint;
14866   ops->works_in_software_mode = works_in_software_mode_masked_watchpoint;
14867   ops->print_it = print_it_masked_watchpoint;
14868   ops->print_one_detail = print_one_detail_masked_watchpoint;
14869   ops->print_mention = print_mention_masked_watchpoint;
14870   ops->print_recreate = print_recreate_masked_watchpoint;
14871
14872   /* Tracepoints.  */
14873   ops = &tracepoint_breakpoint_ops;
14874   *ops = base_breakpoint_ops;
14875   ops->re_set = tracepoint_re_set;
14876   ops->breakpoint_hit = tracepoint_breakpoint_hit;
14877   ops->print_one_detail = tracepoint_print_one_detail;
14878   ops->print_mention = tracepoint_print_mention;
14879   ops->print_recreate = tracepoint_print_recreate;
14880   ops->create_sals_from_address = tracepoint_create_sals_from_address;
14881   ops->create_breakpoints_sal = tracepoint_create_breakpoints_sal;
14882   ops->decode_linespec = tracepoint_decode_linespec;
14883
14884   /* Static tracepoints with marker (`-m').  */
14885   ops = &strace_marker_breakpoint_ops;
14886   *ops = tracepoint_breakpoint_ops;
14887   ops->create_sals_from_address = strace_marker_create_sals_from_address;
14888   ops->create_breakpoints_sal = strace_marker_create_breakpoints_sal;
14889   ops->decode_linespec = strace_marker_decode_linespec;
14890
14891   /* Fork catchpoints.  */
14892   ops = &catch_fork_breakpoint_ops;
14893   *ops = base_breakpoint_ops;
14894   ops->insert_location = insert_catch_fork;
14895   ops->remove_location = remove_catch_fork;
14896   ops->breakpoint_hit = breakpoint_hit_catch_fork;
14897   ops->print_it = print_it_catch_fork;
14898   ops->print_one = print_one_catch_fork;
14899   ops->print_mention = print_mention_catch_fork;
14900   ops->print_recreate = print_recreate_catch_fork;
14901
14902   /* Vfork catchpoints.  */
14903   ops = &catch_vfork_breakpoint_ops;
14904   *ops = base_breakpoint_ops;
14905   ops->insert_location = insert_catch_vfork;
14906   ops->remove_location = remove_catch_vfork;
14907   ops->breakpoint_hit = breakpoint_hit_catch_vfork;
14908   ops->print_it = print_it_catch_vfork;
14909   ops->print_one = print_one_catch_vfork;
14910   ops->print_mention = print_mention_catch_vfork;
14911   ops->print_recreate = print_recreate_catch_vfork;
14912
14913   /* Exec catchpoints.  */
14914   ops = &catch_exec_breakpoint_ops;
14915   *ops = base_breakpoint_ops;
14916   ops->dtor = dtor_catch_exec;
14917   ops->insert_location = insert_catch_exec;
14918   ops->remove_location = remove_catch_exec;
14919   ops->breakpoint_hit = breakpoint_hit_catch_exec;
14920   ops->print_it = print_it_catch_exec;
14921   ops->print_one = print_one_catch_exec;
14922   ops->print_mention = print_mention_catch_exec;
14923   ops->print_recreate = print_recreate_catch_exec;
14924
14925   /* Syscall catchpoints.  */
14926   ops = &catch_syscall_breakpoint_ops;
14927   *ops = base_breakpoint_ops;
14928   ops->dtor = dtor_catch_syscall;
14929   ops->insert_location = insert_catch_syscall;
14930   ops->remove_location = remove_catch_syscall;
14931   ops->breakpoint_hit = breakpoint_hit_catch_syscall;
14932   ops->print_it = print_it_catch_syscall;
14933   ops->print_one = print_one_catch_syscall;
14934   ops->print_mention = print_mention_catch_syscall;
14935   ops->print_recreate = print_recreate_catch_syscall;
14936
14937   /* Solib-related catchpoints.  */
14938   ops = &catch_solib_breakpoint_ops;
14939   *ops = base_breakpoint_ops;
14940   ops->dtor = dtor_catch_solib;
14941   ops->insert_location = insert_catch_solib;
14942   ops->remove_location = remove_catch_solib;
14943   ops->breakpoint_hit = breakpoint_hit_catch_solib;
14944   ops->check_status = check_status_catch_solib;
14945   ops->print_it = print_it_catch_solib;
14946   ops->print_one = print_one_catch_solib;
14947   ops->print_mention = print_mention_catch_solib;
14948   ops->print_recreate = print_recreate_catch_solib;
14949 }
14950
14951 void
14952 _initialize_breakpoint (void)
14953 {
14954   struct cmd_list_element *c;
14955
14956   initialize_breakpoint_ops ();
14957
14958   observer_attach_solib_unloaded (disable_breakpoints_in_unloaded_shlib);
14959   observer_attach_inferior_exit (clear_syscall_counts);
14960   observer_attach_memory_changed (invalidate_bp_value_on_memory_change);
14961
14962   breakpoint_objfile_key = register_objfile_data ();
14963
14964   breakpoint_chain = 0;
14965   /* Don't bother to call set_breakpoint_count.  $bpnum isn't useful
14966      before a breakpoint is set.  */
14967   breakpoint_count = 0;
14968
14969   tracepoint_count = 0;
14970
14971   add_com ("ignore", class_breakpoint, ignore_command, _("\
14972 Set ignore-count of breakpoint number N to COUNT.\n\
14973 Usage is `ignore N COUNT'."));
14974   if (xdb_commands)
14975     add_com_alias ("bc", "ignore", class_breakpoint, 1);
14976
14977   add_com ("commands", class_breakpoint, commands_command, _("\
14978 Set commands to be executed when a breakpoint is hit.\n\
14979 Give breakpoint number as argument after \"commands\".\n\
14980 With no argument, the targeted breakpoint is the last one set.\n\
14981 The commands themselves follow starting on the next line.\n\
14982 Type a line containing \"end\" to indicate the end of them.\n\
14983 Give \"silent\" as the first line to make the breakpoint silent;\n\
14984 then no output is printed when it is hit, except what the commands print."));
14985
14986   add_com ("condition", class_breakpoint, condition_command, _("\
14987 Specify breakpoint number N to break only if COND is true.\n\
14988 Usage is `condition N COND', where N is an integer and COND is an\n\
14989 expression to be evaluated whenever breakpoint N is reached."));
14990
14991   c = add_com ("tbreak", class_breakpoint, tbreak_command, _("\
14992 Set a temporary breakpoint.\n\
14993 Like \"break\" except the breakpoint is only temporary,\n\
14994 so it will be deleted when hit.  Equivalent to \"break\" followed\n\
14995 by using \"enable delete\" on the breakpoint number.\n\
14996 \n"
14997 BREAK_ARGS_HELP ("tbreak")));
14998   set_cmd_completer (c, location_completer);
14999
15000   c = add_com ("hbreak", class_breakpoint, hbreak_command, _("\
15001 Set a hardware assisted breakpoint.\n\
15002 Like \"break\" except the breakpoint requires hardware support,\n\
15003 some target hardware may not have this support.\n\
15004 \n"
15005 BREAK_ARGS_HELP ("hbreak")));
15006   set_cmd_completer (c, location_completer);
15007
15008   c = add_com ("thbreak", class_breakpoint, thbreak_command, _("\
15009 Set a temporary hardware assisted breakpoint.\n\
15010 Like \"hbreak\" except the breakpoint is only temporary,\n\
15011 so it will be deleted when hit.\n\
15012 \n"
15013 BREAK_ARGS_HELP ("thbreak")));
15014   set_cmd_completer (c, location_completer);
15015
15016   add_prefix_cmd ("enable", class_breakpoint, enable_command, _("\
15017 Enable some breakpoints.\n\
15018 Give breakpoint numbers (separated by spaces) as arguments.\n\
15019 With no subcommand, breakpoints are enabled until you command otherwise.\n\
15020 This is used to cancel the effect of the \"disable\" command.\n\
15021 With a subcommand you can enable temporarily."),
15022                   &enablelist, "enable ", 1, &cmdlist);
15023   if (xdb_commands)
15024     add_com ("ab", class_breakpoint, enable_command, _("\
15025 Enable some breakpoints.\n\
15026 Give breakpoint numbers (separated by spaces) as arguments.\n\
15027 With no subcommand, breakpoints are enabled until you command otherwise.\n\
15028 This is used to cancel the effect of the \"disable\" command.\n\
15029 With a subcommand you can enable temporarily."));
15030
15031   add_com_alias ("en", "enable", class_breakpoint, 1);
15032
15033   add_prefix_cmd ("breakpoints", class_breakpoint, enable_command, _("\
15034 Enable some breakpoints.\n\
15035 Give breakpoint numbers (separated by spaces) as arguments.\n\
15036 This is used to cancel the effect of the \"disable\" command.\n\
15037 May be abbreviated to simply \"enable\".\n"),
15038                    &enablebreaklist, "enable breakpoints ", 1, &enablelist);
15039
15040   add_cmd ("once", no_class, enable_once_command, _("\
15041 Enable breakpoints for one hit.  Give breakpoint numbers.\n\
15042 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
15043            &enablebreaklist);
15044
15045   add_cmd ("delete", no_class, enable_delete_command, _("\
15046 Enable breakpoints and delete when hit.  Give breakpoint numbers.\n\
15047 If a breakpoint is hit while enabled in this fashion, it is deleted."),
15048            &enablebreaklist);
15049
15050   add_cmd ("count", no_class, enable_count_command, _("\
15051 Enable breakpoints for COUNT hits.  Give count and then breakpoint numbers.\n\
15052 If a breakpoint is hit while enabled in this fashion,\n\
15053 the count is decremented; when it reaches zero, the breakpoint is disabled."),
15054            &enablebreaklist);
15055
15056   add_cmd ("delete", no_class, enable_delete_command, _("\
15057 Enable breakpoints and delete when hit.  Give breakpoint numbers.\n\
15058 If a breakpoint is hit while enabled in this fashion, it is deleted."),
15059            &enablelist);
15060
15061   add_cmd ("once", no_class, enable_once_command, _("\
15062 Enable breakpoints for one hit.  Give breakpoint numbers.\n\
15063 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
15064            &enablelist);
15065
15066   add_cmd ("count", no_class, enable_count_command, _("\
15067 Enable breakpoints for COUNT hits.  Give count and then breakpoint numbers.\n\
15068 If a breakpoint is hit while enabled in this fashion,\n\
15069 the count is decremented; when it reaches zero, the breakpoint is disabled."),
15070            &enablelist);
15071
15072   add_prefix_cmd ("disable", class_breakpoint, disable_command, _("\
15073 Disable some breakpoints.\n\
15074 Arguments are breakpoint numbers with spaces in between.\n\
15075 To disable all breakpoints, give no argument.\n\
15076 A disabled breakpoint is not forgotten, but has no effect until re-enabled."),
15077                   &disablelist, "disable ", 1, &cmdlist);
15078   add_com_alias ("dis", "disable", class_breakpoint, 1);
15079   add_com_alias ("disa", "disable", class_breakpoint, 1);
15080   if (xdb_commands)
15081     add_com ("sb", class_breakpoint, disable_command, _("\
15082 Disable some breakpoints.\n\
15083 Arguments are breakpoint numbers with spaces in between.\n\
15084 To disable all breakpoints, give no argument.\n\
15085 A disabled breakpoint is not forgotten, but has no effect until re-enabled."));
15086
15087   add_cmd ("breakpoints", class_alias, disable_command, _("\
15088 Disable some breakpoints.\n\
15089 Arguments are breakpoint numbers with spaces in between.\n\
15090 To disable all breakpoints, give no argument.\n\
15091 A disabled breakpoint is not forgotten, but has no effect until re-enabled.\n\
15092 This command may be abbreviated \"disable\"."),
15093            &disablelist);
15094
15095   add_prefix_cmd ("delete", class_breakpoint, delete_command, _("\
15096 Delete some breakpoints or auto-display expressions.\n\
15097 Arguments are breakpoint numbers with spaces in between.\n\
15098 To delete all breakpoints, give no argument.\n\
15099 \n\
15100 Also a prefix command for deletion of other GDB objects.\n\
15101 The \"unset\" command is also an alias for \"delete\"."),
15102                   &deletelist, "delete ", 1, &cmdlist);
15103   add_com_alias ("d", "delete", class_breakpoint, 1);
15104   add_com_alias ("del", "delete", class_breakpoint, 1);
15105   if (xdb_commands)
15106     add_com ("db", class_breakpoint, delete_command, _("\
15107 Delete some breakpoints.\n\
15108 Arguments are breakpoint numbers with spaces in between.\n\
15109 To delete all breakpoints, give no argument.\n"));
15110
15111   add_cmd ("breakpoints", class_alias, delete_command, _("\
15112 Delete some breakpoints or auto-display expressions.\n\
15113 Arguments are breakpoint numbers with spaces in between.\n\
15114 To delete all breakpoints, give no argument.\n\
15115 This command may be abbreviated \"delete\"."),
15116            &deletelist);
15117
15118   add_com ("clear", class_breakpoint, clear_command, _("\
15119 Clear breakpoint at specified line or function.\n\
15120 Argument may be line number, function name, or \"*\" and an address.\n\
15121 If line number is specified, all breakpoints in that line are cleared.\n\
15122 If function is specified, breakpoints at beginning of function are cleared.\n\
15123 If an address is specified, breakpoints at that address are cleared.\n\
15124 \n\
15125 With no argument, clears all breakpoints in the line that the selected frame\n\
15126 is executing in.\n\
15127 \n\
15128 See also the \"delete\" command which clears breakpoints by number."));
15129   add_com_alias ("cl", "clear", class_breakpoint, 1);
15130
15131   c = add_com ("break", class_breakpoint, break_command, _("\
15132 Set breakpoint at specified line or function.\n"
15133 BREAK_ARGS_HELP ("break")));
15134   set_cmd_completer (c, location_completer);
15135
15136   add_com_alias ("b", "break", class_run, 1);
15137   add_com_alias ("br", "break", class_run, 1);
15138   add_com_alias ("bre", "break", class_run, 1);
15139   add_com_alias ("brea", "break", class_run, 1);
15140
15141   if (xdb_commands)
15142    add_com_alias ("ba", "break", class_breakpoint, 1);
15143
15144   if (dbx_commands)
15145     {
15146       add_abbrev_prefix_cmd ("stop", class_breakpoint, stop_command, _("\
15147 Break in function/address or break at a line in the current file."),
15148                              &stoplist, "stop ", 1, &cmdlist);
15149       add_cmd ("in", class_breakpoint, stopin_command,
15150                _("Break in function or address."), &stoplist);
15151       add_cmd ("at", class_breakpoint, stopat_command,
15152                _("Break at a line in the current file."), &stoplist);
15153       add_com ("status", class_info, breakpoints_info, _("\
15154 Status of user-settable breakpoints, or breakpoint number NUMBER.\n\
15155 The \"Type\" column indicates one of:\n\
15156 \tbreakpoint     - normal breakpoint\n\
15157 \twatchpoint     - watchpoint\n\
15158 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
15159 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
15160 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
15161 address and file/line number respectively.\n\
15162 \n\
15163 Convenience variable \"$_\" and default examine address for \"x\"\n\
15164 are set to the address of the last breakpoint listed unless the command\n\
15165 is prefixed with \"server \".\n\n\
15166 Convenience variable \"$bpnum\" contains the number of the last\n\
15167 breakpoint set."));
15168     }
15169
15170   add_info ("breakpoints", breakpoints_info, _("\
15171 Status of specified breakpoints (all user-settable breakpoints if no argument).\n\
15172 The \"Type\" column indicates one of:\n\
15173 \tbreakpoint     - normal breakpoint\n\
15174 \twatchpoint     - watchpoint\n\
15175 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
15176 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
15177 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
15178 address and file/line number respectively.\n\
15179 \n\
15180 Convenience variable \"$_\" and default examine address for \"x\"\n\
15181 are set to the address of the last breakpoint listed unless the command\n\
15182 is prefixed with \"server \".\n\n\
15183 Convenience variable \"$bpnum\" contains the number of the last\n\
15184 breakpoint set."));
15185
15186   add_info_alias ("b", "breakpoints", 1);
15187
15188   if (xdb_commands)
15189     add_com ("lb", class_breakpoint, breakpoints_info, _("\
15190 Status of user-settable breakpoints, or breakpoint number NUMBER.\n\
15191 The \"Type\" column indicates one of:\n\
15192 \tbreakpoint     - normal breakpoint\n\
15193 \twatchpoint     - watchpoint\n\
15194 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
15195 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
15196 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
15197 address and file/line number respectively.\n\
15198 \n\
15199 Convenience variable \"$_\" and default examine address for \"x\"\n\
15200 are set to the address of the last breakpoint listed unless the command\n\
15201 is prefixed with \"server \".\n\n\
15202 Convenience variable \"$bpnum\" contains the number of the last\n\
15203 breakpoint set."));
15204
15205   add_cmd ("breakpoints", class_maintenance, maintenance_info_breakpoints, _("\
15206 Status of all breakpoints, or breakpoint number NUMBER.\n\
15207 The \"Type\" column indicates one of:\n\
15208 \tbreakpoint     - normal breakpoint\n\
15209 \twatchpoint     - watchpoint\n\
15210 \tlongjmp        - internal breakpoint used to step through longjmp()\n\
15211 \tlongjmp resume - internal breakpoint at the target of longjmp()\n\
15212 \tuntil          - internal breakpoint used by the \"until\" command\n\
15213 \tfinish         - internal breakpoint used by the \"finish\" command\n\
15214 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
15215 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
15216 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
15217 address and file/line number respectively.\n\
15218 \n\
15219 Convenience variable \"$_\" and default examine address for \"x\"\n\
15220 are set to the address of the last breakpoint listed unless the command\n\
15221 is prefixed with \"server \".\n\n\
15222 Convenience variable \"$bpnum\" contains the number of the last\n\
15223 breakpoint set."),
15224            &maintenanceinfolist);
15225
15226   add_prefix_cmd ("catch", class_breakpoint, catch_command, _("\
15227 Set catchpoints to catch events."),
15228                   &catch_cmdlist, "catch ",
15229                   0/*allow-unknown*/, &cmdlist);
15230
15231   add_prefix_cmd ("tcatch", class_breakpoint, tcatch_command, _("\
15232 Set temporary catchpoints to catch events."),
15233                   &tcatch_cmdlist, "tcatch ",
15234                   0/*allow-unknown*/, &cmdlist);
15235
15236   /* Add catch and tcatch sub-commands.  */
15237   add_catch_command ("catch", _("\
15238 Catch an exception, when caught."),
15239                      catch_catch_command,
15240                      NULL,
15241                      CATCH_PERMANENT,
15242                      CATCH_TEMPORARY);
15243   add_catch_command ("throw", _("\
15244 Catch an exception, when thrown."),
15245                      catch_throw_command,
15246                      NULL,
15247                      CATCH_PERMANENT,
15248                      CATCH_TEMPORARY);
15249   add_catch_command ("fork", _("Catch calls to fork."),
15250                      catch_fork_command_1,
15251                      NULL,
15252                      (void *) (uintptr_t) catch_fork_permanent,
15253                      (void *) (uintptr_t) catch_fork_temporary);
15254   add_catch_command ("vfork", _("Catch calls to vfork."),
15255                      catch_fork_command_1,
15256                      NULL,
15257                      (void *) (uintptr_t) catch_vfork_permanent,
15258                      (void *) (uintptr_t) catch_vfork_temporary);
15259   add_catch_command ("exec", _("Catch calls to exec."),
15260                      catch_exec_command_1,
15261                      NULL,
15262                      CATCH_PERMANENT,
15263                      CATCH_TEMPORARY);
15264   add_catch_command ("load", _("Catch loads of shared libraries.\n\
15265 Usage: catch load [REGEX]\n\
15266 If REGEX is given, only stop for libraries matching the regular expression."),
15267                      catch_load_command_1,
15268                      NULL,
15269                      CATCH_PERMANENT,
15270                      CATCH_TEMPORARY);
15271   add_catch_command ("unload", _("Catch unloads of shared libraries.\n\
15272 Usage: catch unload [REGEX]\n\
15273 If REGEX is given, only stop for libraries matching the regular expression."),
15274                      catch_unload_command_1,
15275                      NULL,
15276                      CATCH_PERMANENT,
15277                      CATCH_TEMPORARY);
15278   add_catch_command ("syscall", _("\
15279 Catch system calls by their names and/or numbers.\n\
15280 Arguments say which system calls to catch.  If no arguments\n\
15281 are given, every system call will be caught.\n\
15282 Arguments, if given, should be one or more system call names\n\
15283 (if your system supports that), or system call numbers."),
15284                      catch_syscall_command_1,
15285                      catch_syscall_completer,
15286                      CATCH_PERMANENT,
15287                      CATCH_TEMPORARY);
15288
15289   c = add_com ("watch", class_breakpoint, watch_command, _("\
15290 Set a watchpoint for an expression.\n\
15291 Usage: watch [-l|-location] EXPRESSION\n\
15292 A watchpoint stops execution of your program whenever the value of\n\
15293 an expression changes.\n\
15294 If -l or -location is given, this evaluates EXPRESSION and watches\n\
15295 the memory to which it refers."));
15296   set_cmd_completer (c, expression_completer);
15297
15298   c = add_com ("rwatch", class_breakpoint, rwatch_command, _("\
15299 Set a read watchpoint for an expression.\n\
15300 Usage: rwatch [-l|-location] EXPRESSION\n\
15301 A watchpoint stops execution of your program whenever the value of\n\
15302 an expression is read.\n\
15303 If -l or -location is given, this evaluates EXPRESSION and watches\n\
15304 the memory to which it refers."));
15305   set_cmd_completer (c, expression_completer);
15306
15307   c = add_com ("awatch", class_breakpoint, awatch_command, _("\
15308 Set a watchpoint for an expression.\n\
15309 Usage: awatch [-l|-location] EXPRESSION\n\
15310 A watchpoint stops execution of your program whenever the value of\n\
15311 an expression is either read or written.\n\
15312 If -l or -location is given, this evaluates EXPRESSION and watches\n\
15313 the memory to which it refers."));
15314   set_cmd_completer (c, expression_completer);
15315
15316   add_info ("watchpoints", watchpoints_info, _("\
15317 Status of specified watchpoints (all watchpoints if no argument)."));
15318
15319   /* XXX: cagney/2005-02-23: This should be a boolean, and should
15320      respond to changes - contrary to the description.  */
15321   add_setshow_zinteger_cmd ("can-use-hw-watchpoints", class_support,
15322                             &can_use_hw_watchpoints, _("\
15323 Set debugger's willingness to use watchpoint hardware."), _("\
15324 Show debugger's willingness to use watchpoint hardware."), _("\
15325 If zero, gdb will not use hardware for new watchpoints, even if\n\
15326 such is available.  (However, any hardware watchpoints that were\n\
15327 created before setting this to nonzero, will continue to use watchpoint\n\
15328 hardware.)"),
15329                             NULL,
15330                             show_can_use_hw_watchpoints,
15331                             &setlist, &showlist);
15332
15333   can_use_hw_watchpoints = 1;
15334
15335   /* Tracepoint manipulation commands.  */
15336
15337   c = add_com ("trace", class_breakpoint, trace_command, _("\
15338 Set a tracepoint at specified line or function.\n\
15339 \n"
15340 BREAK_ARGS_HELP ("trace") "\n\
15341 Do \"help tracepoints\" for info on other tracepoint commands."));
15342   set_cmd_completer (c, location_completer);
15343
15344   add_com_alias ("tp", "trace", class_alias, 0);
15345   add_com_alias ("tr", "trace", class_alias, 1);
15346   add_com_alias ("tra", "trace", class_alias, 1);
15347   add_com_alias ("trac", "trace", class_alias, 1);
15348
15349   c = add_com ("ftrace", class_breakpoint, ftrace_command, _("\
15350 Set a fast tracepoint at specified line or function.\n\
15351 \n"
15352 BREAK_ARGS_HELP ("ftrace") "\n\
15353 Do \"help tracepoints\" for info on other tracepoint commands."));
15354   set_cmd_completer (c, location_completer);
15355
15356   c = add_com ("strace", class_breakpoint, strace_command, _("\
15357 Set a static tracepoint at specified line, function or marker.\n\
15358 \n\
15359 strace [LOCATION] [if CONDITION]\n\
15360 LOCATION may be a line number, function name, \"*\" and an address,\n\
15361 or -m MARKER_ID.\n\
15362 If a line number is specified, probe the marker at start of code\n\
15363 for that line.  If a function is specified, probe the marker at start\n\
15364 of code for that function.  If an address is specified, probe the marker\n\
15365 at that exact address.  If a marker id is specified, probe the marker\n\
15366 with that name.  With no LOCATION, uses current execution address of\n\
15367 the selected stack frame.\n\
15368 Static tracepoints accept an extra collect action -- ``collect $_sdata''.\n\
15369 This collects arbitrary user data passed in the probe point call to the\n\
15370 tracing library.  You can inspect it when analyzing the trace buffer,\n\
15371 by printing the $_sdata variable like any other convenience variable.\n\
15372 \n\
15373 CONDITION is a boolean expression.\n\
15374 \n\
15375 Multiple tracepoints at one place are permitted, and useful if their\n\
15376 conditions are different.\n\
15377 \n\
15378 Do \"help breakpoints\" for info on other commands dealing with breakpoints.\n\
15379 Do \"help tracepoints\" for info on other tracepoint commands."));
15380   set_cmd_completer (c, location_completer);
15381
15382   add_info ("tracepoints", tracepoints_info, _("\
15383 Status of specified tracepoints (all tracepoints if no argument).\n\
15384 Convenience variable \"$tpnum\" contains the number of the\n\
15385 last tracepoint set."));
15386
15387   add_info_alias ("tp", "tracepoints", 1);
15388
15389   add_cmd ("tracepoints", class_trace, delete_trace_command, _("\
15390 Delete specified tracepoints.\n\
15391 Arguments are tracepoint numbers, separated by spaces.\n\
15392 No argument means delete all tracepoints."),
15393            &deletelist);
15394
15395   c = add_cmd ("tracepoints", class_trace, disable_trace_command, _("\
15396 Disable specified tracepoints.\n\
15397 Arguments are tracepoint numbers, separated by spaces.\n\
15398 No argument means disable all tracepoints."),
15399            &disablelist);
15400   deprecate_cmd (c, "disable");
15401
15402   c = add_cmd ("tracepoints", class_trace, enable_trace_command, _("\
15403 Enable specified tracepoints.\n\
15404 Arguments are tracepoint numbers, separated by spaces.\n\
15405 No argument means enable all tracepoints."),
15406            &enablelist);
15407   deprecate_cmd (c, "enable");
15408
15409   add_com ("passcount", class_trace, trace_pass_command, _("\
15410 Set the passcount for a tracepoint.\n\
15411 The trace will end when the tracepoint has been passed 'count' times.\n\
15412 Usage: passcount COUNT TPNUM, where TPNUM may also be \"all\";\n\
15413 if TPNUM is omitted, passcount refers to the last tracepoint defined."));
15414
15415   add_prefix_cmd ("save", class_breakpoint, save_command,
15416                   _("Save breakpoint definitions as a script."),
15417                   &save_cmdlist, "save ",
15418                   0/*allow-unknown*/, &cmdlist);
15419
15420   c = add_cmd ("breakpoints", class_breakpoint, save_breakpoints_command, _("\
15421 Save current breakpoint definitions as a script.\n\
15422 This includes all types of breakpoints (breakpoints, watchpoints,\n\
15423 catchpoints, tracepoints).  Use the 'source' command in another debug\n\
15424 session to restore them."),
15425                &save_cmdlist);
15426   set_cmd_completer (c, filename_completer);
15427
15428   c = add_cmd ("tracepoints", class_trace, save_tracepoints_command, _("\
15429 Save current tracepoint definitions as a script.\n\
15430 Use the 'source' command in another debug session to restore them."),
15431                &save_cmdlist);
15432   set_cmd_completer (c, filename_completer);
15433
15434   c = add_com_alias ("save-tracepoints", "save tracepoints", class_trace, 0);
15435   deprecate_cmd (c, "save tracepoints");
15436
15437   add_prefix_cmd ("breakpoint", class_maintenance, set_breakpoint_cmd, _("\
15438 Breakpoint specific settings\n\
15439 Configure various breakpoint-specific variables such as\n\
15440 pending breakpoint behavior"),
15441                   &breakpoint_set_cmdlist, "set breakpoint ",
15442                   0/*allow-unknown*/, &setlist);
15443   add_prefix_cmd ("breakpoint", class_maintenance, show_breakpoint_cmd, _("\
15444 Breakpoint specific settings\n\
15445 Configure various breakpoint-specific variables such as\n\
15446 pending breakpoint behavior"),
15447                   &breakpoint_show_cmdlist, "show breakpoint ",
15448                   0/*allow-unknown*/, &showlist);
15449
15450   add_setshow_auto_boolean_cmd ("pending", no_class,
15451                                 &pending_break_support, _("\
15452 Set debugger's behavior regarding pending breakpoints."), _("\
15453 Show debugger's behavior regarding pending breakpoints."), _("\
15454 If on, an unrecognized breakpoint location will cause gdb to create a\n\
15455 pending breakpoint.  If off, an unrecognized breakpoint location results in\n\
15456 an error.  If auto, an unrecognized breakpoint location results in a\n\
15457 user-query to see if a pending breakpoint should be created."),
15458                                 NULL,
15459                                 show_pending_break_support,
15460                                 &breakpoint_set_cmdlist,
15461                                 &breakpoint_show_cmdlist);
15462
15463   pending_break_support = AUTO_BOOLEAN_AUTO;
15464
15465   add_setshow_boolean_cmd ("auto-hw", no_class,
15466                            &automatic_hardware_breakpoints, _("\
15467 Set automatic usage of hardware breakpoints."), _("\
15468 Show automatic usage of hardware breakpoints."), _("\
15469 If set, the debugger will automatically use hardware breakpoints for\n\
15470 breakpoints set with \"break\" but falling in read-only memory.  If not set,\n\
15471 a warning will be emitted for such breakpoints."),
15472                            NULL,
15473                            show_automatic_hardware_breakpoints,
15474                            &breakpoint_set_cmdlist,
15475                            &breakpoint_show_cmdlist);
15476
15477   add_setshow_enum_cmd ("always-inserted", class_support,
15478                         always_inserted_enums, &always_inserted_mode, _("\
15479 Set mode for inserting breakpoints."), _("\
15480 Show mode for inserting breakpoints."), _("\
15481 When this mode is off, breakpoints are inserted in inferior when it is\n\
15482 resumed, and removed when execution stops.  When this mode is on,\n\
15483 breakpoints are inserted immediately and removed only when the user\n\
15484 deletes the breakpoint.  When this mode is auto (which is the default),\n\
15485 the behaviour depends on the non-stop setting (see help set non-stop).\n\
15486 In this case, if gdb is controlling the inferior in non-stop mode, gdb\n\
15487 behaves as if always-inserted mode is on; if gdb is controlling the\n\
15488 inferior in all-stop mode, gdb behaves as if always-inserted mode is off."),
15489                            NULL,
15490                            &show_always_inserted_mode,
15491                            &breakpoint_set_cmdlist,
15492                            &breakpoint_show_cmdlist);
15493
15494   add_setshow_enum_cmd ("condition-evaluation", class_breakpoint,
15495                         condition_evaluation_enums,
15496                         &condition_evaluation_mode_1, _("\
15497 Set mode of breakpoint condition evaluation."), _("\
15498 Show mode of breakpoint condition evaluation."), _("\
15499 When this is set to \"gdb\", breakpoint conditions will be\n\
15500 evaluated on the host's side by GDB.  When it is set to \"target\",\n\
15501 breakpoint conditions will be downloaded to the target (if the target\n\
15502 supports such feature) and conditions will be evaluated on the target's side.\n\
15503 If this is set to \"auto\" (default), this will be automatically set to\n\
15504 \"target\" if it supports condition evaluation, otherwise it will\n\
15505 be set to \"gdb\""),
15506                            &set_condition_evaluation_mode,
15507                            &show_condition_evaluation_mode,
15508                            &breakpoint_set_cmdlist,
15509                            &breakpoint_show_cmdlist);
15510
15511   add_com ("break-range", class_breakpoint, break_range_command, _("\
15512 Set a breakpoint for an address range.\n\
15513 break-range START-LOCATION, END-LOCATION\n\
15514 where START-LOCATION and END-LOCATION can be one of the following:\n\
15515   LINENUM, for that line in the current file,\n\
15516   FILE:LINENUM, for that line in that file,\n\
15517   +OFFSET, for that number of lines after the current line\n\
15518            or the start of the range\n\
15519   FUNCTION, for the first line in that function,\n\
15520   FILE:FUNCTION, to distinguish among like-named static functions.\n\
15521   *ADDRESS, for the instruction at that address.\n\
15522 \n\
15523 The breakpoint will stop execution of the inferior whenever it executes\n\
15524 an instruction at any address within the [START-LOCATION, END-LOCATION]\n\
15525 range (including START-LOCATION and END-LOCATION)."));
15526
15527   automatic_hardware_breakpoints = 1;
15528
15529   observer_attach_about_to_proceed (breakpoint_about_to_proceed);
15530 }