gdb:
[external/binutils.git] / gdb / breakpoint.c
1 /* Everything about breakpoints, for GDB.
2
3    Copyright (C) 1986-2012 Free Software Foundation, Inc.
4
5    This file is part of GDB.
6
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
19
20 #include "defs.h"
21 #include "arch-utils.h"
22 #include <ctype.h>
23 #include "hashtab.h"
24 #include "symtab.h"
25 #include "frame.h"
26 #include "breakpoint.h"
27 #include "tracepoint.h"
28 #include "gdbtypes.h"
29 #include "expression.h"
30 #include "gdbcore.h"
31 #include "gdbcmd.h"
32 #include "value.h"
33 #include "command.h"
34 #include "inferior.h"
35 #include "gdbthread.h"
36 #include "target.h"
37 #include "language.h"
38 #include "gdb_string.h"
39 #include "gdb-demangle.h"
40 #include "filenames.h"
41 #include "annotate.h"
42 #include "symfile.h"
43 #include "objfiles.h"
44 #include "source.h"
45 #include "linespec.h"
46 #include "completer.h"
47 #include "gdb.h"
48 #include "ui-out.h"
49 #include "cli/cli-script.h"
50 #include "gdb_assert.h"
51 #include "block.h"
52 #include "solib.h"
53 #include "solist.h"
54 #include "observer.h"
55 #include "exceptions.h"
56 #include "memattr.h"
57 #include "ada-lang.h"
58 #include "top.h"
59 #include "valprint.h"
60 #include "jit.h"
61 #include "xml-syscall.h"
62 #include "parser-defs.h"
63 #include "gdb_regex.h"
64 #include "probe.h"
65 #include "cli/cli-utils.h"
66 #include "continuations.h"
67 #include "stack.h"
68 #include "skip.h"
69 #include "gdb_regex.h"
70 #include "ax-gdb.h"
71 #include "dummy-frame.h"
72
73 /* readline include files */
74 #include "readline/readline.h"
75 #include "readline/history.h"
76
77 /* readline defines this.  */
78 #undef savestring
79
80 #include "mi/mi-common.h"
81 #include "python/python.h"
82
83 /* Prototypes for local functions.  */
84
85 static void enable_delete_command (char *, int);
86
87 static void enable_once_command (char *, int);
88
89 static void enable_count_command (char *, int);
90
91 static void disable_command (char *, int);
92
93 static void enable_command (char *, int);
94
95 static void map_breakpoint_numbers (char *, void (*) (struct breakpoint *,
96                                                       void *),
97                                     void *);
98
99 static void ignore_command (char *, int);
100
101 static int breakpoint_re_set_one (void *);
102
103 static void breakpoint_re_set_default (struct breakpoint *);
104
105 static void create_sals_from_address_default (char **,
106                                               struct linespec_result *,
107                                               enum bptype, char *,
108                                               char **);
109
110 static void create_breakpoints_sal_default (struct gdbarch *,
111                                             struct linespec_result *,
112                                             struct linespec_sals *,
113                                             char *, char *, enum bptype,
114                                             enum bpdisp, int, int,
115                                             int,
116                                             const struct breakpoint_ops *,
117                                             int, int, int, unsigned);
118
119 static void decode_linespec_default (struct breakpoint *, char **,
120                                      struct symtabs_and_lines *);
121
122 static void clear_command (char *, int);
123
124 static void catch_command (char *, int);
125
126 static int can_use_hardware_watchpoint (struct value *);
127
128 static void break_command_1 (char *, int, int);
129
130 static void mention (struct breakpoint *);
131
132 static struct breakpoint *set_raw_breakpoint_without_location (struct gdbarch *,
133                                                                enum bptype,
134                                                                const struct breakpoint_ops *);
135 static struct bp_location *add_location_to_breakpoint (struct breakpoint *,
136                                                        const struct symtab_and_line *);
137
138 /* This function is used in gdbtk sources and thus can not be made
139    static.  */
140 struct breakpoint *set_raw_breakpoint (struct gdbarch *gdbarch,
141                                        struct symtab_and_line,
142                                        enum bptype,
143                                        const struct breakpoint_ops *);
144
145 static struct breakpoint *
146   momentary_breakpoint_from_master (struct breakpoint *orig,
147                                     enum bptype type,
148                                     const struct breakpoint_ops *ops);
149
150 static void breakpoint_adjustment_warning (CORE_ADDR, CORE_ADDR, int, int);
151
152 static CORE_ADDR adjust_breakpoint_address (struct gdbarch *gdbarch,
153                                             CORE_ADDR bpaddr,
154                                             enum bptype bptype);
155
156 static void describe_other_breakpoints (struct gdbarch *,
157                                         struct program_space *, CORE_ADDR,
158                                         struct obj_section *, int);
159
160 static int breakpoint_address_match (struct address_space *aspace1,
161                                      CORE_ADDR addr1,
162                                      struct address_space *aspace2,
163                                      CORE_ADDR addr2);
164
165 static int watchpoint_locations_match (struct bp_location *loc1,
166                                        struct bp_location *loc2);
167
168 static int breakpoint_location_address_match (struct bp_location *bl,
169                                               struct address_space *aspace,
170                                               CORE_ADDR addr);
171
172 static void breakpoints_info (char *, int);
173
174 static void watchpoints_info (char *, int);
175
176 static int breakpoint_1 (char *, int, 
177                          int (*) (const struct breakpoint *));
178
179 static int breakpoint_cond_eval (void *);
180
181 static void cleanup_executing_breakpoints (void *);
182
183 static void commands_command (char *, int);
184
185 static void condition_command (char *, int);
186
187 typedef enum
188   {
189     mark_inserted,
190     mark_uninserted
191   }
192 insertion_state_t;
193
194 static int remove_breakpoint (struct bp_location *, insertion_state_t);
195 static int remove_breakpoint_1 (struct bp_location *, insertion_state_t);
196
197 static enum print_stop_action print_bp_stop_message (bpstat bs);
198
199 static int watchpoint_check (void *);
200
201 static void maintenance_info_breakpoints (char *, int);
202
203 static int hw_breakpoint_used_count (void);
204
205 static int hw_watchpoint_use_count (struct breakpoint *);
206
207 static int hw_watchpoint_used_count_others (struct breakpoint *except,
208                                             enum bptype type,
209                                             int *other_type_used);
210
211 static void hbreak_command (char *, int);
212
213 static void thbreak_command (char *, int);
214
215 static void enable_breakpoint_disp (struct breakpoint *, enum bpdisp,
216                                     int count);
217
218 static void stop_command (char *arg, int from_tty);
219
220 static void stopin_command (char *arg, int from_tty);
221
222 static void stopat_command (char *arg, int from_tty);
223
224 static char *ep_parse_optional_if_clause (char **arg);
225
226 static void catch_exception_command_1 (enum exception_event_kind ex_event, 
227                                        char *arg, int tempflag, int from_tty);
228
229 static void tcatch_command (char *arg, int from_tty);
230
231 static void detach_single_step_breakpoints (void);
232
233 static int single_step_breakpoint_inserted_here_p (struct address_space *,
234                                                    CORE_ADDR pc);
235
236 static void free_bp_location (struct bp_location *loc);
237 static void incref_bp_location (struct bp_location *loc);
238 static void decref_bp_location (struct bp_location **loc);
239
240 static struct bp_location *allocate_bp_location (struct breakpoint *bpt);
241
242 static void update_global_location_list (int);
243
244 static void update_global_location_list_nothrow (int);
245
246 static int is_hardware_watchpoint (const struct breakpoint *bpt);
247
248 static void insert_breakpoint_locations (void);
249
250 static int syscall_catchpoint_p (struct breakpoint *b);
251
252 static void tracepoints_info (char *, int);
253
254 static void delete_trace_command (char *, int);
255
256 static void enable_trace_command (char *, int);
257
258 static void disable_trace_command (char *, int);
259
260 static void trace_pass_command (char *, int);
261
262 static int is_masked_watchpoint (const struct breakpoint *b);
263
264 static struct bp_location **get_first_locp_gte_addr (CORE_ADDR address);
265
266 /* Return 1 if B refers to a static tracepoint set by marker ("-m"), zero
267    otherwise.  */
268
269 static int strace_marker_p (struct breakpoint *b);
270
271 static void init_catchpoint (struct breakpoint *b,
272                              struct gdbarch *gdbarch, int tempflag,
273                              char *cond_string,
274                              const struct breakpoint_ops *ops);
275
276 /* The abstract base class all breakpoint_ops structures inherit
277    from.  */
278 static struct breakpoint_ops base_breakpoint_ops;
279
280 /* The breakpoint_ops structure to be inherited by all breakpoint_ops
281    that are implemented on top of software or hardware breakpoints
282    (user breakpoints, internal and momentary breakpoints, etc.).  */
283 static struct breakpoint_ops bkpt_base_breakpoint_ops;
284
285 /* Internal breakpoints class type.  */
286 static struct breakpoint_ops internal_breakpoint_ops;
287
288 /* Momentary breakpoints class type.  */
289 static struct breakpoint_ops momentary_breakpoint_ops;
290
291 /* Momentary breakpoints for bp_longjmp and bp_exception class type.  */
292 static struct breakpoint_ops longjmp_breakpoint_ops;
293
294 /* The breakpoint_ops structure to be used in regular user created
295    breakpoints.  */
296 struct breakpoint_ops bkpt_breakpoint_ops;
297
298 /* Breakpoints set on probes.  */
299 static struct breakpoint_ops bkpt_probe_breakpoint_ops;
300
301 /* Dynamic printf class type.  */
302 static struct breakpoint_ops dprintf_breakpoint_ops;
303
304 /* A reference-counted struct command_line.  This lets multiple
305    breakpoints share a single command list.  */
306 struct counted_command_line
307 {
308   /* The reference count.  */
309   int refc;
310
311   /* The command list.  */
312   struct command_line *commands;
313 };
314
315 struct command_line *
316 breakpoint_commands (struct breakpoint *b)
317 {
318   return b->commands ? b->commands->commands : NULL;
319 }
320
321 /* Flag indicating that a command has proceeded the inferior past the
322    current breakpoint.  */
323
324 static int breakpoint_proceeded;
325
326 const char *
327 bpdisp_text (enum bpdisp disp)
328 {
329   /* NOTE: the following values are a part of MI protocol and
330      represent values of 'disp' field returned when inferior stops at
331      a breakpoint.  */
332   static const char * const bpdisps[] = {"del", "dstp", "dis", "keep"};
333
334   return bpdisps[(int) disp];
335 }
336
337 /* Prototypes for exported functions.  */
338 /* If FALSE, gdb will not use hardware support for watchpoints, even
339    if such is available.  */
340 static int can_use_hw_watchpoints;
341
342 static void
343 show_can_use_hw_watchpoints (struct ui_file *file, int from_tty,
344                              struct cmd_list_element *c,
345                              const char *value)
346 {
347   fprintf_filtered (file,
348                     _("Debugger's willingness to use "
349                       "watchpoint hardware is %s.\n"),
350                     value);
351 }
352
353 /* If AUTO_BOOLEAN_FALSE, gdb will not attempt to create pending breakpoints.
354    If AUTO_BOOLEAN_TRUE, gdb will automatically create pending breakpoints
355    for unrecognized breakpoint locations.
356    If AUTO_BOOLEAN_AUTO, gdb will query when breakpoints are unrecognized.  */
357 static enum auto_boolean pending_break_support;
358 static void
359 show_pending_break_support (struct ui_file *file, int from_tty,
360                             struct cmd_list_element *c,
361                             const char *value)
362 {
363   fprintf_filtered (file,
364                     _("Debugger's behavior regarding "
365                       "pending breakpoints is %s.\n"),
366                     value);
367 }
368
369 /* If 1, gdb will automatically use hardware breakpoints for breakpoints
370    set with "break" but falling in read-only memory.
371    If 0, gdb will warn about such breakpoints, but won't automatically
372    use hardware breakpoints.  */
373 static int automatic_hardware_breakpoints;
374 static void
375 show_automatic_hardware_breakpoints (struct ui_file *file, int from_tty,
376                                      struct cmd_list_element *c,
377                                      const char *value)
378 {
379   fprintf_filtered (file,
380                     _("Automatic usage of hardware breakpoints is %s.\n"),
381                     value);
382 }
383
384 /* If on, gdb will keep breakpoints inserted even as inferior is
385    stopped, and immediately insert any new breakpoints.  If off, gdb
386    will insert breakpoints into inferior only when resuming it, and
387    will remove breakpoints upon stop.  If auto, GDB will behave as ON
388    if in non-stop mode, and as OFF if all-stop mode.*/
389
390 static enum auto_boolean always_inserted_mode = AUTO_BOOLEAN_AUTO;
391
392 static void
393 show_always_inserted_mode (struct ui_file *file, int from_tty,
394                      struct cmd_list_element *c, const char *value)
395 {
396   if (always_inserted_mode == AUTO_BOOLEAN_AUTO)
397     fprintf_filtered (file,
398                       _("Always inserted breakpoint "
399                         "mode is %s (currently %s).\n"),
400                       value,
401                       breakpoints_always_inserted_mode () ? "on" : "off");
402   else
403     fprintf_filtered (file, _("Always inserted breakpoint mode is %s.\n"),
404                       value);
405 }
406
407 int
408 breakpoints_always_inserted_mode (void)
409 {
410   return (always_inserted_mode == AUTO_BOOLEAN_TRUE
411           || (always_inserted_mode == AUTO_BOOLEAN_AUTO && non_stop));
412 }
413
414 static const char condition_evaluation_both[] = "host or target";
415
416 /* Modes for breakpoint condition evaluation.  */
417 static const char condition_evaluation_auto[] = "auto";
418 static const char condition_evaluation_host[] = "host";
419 static const char condition_evaluation_target[] = "target";
420 static const char *const condition_evaluation_enums[] = {
421   condition_evaluation_auto,
422   condition_evaluation_host,
423   condition_evaluation_target,
424   NULL
425 };
426
427 /* Global that holds the current mode for breakpoint condition evaluation.  */
428 static const char *condition_evaluation_mode_1 = condition_evaluation_auto;
429
430 /* Global that we use to display information to the user (gets its value from
431    condition_evaluation_mode_1.  */
432 static const char *condition_evaluation_mode = condition_evaluation_auto;
433
434 /* Translate a condition evaluation mode MODE into either "host"
435    or "target".  This is used mostly to translate from "auto" to the
436    real setting that is being used.  It returns the translated
437    evaluation mode.  */
438
439 static const char *
440 translate_condition_evaluation_mode (const char *mode)
441 {
442   if (mode == condition_evaluation_auto)
443     {
444       if (target_supports_evaluation_of_breakpoint_conditions ())
445         return condition_evaluation_target;
446       else
447         return condition_evaluation_host;
448     }
449   else
450     return mode;
451 }
452
453 /* Discovers what condition_evaluation_auto translates to.  */
454
455 static const char *
456 breakpoint_condition_evaluation_mode (void)
457 {
458   return translate_condition_evaluation_mode (condition_evaluation_mode);
459 }
460
461 /* Return true if GDB should evaluate breakpoint conditions or false
462    otherwise.  */
463
464 static int
465 gdb_evaluates_breakpoint_condition_p (void)
466 {
467   const char *mode = breakpoint_condition_evaluation_mode ();
468
469   return (mode == condition_evaluation_host);
470 }
471
472 void _initialize_breakpoint (void);
473
474 /* Are we executing breakpoint commands?  */
475 static int executing_breakpoint_commands;
476
477 /* Are overlay event breakpoints enabled? */
478 static int overlay_events_enabled;
479
480 /* See description in breakpoint.h. */
481 int target_exact_watchpoints = 0;
482
483 /* Walk the following statement or block through all breakpoints.
484    ALL_BREAKPOINTS_SAFE does so even if the statement deletes the
485    current breakpoint.  */
486
487 #define ALL_BREAKPOINTS(B)  for (B = breakpoint_chain; B; B = B->next)
488
489 #define ALL_BREAKPOINTS_SAFE(B,TMP)     \
490         for (B = breakpoint_chain;      \
491              B ? (TMP=B->next, 1): 0;   \
492              B = TMP)
493
494 /* Similar iterator for the low-level breakpoints.  SAFE variant is
495    not provided so update_global_location_list must not be called
496    while executing the block of ALL_BP_LOCATIONS.  */
497
498 #define ALL_BP_LOCATIONS(B,BP_TMP)                                      \
499         for (BP_TMP = bp_location;                                      \
500              BP_TMP < bp_location + bp_location_count && (B = *BP_TMP); \
501              BP_TMP++)
502
503 /* Iterates through locations with address ADDRESS for the currently selected
504    program space.  BP_LOCP_TMP points to each object.  BP_LOCP_START points
505    to where the loop should start from.
506    If BP_LOCP_START is a NULL pointer, the macro automatically seeks the
507    appropriate location to start with.  */
508
509 #define ALL_BP_LOCATIONS_AT_ADDR(BP_LOCP_TMP, BP_LOCP_START, ADDRESS)   \
510         for (BP_LOCP_START = BP_LOCP_START == NULL ? get_first_locp_gte_addr (ADDRESS) : BP_LOCP_START, \
511              BP_LOCP_TMP = BP_LOCP_START;                               \
512              BP_LOCP_START                                              \
513              && (BP_LOCP_TMP < bp_location + bp_location_count          \
514              && (*BP_LOCP_TMP)->address == ADDRESS);                    \
515              BP_LOCP_TMP++)
516
517 /* Iterator for tracepoints only.  */
518
519 #define ALL_TRACEPOINTS(B)  \
520   for (B = breakpoint_chain; B; B = B->next)  \
521     if (is_tracepoint (B))
522
523 /* Chains of all breakpoints defined.  */
524
525 struct breakpoint *breakpoint_chain;
526
527 /* Array is sorted by bp_location_compare - primarily by the ADDRESS.  */
528
529 static struct bp_location **bp_location;
530
531 /* Number of elements of BP_LOCATION.  */
532
533 static unsigned bp_location_count;
534
535 /* Maximum alignment offset between bp_target_info.PLACED_ADDRESS and
536    ADDRESS for the current elements of BP_LOCATION which get a valid
537    result from bp_location_has_shadow.  You can use it for roughly
538    limiting the subrange of BP_LOCATION to scan for shadow bytes for
539    an address you need to read.  */
540
541 static CORE_ADDR bp_location_placed_address_before_address_max;
542
543 /* Maximum offset plus alignment between bp_target_info.PLACED_ADDRESS
544    + bp_target_info.SHADOW_LEN and ADDRESS for the current elements of
545    BP_LOCATION which get a valid result from bp_location_has_shadow.
546    You can use it for roughly limiting the subrange of BP_LOCATION to
547    scan for shadow bytes for an address you need to read.  */
548
549 static CORE_ADDR bp_location_shadow_len_after_address_max;
550
551 /* The locations that no longer correspond to any breakpoint, unlinked
552    from bp_location array, but for which a hit may still be reported
553    by a target.  */
554 VEC(bp_location_p) *moribund_locations = NULL;
555
556 /* Number of last breakpoint made.  */
557
558 static int breakpoint_count;
559
560 /* The value of `breakpoint_count' before the last command that
561    created breakpoints.  If the last (break-like) command created more
562    than one breakpoint, then the difference between BREAKPOINT_COUNT
563    and PREV_BREAKPOINT_COUNT is more than one.  */
564 static int prev_breakpoint_count;
565
566 /* Number of last tracepoint made.  */
567
568 static int tracepoint_count;
569
570 static struct cmd_list_element *breakpoint_set_cmdlist;
571 static struct cmd_list_element *breakpoint_show_cmdlist;
572 struct cmd_list_element *save_cmdlist;
573
574 /* Return whether a breakpoint is an active enabled breakpoint.  */
575 static int
576 breakpoint_enabled (struct breakpoint *b)
577 {
578   return (b->enable_state == bp_enabled);
579 }
580
581 /* Set breakpoint count to NUM.  */
582
583 static void
584 set_breakpoint_count (int num)
585 {
586   prev_breakpoint_count = breakpoint_count;
587   breakpoint_count = num;
588   set_internalvar_integer (lookup_internalvar ("bpnum"), num);
589 }
590
591 /* Used by `start_rbreak_breakpoints' below, to record the current
592    breakpoint count before "rbreak" creates any breakpoint.  */
593 static int rbreak_start_breakpoint_count;
594
595 /* Called at the start an "rbreak" command to record the first
596    breakpoint made.  */
597
598 void
599 start_rbreak_breakpoints (void)
600 {
601   rbreak_start_breakpoint_count = breakpoint_count;
602 }
603
604 /* Called at the end of an "rbreak" command to record the last
605    breakpoint made.  */
606
607 void
608 end_rbreak_breakpoints (void)
609 {
610   prev_breakpoint_count = rbreak_start_breakpoint_count;
611 }
612
613 /* Used in run_command to zero the hit count when a new run starts.  */
614
615 void
616 clear_breakpoint_hit_counts (void)
617 {
618   struct breakpoint *b;
619
620   ALL_BREAKPOINTS (b)
621     b->hit_count = 0;
622 }
623
624 /* Allocate a new counted_command_line with reference count of 1.
625    The new structure owns COMMANDS.  */
626
627 static struct counted_command_line *
628 alloc_counted_command_line (struct command_line *commands)
629 {
630   struct counted_command_line *result
631     = xmalloc (sizeof (struct counted_command_line));
632
633   result->refc = 1;
634   result->commands = commands;
635   return result;
636 }
637
638 /* Increment reference count.  This does nothing if CMD is NULL.  */
639
640 static void
641 incref_counted_command_line (struct counted_command_line *cmd)
642 {
643   if (cmd)
644     ++cmd->refc;
645 }
646
647 /* Decrement reference count.  If the reference count reaches 0,
648    destroy the counted_command_line.  Sets *CMDP to NULL.  This does
649    nothing if *CMDP is NULL.  */
650
651 static void
652 decref_counted_command_line (struct counted_command_line **cmdp)
653 {
654   if (*cmdp)
655     {
656       if (--(*cmdp)->refc == 0)
657         {
658           free_command_lines (&(*cmdp)->commands);
659           xfree (*cmdp);
660         }
661       *cmdp = NULL;
662     }
663 }
664
665 /* A cleanup function that calls decref_counted_command_line.  */
666
667 static void
668 do_cleanup_counted_command_line (void *arg)
669 {
670   decref_counted_command_line (arg);
671 }
672
673 /* Create a cleanup that calls decref_counted_command_line on the
674    argument.  */
675
676 static struct cleanup *
677 make_cleanup_decref_counted_command_line (struct counted_command_line **cmdp)
678 {
679   return make_cleanup (do_cleanup_counted_command_line, cmdp);
680 }
681
682 \f
683 /* Return the breakpoint with the specified number, or NULL
684    if the number does not refer to an existing breakpoint.  */
685
686 struct breakpoint *
687 get_breakpoint (int num)
688 {
689   struct breakpoint *b;
690
691   ALL_BREAKPOINTS (b)
692     if (b->number == num)
693       return b;
694   
695   return NULL;
696 }
697
698 \f
699
700 /* Mark locations as "conditions have changed" in case the target supports
701    evaluating conditions on its side.  */
702
703 static void
704 mark_breakpoint_modified (struct breakpoint *b)
705 {
706   struct bp_location *loc;
707
708   /* This is only meaningful if the target is
709      evaluating conditions and if the user has
710      opted for condition evaluation on the target's
711      side.  */
712   if (gdb_evaluates_breakpoint_condition_p ()
713       || !target_supports_evaluation_of_breakpoint_conditions ())
714     return;
715
716   if (!is_breakpoint (b))
717     return;
718
719   for (loc = b->loc; loc; loc = loc->next)
720     loc->condition_changed = condition_modified;
721 }
722
723 /* Mark location as "conditions have changed" in case the target supports
724    evaluating conditions on its side.  */
725
726 static void
727 mark_breakpoint_location_modified (struct bp_location *loc)
728 {
729   /* This is only meaningful if the target is
730      evaluating conditions and if the user has
731      opted for condition evaluation on the target's
732      side.  */
733   if (gdb_evaluates_breakpoint_condition_p ()
734       || !target_supports_evaluation_of_breakpoint_conditions ())
735
736     return;
737
738   if (!is_breakpoint (loc->owner))
739     return;
740
741   loc->condition_changed = condition_modified;
742 }
743
744 /* Sets the condition-evaluation mode using the static global
745    condition_evaluation_mode.  */
746
747 static void
748 set_condition_evaluation_mode (char *args, int from_tty,
749                                struct cmd_list_element *c)
750 {
751   const char *old_mode, *new_mode;
752
753   if ((condition_evaluation_mode_1 == condition_evaluation_target)
754       && !target_supports_evaluation_of_breakpoint_conditions ())
755     {
756       condition_evaluation_mode_1 = condition_evaluation_mode;
757       warning (_("Target does not support breakpoint condition evaluation.\n"
758                  "Using host evaluation mode instead."));
759       return;
760     }
761
762   new_mode = translate_condition_evaluation_mode (condition_evaluation_mode_1);
763   old_mode = translate_condition_evaluation_mode (condition_evaluation_mode);
764
765   /* Flip the switch.  Flip it even if OLD_MODE == NEW_MODE as one of the
766      settings was "auto".  */
767   condition_evaluation_mode = condition_evaluation_mode_1;
768
769   /* Only update the mode if the user picked a different one.  */
770   if (new_mode != old_mode)
771     {
772       struct bp_location *loc, **loc_tmp;
773       /* If the user switched to a different evaluation mode, we
774          need to synch the changes with the target as follows:
775
776          "host" -> "target": Send all (valid) conditions to the target.
777          "target" -> "host": Remove all the conditions from the target.
778       */
779
780       if (new_mode == condition_evaluation_target)
781         {
782           /* Mark everything modified and synch conditions with the
783              target.  */
784           ALL_BP_LOCATIONS (loc, loc_tmp)
785             mark_breakpoint_location_modified (loc);
786         }
787       else
788         {
789           /* Manually mark non-duplicate locations to synch conditions
790              with the target.  We do this to remove all the conditions the
791              target knows about.  */
792           ALL_BP_LOCATIONS (loc, loc_tmp)
793             if (is_breakpoint (loc->owner) && loc->inserted)
794               loc->needs_update = 1;
795         }
796
797       /* Do the update.  */
798       update_global_location_list (1);
799     }
800
801   return;
802 }
803
804 /* Shows the current mode of breakpoint condition evaluation.  Explicitly shows
805    what "auto" is translating to.  */
806
807 static void
808 show_condition_evaluation_mode (struct ui_file *file, int from_tty,
809                                 struct cmd_list_element *c, const char *value)
810 {
811   if (condition_evaluation_mode == condition_evaluation_auto)
812     fprintf_filtered (file,
813                       _("Breakpoint condition evaluation "
814                         "mode is %s (currently %s).\n"),
815                       value,
816                       breakpoint_condition_evaluation_mode ());
817   else
818     fprintf_filtered (file, _("Breakpoint condition evaluation mode is %s.\n"),
819                       value);
820 }
821
822 /* A comparison function for bp_location AP and BP that is used by
823    bsearch.  This comparison function only cares about addresses, unlike
824    the more general bp_location_compare function.  */
825
826 static int
827 bp_location_compare_addrs (const void *ap, const void *bp)
828 {
829   struct bp_location *a = *(void **) ap;
830   struct bp_location *b = *(void **) bp;
831
832   if (a->address == b->address)
833     return 0;
834   else
835     return ((a->address > b->address) - (a->address < b->address));
836 }
837
838 /* Helper function to skip all bp_locations with addresses
839    less than ADDRESS.  It returns the first bp_location that
840    is greater than or equal to ADDRESS.  If none is found, just
841    return NULL.  */
842
843 static struct bp_location **
844 get_first_locp_gte_addr (CORE_ADDR address)
845 {
846   struct bp_location dummy_loc;
847   struct bp_location *dummy_locp = &dummy_loc;
848   struct bp_location **locp_found = NULL;
849
850   /* Initialize the dummy location's address field.  */
851   memset (&dummy_loc, 0, sizeof (struct bp_location));
852   dummy_loc.address = address;
853
854   /* Find a close match to the first location at ADDRESS.  */
855   locp_found = bsearch (&dummy_locp, bp_location, bp_location_count,
856                         sizeof (struct bp_location **),
857                         bp_location_compare_addrs);
858
859   /* Nothing was found, nothing left to do.  */
860   if (locp_found == NULL)
861     return NULL;
862
863   /* We may have found a location that is at ADDRESS but is not the first in the
864      location's list.  Go backwards (if possible) and locate the first one.  */
865   while ((locp_found - 1) >= bp_location
866          && (*(locp_found - 1))->address == address)
867     locp_found--;
868
869   return locp_found;
870 }
871
872 void
873 set_breakpoint_condition (struct breakpoint *b, char *exp,
874                           int from_tty)
875 {
876   xfree (b->cond_string);
877   b->cond_string = NULL;
878
879   if (is_watchpoint (b))
880     {
881       struct watchpoint *w = (struct watchpoint *) b;
882
883       xfree (w->cond_exp);
884       w->cond_exp = NULL;
885     }
886   else
887     {
888       struct bp_location *loc;
889
890       for (loc = b->loc; loc; loc = loc->next)
891         {
892           xfree (loc->cond);
893           loc->cond = NULL;
894
895           /* No need to free the condition agent expression
896              bytecode (if we have one).  We will handle this
897              when we go through update_global_location_list.  */
898         }
899     }
900
901   if (*exp == 0)
902     {
903       if (from_tty)
904         printf_filtered (_("Breakpoint %d now unconditional.\n"), b->number);
905     }
906   else
907     {
908       char *arg = exp;
909
910       /* I don't know if it matters whether this is the string the user
911          typed in or the decompiled expression.  */
912       b->cond_string = xstrdup (arg);
913       b->condition_not_parsed = 0;
914
915       if (is_watchpoint (b))
916         {
917           struct watchpoint *w = (struct watchpoint *) b;
918
919           innermost_block = NULL;
920           arg = exp;
921           w->cond_exp = parse_exp_1 (&arg, 0, 0, 0);
922           if (*arg)
923             error (_("Junk at end of expression"));
924           w->cond_exp_valid_block = innermost_block;
925         }
926       else
927         {
928           struct bp_location *loc;
929
930           for (loc = b->loc; loc; loc = loc->next)
931             {
932               arg = exp;
933               loc->cond =
934                 parse_exp_1 (&arg, loc->address,
935                              block_for_pc (loc->address), 0);
936               if (*arg)
937                 error (_("Junk at end of expression"));
938             }
939         }
940     }
941   mark_breakpoint_modified (b);
942
943   breakpoints_changed ();
944   observer_notify_breakpoint_modified (b);
945 }
946
947 /* Completion for the "condition" command.  */
948
949 static VEC (char_ptr) *
950 condition_completer (struct cmd_list_element *cmd, char *text, char *word)
951 {
952   char *space;
953
954   text = skip_spaces (text);
955   space = skip_to_space (text);
956   if (*space == '\0')
957     {
958       int len;
959       struct breakpoint *b;
960       VEC (char_ptr) *result = NULL;
961
962       if (text[0] == '$')
963         {
964           /* We don't support completion of history indices.  */
965           if (isdigit (text[1]))
966             return NULL;
967           return complete_internalvar (&text[1]);
968         }
969
970       /* We're completing the breakpoint number.  */
971       len = strlen (text);
972
973       ALL_BREAKPOINTS (b)
974       {
975         int single = b->loc->next == NULL;
976         struct bp_location *loc;
977         int count = 1;
978
979         for (loc = b->loc; loc; loc = loc->next)
980           {
981             char location[50];
982
983             if (single)
984               sprintf (location, "%d", b->number);
985             else
986               sprintf (location, "%d.%d", b->number, count);
987
988             if (strncmp (location, text, len) == 0)
989               VEC_safe_push (char_ptr, result, xstrdup (location));
990
991             ++count;
992           }
993       }
994
995       return result;
996     }
997
998   /* We're completing the expression part.  */
999   text = skip_spaces (space);
1000   return expression_completer (cmd, text, word);
1001 }
1002
1003 /* condition N EXP -- set break condition of breakpoint N to EXP.  */
1004
1005 static void
1006 condition_command (char *arg, int from_tty)
1007 {
1008   struct breakpoint *b;
1009   char *p;
1010   int bnum;
1011
1012   if (arg == 0)
1013     error_no_arg (_("breakpoint number"));
1014
1015   p = arg;
1016   bnum = get_number (&p);
1017   if (bnum == 0)
1018     error (_("Bad breakpoint argument: '%s'"), arg);
1019
1020   ALL_BREAKPOINTS (b)
1021     if (b->number == bnum)
1022       {
1023         /* Check if this breakpoint has a Python object assigned to
1024            it, and if it has a definition of the "stop"
1025            method.  This method and conditions entered into GDB from
1026            the CLI are mutually exclusive.  */
1027         if (b->py_bp_object
1028             && gdbpy_breakpoint_has_py_cond (b->py_bp_object))
1029           error (_("Cannot set a condition where a Python 'stop' "
1030                    "method has been defined in the breakpoint."));
1031         set_breakpoint_condition (b, p, from_tty);
1032
1033         if (is_breakpoint (b))
1034           update_global_location_list (1);
1035
1036         return;
1037       }
1038
1039   error (_("No breakpoint number %d."), bnum);
1040 }
1041
1042 /* Check that COMMAND do not contain commands that are suitable
1043    only for tracepoints and not suitable for ordinary breakpoints.
1044    Throw if any such commands is found.  */
1045
1046 static void
1047 check_no_tracepoint_commands (struct command_line *commands)
1048 {
1049   struct command_line *c;
1050
1051   for (c = commands; c; c = c->next)
1052     {
1053       int i;
1054
1055       if (c->control_type == while_stepping_control)
1056         error (_("The 'while-stepping' command can "
1057                  "only be used for tracepoints"));
1058
1059       for (i = 0; i < c->body_count; ++i)
1060         check_no_tracepoint_commands ((c->body_list)[i]);
1061
1062       /* Not that command parsing removes leading whitespace and comment
1063          lines and also empty lines.  So, we only need to check for
1064          command directly.  */
1065       if (strstr (c->line, "collect ") == c->line)
1066         error (_("The 'collect' command can only be used for tracepoints"));
1067
1068       if (strstr (c->line, "teval ") == c->line)
1069         error (_("The 'teval' command can only be used for tracepoints"));
1070     }
1071 }
1072
1073 /* Encapsulate tests for different types of tracepoints.  */
1074
1075 static int
1076 is_tracepoint_type (enum bptype type)
1077 {
1078   return (type == bp_tracepoint
1079           || type == bp_fast_tracepoint
1080           || type == bp_static_tracepoint);
1081 }
1082
1083 int
1084 is_tracepoint (const struct breakpoint *b)
1085 {
1086   return is_tracepoint_type (b->type);
1087 }
1088
1089 /* A helper function that validates that COMMANDS are valid for a
1090    breakpoint.  This function will throw an exception if a problem is
1091    found.  */
1092
1093 static void
1094 validate_commands_for_breakpoint (struct breakpoint *b,
1095                                   struct command_line *commands)
1096 {
1097   if (is_tracepoint (b))
1098     {
1099       /* We need to verify that each top-level element of commands is
1100          valid for tracepoints, that there's at most one
1101          while-stepping element, and that while-stepping's body has
1102          valid tracing commands excluding nested while-stepping.  */
1103       struct command_line *c;
1104       struct command_line *while_stepping = 0;
1105       for (c = commands; c; c = c->next)
1106         {
1107           if (c->control_type == while_stepping_control)
1108             {
1109               if (b->type == bp_fast_tracepoint)
1110                 error (_("The 'while-stepping' command "
1111                          "cannot be used for fast tracepoint"));
1112               else if (b->type == bp_static_tracepoint)
1113                 error (_("The 'while-stepping' command "
1114                          "cannot be used for static tracepoint"));
1115
1116               if (while_stepping)
1117                 error (_("The 'while-stepping' command "
1118                          "can be used only once"));
1119               else
1120                 while_stepping = c;
1121             }
1122         }
1123       if (while_stepping)
1124         {
1125           struct command_line *c2;
1126
1127           gdb_assert (while_stepping->body_count == 1);
1128           c2 = while_stepping->body_list[0];
1129           for (; c2; c2 = c2->next)
1130             {
1131               if (c2->control_type == while_stepping_control)
1132                 error (_("The 'while-stepping' command cannot be nested"));
1133             }
1134         }
1135     }
1136   else
1137     {
1138       check_no_tracepoint_commands (commands);
1139     }
1140 }
1141
1142 /* Return a vector of all the static tracepoints set at ADDR.  The
1143    caller is responsible for releasing the vector.  */
1144
1145 VEC(breakpoint_p) *
1146 static_tracepoints_here (CORE_ADDR addr)
1147 {
1148   struct breakpoint *b;
1149   VEC(breakpoint_p) *found = 0;
1150   struct bp_location *loc;
1151
1152   ALL_BREAKPOINTS (b)
1153     if (b->type == bp_static_tracepoint)
1154       {
1155         for (loc = b->loc; loc; loc = loc->next)
1156           if (loc->address == addr)
1157             VEC_safe_push(breakpoint_p, found, b);
1158       }
1159
1160   return found;
1161 }
1162
1163 /* Set the command list of B to COMMANDS.  If breakpoint is tracepoint,
1164    validate that only allowed commands are included.  */
1165
1166 void
1167 breakpoint_set_commands (struct breakpoint *b, 
1168                          struct command_line *commands)
1169 {
1170   validate_commands_for_breakpoint (b, commands);
1171
1172   decref_counted_command_line (&b->commands);
1173   b->commands = alloc_counted_command_line (commands);
1174   breakpoints_changed ();
1175   observer_notify_breakpoint_modified (b);
1176 }
1177
1178 /* Set the internal `silent' flag on the breakpoint.  Note that this
1179    is not the same as the "silent" that may appear in the breakpoint's
1180    commands.  */
1181
1182 void
1183 breakpoint_set_silent (struct breakpoint *b, int silent)
1184 {
1185   int old_silent = b->silent;
1186
1187   b->silent = silent;
1188   if (old_silent != silent)
1189     observer_notify_breakpoint_modified (b);
1190 }
1191
1192 /* Set the thread for this breakpoint.  If THREAD is -1, make the
1193    breakpoint work for any thread.  */
1194
1195 void
1196 breakpoint_set_thread (struct breakpoint *b, int thread)
1197 {
1198   int old_thread = b->thread;
1199
1200   b->thread = thread;
1201   if (old_thread != thread)
1202     observer_notify_breakpoint_modified (b);
1203 }
1204
1205 /* Set the task for this breakpoint.  If TASK is 0, make the
1206    breakpoint work for any task.  */
1207
1208 void
1209 breakpoint_set_task (struct breakpoint *b, int task)
1210 {
1211   int old_task = b->task;
1212
1213   b->task = task;
1214   if (old_task != task)
1215     observer_notify_breakpoint_modified (b);
1216 }
1217
1218 void
1219 check_tracepoint_command (char *line, void *closure)
1220 {
1221   struct breakpoint *b = closure;
1222
1223   validate_actionline (&line, b);
1224 }
1225
1226 /* A structure used to pass information through
1227    map_breakpoint_numbers.  */
1228
1229 struct commands_info
1230 {
1231   /* True if the command was typed at a tty.  */
1232   int from_tty;
1233
1234   /* The breakpoint range spec.  */
1235   char *arg;
1236
1237   /* Non-NULL if the body of the commands are being read from this
1238      already-parsed command.  */
1239   struct command_line *control;
1240
1241   /* The command lines read from the user, or NULL if they have not
1242      yet been read.  */
1243   struct counted_command_line *cmd;
1244 };
1245
1246 /* A callback for map_breakpoint_numbers that sets the commands for
1247    commands_command.  */
1248
1249 static void
1250 do_map_commands_command (struct breakpoint *b, void *data)
1251 {
1252   struct commands_info *info = data;
1253
1254   if (info->cmd == NULL)
1255     {
1256       struct command_line *l;
1257
1258       if (info->control != NULL)
1259         l = copy_command_lines (info->control->body_list[0]);
1260       else
1261         {
1262           struct cleanup *old_chain;
1263           char *str;
1264
1265           str = xstrprintf (_("Type commands for breakpoint(s) "
1266                               "%s, one per line."),
1267                             info->arg);
1268
1269           old_chain = make_cleanup (xfree, str);
1270
1271           l = read_command_lines (str,
1272                                   info->from_tty, 1,
1273                                   (is_tracepoint (b)
1274                                    ? check_tracepoint_command : 0),
1275                                   b);
1276
1277           do_cleanups (old_chain);
1278         }
1279
1280       info->cmd = alloc_counted_command_line (l);
1281     }
1282
1283   /* If a breakpoint was on the list more than once, we don't need to
1284      do anything.  */
1285   if (b->commands != info->cmd)
1286     {
1287       validate_commands_for_breakpoint (b, info->cmd->commands);
1288       incref_counted_command_line (info->cmd);
1289       decref_counted_command_line (&b->commands);
1290       b->commands = info->cmd;
1291       breakpoints_changed ();
1292       observer_notify_breakpoint_modified (b);
1293     }
1294 }
1295
1296 static void
1297 commands_command_1 (char *arg, int from_tty, 
1298                     struct command_line *control)
1299 {
1300   struct cleanup *cleanups;
1301   struct commands_info info;
1302
1303   info.from_tty = from_tty;
1304   info.control = control;
1305   info.cmd = NULL;
1306   /* If we read command lines from the user, then `info' will hold an
1307      extra reference to the commands that we must clean up.  */
1308   cleanups = make_cleanup_decref_counted_command_line (&info.cmd);
1309
1310   if (arg == NULL || !*arg)
1311     {
1312       if (breakpoint_count - prev_breakpoint_count > 1)
1313         arg = xstrprintf ("%d-%d", prev_breakpoint_count + 1, 
1314                           breakpoint_count);
1315       else if (breakpoint_count > 0)
1316         arg = xstrprintf ("%d", breakpoint_count);
1317       else
1318         {
1319           /* So that we don't try to free the incoming non-NULL
1320              argument in the cleanup below.  Mapping breakpoint
1321              numbers will fail in this case.  */
1322           arg = NULL;
1323         }
1324     }
1325   else
1326     /* The command loop has some static state, so we need to preserve
1327        our argument.  */
1328     arg = xstrdup (arg);
1329
1330   if (arg != NULL)
1331     make_cleanup (xfree, arg);
1332
1333   info.arg = arg;
1334
1335   map_breakpoint_numbers (arg, do_map_commands_command, &info);
1336
1337   if (info.cmd == NULL)
1338     error (_("No breakpoints specified."));
1339
1340   do_cleanups (cleanups);
1341 }
1342
1343 static void
1344 commands_command (char *arg, int from_tty)
1345 {
1346   commands_command_1 (arg, from_tty, NULL);
1347 }
1348
1349 /* Like commands_command, but instead of reading the commands from
1350    input stream, takes them from an already parsed command structure.
1351
1352    This is used by cli-script.c to DTRT with breakpoint commands
1353    that are part of if and while bodies.  */
1354 enum command_control_type
1355 commands_from_control_command (char *arg, struct command_line *cmd)
1356 {
1357   commands_command_1 (arg, 0, cmd);
1358   return simple_control;
1359 }
1360
1361 /* Return non-zero if BL->TARGET_INFO contains valid information.  */
1362
1363 static int
1364 bp_location_has_shadow (struct bp_location *bl)
1365 {
1366   if (bl->loc_type != bp_loc_software_breakpoint)
1367     return 0;
1368   if (!bl->inserted)
1369     return 0;
1370   if (bl->target_info.shadow_len == 0)
1371     /* BL isn't valid, or doesn't shadow memory.  */
1372     return 0;
1373   return 1;
1374 }
1375
1376 /* Update BUF, which is LEN bytes read from the target address MEMADDR,
1377    by replacing any memory breakpoints with their shadowed contents.
1378
1379    If READBUF is not NULL, this buffer must not overlap with any of
1380    the breakpoint location's shadow_contents buffers.  Otherwise,
1381    a failed assertion internal error will be raised.
1382
1383    The range of shadowed area by each bp_location is:
1384      bl->address - bp_location_placed_address_before_address_max
1385      up to bl->address + bp_location_shadow_len_after_address_max
1386    The range we were requested to resolve shadows for is:
1387      memaddr ... memaddr + len
1388    Thus the safe cutoff boundaries for performance optimization are
1389      memaddr + len <= (bl->address
1390                        - bp_location_placed_address_before_address_max)
1391    and:
1392      bl->address + bp_location_shadow_len_after_address_max <= memaddr  */
1393
1394 void
1395 breakpoint_xfer_memory (gdb_byte *readbuf, gdb_byte *writebuf,
1396                         const gdb_byte *writebuf_org,
1397                         ULONGEST memaddr, LONGEST len)
1398 {
1399   /* Left boundary, right boundary and median element of our binary
1400      search.  */
1401   unsigned bc_l, bc_r, bc;
1402
1403   /* Find BC_L which is a leftmost element which may affect BUF
1404      content.  It is safe to report lower value but a failure to
1405      report higher one.  */
1406
1407   bc_l = 0;
1408   bc_r = bp_location_count;
1409   while (bc_l + 1 < bc_r)
1410     {
1411       struct bp_location *bl;
1412
1413       bc = (bc_l + bc_r) / 2;
1414       bl = bp_location[bc];
1415
1416       /* Check first BL->ADDRESS will not overflow due to the added
1417          constant.  Then advance the left boundary only if we are sure
1418          the BC element can in no way affect the BUF content (MEMADDR
1419          to MEMADDR + LEN range).
1420
1421          Use the BP_LOCATION_SHADOW_LEN_AFTER_ADDRESS_MAX safety
1422          offset so that we cannot miss a breakpoint with its shadow
1423          range tail still reaching MEMADDR.  */
1424
1425       if ((bl->address + bp_location_shadow_len_after_address_max
1426            >= bl->address)
1427           && (bl->address + bp_location_shadow_len_after_address_max
1428               <= memaddr))
1429         bc_l = bc;
1430       else
1431         bc_r = bc;
1432     }
1433
1434   /* Due to the binary search above, we need to make sure we pick the
1435      first location that's at BC_L's address.  E.g., if there are
1436      multiple locations at the same address, BC_L may end up pointing
1437      at a duplicate location, and miss the "master"/"inserted"
1438      location.  Say, given locations L1, L2 and L3 at addresses A and
1439      B:
1440
1441       L1@A, L2@A, L3@B, ...
1442
1443      BC_L could end up pointing at location L2, while the "master"
1444      location could be L1.  Since the `loc->inserted' flag is only set
1445      on "master" locations, we'd forget to restore the shadow of L1
1446      and L2.  */
1447   while (bc_l > 0
1448          && bp_location[bc_l]->address == bp_location[bc_l - 1]->address)
1449     bc_l--;
1450
1451   /* Now do full processing of the found relevant range of elements.  */
1452
1453   for (bc = bc_l; bc < bp_location_count; bc++)
1454   {
1455     struct bp_location *bl = bp_location[bc];
1456     CORE_ADDR bp_addr = 0;
1457     int bp_size = 0;
1458     int bptoffset = 0;
1459
1460     /* bp_location array has BL->OWNER always non-NULL.  */
1461     if (bl->owner->type == bp_none)
1462       warning (_("reading through apparently deleted breakpoint #%d?"),
1463                bl->owner->number);
1464
1465     /* Performance optimization: any further element can no longer affect BUF
1466        content.  */
1467
1468     if (bl->address >= bp_location_placed_address_before_address_max
1469         && memaddr + len <= (bl->address
1470                              - bp_location_placed_address_before_address_max))
1471       break;
1472
1473     if (!bp_location_has_shadow (bl))
1474       continue;
1475     if (!breakpoint_address_match (bl->target_info.placed_address_space, 0,
1476                                    current_program_space->aspace, 0))
1477       continue;
1478
1479     /* Addresses and length of the part of the breakpoint that
1480        we need to copy.  */
1481     bp_addr = bl->target_info.placed_address;
1482     bp_size = bl->target_info.shadow_len;
1483
1484     if (bp_addr + bp_size <= memaddr)
1485       /* The breakpoint is entirely before the chunk of memory we
1486          are reading.  */
1487       continue;
1488
1489     if (bp_addr >= memaddr + len)
1490       /* The breakpoint is entirely after the chunk of memory we are
1491          reading.  */
1492       continue;
1493
1494     /* Offset within shadow_contents.  */
1495     if (bp_addr < memaddr)
1496       {
1497         /* Only copy the second part of the breakpoint.  */
1498         bp_size -= memaddr - bp_addr;
1499         bptoffset = memaddr - bp_addr;
1500         bp_addr = memaddr;
1501       }
1502
1503     if (bp_addr + bp_size > memaddr + len)
1504       {
1505         /* Only copy the first part of the breakpoint.  */
1506         bp_size -= (bp_addr + bp_size) - (memaddr + len);
1507       }
1508
1509     if (readbuf != NULL)
1510       {
1511         /* Verify that the readbuf buffer does not overlap with
1512            the shadow_contents buffer.  */
1513         gdb_assert (bl->target_info.shadow_contents >= readbuf + len
1514                     || readbuf >= (bl->target_info.shadow_contents
1515                                    + bl->target_info.shadow_len));
1516
1517         /* Update the read buffer with this inserted breakpoint's
1518            shadow.  */
1519         memcpy (readbuf + bp_addr - memaddr,
1520                 bl->target_info.shadow_contents + bptoffset, bp_size);
1521       }
1522     else
1523       {
1524         struct gdbarch *gdbarch = bl->gdbarch;
1525         const unsigned char *bp;
1526         CORE_ADDR placed_address = bl->target_info.placed_address;
1527         unsigned placed_size = bl->target_info.placed_size;
1528
1529         /* Update the shadow with what we want to write to memory.  */
1530         memcpy (bl->target_info.shadow_contents + bptoffset,
1531                 writebuf_org + bp_addr - memaddr, bp_size);
1532
1533         /* Determine appropriate breakpoint contents and size for this
1534            address.  */
1535         bp = gdbarch_breakpoint_from_pc (gdbarch, &placed_address, &placed_size);
1536
1537         /* Update the final write buffer with this inserted
1538            breakpoint's INSN.  */
1539         memcpy (writebuf + bp_addr - memaddr, bp + bptoffset, bp_size);
1540       }
1541   }
1542 }
1543 \f
1544
1545 /* Return true if BPT is either a software breakpoint or a hardware
1546    breakpoint.  */
1547
1548 int
1549 is_breakpoint (const struct breakpoint *bpt)
1550 {
1551   return (bpt->type == bp_breakpoint
1552           || bpt->type == bp_hardware_breakpoint
1553           || bpt->type == bp_dprintf);
1554 }
1555
1556 /* Return true if BPT is of any hardware watchpoint kind.  */
1557
1558 static int
1559 is_hardware_watchpoint (const struct breakpoint *bpt)
1560 {
1561   return (bpt->type == bp_hardware_watchpoint
1562           || bpt->type == bp_read_watchpoint
1563           || bpt->type == bp_access_watchpoint);
1564 }
1565
1566 /* Return true if BPT is of any watchpoint kind, hardware or
1567    software.  */
1568
1569 int
1570 is_watchpoint (const struct breakpoint *bpt)
1571 {
1572   return (is_hardware_watchpoint (bpt)
1573           || bpt->type == bp_watchpoint);
1574 }
1575
1576 /* Returns true if the current thread and its running state are safe
1577    to evaluate or update watchpoint B.  Watchpoints on local
1578    expressions need to be evaluated in the context of the thread that
1579    was current when the watchpoint was created, and, that thread needs
1580    to be stopped to be able to select the correct frame context.
1581    Watchpoints on global expressions can be evaluated on any thread,
1582    and in any state.  It is presently left to the target allowing
1583    memory accesses when threads are running.  */
1584
1585 static int
1586 watchpoint_in_thread_scope (struct watchpoint *b)
1587 {
1588   return (b->base.pspace == current_program_space
1589           && (ptid_equal (b->watchpoint_thread, null_ptid)
1590               || (ptid_equal (inferior_ptid, b->watchpoint_thread)
1591                   && !is_executing (inferior_ptid))));
1592 }
1593
1594 /* Set watchpoint B to disp_del_at_next_stop, even including its possible
1595    associated bp_watchpoint_scope breakpoint.  */
1596
1597 static void
1598 watchpoint_del_at_next_stop (struct watchpoint *w)
1599 {
1600   struct breakpoint *b = &w->base;
1601
1602   if (b->related_breakpoint != b)
1603     {
1604       gdb_assert (b->related_breakpoint->type == bp_watchpoint_scope);
1605       gdb_assert (b->related_breakpoint->related_breakpoint == b);
1606       b->related_breakpoint->disposition = disp_del_at_next_stop;
1607       b->related_breakpoint->related_breakpoint = b->related_breakpoint;
1608       b->related_breakpoint = b;
1609     }
1610   b->disposition = disp_del_at_next_stop;
1611 }
1612
1613 /* Assuming that B is a watchpoint:
1614    - Reparse watchpoint expression, if REPARSE is non-zero
1615    - Evaluate expression and store the result in B->val
1616    - Evaluate the condition if there is one, and store the result
1617      in b->loc->cond.
1618    - Update the list of values that must be watched in B->loc.
1619
1620    If the watchpoint disposition is disp_del_at_next_stop, then do
1621    nothing.  If this is local watchpoint that is out of scope, delete
1622    it.
1623
1624    Even with `set breakpoint always-inserted on' the watchpoints are
1625    removed + inserted on each stop here.  Normal breakpoints must
1626    never be removed because they might be missed by a running thread
1627    when debugging in non-stop mode.  On the other hand, hardware
1628    watchpoints (is_hardware_watchpoint; processed here) are specific
1629    to each LWP since they are stored in each LWP's hardware debug
1630    registers.  Therefore, such LWP must be stopped first in order to
1631    be able to modify its hardware watchpoints.
1632
1633    Hardware watchpoints must be reset exactly once after being
1634    presented to the user.  It cannot be done sooner, because it would
1635    reset the data used to present the watchpoint hit to the user.  And
1636    it must not be done later because it could display the same single
1637    watchpoint hit during multiple GDB stops.  Note that the latter is
1638    relevant only to the hardware watchpoint types bp_read_watchpoint
1639    and bp_access_watchpoint.  False hit by bp_hardware_watchpoint is
1640    not user-visible - its hit is suppressed if the memory content has
1641    not changed.
1642
1643    The following constraints influence the location where we can reset
1644    hardware watchpoints:
1645
1646    * target_stopped_by_watchpoint and target_stopped_data_address are
1647      called several times when GDB stops.
1648
1649    [linux] 
1650    * Multiple hardware watchpoints can be hit at the same time,
1651      causing GDB to stop.  GDB only presents one hardware watchpoint
1652      hit at a time as the reason for stopping, and all the other hits
1653      are presented later, one after the other, each time the user
1654      requests the execution to be resumed.  Execution is not resumed
1655      for the threads still having pending hit event stored in
1656      LWP_INFO->STATUS.  While the watchpoint is already removed from
1657      the inferior on the first stop the thread hit event is kept being
1658      reported from its cached value by linux_nat_stopped_data_address
1659      until the real thread resume happens after the watchpoint gets
1660      presented and thus its LWP_INFO->STATUS gets reset.
1661
1662    Therefore the hardware watchpoint hit can get safely reset on the
1663    watchpoint removal from inferior.  */
1664
1665 static void
1666 update_watchpoint (struct watchpoint *b, int reparse)
1667 {
1668   int within_current_scope;
1669   struct frame_id saved_frame_id;
1670   int frame_saved;
1671
1672   /* If this is a local watchpoint, we only want to check if the
1673      watchpoint frame is in scope if the current thread is the thread
1674      that was used to create the watchpoint.  */
1675   if (!watchpoint_in_thread_scope (b))
1676     return;
1677
1678   if (b->base.disposition == disp_del_at_next_stop)
1679     return;
1680  
1681   frame_saved = 0;
1682
1683   /* Determine if the watchpoint is within scope.  */
1684   if (b->exp_valid_block == NULL)
1685     within_current_scope = 1;
1686   else
1687     {
1688       struct frame_info *fi = get_current_frame ();
1689       struct gdbarch *frame_arch = get_frame_arch (fi);
1690       CORE_ADDR frame_pc = get_frame_pc (fi);
1691
1692       /* If we're in a function epilogue, unwinding may not work
1693          properly, so do not attempt to recreate locations at this
1694          point.  See similar comments in watchpoint_check.  */
1695       if (gdbarch_in_function_epilogue_p (frame_arch, frame_pc))
1696         return;
1697
1698       /* Save the current frame's ID so we can restore it after
1699          evaluating the watchpoint expression on its own frame.  */
1700       /* FIXME drow/2003-09-09: It would be nice if evaluate_expression
1701          took a frame parameter, so that we didn't have to change the
1702          selected frame.  */
1703       frame_saved = 1;
1704       saved_frame_id = get_frame_id (get_selected_frame (NULL));
1705
1706       fi = frame_find_by_id (b->watchpoint_frame);
1707       within_current_scope = (fi != NULL);
1708       if (within_current_scope)
1709         select_frame (fi);
1710     }
1711
1712   /* We don't free locations.  They are stored in the bp_location array
1713      and update_global_location_list will eventually delete them and
1714      remove breakpoints if needed.  */
1715   b->base.loc = NULL;
1716
1717   if (within_current_scope && reparse)
1718     {
1719       char *s;
1720
1721       if (b->exp)
1722         {
1723           xfree (b->exp);
1724           b->exp = NULL;
1725         }
1726       s = b->exp_string_reparse ? b->exp_string_reparse : b->exp_string;
1727       b->exp = parse_exp_1 (&s, 0, b->exp_valid_block, 0);
1728       /* If the meaning of expression itself changed, the old value is
1729          no longer relevant.  We don't want to report a watchpoint hit
1730          to the user when the old value and the new value may actually
1731          be completely different objects.  */
1732       value_free (b->val);
1733       b->val = NULL;
1734       b->val_valid = 0;
1735
1736       /* Note that unlike with breakpoints, the watchpoint's condition
1737          expression is stored in the breakpoint object, not in the
1738          locations (re)created below.  */
1739       if (b->base.cond_string != NULL)
1740         {
1741           if (b->cond_exp != NULL)
1742             {
1743               xfree (b->cond_exp);
1744               b->cond_exp = NULL;
1745             }
1746
1747           s = b->base.cond_string;
1748           b->cond_exp = parse_exp_1 (&s, 0, b->cond_exp_valid_block, 0);
1749         }
1750     }
1751
1752   /* If we failed to parse the expression, for example because
1753      it refers to a global variable in a not-yet-loaded shared library,
1754      don't try to insert watchpoint.  We don't automatically delete
1755      such watchpoint, though, since failure to parse expression
1756      is different from out-of-scope watchpoint.  */
1757   if ( !target_has_execution)
1758     {
1759       /* Without execution, memory can't change.  No use to try and
1760          set watchpoint locations.  The watchpoint will be reset when
1761          the target gains execution, through breakpoint_re_set.  */
1762     }
1763   else if (within_current_scope && b->exp)
1764     {
1765       int pc = 0;
1766       struct value *val_chain, *v, *result, *next;
1767       struct program_space *frame_pspace;
1768
1769       fetch_subexp_value (b->exp, &pc, &v, &result, &val_chain);
1770
1771       /* Avoid setting b->val if it's already set.  The meaning of
1772          b->val is 'the last value' user saw, and we should update
1773          it only if we reported that last value to user.  As it
1774          happens, the code that reports it updates b->val directly.
1775          We don't keep track of the memory value for masked
1776          watchpoints.  */
1777       if (!b->val_valid && !is_masked_watchpoint (&b->base))
1778         {
1779           b->val = v;
1780           b->val_valid = 1;
1781         }
1782
1783       frame_pspace = get_frame_program_space (get_selected_frame (NULL));
1784
1785       /* Look at each value on the value chain.  */
1786       for (v = val_chain; v; v = value_next (v))
1787         {
1788           /* If it's a memory location, and GDB actually needed
1789              its contents to evaluate the expression, then we
1790              must watch it.  If the first value returned is
1791              still lazy, that means an error occurred reading it;
1792              watch it anyway in case it becomes readable.  */
1793           if (VALUE_LVAL (v) == lval_memory
1794               && (v == val_chain || ! value_lazy (v)))
1795             {
1796               struct type *vtype = check_typedef (value_type (v));
1797
1798               /* We only watch structs and arrays if user asked
1799                  for it explicitly, never if they just happen to
1800                  appear in the middle of some value chain.  */
1801               if (v == result
1802                   || (TYPE_CODE (vtype) != TYPE_CODE_STRUCT
1803                       && TYPE_CODE (vtype) != TYPE_CODE_ARRAY))
1804                 {
1805                   CORE_ADDR addr;
1806                   int len, type;
1807                   struct bp_location *loc, **tmp;
1808
1809                   addr = value_address (v);
1810                   len = TYPE_LENGTH (value_type (v));
1811                   type = hw_write;
1812                   if (b->base.type == bp_read_watchpoint)
1813                     type = hw_read;
1814                   else if (b->base.type == bp_access_watchpoint)
1815                     type = hw_access;
1816
1817                   loc = allocate_bp_location (&b->base);
1818                   for (tmp = &(b->base.loc); *tmp != NULL; tmp = &((*tmp)->next))
1819                     ;
1820                   *tmp = loc;
1821                   loc->gdbarch = get_type_arch (value_type (v));
1822
1823                   loc->pspace = frame_pspace;
1824                   loc->address = addr;
1825                   loc->length = len;
1826                   loc->watchpoint_type = type;
1827                 }
1828             }
1829         }
1830
1831       /* Change the type of breakpoint between hardware assisted or
1832          an ordinary watchpoint depending on the hardware support
1833          and free hardware slots.  REPARSE is set when the inferior
1834          is started.  */
1835       if (reparse)
1836         {
1837           int reg_cnt;
1838           enum bp_loc_type loc_type;
1839           struct bp_location *bl;
1840
1841           reg_cnt = can_use_hardware_watchpoint (val_chain);
1842
1843           if (reg_cnt)
1844             {
1845               int i, target_resources_ok, other_type_used;
1846               enum bptype type;
1847
1848               /* Use an exact watchpoint when there's only one memory region to be
1849                  watched, and only one debug register is needed to watch it.  */
1850               b->exact = target_exact_watchpoints && reg_cnt == 1;
1851
1852               /* We need to determine how many resources are already
1853                  used for all other hardware watchpoints plus this one
1854                  to see if we still have enough resources to also fit
1855                  this watchpoint in as well.  */
1856
1857               /* If this is a software watchpoint, we try to turn it
1858                  to a hardware one -- count resources as if B was of
1859                  hardware watchpoint type.  */
1860               type = b->base.type;
1861               if (type == bp_watchpoint)
1862                 type = bp_hardware_watchpoint;
1863
1864               /* This watchpoint may or may not have been placed on
1865                  the list yet at this point (it won't be in the list
1866                  if we're trying to create it for the first time,
1867                  through watch_command), so always account for it
1868                  manually.  */
1869
1870               /* Count resources used by all watchpoints except B.  */
1871               i = hw_watchpoint_used_count_others (&b->base, type, &other_type_used);
1872
1873               /* Add in the resources needed for B.  */
1874               i += hw_watchpoint_use_count (&b->base);
1875
1876               target_resources_ok
1877                 = target_can_use_hardware_watchpoint (type, i, other_type_used);
1878               if (target_resources_ok <= 0)
1879                 {
1880                   int sw_mode = b->base.ops->works_in_software_mode (&b->base);
1881
1882                   if (target_resources_ok == 0 && !sw_mode)
1883                     error (_("Target does not support this type of "
1884                              "hardware watchpoint."));
1885                   else if (target_resources_ok < 0 && !sw_mode)
1886                     error (_("There are not enough available hardware "
1887                              "resources for this watchpoint."));
1888
1889                   /* Downgrade to software watchpoint.  */
1890                   b->base.type = bp_watchpoint;
1891                 }
1892               else
1893                 {
1894                   /* If this was a software watchpoint, we've just
1895                      found we have enough resources to turn it to a
1896                      hardware watchpoint.  Otherwise, this is a
1897                      nop.  */
1898                   b->base.type = type;
1899                 }
1900             }
1901           else if (!b->base.ops->works_in_software_mode (&b->base))
1902             error (_("Expression cannot be implemented with "
1903                      "read/access watchpoint."));
1904           else
1905             b->base.type = bp_watchpoint;
1906
1907           loc_type = (b->base.type == bp_watchpoint? bp_loc_other
1908                       : bp_loc_hardware_watchpoint);
1909           for (bl = b->base.loc; bl; bl = bl->next)
1910             bl->loc_type = loc_type;
1911         }
1912
1913       for (v = val_chain; v; v = next)
1914         {
1915           next = value_next (v);
1916           if (v != b->val)
1917             value_free (v);
1918         }
1919
1920       /* If a software watchpoint is not watching any memory, then the
1921          above left it without any location set up.  But,
1922          bpstat_stop_status requires a location to be able to report
1923          stops, so make sure there's at least a dummy one.  */
1924       if (b->base.type == bp_watchpoint && b->base.loc == NULL)
1925         {
1926           struct breakpoint *base = &b->base;
1927           base->loc = allocate_bp_location (base);
1928           base->loc->pspace = frame_pspace;
1929           base->loc->address = -1;
1930           base->loc->length = -1;
1931           base->loc->watchpoint_type = -1;
1932         }
1933     }
1934   else if (!within_current_scope)
1935     {
1936       printf_filtered (_("\
1937 Watchpoint %d deleted because the program has left the block\n\
1938 in which its expression is valid.\n"),
1939                        b->base.number);
1940       watchpoint_del_at_next_stop (b);
1941     }
1942
1943   /* Restore the selected frame.  */
1944   if (frame_saved)
1945     select_frame (frame_find_by_id (saved_frame_id));
1946 }
1947
1948
1949 /* Returns 1 iff breakpoint location should be
1950    inserted in the inferior.  We don't differentiate the type of BL's owner
1951    (breakpoint vs. tracepoint), although insert_location in tracepoint's
1952    breakpoint_ops is not defined, because in insert_bp_location,
1953    tracepoint's insert_location will not be called.  */
1954 static int
1955 should_be_inserted (struct bp_location *bl)
1956 {
1957   if (bl->owner == NULL || !breakpoint_enabled (bl->owner))
1958     return 0;
1959
1960   if (bl->owner->disposition == disp_del_at_next_stop)
1961     return 0;
1962
1963   if (!bl->enabled || bl->shlib_disabled || bl->duplicate)
1964     return 0;
1965
1966   if (user_breakpoint_p (bl->owner) && bl->pspace->executing_startup)
1967     return 0;
1968
1969   /* This is set for example, when we're attached to the parent of a
1970      vfork, and have detached from the child.  The child is running
1971      free, and we expect it to do an exec or exit, at which point the
1972      OS makes the parent schedulable again (and the target reports
1973      that the vfork is done).  Until the child is done with the shared
1974      memory region, do not insert breakpoints in the parent, otherwise
1975      the child could still trip on the parent's breakpoints.  Since
1976      the parent is blocked anyway, it won't miss any breakpoint.  */
1977   if (bl->pspace->breakpoints_not_allowed)
1978     return 0;
1979
1980   return 1;
1981 }
1982
1983 /* Same as should_be_inserted but does the check assuming
1984    that the location is not duplicated.  */
1985
1986 static int
1987 unduplicated_should_be_inserted (struct bp_location *bl)
1988 {
1989   int result;
1990   const int save_duplicate = bl->duplicate;
1991
1992   bl->duplicate = 0;
1993   result = should_be_inserted (bl);
1994   bl->duplicate = save_duplicate;
1995   return result;
1996 }
1997
1998 /* Parses a conditional described by an expression COND into an
1999    agent expression bytecode suitable for evaluation
2000    by the bytecode interpreter.  Return NULL if there was
2001    any error during parsing.  */
2002
2003 static struct agent_expr *
2004 parse_cond_to_aexpr (CORE_ADDR scope, struct expression *cond)
2005 {
2006   struct agent_expr *aexpr = NULL;
2007   struct cleanup *old_chain = NULL;
2008   volatile struct gdb_exception ex;
2009
2010   if (!cond)
2011     return NULL;
2012
2013   /* We don't want to stop processing, so catch any errors
2014      that may show up.  */
2015   TRY_CATCH (ex, RETURN_MASK_ERROR)
2016     {
2017       aexpr = gen_eval_for_expr (scope, cond);
2018     }
2019
2020   if (ex.reason < 0)
2021     {
2022       /* If we got here, it means the condition could not be parsed to a valid
2023          bytecode expression and thus can't be evaluated on the target's side.
2024          It's no use iterating through the conditions.  */
2025       return NULL;
2026     }
2027
2028   /* We have a valid agent expression.  */
2029   return aexpr;
2030 }
2031
2032 /* Based on location BL, create a list of breakpoint conditions to be
2033    passed on to the target.  If we have duplicated locations with different
2034    conditions, we will add such conditions to the list.  The idea is that the
2035    target will evaluate the list of conditions and will only notify GDB when
2036    one of them is true.  */
2037
2038 static void
2039 build_target_condition_list (struct bp_location *bl)
2040 {
2041   struct bp_location **locp = NULL, **loc2p;
2042   int null_condition_or_parse_error = 0;
2043   int modified = bl->needs_update;
2044   struct bp_location *loc;
2045
2046   /* This is only meaningful if the target is
2047      evaluating conditions and if the user has
2048      opted for condition evaluation on the target's
2049      side.  */
2050   if (gdb_evaluates_breakpoint_condition_p ()
2051       || !target_supports_evaluation_of_breakpoint_conditions ())
2052     return;
2053
2054   /* Do a first pass to check for locations with no assigned
2055      conditions or conditions that fail to parse to a valid agent expression
2056      bytecode.  If any of these happen, then it's no use to send conditions
2057      to the target since this location will always trigger and generate a
2058      response back to GDB.  */
2059   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2060     {
2061       loc = (*loc2p);
2062       if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2063         {
2064           if (modified)
2065             {
2066               struct agent_expr *aexpr;
2067
2068               /* Re-parse the conditions since something changed.  In that
2069                  case we already freed the condition bytecodes (see
2070                  force_breakpoint_reinsertion).  We just
2071                  need to parse the condition to bytecodes again.  */
2072               aexpr = parse_cond_to_aexpr (bl->address, loc->cond);
2073               loc->cond_bytecode = aexpr;
2074
2075               /* Check if we managed to parse the conditional expression
2076                  correctly.  If not, we will not send this condition
2077                  to the target.  */
2078               if (aexpr)
2079                 continue;
2080             }
2081
2082           /* If we have a NULL bytecode expression, it means something
2083              went wrong or we have a null condition expression.  */
2084           if (!loc->cond_bytecode)
2085             {
2086               null_condition_or_parse_error = 1;
2087               break;
2088             }
2089         }
2090     }
2091
2092   /* If any of these happened, it means we will have to evaluate the conditions
2093      for the location's address on gdb's side.  It is no use keeping bytecodes
2094      for all the other duplicate locations, thus we free all of them here.
2095
2096      This is so we have a finer control over which locations' conditions are
2097      being evaluated by GDB or the remote stub.  */
2098   if (null_condition_or_parse_error)
2099     {
2100       ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2101         {
2102           loc = (*loc2p);
2103           if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2104             {
2105               /* Only go as far as the first NULL bytecode is
2106                  located.  */
2107               if (!loc->cond_bytecode)
2108                 return;
2109
2110               free_agent_expr (loc->cond_bytecode);
2111               loc->cond_bytecode = NULL;
2112             }
2113         }
2114     }
2115
2116   /* No NULL conditions or failed bytecode generation.  Build a condition list
2117      for this location's address.  */
2118   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2119     {
2120       loc = (*loc2p);
2121       if (loc->cond
2122           && is_breakpoint (loc->owner)
2123           && loc->pspace->num == bl->pspace->num
2124           && loc->owner->enable_state == bp_enabled
2125           && loc->enabled)
2126         /* Add the condition to the vector.  This will be used later to send the
2127            conditions to the target.  */
2128         VEC_safe_push (agent_expr_p, bl->target_info.conditions,
2129                        loc->cond_bytecode);
2130     }
2131
2132   return;
2133 }
2134
2135 /* Insert a low-level "breakpoint" of some type.  BL is the breakpoint
2136    location.  Any error messages are printed to TMP_ERROR_STREAM; and
2137    DISABLED_BREAKS, and HW_BREAKPOINT_ERROR are used to report problems.
2138    Returns 0 for success, 1 if the bp_location type is not supported or
2139    -1 for failure.
2140
2141    NOTE drow/2003-09-09: This routine could be broken down to an
2142    object-style method for each breakpoint or catchpoint type.  */
2143 static int
2144 insert_bp_location (struct bp_location *bl,
2145                     struct ui_file *tmp_error_stream,
2146                     int *disabled_breaks,
2147                     int *hw_breakpoint_error)
2148 {
2149   int val = 0;
2150
2151   if (!should_be_inserted (bl) || (bl->inserted && !bl->needs_update))
2152     return 0;
2153
2154   /* Note we don't initialize bl->target_info, as that wipes out
2155      the breakpoint location's shadow_contents if the breakpoint
2156      is still inserted at that location.  This in turn breaks
2157      target_read_memory which depends on these buffers when
2158      a memory read is requested at the breakpoint location:
2159      Once the target_info has been wiped, we fail to see that
2160      we have a breakpoint inserted at that address and thus
2161      read the breakpoint instead of returning the data saved in
2162      the breakpoint location's shadow contents.  */
2163   bl->target_info.placed_address = bl->address;
2164   bl->target_info.placed_address_space = bl->pspace->aspace;
2165   bl->target_info.length = bl->length;
2166
2167   /* When working with target-side conditions, we must pass all the conditions
2168      for the same breakpoint address down to the target since GDB will not
2169      insert those locations.  With a list of breakpoint conditions, the target
2170      can decide when to stop and notify GDB.  */
2171
2172   if (is_breakpoint (bl->owner))
2173     {
2174       build_target_condition_list (bl);
2175       /* Reset the condition modification marker.  */
2176       bl->needs_update = 0;
2177     }
2178
2179   if (bl->loc_type == bp_loc_software_breakpoint
2180       || bl->loc_type == bp_loc_hardware_breakpoint)
2181     {
2182       if (bl->owner->type != bp_hardware_breakpoint)
2183         {
2184           /* If the explicitly specified breakpoint type
2185              is not hardware breakpoint, check the memory map to see
2186              if the breakpoint address is in read only memory or not.
2187
2188              Two important cases are:
2189              - location type is not hardware breakpoint, memory
2190              is readonly.  We change the type of the location to
2191              hardware breakpoint.
2192              - location type is hardware breakpoint, memory is
2193              read-write.  This means we've previously made the
2194              location hardware one, but then the memory map changed,
2195              so we undo.
2196              
2197              When breakpoints are removed, remove_breakpoints will use
2198              location types we've just set here, the only possible
2199              problem is that memory map has changed during running
2200              program, but it's not going to work anyway with current
2201              gdb.  */
2202           struct mem_region *mr 
2203             = lookup_mem_region (bl->target_info.placed_address);
2204           
2205           if (mr)
2206             {
2207               if (automatic_hardware_breakpoints)
2208                 {
2209                   enum bp_loc_type new_type;
2210                   
2211                   if (mr->attrib.mode != MEM_RW)
2212                     new_type = bp_loc_hardware_breakpoint;
2213                   else 
2214                     new_type = bp_loc_software_breakpoint;
2215                   
2216                   if (new_type != bl->loc_type)
2217                     {
2218                       static int said = 0;
2219
2220                       bl->loc_type = new_type;
2221                       if (!said)
2222                         {
2223                           fprintf_filtered (gdb_stdout,
2224                                             _("Note: automatically using "
2225                                               "hardware breakpoints for "
2226                                               "read-only addresses.\n"));
2227                           said = 1;
2228                         }
2229                     }
2230                 }
2231               else if (bl->loc_type == bp_loc_software_breakpoint
2232                        && mr->attrib.mode != MEM_RW)        
2233                 warning (_("cannot set software breakpoint "
2234                            "at readonly address %s"),
2235                          paddress (bl->gdbarch, bl->address));
2236             }
2237         }
2238         
2239       /* First check to see if we have to handle an overlay.  */
2240       if (overlay_debugging == ovly_off
2241           || bl->section == NULL
2242           || !(section_is_overlay (bl->section)))
2243         {
2244           /* No overlay handling: just set the breakpoint.  */
2245
2246           val = bl->owner->ops->insert_location (bl);
2247         }
2248       else
2249         {
2250           /* This breakpoint is in an overlay section.
2251              Shall we set a breakpoint at the LMA?  */
2252           if (!overlay_events_enabled)
2253             {
2254               /* Yes -- overlay event support is not active, 
2255                  so we must try to set a breakpoint at the LMA.
2256                  This will not work for a hardware breakpoint.  */
2257               if (bl->loc_type == bp_loc_hardware_breakpoint)
2258                 warning (_("hardware breakpoint %d not supported in overlay!"),
2259                          bl->owner->number);
2260               else
2261                 {
2262                   CORE_ADDR addr = overlay_unmapped_address (bl->address,
2263                                                              bl->section);
2264                   /* Set a software (trap) breakpoint at the LMA.  */
2265                   bl->overlay_target_info = bl->target_info;
2266                   bl->overlay_target_info.placed_address = addr;
2267                   val = target_insert_breakpoint (bl->gdbarch,
2268                                                   &bl->overlay_target_info);
2269                   if (val != 0)
2270                     fprintf_unfiltered (tmp_error_stream,
2271                                         "Overlay breakpoint %d "
2272                                         "failed: in ROM?\n",
2273                                         bl->owner->number);
2274                 }
2275             }
2276           /* Shall we set a breakpoint at the VMA? */
2277           if (section_is_mapped (bl->section))
2278             {
2279               /* Yes.  This overlay section is mapped into memory.  */
2280               val = bl->owner->ops->insert_location (bl);
2281             }
2282           else
2283             {
2284               /* No.  This breakpoint will not be inserted.  
2285                  No error, but do not mark the bp as 'inserted'.  */
2286               return 0;
2287             }
2288         }
2289
2290       if (val)
2291         {
2292           /* Can't set the breakpoint.  */
2293           if (solib_name_from_address (bl->pspace, bl->address))
2294             {
2295               /* See also: disable_breakpoints_in_shlibs.  */
2296               val = 0;
2297               bl->shlib_disabled = 1;
2298               observer_notify_breakpoint_modified (bl->owner);
2299               if (!*disabled_breaks)
2300                 {
2301                   fprintf_unfiltered (tmp_error_stream, 
2302                                       "Cannot insert breakpoint %d.\n", 
2303                                       bl->owner->number);
2304                   fprintf_unfiltered (tmp_error_stream, 
2305                                       "Temporarily disabling shared "
2306                                       "library breakpoints:\n");
2307                 }
2308               *disabled_breaks = 1;
2309               fprintf_unfiltered (tmp_error_stream,
2310                                   "breakpoint #%d\n", bl->owner->number);
2311             }
2312           else
2313             {
2314               if (bl->loc_type == bp_loc_hardware_breakpoint)
2315                 {
2316                   *hw_breakpoint_error = 1;
2317                   fprintf_unfiltered (tmp_error_stream,
2318                                       "Cannot insert hardware "
2319                                       "breakpoint %d.\n",
2320                                       bl->owner->number);
2321                 }
2322               else
2323                 {
2324                   fprintf_unfiltered (tmp_error_stream, 
2325                                       "Cannot insert breakpoint %d.\n", 
2326                                       bl->owner->number);
2327                   fprintf_filtered (tmp_error_stream, 
2328                                     "Error accessing memory address ");
2329                   fputs_filtered (paddress (bl->gdbarch, bl->address),
2330                                   tmp_error_stream);
2331                   fprintf_filtered (tmp_error_stream, ": %s.\n",
2332                                     safe_strerror (val));
2333                 }
2334
2335             }
2336         }
2337       else
2338         bl->inserted = 1;
2339
2340       return val;
2341     }
2342
2343   else if (bl->loc_type == bp_loc_hardware_watchpoint
2344            /* NOTE drow/2003-09-08: This state only exists for removing
2345               watchpoints.  It's not clear that it's necessary...  */
2346            && bl->owner->disposition != disp_del_at_next_stop)
2347     {
2348       gdb_assert (bl->owner->ops != NULL
2349                   && bl->owner->ops->insert_location != NULL);
2350
2351       val = bl->owner->ops->insert_location (bl);
2352
2353       /* If trying to set a read-watchpoint, and it turns out it's not
2354          supported, try emulating one with an access watchpoint.  */
2355       if (val == 1 && bl->watchpoint_type == hw_read)
2356         {
2357           struct bp_location *loc, **loc_temp;
2358
2359           /* But don't try to insert it, if there's already another
2360              hw_access location that would be considered a duplicate
2361              of this one.  */
2362           ALL_BP_LOCATIONS (loc, loc_temp)
2363             if (loc != bl
2364                 && loc->watchpoint_type == hw_access
2365                 && watchpoint_locations_match (bl, loc))
2366               {
2367                 bl->duplicate = 1;
2368                 bl->inserted = 1;
2369                 bl->target_info = loc->target_info;
2370                 bl->watchpoint_type = hw_access;
2371                 val = 0;
2372                 break;
2373               }
2374
2375           if (val == 1)
2376             {
2377               bl->watchpoint_type = hw_access;
2378               val = bl->owner->ops->insert_location (bl);
2379
2380               if (val)
2381                 /* Back to the original value.  */
2382                 bl->watchpoint_type = hw_read;
2383             }
2384         }
2385
2386       bl->inserted = (val == 0);
2387     }
2388
2389   else if (bl->owner->type == bp_catchpoint)
2390     {
2391       gdb_assert (bl->owner->ops != NULL
2392                   && bl->owner->ops->insert_location != NULL);
2393
2394       val = bl->owner->ops->insert_location (bl);
2395       if (val)
2396         {
2397           bl->owner->enable_state = bp_disabled;
2398
2399           if (val == 1)
2400             warning (_("\
2401 Error inserting catchpoint %d: Your system does not support this type\n\
2402 of catchpoint."), bl->owner->number);
2403           else
2404             warning (_("Error inserting catchpoint %d."), bl->owner->number);
2405         }
2406
2407       bl->inserted = (val == 0);
2408
2409       /* We've already printed an error message if there was a problem
2410          inserting this catchpoint, and we've disabled the catchpoint,
2411          so just return success.  */
2412       return 0;
2413     }
2414
2415   return 0;
2416 }
2417
2418 /* This function is called when program space PSPACE is about to be
2419    deleted.  It takes care of updating breakpoints to not reference
2420    PSPACE anymore.  */
2421
2422 void
2423 breakpoint_program_space_exit (struct program_space *pspace)
2424 {
2425   struct breakpoint *b, *b_temp;
2426   struct bp_location *loc, **loc_temp;
2427
2428   /* Remove any breakpoint that was set through this program space.  */
2429   ALL_BREAKPOINTS_SAFE (b, b_temp)
2430     {
2431       if (b->pspace == pspace)
2432         delete_breakpoint (b);
2433     }
2434
2435   /* Breakpoints set through other program spaces could have locations
2436      bound to PSPACE as well.  Remove those.  */
2437   ALL_BP_LOCATIONS (loc, loc_temp)
2438     {
2439       struct bp_location *tmp;
2440
2441       if (loc->pspace == pspace)
2442         {
2443           /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
2444           if (loc->owner->loc == loc)
2445             loc->owner->loc = loc->next;
2446           else
2447             for (tmp = loc->owner->loc; tmp->next != NULL; tmp = tmp->next)
2448               if (tmp->next == loc)
2449                 {
2450                   tmp->next = loc->next;
2451                   break;
2452                 }
2453         }
2454     }
2455
2456   /* Now update the global location list to permanently delete the
2457      removed locations above.  */
2458   update_global_location_list (0);
2459 }
2460
2461 /* Make sure all breakpoints are inserted in inferior.
2462    Throws exception on any error.
2463    A breakpoint that is already inserted won't be inserted
2464    again, so calling this function twice is safe.  */
2465 void
2466 insert_breakpoints (void)
2467 {
2468   struct breakpoint *bpt;
2469
2470   ALL_BREAKPOINTS (bpt)
2471     if (is_hardware_watchpoint (bpt))
2472       {
2473         struct watchpoint *w = (struct watchpoint *) bpt;
2474
2475         update_watchpoint (w, 0 /* don't reparse.  */);
2476       }
2477
2478   update_global_location_list (1);
2479
2480   /* update_global_location_list does not insert breakpoints when
2481      always_inserted_mode is not enabled.  Explicitly insert them
2482      now.  */
2483   if (!breakpoints_always_inserted_mode ())
2484     insert_breakpoint_locations ();
2485 }
2486
2487 /* Invoke CALLBACK for each of bp_location.  */
2488
2489 void
2490 iterate_over_bp_locations (walk_bp_location_callback callback)
2491 {
2492   struct bp_location *loc, **loc_tmp;
2493
2494   ALL_BP_LOCATIONS (loc, loc_tmp)
2495     {
2496       callback (loc, NULL);
2497     }
2498 }
2499
2500 /* This is used when we need to synch breakpoint conditions between GDB and the
2501    target.  It is the case with deleting and disabling of breakpoints when using
2502    always-inserted mode.  */
2503
2504 static void
2505 update_inserted_breakpoint_locations (void)
2506 {
2507   struct bp_location *bl, **blp_tmp;
2508   int error_flag = 0;
2509   int val = 0;
2510   int disabled_breaks = 0;
2511   int hw_breakpoint_error = 0;
2512
2513   struct ui_file *tmp_error_stream = mem_fileopen ();
2514   struct cleanup *cleanups = make_cleanup_ui_file_delete (tmp_error_stream);
2515
2516   /* Explicitly mark the warning -- this will only be printed if
2517      there was an error.  */
2518   fprintf_unfiltered (tmp_error_stream, "Warning:\n");
2519
2520   save_current_space_and_thread ();
2521
2522   ALL_BP_LOCATIONS (bl, blp_tmp)
2523     {
2524       /* We only want to update software breakpoints and hardware
2525          breakpoints.  */
2526       if (!is_breakpoint (bl->owner))
2527         continue;
2528
2529       /* We only want to update locations that are already inserted
2530          and need updating.  This is to avoid unwanted insertion during
2531          deletion of breakpoints.  */
2532       if (!bl->inserted || (bl->inserted && !bl->needs_update))
2533         continue;
2534
2535       switch_to_program_space_and_thread (bl->pspace);
2536
2537       /* For targets that support global breakpoints, there's no need
2538          to select an inferior to insert breakpoint to.  In fact, even
2539          if we aren't attached to any process yet, we should still
2540          insert breakpoints.  */
2541       if (!gdbarch_has_global_breakpoints (target_gdbarch)
2542           && ptid_equal (inferior_ptid, null_ptid))
2543         continue;
2544
2545       val = insert_bp_location (bl, tmp_error_stream, &disabled_breaks,
2546                                     &hw_breakpoint_error);
2547       if (val)
2548         error_flag = val;
2549     }
2550
2551   if (error_flag)
2552     {
2553       target_terminal_ours_for_output ();
2554       error_stream (tmp_error_stream);
2555     }
2556
2557   do_cleanups (cleanups);
2558 }
2559
2560 /* Used when starting or continuing the program.  */
2561
2562 static void
2563 insert_breakpoint_locations (void)
2564 {
2565   struct breakpoint *bpt;
2566   struct bp_location *bl, **blp_tmp;
2567   int error_flag = 0;
2568   int val = 0;
2569   int disabled_breaks = 0;
2570   int hw_breakpoint_error = 0;
2571
2572   struct ui_file *tmp_error_stream = mem_fileopen ();
2573   struct cleanup *cleanups = make_cleanup_ui_file_delete (tmp_error_stream);
2574   
2575   /* Explicitly mark the warning -- this will only be printed if
2576      there was an error.  */
2577   fprintf_unfiltered (tmp_error_stream, "Warning:\n");
2578
2579   save_current_space_and_thread ();
2580
2581   ALL_BP_LOCATIONS (bl, blp_tmp)
2582     {
2583       if (!should_be_inserted (bl) || (bl->inserted && !bl->needs_update))
2584         continue;
2585
2586       /* There is no point inserting thread-specific breakpoints if
2587          the thread no longer exists.  ALL_BP_LOCATIONS bp_location
2588          has BL->OWNER always non-NULL.  */
2589       if (bl->owner->thread != -1
2590           && !valid_thread_id (bl->owner->thread))
2591         continue;
2592
2593       switch_to_program_space_and_thread (bl->pspace);
2594
2595       /* For targets that support global breakpoints, there's no need
2596          to select an inferior to insert breakpoint to.  In fact, even
2597          if we aren't attached to any process yet, we should still
2598          insert breakpoints.  */
2599       if (!gdbarch_has_global_breakpoints (target_gdbarch)
2600           && ptid_equal (inferior_ptid, null_ptid))
2601         continue;
2602
2603       val = insert_bp_location (bl, tmp_error_stream, &disabled_breaks,
2604                                     &hw_breakpoint_error);
2605       if (val)
2606         error_flag = val;
2607     }
2608
2609   /* If we failed to insert all locations of a watchpoint, remove
2610      them, as half-inserted watchpoint is of limited use.  */
2611   ALL_BREAKPOINTS (bpt)  
2612     {
2613       int some_failed = 0;
2614       struct bp_location *loc;
2615
2616       if (!is_hardware_watchpoint (bpt))
2617         continue;
2618
2619       if (!breakpoint_enabled (bpt))
2620         continue;
2621
2622       if (bpt->disposition == disp_del_at_next_stop)
2623         continue;
2624       
2625       for (loc = bpt->loc; loc; loc = loc->next)
2626         if (!loc->inserted && should_be_inserted (loc))
2627           {
2628             some_failed = 1;
2629             break;
2630           }
2631       if (some_failed)
2632         {
2633           for (loc = bpt->loc; loc; loc = loc->next)
2634             if (loc->inserted)
2635               remove_breakpoint (loc, mark_uninserted);
2636
2637           hw_breakpoint_error = 1;
2638           fprintf_unfiltered (tmp_error_stream,
2639                               "Could not insert hardware watchpoint %d.\n", 
2640                               bpt->number);
2641           error_flag = -1;
2642         }
2643     }
2644
2645   if (error_flag)
2646     {
2647       /* If a hardware breakpoint or watchpoint was inserted, add a
2648          message about possibly exhausted resources.  */
2649       if (hw_breakpoint_error)
2650         {
2651           fprintf_unfiltered (tmp_error_stream, 
2652                               "Could not insert hardware breakpoints:\n\
2653 You may have requested too many hardware breakpoints/watchpoints.\n");
2654         }
2655       target_terminal_ours_for_output ();
2656       error_stream (tmp_error_stream);
2657     }
2658
2659   do_cleanups (cleanups);
2660 }
2661
2662 /* Used when the program stops.
2663    Returns zero if successful, or non-zero if there was a problem
2664    removing a breakpoint location.  */
2665
2666 int
2667 remove_breakpoints (void)
2668 {
2669   struct bp_location *bl, **blp_tmp;
2670   int val = 0;
2671
2672   ALL_BP_LOCATIONS (bl, blp_tmp)
2673   {
2674     if (bl->inserted && !is_tracepoint (bl->owner))
2675       val |= remove_breakpoint (bl, mark_uninserted);
2676   }
2677   return val;
2678 }
2679
2680 /* Remove breakpoints of process PID.  */
2681
2682 int
2683 remove_breakpoints_pid (int pid)
2684 {
2685   struct bp_location *bl, **blp_tmp;
2686   int val;
2687   struct inferior *inf = find_inferior_pid (pid);
2688
2689   ALL_BP_LOCATIONS (bl, blp_tmp)
2690   {
2691     if (bl->pspace != inf->pspace)
2692       continue;
2693
2694     if (bl->inserted)
2695       {
2696         val = remove_breakpoint (bl, mark_uninserted);
2697         if (val != 0)
2698           return val;
2699       }
2700   }
2701   return 0;
2702 }
2703
2704 int
2705 reattach_breakpoints (int pid)
2706 {
2707   struct cleanup *old_chain;
2708   struct bp_location *bl, **blp_tmp;
2709   int val;
2710   struct ui_file *tmp_error_stream;
2711   int dummy1 = 0, dummy2 = 0;
2712   struct inferior *inf;
2713   struct thread_info *tp;
2714
2715   tp = any_live_thread_of_process (pid);
2716   if (tp == NULL)
2717     return 1;
2718
2719   inf = find_inferior_pid (pid);
2720   old_chain = save_inferior_ptid ();
2721
2722   inferior_ptid = tp->ptid;
2723
2724   tmp_error_stream = mem_fileopen ();
2725   make_cleanup_ui_file_delete (tmp_error_stream);
2726
2727   ALL_BP_LOCATIONS (bl, blp_tmp)
2728   {
2729     if (bl->pspace != inf->pspace)
2730       continue;
2731
2732     if (bl->inserted)
2733       {
2734         bl->inserted = 0;
2735         val = insert_bp_location (bl, tmp_error_stream, &dummy1, &dummy2);
2736         if (val != 0)
2737           {
2738             do_cleanups (old_chain);
2739             return val;
2740           }
2741       }
2742   }
2743   do_cleanups (old_chain);
2744   return 0;
2745 }
2746
2747 static int internal_breakpoint_number = -1;
2748
2749 /* Set the breakpoint number of B, depending on the value of INTERNAL.
2750    If INTERNAL is non-zero, the breakpoint number will be populated
2751    from internal_breakpoint_number and that variable decremented.
2752    Otherwise the breakpoint number will be populated from
2753    breakpoint_count and that value incremented.  Internal breakpoints
2754    do not set the internal var bpnum.  */
2755 static void
2756 set_breakpoint_number (int internal, struct breakpoint *b)
2757 {
2758   if (internal)
2759     b->number = internal_breakpoint_number--;
2760   else
2761     {
2762       set_breakpoint_count (breakpoint_count + 1);
2763       b->number = breakpoint_count;
2764     }
2765 }
2766
2767 static struct breakpoint *
2768 create_internal_breakpoint (struct gdbarch *gdbarch,
2769                             CORE_ADDR address, enum bptype type,
2770                             const struct breakpoint_ops *ops)
2771 {
2772   struct symtab_and_line sal;
2773   struct breakpoint *b;
2774
2775   init_sal (&sal);              /* Initialize to zeroes.  */
2776
2777   sal.pc = address;
2778   sal.section = find_pc_overlay (sal.pc);
2779   sal.pspace = current_program_space;
2780
2781   b = set_raw_breakpoint (gdbarch, sal, type, ops);
2782   b->number = internal_breakpoint_number--;
2783   b->disposition = disp_donttouch;
2784
2785   return b;
2786 }
2787
2788 static const char *const longjmp_names[] =
2789   {
2790     "longjmp", "_longjmp", "siglongjmp", "_siglongjmp"
2791   };
2792 #define NUM_LONGJMP_NAMES ARRAY_SIZE(longjmp_names)
2793
2794 /* Per-objfile data private to breakpoint.c.  */
2795 struct breakpoint_objfile_data
2796 {
2797   /* Minimal symbol for "_ovly_debug_event" (if any).  */
2798   struct minimal_symbol *overlay_msym;
2799
2800   /* Minimal symbol(s) for "longjmp", "siglongjmp", etc. (if any).  */
2801   struct minimal_symbol *longjmp_msym[NUM_LONGJMP_NAMES];
2802
2803   /* True if we have looked for longjmp probes.  */
2804   int longjmp_searched;
2805
2806   /* SystemTap probe points for longjmp (if any).  */
2807   VEC (probe_p) *longjmp_probes;
2808
2809   /* Minimal symbol for "std::terminate()" (if any).  */
2810   struct minimal_symbol *terminate_msym;
2811
2812   /* Minimal symbol for "_Unwind_DebugHook" (if any).  */
2813   struct minimal_symbol *exception_msym;
2814
2815   /* True if we have looked for exception probes.  */
2816   int exception_searched;
2817
2818   /* SystemTap probe points for unwinding (if any).  */
2819   VEC (probe_p) *exception_probes;
2820 };
2821
2822 static const struct objfile_data *breakpoint_objfile_key;
2823
2824 /* Minimal symbol not found sentinel.  */
2825 static struct minimal_symbol msym_not_found;
2826
2827 /* Returns TRUE if MSYM point to the "not found" sentinel.  */
2828
2829 static int
2830 msym_not_found_p (const struct minimal_symbol *msym)
2831 {
2832   return msym == &msym_not_found;
2833 }
2834
2835 /* Return per-objfile data needed by breakpoint.c.
2836    Allocate the data if necessary.  */
2837
2838 static struct breakpoint_objfile_data *
2839 get_breakpoint_objfile_data (struct objfile *objfile)
2840 {
2841   struct breakpoint_objfile_data *bp_objfile_data;
2842
2843   bp_objfile_data = objfile_data (objfile, breakpoint_objfile_key);
2844   if (bp_objfile_data == NULL)
2845     {
2846       bp_objfile_data = obstack_alloc (&objfile->objfile_obstack,
2847                                        sizeof (*bp_objfile_data));
2848
2849       memset (bp_objfile_data, 0, sizeof (*bp_objfile_data));
2850       set_objfile_data (objfile, breakpoint_objfile_key, bp_objfile_data);
2851     }
2852   return bp_objfile_data;
2853 }
2854
2855 static void
2856 free_breakpoint_probes (struct objfile *obj, void *data)
2857 {
2858   struct breakpoint_objfile_data *bp_objfile_data = data;
2859
2860   VEC_free (probe_p, bp_objfile_data->longjmp_probes);
2861   VEC_free (probe_p, bp_objfile_data->exception_probes);
2862 }
2863
2864 static void
2865 create_overlay_event_breakpoint (void)
2866 {
2867   struct objfile *objfile;
2868   const char *const func_name = "_ovly_debug_event";
2869
2870   ALL_OBJFILES (objfile)
2871     {
2872       struct breakpoint *b;
2873       struct breakpoint_objfile_data *bp_objfile_data;
2874       CORE_ADDR addr;
2875
2876       bp_objfile_data = get_breakpoint_objfile_data (objfile);
2877
2878       if (msym_not_found_p (bp_objfile_data->overlay_msym))
2879         continue;
2880
2881       if (bp_objfile_data->overlay_msym == NULL)
2882         {
2883           struct minimal_symbol *m;
2884
2885           m = lookup_minimal_symbol_text (func_name, objfile);
2886           if (m == NULL)
2887             {
2888               /* Avoid future lookups in this objfile.  */
2889               bp_objfile_data->overlay_msym = &msym_not_found;
2890               continue;
2891             }
2892           bp_objfile_data->overlay_msym = m;
2893         }
2894
2895       addr = SYMBOL_VALUE_ADDRESS (bp_objfile_data->overlay_msym);
2896       b = create_internal_breakpoint (get_objfile_arch (objfile), addr,
2897                                       bp_overlay_event,
2898                                       &internal_breakpoint_ops);
2899       b->addr_string = xstrdup (func_name);
2900
2901       if (overlay_debugging == ovly_auto)
2902         {
2903           b->enable_state = bp_enabled;
2904           overlay_events_enabled = 1;
2905         }
2906       else
2907        {
2908          b->enable_state = bp_disabled;
2909          overlay_events_enabled = 0;
2910        }
2911     }
2912   update_global_location_list (1);
2913 }
2914
2915 static void
2916 create_longjmp_master_breakpoint (void)
2917 {
2918   struct program_space *pspace;
2919   struct cleanup *old_chain;
2920
2921   old_chain = save_current_program_space ();
2922
2923   ALL_PSPACES (pspace)
2924   {
2925     struct objfile *objfile;
2926
2927     set_current_program_space (pspace);
2928
2929     ALL_OBJFILES (objfile)
2930     {
2931       int i;
2932       struct gdbarch *gdbarch;
2933       struct breakpoint_objfile_data *bp_objfile_data;
2934
2935       gdbarch = get_objfile_arch (objfile);
2936       if (!gdbarch_get_longjmp_target_p (gdbarch))
2937         continue;
2938
2939       bp_objfile_data = get_breakpoint_objfile_data (objfile);
2940
2941       if (!bp_objfile_data->longjmp_searched)
2942         {
2943           bp_objfile_data->longjmp_probes
2944             = find_probes_in_objfile (objfile, "libc", "longjmp");
2945           bp_objfile_data->longjmp_searched = 1;
2946         }
2947
2948       if (bp_objfile_data->longjmp_probes != NULL)
2949         {
2950           int i;
2951           struct probe *probe;
2952           struct gdbarch *gdbarch = get_objfile_arch (objfile);
2953
2954           for (i = 0;
2955                VEC_iterate (probe_p,
2956                             bp_objfile_data->longjmp_probes,
2957                             i, probe);
2958                ++i)
2959             {
2960               struct breakpoint *b;
2961
2962               b = create_internal_breakpoint (gdbarch, probe->address,
2963                                               bp_longjmp_master,
2964                                               &internal_breakpoint_ops);
2965               b->addr_string = xstrdup ("-probe-stap libc:longjmp");
2966               b->enable_state = bp_disabled;
2967             }
2968
2969           continue;
2970         }
2971
2972       for (i = 0; i < NUM_LONGJMP_NAMES; i++)
2973         {
2974           struct breakpoint *b;
2975           const char *func_name;
2976           CORE_ADDR addr;
2977
2978           if (msym_not_found_p (bp_objfile_data->longjmp_msym[i]))
2979             continue;
2980
2981           func_name = longjmp_names[i];
2982           if (bp_objfile_data->longjmp_msym[i] == NULL)
2983             {
2984               struct minimal_symbol *m;
2985
2986               m = lookup_minimal_symbol_text (func_name, objfile);
2987               if (m == NULL)
2988                 {
2989                   /* Prevent future lookups in this objfile.  */
2990                   bp_objfile_data->longjmp_msym[i] = &msym_not_found;
2991                   continue;
2992                 }
2993               bp_objfile_data->longjmp_msym[i] = m;
2994             }
2995
2996           addr = SYMBOL_VALUE_ADDRESS (bp_objfile_data->longjmp_msym[i]);
2997           b = create_internal_breakpoint (gdbarch, addr, bp_longjmp_master,
2998                                           &internal_breakpoint_ops);
2999           b->addr_string = xstrdup (func_name);
3000           b->enable_state = bp_disabled;
3001         }
3002     }
3003   }
3004   update_global_location_list (1);
3005
3006   do_cleanups (old_chain);
3007 }
3008
3009 /* Create a master std::terminate breakpoint.  */
3010 static void
3011 create_std_terminate_master_breakpoint (void)
3012 {
3013   struct program_space *pspace;
3014   struct cleanup *old_chain;
3015   const char *const func_name = "std::terminate()";
3016
3017   old_chain = save_current_program_space ();
3018
3019   ALL_PSPACES (pspace)
3020   {
3021     struct objfile *objfile;
3022     CORE_ADDR addr;
3023
3024     set_current_program_space (pspace);
3025
3026     ALL_OBJFILES (objfile)
3027     {
3028       struct breakpoint *b;
3029       struct breakpoint_objfile_data *bp_objfile_data;
3030
3031       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3032
3033       if (msym_not_found_p (bp_objfile_data->terminate_msym))
3034         continue;
3035
3036       if (bp_objfile_data->terminate_msym == NULL)
3037         {
3038           struct minimal_symbol *m;
3039
3040           m = lookup_minimal_symbol (func_name, NULL, objfile);
3041           if (m == NULL || (MSYMBOL_TYPE (m) != mst_text
3042                             && MSYMBOL_TYPE (m) != mst_file_text))
3043             {
3044               /* Prevent future lookups in this objfile.  */
3045               bp_objfile_data->terminate_msym = &msym_not_found;
3046               continue;
3047             }
3048           bp_objfile_data->terminate_msym = m;
3049         }
3050
3051       addr = SYMBOL_VALUE_ADDRESS (bp_objfile_data->terminate_msym);
3052       b = create_internal_breakpoint (get_objfile_arch (objfile), addr,
3053                                       bp_std_terminate_master,
3054                                       &internal_breakpoint_ops);
3055       b->addr_string = xstrdup (func_name);
3056       b->enable_state = bp_disabled;
3057     }
3058   }
3059
3060   update_global_location_list (1);
3061
3062   do_cleanups (old_chain);
3063 }
3064
3065 /* Install a master breakpoint on the unwinder's debug hook.  */
3066
3067 static void
3068 create_exception_master_breakpoint (void)
3069 {
3070   struct objfile *objfile;
3071   const char *const func_name = "_Unwind_DebugHook";
3072
3073   ALL_OBJFILES (objfile)
3074     {
3075       struct breakpoint *b;
3076       struct gdbarch *gdbarch;
3077       struct breakpoint_objfile_data *bp_objfile_data;
3078       CORE_ADDR addr;
3079
3080       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3081
3082       /* We prefer the SystemTap probe point if it exists.  */
3083       if (!bp_objfile_data->exception_searched)
3084         {
3085           bp_objfile_data->exception_probes
3086             = find_probes_in_objfile (objfile, "libgcc", "unwind");
3087           bp_objfile_data->exception_searched = 1;
3088         }
3089
3090       if (bp_objfile_data->exception_probes != NULL)
3091         {
3092           struct gdbarch *gdbarch = get_objfile_arch (objfile);
3093           int i;
3094           struct probe *probe;
3095
3096           for (i = 0;
3097                VEC_iterate (probe_p,
3098                             bp_objfile_data->exception_probes,
3099                             i, probe);
3100                ++i)
3101             {
3102               struct breakpoint *b;
3103
3104               b = create_internal_breakpoint (gdbarch, probe->address,
3105                                               bp_exception_master,
3106                                               &internal_breakpoint_ops);
3107               b->addr_string = xstrdup ("-probe-stap libgcc:unwind");
3108               b->enable_state = bp_disabled;
3109             }
3110
3111           continue;
3112         }
3113
3114       /* Otherwise, try the hook function.  */
3115
3116       if (msym_not_found_p (bp_objfile_data->exception_msym))
3117         continue;
3118
3119       gdbarch = get_objfile_arch (objfile);
3120
3121       if (bp_objfile_data->exception_msym == NULL)
3122         {
3123           struct minimal_symbol *debug_hook;
3124
3125           debug_hook = lookup_minimal_symbol (func_name, NULL, objfile);
3126           if (debug_hook == NULL)
3127             {
3128               bp_objfile_data->exception_msym = &msym_not_found;
3129               continue;
3130             }
3131
3132           bp_objfile_data->exception_msym = debug_hook;
3133         }
3134
3135       addr = SYMBOL_VALUE_ADDRESS (bp_objfile_data->exception_msym);
3136       addr = gdbarch_convert_from_func_ptr_addr (gdbarch, addr,
3137                                                  &current_target);
3138       b = create_internal_breakpoint (gdbarch, addr, bp_exception_master,
3139                                       &internal_breakpoint_ops);
3140       b->addr_string = xstrdup (func_name);
3141       b->enable_state = bp_disabled;
3142     }
3143
3144   update_global_location_list (1);
3145 }
3146
3147 void
3148 update_breakpoints_after_exec (void)
3149 {
3150   struct breakpoint *b, *b_tmp;
3151   struct bp_location *bploc, **bplocp_tmp;
3152
3153   /* We're about to delete breakpoints from GDB's lists.  If the
3154      INSERTED flag is true, GDB will try to lift the breakpoints by
3155      writing the breakpoints' "shadow contents" back into memory.  The
3156      "shadow contents" are NOT valid after an exec, so GDB should not
3157      do that.  Instead, the target is responsible from marking
3158      breakpoints out as soon as it detects an exec.  We don't do that
3159      here instead, because there may be other attempts to delete
3160      breakpoints after detecting an exec and before reaching here.  */
3161   ALL_BP_LOCATIONS (bploc, bplocp_tmp)
3162     if (bploc->pspace == current_program_space)
3163       gdb_assert (!bploc->inserted);
3164
3165   ALL_BREAKPOINTS_SAFE (b, b_tmp)
3166   {
3167     if (b->pspace != current_program_space)
3168       continue;
3169
3170     /* Solib breakpoints must be explicitly reset after an exec().  */
3171     if (b->type == bp_shlib_event)
3172       {
3173         delete_breakpoint (b);
3174         continue;
3175       }
3176
3177     /* JIT breakpoints must be explicitly reset after an exec().  */
3178     if (b->type == bp_jit_event)
3179       {
3180         delete_breakpoint (b);
3181         continue;
3182       }
3183
3184     /* Thread event breakpoints must be set anew after an exec(),
3185        as must overlay event and longjmp master breakpoints.  */
3186     if (b->type == bp_thread_event || b->type == bp_overlay_event
3187         || b->type == bp_longjmp_master || b->type == bp_std_terminate_master
3188         || b->type == bp_exception_master)
3189       {
3190         delete_breakpoint (b);
3191         continue;
3192       }
3193
3194     /* Step-resume breakpoints are meaningless after an exec().  */
3195     if (b->type == bp_step_resume || b->type == bp_hp_step_resume)
3196       {
3197         delete_breakpoint (b);
3198         continue;
3199       }
3200
3201     /* Longjmp and longjmp-resume breakpoints are also meaningless
3202        after an exec.  */
3203     if (b->type == bp_longjmp || b->type == bp_longjmp_resume
3204         || b->type == bp_longjmp_call_dummy
3205         || b->type == bp_exception || b->type == bp_exception_resume)
3206       {
3207         delete_breakpoint (b);
3208         continue;
3209       }
3210
3211     if (b->type == bp_catchpoint)
3212       {
3213         /* For now, none of the bp_catchpoint breakpoints need to
3214            do anything at this point.  In the future, if some of
3215            the catchpoints need to something, we will need to add
3216            a new method, and call this method from here.  */
3217         continue;
3218       }
3219
3220     /* bp_finish is a special case.  The only way we ought to be able
3221        to see one of these when an exec() has happened, is if the user
3222        caught a vfork, and then said "finish".  Ordinarily a finish just
3223        carries them to the call-site of the current callee, by setting
3224        a temporary bp there and resuming.  But in this case, the finish
3225        will carry them entirely through the vfork & exec.
3226
3227        We don't want to allow a bp_finish to remain inserted now.  But
3228        we can't safely delete it, 'cause finish_command has a handle to
3229        the bp on a bpstat, and will later want to delete it.  There's a
3230        chance (and I've seen it happen) that if we delete the bp_finish
3231        here, that its storage will get reused by the time finish_command
3232        gets 'round to deleting the "use to be a bp_finish" breakpoint.
3233        We really must allow finish_command to delete a bp_finish.
3234
3235        In the absence of a general solution for the "how do we know
3236        it's safe to delete something others may have handles to?"
3237        problem, what we'll do here is just uninsert the bp_finish, and
3238        let finish_command delete it.
3239
3240        (We know the bp_finish is "doomed" in the sense that it's
3241        momentary, and will be deleted as soon as finish_command sees
3242        the inferior stopped.  So it doesn't matter that the bp's
3243        address is probably bogus in the new a.out, unlike e.g., the
3244        solib breakpoints.)  */
3245
3246     if (b->type == bp_finish)
3247       {
3248         continue;
3249       }
3250
3251     /* Without a symbolic address, we have little hope of the
3252        pre-exec() address meaning the same thing in the post-exec()
3253        a.out.  */
3254     if (b->addr_string == NULL)
3255       {
3256         delete_breakpoint (b);
3257         continue;
3258       }
3259   }
3260   /* FIXME what about longjmp breakpoints?  Re-create them here?  */
3261   create_overlay_event_breakpoint ();
3262   create_longjmp_master_breakpoint ();
3263   create_std_terminate_master_breakpoint ();
3264   create_exception_master_breakpoint ();
3265 }
3266
3267 int
3268 detach_breakpoints (int pid)
3269 {
3270   struct bp_location *bl, **blp_tmp;
3271   int val = 0;
3272   struct cleanup *old_chain = save_inferior_ptid ();
3273   struct inferior *inf = current_inferior ();
3274
3275   if (pid == PIDGET (inferior_ptid))
3276     error (_("Cannot detach breakpoints of inferior_ptid"));
3277
3278   /* Set inferior_ptid; remove_breakpoint_1 uses this global.  */
3279   inferior_ptid = pid_to_ptid (pid);
3280   ALL_BP_LOCATIONS (bl, blp_tmp)
3281   {
3282     if (bl->pspace != inf->pspace)
3283       continue;
3284
3285     if (bl->inserted)
3286       val |= remove_breakpoint_1 (bl, mark_inserted);
3287   }
3288
3289   /* Detach single-step breakpoints as well.  */
3290   detach_single_step_breakpoints ();
3291
3292   do_cleanups (old_chain);
3293   return val;
3294 }
3295
3296 /* Remove the breakpoint location BL from the current address space.
3297    Note that this is used to detach breakpoints from a child fork.
3298    When we get here, the child isn't in the inferior list, and neither
3299    do we have objects to represent its address space --- we should
3300    *not* look at bl->pspace->aspace here.  */
3301
3302 static int
3303 remove_breakpoint_1 (struct bp_location *bl, insertion_state_t is)
3304 {
3305   int val;
3306
3307   /* BL is never in moribund_locations by our callers.  */
3308   gdb_assert (bl->owner != NULL);
3309
3310   if (bl->owner->enable_state == bp_permanent)
3311     /* Permanent breakpoints cannot be inserted or removed.  */
3312     return 0;
3313
3314   /* The type of none suggests that owner is actually deleted.
3315      This should not ever happen.  */
3316   gdb_assert (bl->owner->type != bp_none);
3317
3318   if (bl->loc_type == bp_loc_software_breakpoint
3319       || bl->loc_type == bp_loc_hardware_breakpoint)
3320     {
3321       /* "Normal" instruction breakpoint: either the standard
3322          trap-instruction bp (bp_breakpoint), or a
3323          bp_hardware_breakpoint.  */
3324
3325       /* First check to see if we have to handle an overlay.  */
3326       if (overlay_debugging == ovly_off
3327           || bl->section == NULL
3328           || !(section_is_overlay (bl->section)))
3329         {
3330           /* No overlay handling: just remove the breakpoint.  */
3331           val = bl->owner->ops->remove_location (bl);
3332         }
3333       else
3334         {
3335           /* This breakpoint is in an overlay section.
3336              Did we set a breakpoint at the LMA?  */
3337           if (!overlay_events_enabled)
3338               {
3339                 /* Yes -- overlay event support is not active, so we
3340                    should have set a breakpoint at the LMA.  Remove it.  
3341                 */
3342                 /* Ignore any failures: if the LMA is in ROM, we will
3343                    have already warned when we failed to insert it.  */
3344                 if (bl->loc_type == bp_loc_hardware_breakpoint)
3345                   target_remove_hw_breakpoint (bl->gdbarch,
3346                                                &bl->overlay_target_info);
3347                 else
3348                   target_remove_breakpoint (bl->gdbarch,
3349                                             &bl->overlay_target_info);
3350               }
3351           /* Did we set a breakpoint at the VMA? 
3352              If so, we will have marked the breakpoint 'inserted'.  */
3353           if (bl->inserted)
3354             {
3355               /* Yes -- remove it.  Previously we did not bother to
3356                  remove the breakpoint if the section had been
3357                  unmapped, but let's not rely on that being safe.  We
3358                  don't know what the overlay manager might do.  */
3359
3360               /* However, we should remove *software* breakpoints only
3361                  if the section is still mapped, or else we overwrite
3362                  wrong code with the saved shadow contents.  */
3363               if (bl->loc_type == bp_loc_hardware_breakpoint
3364                   || section_is_mapped (bl->section))
3365                 val = bl->owner->ops->remove_location (bl);
3366               else
3367                 val = 0;
3368             }
3369           else
3370             {
3371               /* No -- not inserted, so no need to remove.  No error.  */
3372               val = 0;
3373             }
3374         }
3375
3376       /* In some cases, we might not be able to remove a breakpoint
3377          in a shared library that has already been removed, but we
3378          have not yet processed the shlib unload event.  */
3379       if (val && solib_name_from_address (bl->pspace, bl->address))
3380         val = 0;
3381
3382       if (val)
3383         return val;
3384       bl->inserted = (is == mark_inserted);
3385     }
3386   else if (bl->loc_type == bp_loc_hardware_watchpoint)
3387     {
3388       gdb_assert (bl->owner->ops != NULL
3389                   && bl->owner->ops->remove_location != NULL);
3390
3391       bl->inserted = (is == mark_inserted);
3392       bl->owner->ops->remove_location (bl);
3393
3394       /* Failure to remove any of the hardware watchpoints comes here.  */
3395       if ((is == mark_uninserted) && (bl->inserted))
3396         warning (_("Could not remove hardware watchpoint %d."),
3397                  bl->owner->number);
3398     }
3399   else if (bl->owner->type == bp_catchpoint
3400            && breakpoint_enabled (bl->owner)
3401            && !bl->duplicate)
3402     {
3403       gdb_assert (bl->owner->ops != NULL
3404                   && bl->owner->ops->remove_location != NULL);
3405
3406       val = bl->owner->ops->remove_location (bl);
3407       if (val)
3408         return val;
3409
3410       bl->inserted = (is == mark_inserted);
3411     }
3412
3413   return 0;
3414 }
3415
3416 static int
3417 remove_breakpoint (struct bp_location *bl, insertion_state_t is)
3418 {
3419   int ret;
3420   struct cleanup *old_chain;
3421
3422   /* BL is never in moribund_locations by our callers.  */
3423   gdb_assert (bl->owner != NULL);
3424
3425   if (bl->owner->enable_state == bp_permanent)
3426     /* Permanent breakpoints cannot be inserted or removed.  */
3427     return 0;
3428
3429   /* The type of none suggests that owner is actually deleted.
3430      This should not ever happen.  */
3431   gdb_assert (bl->owner->type != bp_none);
3432
3433   old_chain = save_current_space_and_thread ();
3434
3435   switch_to_program_space_and_thread (bl->pspace);
3436
3437   ret = remove_breakpoint_1 (bl, is);
3438
3439   do_cleanups (old_chain);
3440   return ret;
3441 }
3442
3443 /* Clear the "inserted" flag in all breakpoints.  */
3444
3445 void
3446 mark_breakpoints_out (void)
3447 {
3448   struct bp_location *bl, **blp_tmp;
3449
3450   ALL_BP_LOCATIONS (bl, blp_tmp)
3451     if (bl->pspace == current_program_space)
3452       bl->inserted = 0;
3453 }
3454
3455 /* Clear the "inserted" flag in all breakpoints and delete any
3456    breakpoints which should go away between runs of the program.
3457
3458    Plus other such housekeeping that has to be done for breakpoints
3459    between runs.
3460
3461    Note: this function gets called at the end of a run (by
3462    generic_mourn_inferior) and when a run begins (by
3463    init_wait_for_inferior).  */
3464
3465
3466
3467 void
3468 breakpoint_init_inferior (enum inf_context context)
3469 {
3470   struct breakpoint *b, *b_tmp;
3471   struct bp_location *bl, **blp_tmp;
3472   int ix;
3473   struct program_space *pspace = current_program_space;
3474
3475   /* If breakpoint locations are shared across processes, then there's
3476      nothing to do.  */
3477   if (gdbarch_has_global_breakpoints (target_gdbarch))
3478     return;
3479
3480   ALL_BP_LOCATIONS (bl, blp_tmp)
3481   {
3482     /* ALL_BP_LOCATIONS bp_location has BL->OWNER always non-NULL.  */
3483     if (bl->pspace == pspace
3484         && bl->owner->enable_state != bp_permanent)
3485       bl->inserted = 0;
3486   }
3487
3488   ALL_BREAKPOINTS_SAFE (b, b_tmp)
3489   {
3490     if (b->loc && b->loc->pspace != pspace)
3491       continue;
3492
3493     switch (b->type)
3494       {
3495       case bp_call_dummy:
3496       case bp_longjmp_call_dummy:
3497
3498         /* If the call dummy breakpoint is at the entry point it will
3499            cause problems when the inferior is rerun, so we better get
3500            rid of it.  */
3501
3502       case bp_watchpoint_scope:
3503
3504         /* Also get rid of scope breakpoints.  */
3505
3506       case bp_shlib_event:
3507
3508         /* Also remove solib event breakpoints.  Their addresses may
3509            have changed since the last time we ran the program.
3510            Actually we may now be debugging against different target;
3511            and so the solib backend that installed this breakpoint may
3512            not be used in by the target.  E.g.,
3513
3514            (gdb) file prog-linux
3515            (gdb) run               # native linux target
3516            ...
3517            (gdb) kill
3518            (gdb) file prog-win.exe
3519            (gdb) tar rem :9999     # remote Windows gdbserver.
3520         */
3521
3522       case bp_step_resume:
3523
3524         /* Also remove step-resume breakpoints.  */
3525
3526         delete_breakpoint (b);
3527         break;
3528
3529       case bp_watchpoint:
3530       case bp_hardware_watchpoint:
3531       case bp_read_watchpoint:
3532       case bp_access_watchpoint:
3533         {
3534           struct watchpoint *w = (struct watchpoint *) b;
3535
3536           /* Likewise for watchpoints on local expressions.  */
3537           if (w->exp_valid_block != NULL)
3538             delete_breakpoint (b);
3539           else if (context == inf_starting)
3540             {
3541               /* Reset val field to force reread of starting value in
3542                  insert_breakpoints.  */
3543               if (w->val)
3544                 value_free (w->val);
3545               w->val = NULL;
3546               w->val_valid = 0;
3547           }
3548         }
3549         break;
3550       default:
3551         break;
3552       }
3553   }
3554
3555   /* Get rid of the moribund locations.  */
3556   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, bl); ++ix)
3557     decref_bp_location (&bl);
3558   VEC_free (bp_location_p, moribund_locations);
3559 }
3560
3561 /* These functions concern about actual breakpoints inserted in the
3562    target --- to e.g. check if we need to do decr_pc adjustment or if
3563    we need to hop over the bkpt --- so we check for address space
3564    match, not program space.  */
3565
3566 /* breakpoint_here_p (PC) returns non-zero if an enabled breakpoint
3567    exists at PC.  It returns ordinary_breakpoint_here if it's an
3568    ordinary breakpoint, or permanent_breakpoint_here if it's a
3569    permanent breakpoint.
3570    - When continuing from a location with an ordinary breakpoint, we
3571      actually single step once before calling insert_breakpoints.
3572    - When continuing from a location with a permanent breakpoint, we
3573      need to use the `SKIP_PERMANENT_BREAKPOINT' macro, provided by
3574      the target, to advance the PC past the breakpoint.  */
3575
3576 enum breakpoint_here
3577 breakpoint_here_p (struct address_space *aspace, CORE_ADDR pc)
3578 {
3579   struct bp_location *bl, **blp_tmp;
3580   int any_breakpoint_here = 0;
3581
3582   ALL_BP_LOCATIONS (bl, blp_tmp)
3583     {
3584       if (bl->loc_type != bp_loc_software_breakpoint
3585           && bl->loc_type != bp_loc_hardware_breakpoint)
3586         continue;
3587
3588       /* ALL_BP_LOCATIONS bp_location has BL->OWNER always non-NULL.  */
3589       if ((breakpoint_enabled (bl->owner)
3590            || bl->owner->enable_state == bp_permanent)
3591           && breakpoint_location_address_match (bl, aspace, pc))
3592         {
3593           if (overlay_debugging 
3594               && section_is_overlay (bl->section)
3595               && !section_is_mapped (bl->section))
3596             continue;           /* unmapped overlay -- can't be a match */
3597           else if (bl->owner->enable_state == bp_permanent)
3598             return permanent_breakpoint_here;
3599           else
3600             any_breakpoint_here = 1;
3601         }
3602     }
3603
3604   return any_breakpoint_here ? ordinary_breakpoint_here : 0;
3605 }
3606
3607 /* Return true if there's a moribund breakpoint at PC.  */
3608
3609 int
3610 moribund_breakpoint_here_p (struct address_space *aspace, CORE_ADDR pc)
3611 {
3612   struct bp_location *loc;
3613   int ix;
3614
3615   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
3616     if (breakpoint_location_address_match (loc, aspace, pc))
3617       return 1;
3618
3619   return 0;
3620 }
3621
3622 /* Returns non-zero if there's a breakpoint inserted at PC, which is
3623    inserted using regular breakpoint_chain / bp_location array
3624    mechanism.  This does not check for single-step breakpoints, which
3625    are inserted and removed using direct target manipulation.  */
3626
3627 int
3628 regular_breakpoint_inserted_here_p (struct address_space *aspace, 
3629                                     CORE_ADDR pc)
3630 {
3631   struct bp_location *bl, **blp_tmp;
3632
3633   ALL_BP_LOCATIONS (bl, blp_tmp)
3634     {
3635       if (bl->loc_type != bp_loc_software_breakpoint
3636           && bl->loc_type != bp_loc_hardware_breakpoint)
3637         continue;
3638
3639       if (bl->inserted
3640           && breakpoint_location_address_match (bl, aspace, pc))
3641         {
3642           if (overlay_debugging 
3643               && section_is_overlay (bl->section)
3644               && !section_is_mapped (bl->section))
3645             continue;           /* unmapped overlay -- can't be a match */
3646           else
3647             return 1;
3648         }
3649     }
3650   return 0;
3651 }
3652
3653 /* Returns non-zero iff there's either regular breakpoint
3654    or a single step breakpoint inserted at PC.  */
3655
3656 int
3657 breakpoint_inserted_here_p (struct address_space *aspace, CORE_ADDR pc)
3658 {
3659   if (regular_breakpoint_inserted_here_p (aspace, pc))
3660     return 1;
3661
3662   if (single_step_breakpoint_inserted_here_p (aspace, pc))
3663     return 1;
3664
3665   return 0;
3666 }
3667
3668 /* This function returns non-zero iff there is a software breakpoint
3669    inserted at PC.  */
3670
3671 int
3672 software_breakpoint_inserted_here_p (struct address_space *aspace,
3673                                      CORE_ADDR pc)
3674 {
3675   struct bp_location *bl, **blp_tmp;
3676
3677   ALL_BP_LOCATIONS (bl, blp_tmp)
3678     {
3679       if (bl->loc_type != bp_loc_software_breakpoint)
3680         continue;
3681
3682       if (bl->inserted
3683           && breakpoint_address_match (bl->pspace->aspace, bl->address,
3684                                        aspace, pc))
3685         {
3686           if (overlay_debugging 
3687               && section_is_overlay (bl->section)
3688               && !section_is_mapped (bl->section))
3689             continue;           /* unmapped overlay -- can't be a match */
3690           else
3691             return 1;
3692         }
3693     }
3694
3695   /* Also check for software single-step breakpoints.  */
3696   if (single_step_breakpoint_inserted_here_p (aspace, pc))
3697     return 1;
3698
3699   return 0;
3700 }
3701
3702 int
3703 hardware_watchpoint_inserted_in_range (struct address_space *aspace,
3704                                        CORE_ADDR addr, ULONGEST len)
3705 {
3706   struct breakpoint *bpt;
3707
3708   ALL_BREAKPOINTS (bpt)
3709     {
3710       struct bp_location *loc;
3711
3712       if (bpt->type != bp_hardware_watchpoint
3713           && bpt->type != bp_access_watchpoint)
3714         continue;
3715
3716       if (!breakpoint_enabled (bpt))
3717         continue;
3718
3719       for (loc = bpt->loc; loc; loc = loc->next)
3720         if (loc->pspace->aspace == aspace && loc->inserted)
3721           {
3722             CORE_ADDR l, h;
3723
3724             /* Check for intersection.  */
3725             l = max (loc->address, addr);
3726             h = min (loc->address + loc->length, addr + len);
3727             if (l < h)
3728               return 1;
3729           }
3730     }
3731   return 0;
3732 }
3733
3734 /* breakpoint_thread_match (PC, PTID) returns true if the breakpoint at
3735    PC is valid for process/thread PTID.  */
3736
3737 int
3738 breakpoint_thread_match (struct address_space *aspace, CORE_ADDR pc,
3739                          ptid_t ptid)
3740 {
3741   struct bp_location *bl, **blp_tmp;
3742   /* The thread and task IDs associated to PTID, computed lazily.  */
3743   int thread = -1;
3744   int task = 0;
3745   
3746   ALL_BP_LOCATIONS (bl, blp_tmp)
3747     {
3748       if (bl->loc_type != bp_loc_software_breakpoint
3749           && bl->loc_type != bp_loc_hardware_breakpoint)
3750         continue;
3751
3752       /* ALL_BP_LOCATIONS bp_location has bl->OWNER always non-NULL.  */
3753       if (!breakpoint_enabled (bl->owner)
3754           && bl->owner->enable_state != bp_permanent)
3755         continue;
3756
3757       if (!breakpoint_location_address_match (bl, aspace, pc))
3758         continue;
3759
3760       if (bl->owner->thread != -1)
3761         {
3762           /* This is a thread-specific breakpoint.  Check that ptid
3763              matches that thread.  If thread hasn't been computed yet,
3764              it is now time to do so.  */
3765           if (thread == -1)
3766             thread = pid_to_thread_id (ptid);
3767           if (bl->owner->thread != thread)
3768             continue;
3769         }
3770
3771       if (bl->owner->task != 0)
3772         {
3773           /* This is a task-specific breakpoint.  Check that ptid
3774              matches that task.  If task hasn't been computed yet,
3775              it is now time to do so.  */
3776           if (task == 0)
3777             task = ada_get_task_number (ptid);
3778           if (bl->owner->task != task)
3779             continue;
3780         }
3781
3782       if (overlay_debugging 
3783           && section_is_overlay (bl->section)
3784           && !section_is_mapped (bl->section))
3785         continue;           /* unmapped overlay -- can't be a match */
3786
3787       return 1;
3788     }
3789
3790   return 0;
3791 }
3792 \f
3793
3794 /* bpstat stuff.  External routines' interfaces are documented
3795    in breakpoint.h.  */
3796
3797 int
3798 is_catchpoint (struct breakpoint *ep)
3799 {
3800   return (ep->type == bp_catchpoint);
3801 }
3802
3803 /* Frees any storage that is part of a bpstat.  Does not walk the
3804    'next' chain.  */
3805
3806 static void
3807 bpstat_free (bpstat bs)
3808 {
3809   if (bs->old_val != NULL)
3810     value_free (bs->old_val);
3811   decref_counted_command_line (&bs->commands);
3812   decref_bp_location (&bs->bp_location_at);
3813   xfree (bs);
3814 }
3815
3816 /* Clear a bpstat so that it says we are not at any breakpoint.
3817    Also free any storage that is part of a bpstat.  */
3818
3819 void
3820 bpstat_clear (bpstat *bsp)
3821 {
3822   bpstat p;
3823   bpstat q;
3824
3825   if (bsp == 0)
3826     return;
3827   p = *bsp;
3828   while (p != NULL)
3829     {
3830       q = p->next;
3831       bpstat_free (p);
3832       p = q;
3833     }
3834   *bsp = NULL;
3835 }
3836
3837 /* Return a copy of a bpstat.  Like "bs1 = bs2" but all storage that
3838    is part of the bpstat is copied as well.  */
3839
3840 bpstat
3841 bpstat_copy (bpstat bs)
3842 {
3843   bpstat p = NULL;
3844   bpstat tmp;
3845   bpstat retval = NULL;
3846
3847   if (bs == NULL)
3848     return bs;
3849
3850   for (; bs != NULL; bs = bs->next)
3851     {
3852       tmp = (bpstat) xmalloc (sizeof (*tmp));
3853       memcpy (tmp, bs, sizeof (*tmp));
3854       incref_counted_command_line (tmp->commands);
3855       incref_bp_location (tmp->bp_location_at);
3856       if (bs->old_val != NULL)
3857         {
3858           tmp->old_val = value_copy (bs->old_val);
3859           release_value (tmp->old_val);
3860         }
3861
3862       if (p == NULL)
3863         /* This is the first thing in the chain.  */
3864         retval = tmp;
3865       else
3866         p->next = tmp;
3867       p = tmp;
3868     }
3869   p->next = NULL;
3870   return retval;
3871 }
3872
3873 /* Find the bpstat associated with this breakpoint.  */
3874
3875 bpstat
3876 bpstat_find_breakpoint (bpstat bsp, struct breakpoint *breakpoint)
3877 {
3878   if (bsp == NULL)
3879     return NULL;
3880
3881   for (; bsp != NULL; bsp = bsp->next)
3882     {
3883       if (bsp->breakpoint_at == breakpoint)
3884         return bsp;
3885     }
3886   return NULL;
3887 }
3888
3889 /* Put in *NUM the breakpoint number of the first breakpoint we are
3890    stopped at.  *BSP upon return is a bpstat which points to the
3891    remaining breakpoints stopped at (but which is not guaranteed to be
3892    good for anything but further calls to bpstat_num).
3893
3894    Return 0 if passed a bpstat which does not indicate any breakpoints.
3895    Return -1 if stopped at a breakpoint that has been deleted since
3896    we set it.
3897    Return 1 otherwise.  */
3898
3899 int
3900 bpstat_num (bpstat *bsp, int *num)
3901 {
3902   struct breakpoint *b;
3903
3904   if ((*bsp) == NULL)
3905     return 0;                   /* No more breakpoint values */
3906
3907   /* We assume we'll never have several bpstats that correspond to a
3908      single breakpoint -- otherwise, this function might return the
3909      same number more than once and this will look ugly.  */
3910   b = (*bsp)->breakpoint_at;
3911   *bsp = (*bsp)->next;
3912   if (b == NULL)
3913     return -1;                  /* breakpoint that's been deleted since */
3914
3915   *num = b->number;             /* We have its number */
3916   return 1;
3917 }
3918
3919 /* See breakpoint.h.  */
3920
3921 void
3922 bpstat_clear_actions (void)
3923 {
3924   struct thread_info *tp;
3925   bpstat bs;
3926
3927   if (ptid_equal (inferior_ptid, null_ptid))
3928     return;
3929
3930   tp = find_thread_ptid (inferior_ptid);
3931   if (tp == NULL)
3932     return;
3933
3934   for (bs = tp->control.stop_bpstat; bs != NULL; bs = bs->next)
3935     {
3936       decref_counted_command_line (&bs->commands);
3937
3938       if (bs->old_val != NULL)
3939         {
3940           value_free (bs->old_val);
3941           bs->old_val = NULL;
3942         }
3943     }
3944 }
3945
3946 /* Called when a command is about to proceed the inferior.  */
3947
3948 static void
3949 breakpoint_about_to_proceed (void)
3950 {
3951   if (!ptid_equal (inferior_ptid, null_ptid))
3952     {
3953       struct thread_info *tp = inferior_thread ();
3954
3955       /* Allow inferior function calls in breakpoint commands to not
3956          interrupt the command list.  When the call finishes
3957          successfully, the inferior will be standing at the same
3958          breakpoint as if nothing happened.  */
3959       if (tp->control.in_infcall)
3960         return;
3961     }
3962
3963   breakpoint_proceeded = 1;
3964 }
3965
3966 /* Stub for cleaning up our state if we error-out of a breakpoint
3967    command.  */
3968 static void
3969 cleanup_executing_breakpoints (void *ignore)
3970 {
3971   executing_breakpoint_commands = 0;
3972 }
3973
3974 /* Return non-zero iff CMD as the first line of a command sequence is `silent'
3975    or its equivalent.  */
3976
3977 static int
3978 command_line_is_silent (struct command_line *cmd)
3979 {
3980   return cmd && (strcmp ("silent", cmd->line) == 0
3981                  || (xdb_commands && strcmp ("Q", cmd->line) == 0));
3982 }
3983
3984 /* Execute all the commands associated with all the breakpoints at
3985    this location.  Any of these commands could cause the process to
3986    proceed beyond this point, etc.  We look out for such changes by
3987    checking the global "breakpoint_proceeded" after each command.
3988
3989    Returns true if a breakpoint command resumed the inferior.  In that
3990    case, it is the caller's responsibility to recall it again with the
3991    bpstat of the current thread.  */
3992
3993 static int
3994 bpstat_do_actions_1 (bpstat *bsp)
3995 {
3996   bpstat bs;
3997   struct cleanup *old_chain;
3998   int again = 0;
3999
4000   /* Avoid endless recursion if a `source' command is contained
4001      in bs->commands.  */
4002   if (executing_breakpoint_commands)
4003     return 0;
4004
4005   executing_breakpoint_commands = 1;
4006   old_chain = make_cleanup (cleanup_executing_breakpoints, 0);
4007
4008   prevent_dont_repeat ();
4009
4010   /* This pointer will iterate over the list of bpstat's.  */
4011   bs = *bsp;
4012
4013   breakpoint_proceeded = 0;
4014   for (; bs != NULL; bs = bs->next)
4015     {
4016       struct counted_command_line *ccmd;
4017       struct command_line *cmd;
4018       struct cleanup *this_cmd_tree_chain;
4019
4020       /* Take ownership of the BSP's command tree, if it has one.
4021
4022          The command tree could legitimately contain commands like
4023          'step' and 'next', which call clear_proceed_status, which
4024          frees stop_bpstat's command tree.  To make sure this doesn't
4025          free the tree we're executing out from under us, we need to
4026          take ownership of the tree ourselves.  Since a given bpstat's
4027          commands are only executed once, we don't need to copy it; we
4028          can clear the pointer in the bpstat, and make sure we free
4029          the tree when we're done.  */
4030       ccmd = bs->commands;
4031       bs->commands = NULL;
4032       this_cmd_tree_chain = make_cleanup_decref_counted_command_line (&ccmd);
4033       cmd = ccmd ? ccmd->commands : NULL;
4034       if (command_line_is_silent (cmd))
4035         {
4036           /* The action has been already done by bpstat_stop_status.  */
4037           cmd = cmd->next;
4038         }
4039
4040       while (cmd != NULL)
4041         {
4042           execute_control_command (cmd);
4043
4044           if (breakpoint_proceeded)
4045             break;
4046           else
4047             cmd = cmd->next;
4048         }
4049
4050       /* We can free this command tree now.  */
4051       do_cleanups (this_cmd_tree_chain);
4052
4053       if (breakpoint_proceeded)
4054         {
4055           if (target_can_async_p ())
4056             /* If we are in async mode, then the target might be still
4057                running, not stopped at any breakpoint, so nothing for
4058                us to do here -- just return to the event loop.  */
4059             ;
4060           else
4061             /* In sync mode, when execute_control_command returns
4062                we're already standing on the next breakpoint.
4063                Breakpoint commands for that stop were not run, since
4064                execute_command does not run breakpoint commands --
4065                only command_line_handler does, but that one is not
4066                involved in execution of breakpoint commands.  So, we
4067                can now execute breakpoint commands.  It should be
4068                noted that making execute_command do bpstat actions is
4069                not an option -- in this case we'll have recursive
4070                invocation of bpstat for each breakpoint with a
4071                command, and can easily blow up GDB stack.  Instead, we
4072                return true, which will trigger the caller to recall us
4073                with the new stop_bpstat.  */
4074             again = 1;
4075           break;
4076         }
4077     }
4078   do_cleanups (old_chain);
4079   return again;
4080 }
4081
4082 void
4083 bpstat_do_actions (void)
4084 {
4085   struct cleanup *cleanup_if_error = make_bpstat_clear_actions_cleanup ();
4086
4087   /* Do any commands attached to breakpoint we are stopped at.  */
4088   while (!ptid_equal (inferior_ptid, null_ptid)
4089          && target_has_execution
4090          && !is_exited (inferior_ptid)
4091          && !is_executing (inferior_ptid))
4092     /* Since in sync mode, bpstat_do_actions may resume the inferior,
4093        and only return when it is stopped at the next breakpoint, we
4094        keep doing breakpoint actions until it returns false to
4095        indicate the inferior was not resumed.  */
4096     if (!bpstat_do_actions_1 (&inferior_thread ()->control.stop_bpstat))
4097       break;
4098
4099   discard_cleanups (cleanup_if_error);
4100 }
4101
4102 /* Print out the (old or new) value associated with a watchpoint.  */
4103
4104 static void
4105 watchpoint_value_print (struct value *val, struct ui_file *stream)
4106 {
4107   if (val == NULL)
4108     fprintf_unfiltered (stream, _("<unreadable>"));
4109   else
4110     {
4111       struct value_print_options opts;
4112       get_user_print_options (&opts);
4113       value_print (val, stream, &opts);
4114     }
4115 }
4116
4117 /* Generic routine for printing messages indicating why we
4118    stopped.  The behavior of this function depends on the value
4119    'print_it' in the bpstat structure.  Under some circumstances we
4120    may decide not to print anything here and delegate the task to
4121    normal_stop().  */
4122
4123 static enum print_stop_action
4124 print_bp_stop_message (bpstat bs)
4125 {
4126   switch (bs->print_it)
4127     {
4128     case print_it_noop:
4129       /* Nothing should be printed for this bpstat entry.  */
4130       return PRINT_UNKNOWN;
4131       break;
4132
4133     case print_it_done:
4134       /* We still want to print the frame, but we already printed the
4135          relevant messages.  */
4136       return PRINT_SRC_AND_LOC;
4137       break;
4138
4139     case print_it_normal:
4140       {
4141         struct breakpoint *b = bs->breakpoint_at;
4142
4143         /* bs->breakpoint_at can be NULL if it was a momentary breakpoint
4144            which has since been deleted.  */
4145         if (b == NULL)
4146           return PRINT_UNKNOWN;
4147
4148         /* Normal case.  Call the breakpoint's print_it method.  */
4149         return b->ops->print_it (bs);
4150       }
4151       break;
4152
4153     default:
4154       internal_error (__FILE__, __LINE__,
4155                       _("print_bp_stop_message: unrecognized enum value"));
4156       break;
4157     }
4158 }
4159
4160 /* A helper function that prints a shared library stopped event.  */
4161
4162 static void
4163 print_solib_event (int is_catchpoint)
4164 {
4165   int any_deleted
4166     = !VEC_empty (char_ptr, current_program_space->deleted_solibs);
4167   int any_added
4168     = !VEC_empty (so_list_ptr, current_program_space->added_solibs);
4169
4170   if (!is_catchpoint)
4171     {
4172       if (any_added || any_deleted)
4173         ui_out_text (current_uiout,
4174                      _("Stopped due to shared library event:\n"));
4175       else
4176         ui_out_text (current_uiout,
4177                      _("Stopped due to shared library event (no "
4178                        "libraries added or removed)\n"));
4179     }
4180
4181   if (ui_out_is_mi_like_p (current_uiout))
4182     ui_out_field_string (current_uiout, "reason",
4183                          async_reason_lookup (EXEC_ASYNC_SOLIB_EVENT));
4184
4185   if (any_deleted)
4186     {
4187       struct cleanup *cleanup;
4188       char *name;
4189       int ix;
4190
4191       ui_out_text (current_uiout, _("  Inferior unloaded "));
4192       cleanup = make_cleanup_ui_out_list_begin_end (current_uiout,
4193                                                     "removed");
4194       for (ix = 0;
4195            VEC_iterate (char_ptr, current_program_space->deleted_solibs,
4196                         ix, name);
4197            ++ix)
4198         {
4199           if (ix > 0)
4200             ui_out_text (current_uiout, "    ");
4201           ui_out_field_string (current_uiout, "library", name);
4202           ui_out_text (current_uiout, "\n");
4203         }
4204
4205       do_cleanups (cleanup);
4206     }
4207
4208   if (any_added)
4209     {
4210       struct so_list *iter;
4211       int ix;
4212       struct cleanup *cleanup;
4213
4214       ui_out_text (current_uiout, _("  Inferior loaded "));
4215       cleanup = make_cleanup_ui_out_list_begin_end (current_uiout,
4216                                                     "added");
4217       for (ix = 0;
4218            VEC_iterate (so_list_ptr, current_program_space->added_solibs,
4219                         ix, iter);
4220            ++ix)
4221         {
4222           if (ix > 0)
4223             ui_out_text (current_uiout, "    ");
4224           ui_out_field_string (current_uiout, "library", iter->so_name);
4225           ui_out_text (current_uiout, "\n");
4226         }
4227
4228       do_cleanups (cleanup);
4229     }
4230 }
4231
4232 /* Print a message indicating what happened.  This is called from
4233    normal_stop().  The input to this routine is the head of the bpstat
4234    list - a list of the eventpoints that caused this stop.  KIND is
4235    the target_waitkind for the stopping event.  This
4236    routine calls the generic print routine for printing a message
4237    about reasons for stopping.  This will print (for example) the
4238    "Breakpoint n," part of the output.  The return value of this
4239    routine is one of:
4240
4241    PRINT_UNKNOWN: Means we printed nothing.
4242    PRINT_SRC_AND_LOC: Means we printed something, and expect subsequent
4243    code to print the location.  An example is 
4244    "Breakpoint 1, " which should be followed by
4245    the location.
4246    PRINT_SRC_ONLY: Means we printed something, but there is no need
4247    to also print the location part of the message.
4248    An example is the catch/throw messages, which
4249    don't require a location appended to the end.
4250    PRINT_NOTHING: We have done some printing and we don't need any 
4251    further info to be printed.  */
4252
4253 enum print_stop_action
4254 bpstat_print (bpstat bs, int kind)
4255 {
4256   int val;
4257
4258   /* Maybe another breakpoint in the chain caused us to stop.
4259      (Currently all watchpoints go on the bpstat whether hit or not.
4260      That probably could (should) be changed, provided care is taken
4261      with respect to bpstat_explains_signal).  */
4262   for (; bs; bs = bs->next)
4263     {
4264       val = print_bp_stop_message (bs);
4265       if (val == PRINT_SRC_ONLY 
4266           || val == PRINT_SRC_AND_LOC 
4267           || val == PRINT_NOTHING)
4268         return val;
4269     }
4270
4271   /* If we had hit a shared library event breakpoint,
4272      print_bp_stop_message would print out this message.  If we hit an
4273      OS-level shared library event, do the same thing.  */
4274   if (kind == TARGET_WAITKIND_LOADED)
4275     {
4276       print_solib_event (0);
4277       return PRINT_NOTHING;
4278     }
4279
4280   /* We reached the end of the chain, or we got a null BS to start
4281      with and nothing was printed.  */
4282   return PRINT_UNKNOWN;
4283 }
4284
4285 /* Evaluate the expression EXP and return 1 if value is zero.  This is
4286    used inside a catch_errors to evaluate the breakpoint condition.
4287    The argument is a "struct expression *" that has been cast to a
4288    "char *" to make it pass through catch_errors.  */
4289
4290 static int
4291 breakpoint_cond_eval (void *exp)
4292 {
4293   struct value *mark = value_mark ();
4294   int i = !value_true (evaluate_expression ((struct expression *) exp));
4295
4296   value_free_to_mark (mark);
4297   return i;
4298 }
4299
4300 /* Allocate a new bpstat.  Link it to the FIFO list by BS_LINK_POINTER.  */
4301
4302 static bpstat
4303 bpstat_alloc (struct bp_location *bl, bpstat **bs_link_pointer)
4304 {
4305   bpstat bs;
4306
4307   bs = (bpstat) xmalloc (sizeof (*bs));
4308   bs->next = NULL;
4309   **bs_link_pointer = bs;
4310   *bs_link_pointer = &bs->next;
4311   bs->breakpoint_at = bl->owner;
4312   bs->bp_location_at = bl;
4313   incref_bp_location (bl);
4314   /* If the condition is false, etc., don't do the commands.  */
4315   bs->commands = NULL;
4316   bs->old_val = NULL;
4317   bs->print_it = print_it_normal;
4318   return bs;
4319 }
4320 \f
4321 /* The target has stopped with waitstatus WS.  Check if any hardware
4322    watchpoints have triggered, according to the target.  */
4323
4324 int
4325 watchpoints_triggered (struct target_waitstatus *ws)
4326 {
4327   int stopped_by_watchpoint = target_stopped_by_watchpoint ();
4328   CORE_ADDR addr;
4329   struct breakpoint *b;
4330
4331   if (!stopped_by_watchpoint)
4332     {
4333       /* We were not stopped by a watchpoint.  Mark all watchpoints
4334          as not triggered.  */
4335       ALL_BREAKPOINTS (b)
4336         if (is_hardware_watchpoint (b))
4337           {
4338             struct watchpoint *w = (struct watchpoint *) b;
4339
4340             w->watchpoint_triggered = watch_triggered_no;
4341           }
4342
4343       return 0;
4344     }
4345
4346   if (!target_stopped_data_address (&current_target, &addr))
4347     {
4348       /* We were stopped by a watchpoint, but we don't know where.
4349          Mark all watchpoints as unknown.  */
4350       ALL_BREAKPOINTS (b)
4351         if (is_hardware_watchpoint (b))
4352           {
4353             struct watchpoint *w = (struct watchpoint *) b;
4354
4355             w->watchpoint_triggered = watch_triggered_unknown;
4356           }
4357
4358       return stopped_by_watchpoint;
4359     }
4360
4361   /* The target could report the data address.  Mark watchpoints
4362      affected by this data address as triggered, and all others as not
4363      triggered.  */
4364
4365   ALL_BREAKPOINTS (b)
4366     if (is_hardware_watchpoint (b))
4367       {
4368         struct watchpoint *w = (struct watchpoint *) b;
4369         struct bp_location *loc;
4370
4371         w->watchpoint_triggered = watch_triggered_no;
4372         for (loc = b->loc; loc; loc = loc->next)
4373           {
4374             if (is_masked_watchpoint (b))
4375               {
4376                 CORE_ADDR newaddr = addr & w->hw_wp_mask;
4377                 CORE_ADDR start = loc->address & w->hw_wp_mask;
4378
4379                 if (newaddr == start)
4380                   {
4381                     w->watchpoint_triggered = watch_triggered_yes;
4382                     break;
4383                   }
4384               }
4385             /* Exact match not required.  Within range is sufficient.  */
4386             else if (target_watchpoint_addr_within_range (&current_target,
4387                                                          addr, loc->address,
4388                                                          loc->length))
4389               {
4390                 w->watchpoint_triggered = watch_triggered_yes;
4391                 break;
4392               }
4393           }
4394       }
4395
4396   return 1;
4397 }
4398
4399 /* Possible return values for watchpoint_check (this can't be an enum
4400    because of check_errors).  */
4401 /* The watchpoint has been deleted.  */
4402 #define WP_DELETED 1
4403 /* The value has changed.  */
4404 #define WP_VALUE_CHANGED 2
4405 /* The value has not changed.  */
4406 #define WP_VALUE_NOT_CHANGED 3
4407 /* Ignore this watchpoint, no matter if the value changed or not.  */
4408 #define WP_IGNORE 4
4409
4410 #define BP_TEMPFLAG 1
4411 #define BP_HARDWAREFLAG 2
4412
4413 /* Evaluate watchpoint condition expression and check if its value
4414    changed.
4415
4416    P should be a pointer to struct bpstat, but is defined as a void *
4417    in order for this function to be usable with catch_errors.  */
4418
4419 static int
4420 watchpoint_check (void *p)
4421 {
4422   bpstat bs = (bpstat) p;
4423   struct watchpoint *b;
4424   struct frame_info *fr;
4425   int within_current_scope;
4426
4427   /* BS is built from an existing struct breakpoint.  */
4428   gdb_assert (bs->breakpoint_at != NULL);
4429   b = (struct watchpoint *) bs->breakpoint_at;
4430
4431   /* If this is a local watchpoint, we only want to check if the
4432      watchpoint frame is in scope if the current thread is the thread
4433      that was used to create the watchpoint.  */
4434   if (!watchpoint_in_thread_scope (b))
4435     return WP_IGNORE;
4436
4437   if (b->exp_valid_block == NULL)
4438     within_current_scope = 1;
4439   else
4440     {
4441       struct frame_info *frame = get_current_frame ();
4442       struct gdbarch *frame_arch = get_frame_arch (frame);
4443       CORE_ADDR frame_pc = get_frame_pc (frame);
4444
4445       /* in_function_epilogue_p() returns a non-zero value if we're
4446          still in the function but the stack frame has already been
4447          invalidated.  Since we can't rely on the values of local
4448          variables after the stack has been destroyed, we are treating
4449          the watchpoint in that state as `not changed' without further
4450          checking.  Don't mark watchpoints as changed if the current
4451          frame is in an epilogue - even if they are in some other
4452          frame, our view of the stack is likely to be wrong and
4453          frame_find_by_id could error out.  */
4454       if (gdbarch_in_function_epilogue_p (frame_arch, frame_pc))
4455         return WP_IGNORE;
4456
4457       fr = frame_find_by_id (b->watchpoint_frame);
4458       within_current_scope = (fr != NULL);
4459
4460       /* If we've gotten confused in the unwinder, we might have
4461          returned a frame that can't describe this variable.  */
4462       if (within_current_scope)
4463         {
4464           struct symbol *function;
4465
4466           function = get_frame_function (fr);
4467           if (function == NULL
4468               || !contained_in (b->exp_valid_block,
4469                                 SYMBOL_BLOCK_VALUE (function)))
4470             within_current_scope = 0;
4471         }
4472
4473       if (within_current_scope)
4474         /* If we end up stopping, the current frame will get selected
4475            in normal_stop.  So this call to select_frame won't affect
4476            the user.  */
4477         select_frame (fr);
4478     }
4479
4480   if (within_current_scope)
4481     {
4482       /* We use value_{,free_to_}mark because it could be a *long*
4483          time before we return to the command level and call
4484          free_all_values.  We can't call free_all_values because we
4485          might be in the middle of evaluating a function call.  */
4486
4487       int pc = 0;
4488       struct value *mark;
4489       struct value *new_val;
4490
4491       if (is_masked_watchpoint (&b->base))
4492         /* Since we don't know the exact trigger address (from
4493            stopped_data_address), just tell the user we've triggered
4494            a mask watchpoint.  */
4495         return WP_VALUE_CHANGED;
4496
4497       mark = value_mark ();
4498       fetch_subexp_value (b->exp, &pc, &new_val, NULL, NULL);
4499
4500       /* We use value_equal_contents instead of value_equal because
4501          the latter coerces an array to a pointer, thus comparing just
4502          the address of the array instead of its contents.  This is
4503          not what we want.  */
4504       if ((b->val != NULL) != (new_val != NULL)
4505           || (b->val != NULL && !value_equal_contents (b->val, new_val)))
4506         {
4507           if (new_val != NULL)
4508             {
4509               release_value (new_val);
4510               value_free_to_mark (mark);
4511             }
4512           bs->old_val = b->val;
4513           b->val = new_val;
4514           b->val_valid = 1;
4515           return WP_VALUE_CHANGED;
4516         }
4517       else
4518         {
4519           /* Nothing changed.  */
4520           value_free_to_mark (mark);
4521           return WP_VALUE_NOT_CHANGED;
4522         }
4523     }
4524   else
4525     {
4526       struct ui_out *uiout = current_uiout;
4527
4528       /* This seems like the only logical thing to do because
4529          if we temporarily ignored the watchpoint, then when
4530          we reenter the block in which it is valid it contains
4531          garbage (in the case of a function, it may have two
4532          garbage values, one before and one after the prologue).
4533          So we can't even detect the first assignment to it and
4534          watch after that (since the garbage may or may not equal
4535          the first value assigned).  */
4536       /* We print all the stop information in
4537          breakpoint_ops->print_it, but in this case, by the time we
4538          call breakpoint_ops->print_it this bp will be deleted
4539          already.  So we have no choice but print the information
4540          here.  */
4541       if (ui_out_is_mi_like_p (uiout))
4542         ui_out_field_string
4543           (uiout, "reason", async_reason_lookup (EXEC_ASYNC_WATCHPOINT_SCOPE));
4544       ui_out_text (uiout, "\nWatchpoint ");
4545       ui_out_field_int (uiout, "wpnum", b->base.number);
4546       ui_out_text (uiout,
4547                    " deleted because the program has left the block in\n\
4548 which its expression is valid.\n");     
4549
4550       /* Make sure the watchpoint's commands aren't executed.  */
4551       decref_counted_command_line (&b->base.commands);
4552       watchpoint_del_at_next_stop (b);
4553
4554       return WP_DELETED;
4555     }
4556 }
4557
4558 /* Return true if it looks like target has stopped due to hitting
4559    breakpoint location BL.  This function does not check if we should
4560    stop, only if BL explains the stop.  */
4561
4562 static int
4563 bpstat_check_location (const struct bp_location *bl,
4564                        struct address_space *aspace, CORE_ADDR bp_addr,
4565                        const struct target_waitstatus *ws)
4566 {
4567   struct breakpoint *b = bl->owner;
4568
4569   /* BL is from an existing breakpoint.  */
4570   gdb_assert (b != NULL);
4571
4572   return b->ops->breakpoint_hit (bl, aspace, bp_addr, ws);
4573 }
4574
4575 /* Determine if the watched values have actually changed, and we
4576    should stop.  If not, set BS->stop to 0.  */
4577
4578 static void
4579 bpstat_check_watchpoint (bpstat bs)
4580 {
4581   const struct bp_location *bl;
4582   struct watchpoint *b;
4583
4584   /* BS is built for existing struct breakpoint.  */
4585   bl = bs->bp_location_at;
4586   gdb_assert (bl != NULL);
4587   b = (struct watchpoint *) bs->breakpoint_at;
4588   gdb_assert (b != NULL);
4589
4590     {
4591       int must_check_value = 0;
4592       
4593       if (b->base.type == bp_watchpoint)
4594         /* For a software watchpoint, we must always check the
4595            watched value.  */
4596         must_check_value = 1;
4597       else if (b->watchpoint_triggered == watch_triggered_yes)
4598         /* We have a hardware watchpoint (read, write, or access)
4599            and the target earlier reported an address watched by
4600            this watchpoint.  */
4601         must_check_value = 1;
4602       else if (b->watchpoint_triggered == watch_triggered_unknown
4603                && b->base.type == bp_hardware_watchpoint)
4604         /* We were stopped by a hardware watchpoint, but the target could
4605            not report the data address.  We must check the watchpoint's
4606            value.  Access and read watchpoints are out of luck; without
4607            a data address, we can't figure it out.  */
4608         must_check_value = 1;
4609
4610       if (must_check_value)
4611         {
4612           char *message
4613             = xstrprintf ("Error evaluating expression for watchpoint %d\n",
4614                           b->base.number);
4615           struct cleanup *cleanups = make_cleanup (xfree, message);
4616           int e = catch_errors (watchpoint_check, bs, message,
4617                                 RETURN_MASK_ALL);
4618           do_cleanups (cleanups);
4619           switch (e)
4620             {
4621             case WP_DELETED:
4622               /* We've already printed what needs to be printed.  */
4623               bs->print_it = print_it_done;
4624               /* Stop.  */
4625               break;
4626             case WP_IGNORE:
4627               bs->print_it = print_it_noop;
4628               bs->stop = 0;
4629               break;
4630             case WP_VALUE_CHANGED:
4631               if (b->base.type == bp_read_watchpoint)
4632                 {
4633                   /* There are two cases to consider here:
4634
4635                      1. We're watching the triggered memory for reads.
4636                      In that case, trust the target, and always report
4637                      the watchpoint hit to the user.  Even though
4638                      reads don't cause value changes, the value may
4639                      have changed since the last time it was read, and
4640                      since we're not trapping writes, we will not see
4641                      those, and as such we should ignore our notion of
4642                      old value.
4643
4644                      2. We're watching the triggered memory for both
4645                      reads and writes.  There are two ways this may
4646                      happen:
4647
4648                      2.1. This is a target that can't break on data
4649                      reads only, but can break on accesses (reads or
4650                      writes), such as e.g., x86.  We detect this case
4651                      at the time we try to insert read watchpoints.
4652
4653                      2.2. Otherwise, the target supports read
4654                      watchpoints, but, the user set an access or write
4655                      watchpoint watching the same memory as this read
4656                      watchpoint.
4657
4658                      If we're watching memory writes as well as reads,
4659                      ignore watchpoint hits when we find that the
4660                      value hasn't changed, as reads don't cause
4661                      changes.  This still gives false positives when
4662                      the program writes the same value to memory as
4663                      what there was already in memory (we will confuse
4664                      it for a read), but it's much better than
4665                      nothing.  */
4666
4667                   int other_write_watchpoint = 0;
4668
4669                   if (bl->watchpoint_type == hw_read)
4670                     {
4671                       struct breakpoint *other_b;
4672
4673                       ALL_BREAKPOINTS (other_b)
4674                         if (other_b->type == bp_hardware_watchpoint
4675                             || other_b->type == bp_access_watchpoint)
4676                           {
4677                             struct watchpoint *other_w =
4678                               (struct watchpoint *) other_b;
4679
4680                             if (other_w->watchpoint_triggered
4681                                 == watch_triggered_yes)
4682                               {
4683                                 other_write_watchpoint = 1;
4684                                 break;
4685                               }
4686                           }
4687                     }
4688
4689                   if (other_write_watchpoint
4690                       || bl->watchpoint_type == hw_access)
4691                     {
4692                       /* We're watching the same memory for writes,
4693                          and the value changed since the last time we
4694                          updated it, so this trap must be for a write.
4695                          Ignore it.  */
4696                       bs->print_it = print_it_noop;
4697                       bs->stop = 0;
4698                     }
4699                 }
4700               break;
4701             case WP_VALUE_NOT_CHANGED:
4702               if (b->base.type == bp_hardware_watchpoint
4703                   || b->base.type == bp_watchpoint)
4704                 {
4705                   /* Don't stop: write watchpoints shouldn't fire if
4706                      the value hasn't changed.  */
4707                   bs->print_it = print_it_noop;
4708                   bs->stop = 0;
4709                 }
4710               /* Stop.  */
4711               break;
4712             default:
4713               /* Can't happen.  */
4714             case 0:
4715               /* Error from catch_errors.  */
4716               printf_filtered (_("Watchpoint %d deleted.\n"), b->base.number);
4717               watchpoint_del_at_next_stop (b);
4718               /* We've already printed what needs to be printed.  */
4719               bs->print_it = print_it_done;
4720               break;
4721             }
4722         }
4723       else      /* must_check_value == 0 */
4724         {
4725           /* This is a case where some watchpoint(s) triggered, but
4726              not at the address of this watchpoint, or else no
4727              watchpoint triggered after all.  So don't print
4728              anything for this watchpoint.  */
4729           bs->print_it = print_it_noop;
4730           bs->stop = 0;
4731         }
4732     }
4733 }
4734
4735
4736 /* Check conditions (condition proper, frame, thread and ignore count)
4737    of breakpoint referred to by BS.  If we should not stop for this
4738    breakpoint, set BS->stop to 0.  */
4739
4740 static void
4741 bpstat_check_breakpoint_conditions (bpstat bs, ptid_t ptid)
4742 {
4743   int thread_id = pid_to_thread_id (ptid);
4744   const struct bp_location *bl;
4745   struct breakpoint *b;
4746
4747   /* BS is built for existing struct breakpoint.  */
4748   bl = bs->bp_location_at;
4749   gdb_assert (bl != NULL);
4750   b = bs->breakpoint_at;
4751   gdb_assert (b != NULL);
4752
4753   /* Even if the target evaluated the condition on its end and notified GDB, we
4754      need to do so again since GDB does not know if we stopped due to a
4755      breakpoint or a single step breakpoint.  */
4756
4757   if (frame_id_p (b->frame_id)
4758       && !frame_id_eq (b->frame_id, get_stack_frame_id (get_current_frame ())))
4759     bs->stop = 0;
4760   else if (bs->stop)
4761     {
4762       int value_is_zero = 0;
4763       struct expression *cond;
4764
4765       /* Evaluate Python breakpoints that have a "stop"
4766          method implemented.  */
4767       if (b->py_bp_object)
4768         bs->stop = gdbpy_should_stop (b->py_bp_object);
4769
4770       if (is_watchpoint (b))
4771         {
4772           struct watchpoint *w = (struct watchpoint *) b;
4773
4774           cond = w->cond_exp;
4775         }
4776       else
4777         cond = bl->cond;
4778
4779       if (cond && b->disposition != disp_del_at_next_stop)
4780         {
4781           int within_current_scope = 1;
4782           struct watchpoint * w;
4783
4784           /* We use value_mark and value_free_to_mark because it could
4785              be a long time before we return to the command level and
4786              call free_all_values.  We can't call free_all_values
4787              because we might be in the middle of evaluating a
4788              function call.  */
4789           struct value *mark = value_mark ();
4790
4791           if (is_watchpoint (b))
4792             w = (struct watchpoint *) b;
4793           else
4794             w = NULL;
4795
4796           /* Need to select the frame, with all that implies so that
4797              the conditions will have the right context.  Because we
4798              use the frame, we will not see an inlined function's
4799              variables when we arrive at a breakpoint at the start
4800              of the inlined function; the current frame will be the
4801              call site.  */
4802           if (w == NULL || w->cond_exp_valid_block == NULL)
4803             select_frame (get_current_frame ());
4804           else
4805             {
4806               struct frame_info *frame;
4807
4808               /* For local watchpoint expressions, which particular
4809                  instance of a local is being watched matters, so we
4810                  keep track of the frame to evaluate the expression
4811                  in.  To evaluate the condition however, it doesn't
4812                  really matter which instantiation of the function
4813                  where the condition makes sense triggers the
4814                  watchpoint.  This allows an expression like "watch
4815                  global if q > 10" set in `func', catch writes to
4816                  global on all threads that call `func', or catch
4817                  writes on all recursive calls of `func' by a single
4818                  thread.  We simply always evaluate the condition in
4819                  the innermost frame that's executing where it makes
4820                  sense to evaluate the condition.  It seems
4821                  intuitive.  */
4822               frame = block_innermost_frame (w->cond_exp_valid_block);
4823               if (frame != NULL)
4824                 select_frame (frame);
4825               else
4826                 within_current_scope = 0;
4827             }
4828           if (within_current_scope)
4829             value_is_zero
4830               = catch_errors (breakpoint_cond_eval, cond,
4831                               "Error in testing breakpoint condition:\n",
4832                               RETURN_MASK_ALL);
4833           else
4834             {
4835               warning (_("Watchpoint condition cannot be tested "
4836                          "in the current scope"));
4837               /* If we failed to set the right context for this
4838                  watchpoint, unconditionally report it.  */
4839               value_is_zero = 0;
4840             }
4841           /* FIXME-someday, should give breakpoint #.  */
4842           value_free_to_mark (mark);
4843         }
4844
4845       if (cond && value_is_zero)
4846         {
4847           bs->stop = 0;
4848         }
4849       else if (b->thread != -1 && b->thread != thread_id)
4850         {
4851           bs->stop = 0;
4852         }
4853       else if (b->ignore_count > 0)
4854         {
4855           b->ignore_count--;
4856           annotate_ignore_count_change ();
4857           bs->stop = 0;
4858           /* Increase the hit count even though we don't stop.  */
4859           ++(b->hit_count);
4860           observer_notify_breakpoint_modified (b);
4861         }       
4862     }
4863 }
4864
4865
4866 /* Get a bpstat associated with having just stopped at address
4867    BP_ADDR in thread PTID.
4868
4869    Determine whether we stopped at a breakpoint, etc, or whether we
4870    don't understand this stop.  Result is a chain of bpstat's such
4871    that:
4872
4873    if we don't understand the stop, the result is a null pointer.
4874
4875    if we understand why we stopped, the result is not null.
4876
4877    Each element of the chain refers to a particular breakpoint or
4878    watchpoint at which we have stopped.  (We may have stopped for
4879    several reasons concurrently.)
4880
4881    Each element of the chain has valid next, breakpoint_at,
4882    commands, FIXME??? fields.  */
4883
4884 bpstat
4885 bpstat_stop_status (struct address_space *aspace,
4886                     CORE_ADDR bp_addr, ptid_t ptid,
4887                     const struct target_waitstatus *ws)
4888 {
4889   struct breakpoint *b = NULL;
4890   struct bp_location *bl;
4891   struct bp_location *loc;
4892   /* First item of allocated bpstat's.  */
4893   bpstat bs_head = NULL, *bs_link = &bs_head;
4894   /* Pointer to the last thing in the chain currently.  */
4895   bpstat bs;
4896   int ix;
4897   int need_remove_insert;
4898   int removed_any;
4899
4900   /* First, build the bpstat chain with locations that explain a
4901      target stop, while being careful to not set the target running,
4902      as that may invalidate locations (in particular watchpoint
4903      locations are recreated).  Resuming will happen here with
4904      breakpoint conditions or watchpoint expressions that include
4905      inferior function calls.  */
4906
4907   ALL_BREAKPOINTS (b)
4908     {
4909       if (!breakpoint_enabled (b) && b->enable_state != bp_permanent)
4910         continue;
4911
4912       for (bl = b->loc; bl != NULL; bl = bl->next)
4913         {
4914           /* For hardware watchpoints, we look only at the first
4915              location.  The watchpoint_check function will work on the
4916              entire expression, not the individual locations.  For
4917              read watchpoints, the watchpoints_triggered function has
4918              checked all locations already.  */
4919           if (b->type == bp_hardware_watchpoint && bl != b->loc)
4920             break;
4921
4922           if (bl->shlib_disabled)
4923             continue;
4924
4925           if (!bpstat_check_location (bl, aspace, bp_addr, ws))
4926             continue;
4927
4928           /* Come here if it's a watchpoint, or if the break address
4929              matches.  */
4930
4931           bs = bpstat_alloc (bl, &bs_link);     /* Alloc a bpstat to
4932                                                    explain stop.  */
4933
4934           /* Assume we stop.  Should we find a watchpoint that is not
4935              actually triggered, or if the condition of the breakpoint
4936              evaluates as false, we'll reset 'stop' to 0.  */
4937           bs->stop = 1;
4938           bs->print = 1;
4939
4940           /* If this is a scope breakpoint, mark the associated
4941              watchpoint as triggered so that we will handle the
4942              out-of-scope event.  We'll get to the watchpoint next
4943              iteration.  */
4944           if (b->type == bp_watchpoint_scope && b->related_breakpoint != b)
4945             {
4946               struct watchpoint *w = (struct watchpoint *) b->related_breakpoint;
4947
4948               w->watchpoint_triggered = watch_triggered_yes;
4949             }
4950         }
4951     }
4952
4953   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
4954     {
4955       if (breakpoint_location_address_match (loc, aspace, bp_addr))
4956         {
4957           bs = bpstat_alloc (loc, &bs_link);
4958           /* For hits of moribund locations, we should just proceed.  */
4959           bs->stop = 0;
4960           bs->print = 0;
4961           bs->print_it = print_it_noop;
4962         }
4963     }
4964
4965   /* A bit of special processing for shlib breakpoints.  We need to
4966      process solib loading here, so that the lists of loaded and
4967      unloaded libraries are correct before we handle "catch load" and
4968      "catch unload".  */
4969   for (bs = bs_head; bs != NULL; bs = bs->next)
4970     {
4971       if (bs->breakpoint_at && bs->breakpoint_at->type == bp_shlib_event)
4972         {
4973           handle_solib_event ();
4974           break;
4975         }
4976     }
4977
4978   /* Now go through the locations that caused the target to stop, and
4979      check whether we're interested in reporting this stop to higher
4980      layers, or whether we should resume the target transparently.  */
4981
4982   removed_any = 0;
4983
4984   for (bs = bs_head; bs != NULL; bs = bs->next)
4985     {
4986       if (!bs->stop)
4987         continue;
4988
4989       b = bs->breakpoint_at;
4990       b->ops->check_status (bs);
4991       if (bs->stop)
4992         {
4993           bpstat_check_breakpoint_conditions (bs, ptid);
4994
4995           if (bs->stop)
4996             {
4997               ++(b->hit_count);
4998               observer_notify_breakpoint_modified (b);
4999
5000               /* We will stop here.  */
5001               if (b->disposition == disp_disable)
5002                 {
5003                   --(b->enable_count);
5004                   if (b->enable_count <= 0
5005                       && b->enable_state != bp_permanent)
5006                     b->enable_state = bp_disabled;
5007                   removed_any = 1;
5008                 }
5009               if (b->silent)
5010                 bs->print = 0;
5011               bs->commands = b->commands;
5012               incref_counted_command_line (bs->commands);
5013               if (command_line_is_silent (bs->commands
5014                                           ? bs->commands->commands : NULL))
5015                 bs->print = 0;
5016             }
5017
5018         }
5019
5020       /* Print nothing for this entry if we don't stop or don't
5021          print.  */
5022       if (!bs->stop || !bs->print)
5023         bs->print_it = print_it_noop;
5024     }
5025
5026   /* If we aren't stopping, the value of some hardware watchpoint may
5027      not have changed, but the intermediate memory locations we are
5028      watching may have.  Don't bother if we're stopping; this will get
5029      done later.  */
5030   need_remove_insert = 0;
5031   if (! bpstat_causes_stop (bs_head))
5032     for (bs = bs_head; bs != NULL; bs = bs->next)
5033       if (!bs->stop
5034           && bs->breakpoint_at
5035           && is_hardware_watchpoint (bs->breakpoint_at))
5036         {
5037           struct watchpoint *w = (struct watchpoint *) bs->breakpoint_at;
5038
5039           update_watchpoint (w, 0 /* don't reparse.  */);
5040           need_remove_insert = 1;
5041         }
5042
5043   if (need_remove_insert)
5044     update_global_location_list (1);
5045   else if (removed_any)
5046     update_global_location_list (0);
5047
5048   return bs_head;
5049 }
5050
5051 static void
5052 handle_jit_event (void)
5053 {
5054   struct frame_info *frame;
5055   struct gdbarch *gdbarch;
5056
5057   /* Switch terminal for any messages produced by
5058      breakpoint_re_set.  */
5059   target_terminal_ours_for_output ();
5060
5061   frame = get_current_frame ();
5062   gdbarch = get_frame_arch (frame);
5063
5064   jit_event_handler (gdbarch);
5065
5066   target_terminal_inferior ();
5067 }
5068
5069 /* Handle an solib event by calling solib_add.  */
5070
5071 void
5072 handle_solib_event (void)
5073 {
5074   clear_program_space_solib_cache (current_inferior ()->pspace);
5075
5076   /* Check for any newly added shared libraries if we're supposed to
5077      be adding them automatically.  Switch terminal for any messages
5078      produced by breakpoint_re_set.  */
5079   target_terminal_ours_for_output ();
5080 #ifdef SOLIB_ADD
5081   SOLIB_ADD (NULL, 0, &current_target, auto_solib_add);
5082 #else
5083   solib_add (NULL, 0, &current_target, auto_solib_add);
5084 #endif
5085   target_terminal_inferior ();
5086 }
5087
5088 /* Prepare WHAT final decision for infrun.  */
5089
5090 /* Decide what infrun needs to do with this bpstat.  */
5091
5092 struct bpstat_what
5093 bpstat_what (bpstat bs_head)
5094 {
5095   struct bpstat_what retval;
5096   int jit_event = 0;
5097   bpstat bs;
5098
5099   retval.main_action = BPSTAT_WHAT_KEEP_CHECKING;
5100   retval.call_dummy = STOP_NONE;
5101   retval.is_longjmp = 0;
5102
5103   for (bs = bs_head; bs != NULL; bs = bs->next)
5104     {
5105       /* Extract this BS's action.  After processing each BS, we check
5106          if its action overrides all we've seem so far.  */
5107       enum bpstat_what_main_action this_action = BPSTAT_WHAT_KEEP_CHECKING;
5108       enum bptype bptype;
5109
5110       if (bs->breakpoint_at == NULL)
5111         {
5112           /* I suspect this can happen if it was a momentary
5113              breakpoint which has since been deleted.  */
5114           bptype = bp_none;
5115         }
5116       else
5117         bptype = bs->breakpoint_at->type;
5118
5119       switch (bptype)
5120         {
5121         case bp_none:
5122           break;
5123         case bp_breakpoint:
5124         case bp_hardware_breakpoint:
5125         case bp_until:
5126         case bp_finish:
5127         case bp_shlib_event:
5128           if (bs->stop)
5129             {
5130               if (bs->print)
5131                 this_action = BPSTAT_WHAT_STOP_NOISY;
5132               else
5133                 this_action = BPSTAT_WHAT_STOP_SILENT;
5134             }
5135           else
5136             this_action = BPSTAT_WHAT_SINGLE;
5137           break;
5138         case bp_watchpoint:
5139         case bp_hardware_watchpoint:
5140         case bp_read_watchpoint:
5141         case bp_access_watchpoint:
5142           if (bs->stop)
5143             {
5144               if (bs->print)
5145                 this_action = BPSTAT_WHAT_STOP_NOISY;
5146               else
5147                 this_action = BPSTAT_WHAT_STOP_SILENT;
5148             }
5149           else
5150             {
5151               /* There was a watchpoint, but we're not stopping.
5152                  This requires no further action.  */
5153             }
5154           break;
5155         case bp_longjmp:
5156         case bp_longjmp_call_dummy:
5157         case bp_exception:
5158           this_action = BPSTAT_WHAT_SET_LONGJMP_RESUME;
5159           retval.is_longjmp = bptype != bp_exception;
5160           break;
5161         case bp_longjmp_resume:
5162         case bp_exception_resume:
5163           this_action = BPSTAT_WHAT_CLEAR_LONGJMP_RESUME;
5164           retval.is_longjmp = bptype == bp_longjmp_resume;
5165           break;
5166         case bp_step_resume:
5167           if (bs->stop)
5168             this_action = BPSTAT_WHAT_STEP_RESUME;
5169           else
5170             {
5171               /* It is for the wrong frame.  */
5172               this_action = BPSTAT_WHAT_SINGLE;
5173             }
5174           break;
5175         case bp_hp_step_resume:
5176           if (bs->stop)
5177             this_action = BPSTAT_WHAT_HP_STEP_RESUME;
5178           else
5179             {
5180               /* It is for the wrong frame.  */
5181               this_action = BPSTAT_WHAT_SINGLE;
5182             }
5183           break;
5184         case bp_watchpoint_scope:
5185         case bp_thread_event:
5186         case bp_overlay_event:
5187         case bp_longjmp_master:
5188         case bp_std_terminate_master:
5189         case bp_exception_master:
5190           this_action = BPSTAT_WHAT_SINGLE;
5191           break;
5192         case bp_catchpoint:
5193           if (bs->stop)
5194             {
5195               if (bs->print)
5196                 this_action = BPSTAT_WHAT_STOP_NOISY;
5197               else
5198                 this_action = BPSTAT_WHAT_STOP_SILENT;
5199             }
5200           else
5201             {
5202               /* There was a catchpoint, but we're not stopping.
5203                  This requires no further action.  */
5204             }
5205           break;
5206         case bp_jit_event:
5207           jit_event = 1;
5208           this_action = BPSTAT_WHAT_SINGLE;
5209           break;
5210         case bp_call_dummy:
5211           /* Make sure the action is stop (silent or noisy),
5212              so infrun.c pops the dummy frame.  */
5213           retval.call_dummy = STOP_STACK_DUMMY;
5214           this_action = BPSTAT_WHAT_STOP_SILENT;
5215           break;
5216         case bp_std_terminate:
5217           /* Make sure the action is stop (silent or noisy),
5218              so infrun.c pops the dummy frame.  */
5219           retval.call_dummy = STOP_STD_TERMINATE;
5220           this_action = BPSTAT_WHAT_STOP_SILENT;
5221           break;
5222         case bp_tracepoint:
5223         case bp_fast_tracepoint:
5224         case bp_static_tracepoint:
5225           /* Tracepoint hits should not be reported back to GDB, and
5226              if one got through somehow, it should have been filtered
5227              out already.  */
5228           internal_error (__FILE__, __LINE__,
5229                           _("bpstat_what: tracepoint encountered"));
5230           break;
5231         case bp_gnu_ifunc_resolver:
5232           /* Step over it (and insert bp_gnu_ifunc_resolver_return).  */
5233           this_action = BPSTAT_WHAT_SINGLE;
5234           break;
5235         case bp_gnu_ifunc_resolver_return:
5236           /* The breakpoint will be removed, execution will restart from the
5237              PC of the former breakpoint.  */
5238           this_action = BPSTAT_WHAT_KEEP_CHECKING;
5239           break;
5240
5241         case bp_dprintf:
5242           this_action = BPSTAT_WHAT_STOP_SILENT;
5243           break;
5244
5245         default:
5246           internal_error (__FILE__, __LINE__,
5247                           _("bpstat_what: unhandled bptype %d"), (int) bptype);
5248         }
5249
5250       retval.main_action = max (retval.main_action, this_action);
5251     }
5252
5253   /* These operations may affect the bs->breakpoint_at state so they are
5254      delayed after MAIN_ACTION is decided above.  */
5255
5256   if (jit_event)
5257     {
5258       if (debug_infrun)
5259         fprintf_unfiltered (gdb_stdlog, "bpstat_what: bp_jit_event\n");
5260
5261       handle_jit_event ();
5262     }
5263
5264   for (bs = bs_head; bs != NULL; bs = bs->next)
5265     {
5266       struct breakpoint *b = bs->breakpoint_at;
5267
5268       if (b == NULL)
5269         continue;
5270       switch (b->type)
5271         {
5272         case bp_gnu_ifunc_resolver:
5273           gnu_ifunc_resolver_stop (b);
5274           break;
5275         case bp_gnu_ifunc_resolver_return:
5276           gnu_ifunc_resolver_return_stop (b);
5277           break;
5278         }
5279     }
5280
5281   return retval;
5282 }
5283
5284 /* Nonzero if we should step constantly (e.g. watchpoints on machines
5285    without hardware support).  This isn't related to a specific bpstat,
5286    just to things like whether watchpoints are set.  */
5287
5288 int
5289 bpstat_should_step (void)
5290 {
5291   struct breakpoint *b;
5292
5293   ALL_BREAKPOINTS (b)
5294     if (breakpoint_enabled (b) && b->type == bp_watchpoint && b->loc != NULL)
5295       return 1;
5296   return 0;
5297 }
5298
5299 int
5300 bpstat_causes_stop (bpstat bs)
5301 {
5302   for (; bs != NULL; bs = bs->next)
5303     if (bs->stop)
5304       return 1;
5305
5306   return 0;
5307 }
5308
5309 \f
5310
5311 /* Compute a string of spaces suitable to indent the next line
5312    so it starts at the position corresponding to the table column
5313    named COL_NAME in the currently active table of UIOUT.  */
5314
5315 static char *
5316 wrap_indent_at_field (struct ui_out *uiout, const char *col_name)
5317 {
5318   static char wrap_indent[80];
5319   int i, total_width, width, align;
5320   char *text;
5321
5322   total_width = 0;
5323   for (i = 1; ui_out_query_field (uiout, i, &width, &align, &text); i++)
5324     {
5325       if (strcmp (text, col_name) == 0)
5326         {
5327           gdb_assert (total_width < sizeof wrap_indent);
5328           memset (wrap_indent, ' ', total_width);
5329           wrap_indent[total_width] = 0;
5330
5331           return wrap_indent;
5332         }
5333
5334       total_width += width + 1;
5335     }
5336
5337   return NULL;
5338 }
5339
5340 /* Determine if the locations of this breakpoint will have their conditions
5341    evaluated by the target, host or a mix of both.  Returns the following:
5342
5343     "host": Host evals condition.
5344     "host or target": Host or Target evals condition.
5345     "target": Target evals condition.
5346 */
5347
5348 static const char *
5349 bp_condition_evaluator (struct breakpoint *b)
5350 {
5351   struct bp_location *bl;
5352   char host_evals = 0;
5353   char target_evals = 0;
5354
5355   if (!b)
5356     return NULL;
5357
5358   if (!is_breakpoint (b))
5359     return NULL;
5360
5361   if (gdb_evaluates_breakpoint_condition_p ()
5362       || !target_supports_evaluation_of_breakpoint_conditions ())
5363     return condition_evaluation_host;
5364
5365   for (bl = b->loc; bl; bl = bl->next)
5366     {
5367       if (bl->cond_bytecode)
5368         target_evals++;
5369       else
5370         host_evals++;
5371     }
5372
5373   if (host_evals && target_evals)
5374     return condition_evaluation_both;
5375   else if (target_evals)
5376     return condition_evaluation_target;
5377   else
5378     return condition_evaluation_host;
5379 }
5380
5381 /* Determine the breakpoint location's condition evaluator.  This is
5382    similar to bp_condition_evaluator, but for locations.  */
5383
5384 static const char *
5385 bp_location_condition_evaluator (struct bp_location *bl)
5386 {
5387   if (bl && !is_breakpoint (bl->owner))
5388     return NULL;
5389
5390   if (gdb_evaluates_breakpoint_condition_p ()
5391       || !target_supports_evaluation_of_breakpoint_conditions ())
5392     return condition_evaluation_host;
5393
5394   if (bl && bl->cond_bytecode)
5395     return condition_evaluation_target;
5396   else
5397     return condition_evaluation_host;
5398 }
5399
5400 /* Print the LOC location out of the list of B->LOC locations.  */
5401
5402 static void
5403 print_breakpoint_location (struct breakpoint *b,
5404                            struct bp_location *loc)
5405 {
5406   struct ui_out *uiout = current_uiout;
5407   struct cleanup *old_chain = save_current_program_space ();
5408
5409   if (loc != NULL && loc->shlib_disabled)
5410     loc = NULL;
5411
5412   if (loc != NULL)
5413     set_current_program_space (loc->pspace);
5414
5415   if (b->display_canonical)
5416     ui_out_field_string (uiout, "what", b->addr_string);
5417   else if (loc && loc->source_file)
5418     {
5419       struct symbol *sym 
5420         = find_pc_sect_function (loc->address, loc->section);
5421       if (sym)
5422         {
5423           ui_out_text (uiout, "in ");
5424           ui_out_field_string (uiout, "func",
5425                                SYMBOL_PRINT_NAME (sym));
5426           ui_out_text (uiout, " ");
5427           ui_out_wrap_hint (uiout, wrap_indent_at_field (uiout, "what"));
5428           ui_out_text (uiout, "at ");
5429         }
5430       ui_out_field_string (uiout, "file", loc->source_file);
5431       ui_out_text (uiout, ":");
5432       
5433       if (ui_out_is_mi_like_p (uiout))
5434         {
5435           struct symtab_and_line sal = find_pc_line (loc->address, 0);
5436           char *fullname = symtab_to_fullname (sal.symtab);
5437           
5438           if (fullname)
5439             ui_out_field_string (uiout, "fullname", fullname);
5440         }
5441       
5442       ui_out_field_int (uiout, "line", loc->line_number);
5443     }
5444   else if (loc)
5445     {
5446       struct ui_file *stb = mem_fileopen ();
5447       struct cleanup *stb_chain = make_cleanup_ui_file_delete (stb);
5448
5449       print_address_symbolic (loc->gdbarch, loc->address, stb,
5450                               demangle, "");
5451       ui_out_field_stream (uiout, "at", stb);
5452
5453       do_cleanups (stb_chain);
5454     }
5455   else
5456     ui_out_field_string (uiout, "pending", b->addr_string);
5457
5458   if (loc && is_breakpoint (b)
5459       && breakpoint_condition_evaluation_mode () == condition_evaluation_target
5460       && bp_condition_evaluator (b) == condition_evaluation_both)
5461     {
5462       ui_out_text (uiout, " (");
5463       ui_out_field_string (uiout, "evaluated-by",
5464                            bp_location_condition_evaluator (loc));
5465       ui_out_text (uiout, ")");
5466     }
5467
5468   do_cleanups (old_chain);
5469 }
5470
5471 static const char *
5472 bptype_string (enum bptype type)
5473 {
5474   struct ep_type_description
5475     {
5476       enum bptype type;
5477       char *description;
5478     };
5479   static struct ep_type_description bptypes[] =
5480   {
5481     {bp_none, "?deleted?"},
5482     {bp_breakpoint, "breakpoint"},
5483     {bp_hardware_breakpoint, "hw breakpoint"},
5484     {bp_until, "until"},
5485     {bp_finish, "finish"},
5486     {bp_watchpoint, "watchpoint"},
5487     {bp_hardware_watchpoint, "hw watchpoint"},
5488     {bp_read_watchpoint, "read watchpoint"},
5489     {bp_access_watchpoint, "acc watchpoint"},
5490     {bp_longjmp, "longjmp"},
5491     {bp_longjmp_resume, "longjmp resume"},
5492     {bp_longjmp_call_dummy, "longjmp for call dummy"},
5493     {bp_exception, "exception"},
5494     {bp_exception_resume, "exception resume"},
5495     {bp_step_resume, "step resume"},
5496     {bp_hp_step_resume, "high-priority step resume"},
5497     {bp_watchpoint_scope, "watchpoint scope"},
5498     {bp_call_dummy, "call dummy"},
5499     {bp_std_terminate, "std::terminate"},
5500     {bp_shlib_event, "shlib events"},
5501     {bp_thread_event, "thread events"},
5502     {bp_overlay_event, "overlay events"},
5503     {bp_longjmp_master, "longjmp master"},
5504     {bp_std_terminate_master, "std::terminate master"},
5505     {bp_exception_master, "exception master"},
5506     {bp_catchpoint, "catchpoint"},
5507     {bp_tracepoint, "tracepoint"},
5508     {bp_fast_tracepoint, "fast tracepoint"},
5509     {bp_static_tracepoint, "static tracepoint"},
5510     {bp_dprintf, "dprintf"},
5511     {bp_jit_event, "jit events"},
5512     {bp_gnu_ifunc_resolver, "STT_GNU_IFUNC resolver"},
5513     {bp_gnu_ifunc_resolver_return, "STT_GNU_IFUNC resolver return"},
5514   };
5515
5516   if (((int) type >= (sizeof (bptypes) / sizeof (bptypes[0])))
5517       || ((int) type != bptypes[(int) type].type))
5518     internal_error (__FILE__, __LINE__,
5519                     _("bptypes table does not describe type #%d."),
5520                     (int) type);
5521
5522   return bptypes[(int) type].description;
5523 }
5524
5525 /* Print B to gdb_stdout.  */
5526
5527 static void
5528 print_one_breakpoint_location (struct breakpoint *b,
5529                                struct bp_location *loc,
5530                                int loc_number,
5531                                struct bp_location **last_loc,
5532                                int allflag)
5533 {
5534   struct command_line *l;
5535   static char bpenables[] = "nynny";
5536
5537   struct ui_out *uiout = current_uiout;
5538   int header_of_multiple = 0;
5539   int part_of_multiple = (loc != NULL);
5540   struct value_print_options opts;
5541
5542   get_user_print_options (&opts);
5543
5544   gdb_assert (!loc || loc_number != 0);
5545   /* See comment in print_one_breakpoint concerning treatment of
5546      breakpoints with single disabled location.  */
5547   if (loc == NULL 
5548       && (b->loc != NULL 
5549           && (b->loc->next != NULL || !b->loc->enabled)))
5550     header_of_multiple = 1;
5551   if (loc == NULL)
5552     loc = b->loc;
5553
5554   annotate_record ();
5555
5556   /* 1 */
5557   annotate_field (0);
5558   if (part_of_multiple)
5559     {
5560       char *formatted;
5561       formatted = xstrprintf ("%d.%d", b->number, loc_number);
5562       ui_out_field_string (uiout, "number", formatted);
5563       xfree (formatted);
5564     }
5565   else
5566     {
5567       ui_out_field_int (uiout, "number", b->number);
5568     }
5569
5570   /* 2 */
5571   annotate_field (1);
5572   if (part_of_multiple)
5573     ui_out_field_skip (uiout, "type");
5574   else
5575     ui_out_field_string (uiout, "type", bptype_string (b->type));
5576
5577   /* 3 */
5578   annotate_field (2);
5579   if (part_of_multiple)
5580     ui_out_field_skip (uiout, "disp");
5581   else
5582     ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
5583
5584
5585   /* 4 */
5586   annotate_field (3);
5587   if (part_of_multiple)
5588     ui_out_field_string (uiout, "enabled", loc->enabled ? "y" : "n");
5589   else
5590     ui_out_field_fmt (uiout, "enabled", "%c", 
5591                       bpenables[(int) b->enable_state]);
5592   ui_out_spaces (uiout, 2);
5593
5594   
5595   /* 5 and 6 */
5596   if (b->ops != NULL && b->ops->print_one != NULL)
5597     {
5598       /* Although the print_one can possibly print all locations,
5599          calling it here is not likely to get any nice result.  So,
5600          make sure there's just one location.  */
5601       gdb_assert (b->loc == NULL || b->loc->next == NULL);
5602       b->ops->print_one (b, last_loc);
5603     }
5604   else
5605     switch (b->type)
5606       {
5607       case bp_none:
5608         internal_error (__FILE__, __LINE__,
5609                         _("print_one_breakpoint: bp_none encountered\n"));
5610         break;
5611
5612       case bp_watchpoint:
5613       case bp_hardware_watchpoint:
5614       case bp_read_watchpoint:
5615       case bp_access_watchpoint:
5616         {
5617           struct watchpoint *w = (struct watchpoint *) b;
5618
5619           /* Field 4, the address, is omitted (which makes the columns
5620              not line up too nicely with the headers, but the effect
5621              is relatively readable).  */
5622           if (opts.addressprint)
5623             ui_out_field_skip (uiout, "addr");
5624           annotate_field (5);
5625           ui_out_field_string (uiout, "what", w->exp_string);
5626         }
5627         break;
5628
5629       case bp_breakpoint:
5630       case bp_hardware_breakpoint:
5631       case bp_until:
5632       case bp_finish:
5633       case bp_longjmp:
5634       case bp_longjmp_resume:
5635       case bp_longjmp_call_dummy:
5636       case bp_exception:
5637       case bp_exception_resume:
5638       case bp_step_resume:
5639       case bp_hp_step_resume:
5640       case bp_watchpoint_scope:
5641       case bp_call_dummy:
5642       case bp_std_terminate:
5643       case bp_shlib_event:
5644       case bp_thread_event:
5645       case bp_overlay_event:
5646       case bp_longjmp_master:
5647       case bp_std_terminate_master:
5648       case bp_exception_master:
5649       case bp_tracepoint:
5650       case bp_fast_tracepoint:
5651       case bp_static_tracepoint:
5652       case bp_dprintf:
5653       case bp_jit_event:
5654       case bp_gnu_ifunc_resolver:
5655       case bp_gnu_ifunc_resolver_return:
5656         if (opts.addressprint)
5657           {
5658             annotate_field (4);
5659             if (header_of_multiple)
5660               ui_out_field_string (uiout, "addr", "<MULTIPLE>");
5661             else if (b->loc == NULL || loc->shlib_disabled)
5662               ui_out_field_string (uiout, "addr", "<PENDING>");
5663             else
5664               ui_out_field_core_addr (uiout, "addr",
5665                                       loc->gdbarch, loc->address);
5666           }
5667         annotate_field (5);
5668         if (!header_of_multiple)
5669           print_breakpoint_location (b, loc);
5670         if (b->loc)
5671           *last_loc = b->loc;
5672         break;
5673       }
5674
5675
5676   /* For backward compatibility, don't display inferiors unless there
5677      are several.  */
5678   if (loc != NULL
5679       && !header_of_multiple
5680       && (allflag
5681           || (!gdbarch_has_global_breakpoints (target_gdbarch)
5682               && (number_of_program_spaces () > 1
5683                   || number_of_inferiors () > 1)
5684               /* LOC is for existing B, it cannot be in
5685                  moribund_locations and thus having NULL OWNER.  */
5686               && loc->owner->type != bp_catchpoint)))
5687     {
5688       struct inferior *inf;
5689       int first = 1;
5690
5691       for (inf = inferior_list; inf != NULL; inf = inf->next)
5692         {
5693           if (inf->pspace == loc->pspace)
5694             {
5695               if (first)
5696                 {
5697                   first = 0;
5698                   ui_out_text (uiout, " inf ");
5699                 }
5700               else
5701                 ui_out_text (uiout, ", ");
5702               ui_out_text (uiout, plongest (inf->num));
5703             }
5704         }
5705     }
5706
5707   if (!part_of_multiple)
5708     {
5709       if (b->thread != -1)
5710         {
5711           /* FIXME: This seems to be redundant and lost here; see the
5712              "stop only in" line a little further down.  */
5713           ui_out_text (uiout, " thread ");
5714           ui_out_field_int (uiout, "thread", b->thread);
5715         }
5716       else if (b->task != 0)
5717         {
5718           ui_out_text (uiout, " task ");
5719           ui_out_field_int (uiout, "task", b->task);
5720         }
5721     }
5722
5723   ui_out_text (uiout, "\n");
5724
5725   if (!part_of_multiple)
5726     b->ops->print_one_detail (b, uiout);
5727
5728   if (part_of_multiple && frame_id_p (b->frame_id))
5729     {
5730       annotate_field (6);
5731       ui_out_text (uiout, "\tstop only in stack frame at ");
5732       /* FIXME: cagney/2002-12-01: Shouldn't be poking around inside
5733          the frame ID.  */
5734       ui_out_field_core_addr (uiout, "frame",
5735                               b->gdbarch, b->frame_id.stack_addr);
5736       ui_out_text (uiout, "\n");
5737     }
5738   
5739   if (!part_of_multiple && b->cond_string)
5740     {
5741       annotate_field (7);
5742       if (is_tracepoint (b))
5743         ui_out_text (uiout, "\ttrace only if ");
5744       else
5745         ui_out_text (uiout, "\tstop only if ");
5746       ui_out_field_string (uiout, "cond", b->cond_string);
5747
5748       /* Print whether the target is doing the breakpoint's condition
5749          evaluation.  If GDB is doing the evaluation, don't print anything.  */
5750       if (is_breakpoint (b)
5751           && breakpoint_condition_evaluation_mode ()
5752           == condition_evaluation_target)
5753         {
5754           ui_out_text (uiout, " (");
5755           ui_out_field_string (uiout, "evaluated-by",
5756                                bp_condition_evaluator (b));
5757           ui_out_text (uiout, " evals)");
5758         }
5759       ui_out_text (uiout, "\n");
5760     }
5761
5762   if (!part_of_multiple && b->thread != -1)
5763     {
5764       /* FIXME should make an annotation for this.  */
5765       ui_out_text (uiout, "\tstop only in thread ");
5766       ui_out_field_int (uiout, "thread", b->thread);
5767       ui_out_text (uiout, "\n");
5768     }
5769   
5770   if (!part_of_multiple && b->hit_count)
5771     {
5772       /* FIXME should make an annotation for this.  */
5773       if (is_catchpoint (b))
5774         ui_out_text (uiout, "\tcatchpoint");
5775       else if (is_tracepoint (b))
5776         ui_out_text (uiout, "\ttracepoint");
5777       else
5778         ui_out_text (uiout, "\tbreakpoint");
5779       ui_out_text (uiout, " already hit ");
5780       ui_out_field_int (uiout, "times", b->hit_count);
5781       if (b->hit_count == 1)
5782         ui_out_text (uiout, " time\n");
5783       else
5784         ui_out_text (uiout, " times\n");
5785     }
5786   
5787   /* Output the count also if it is zero, but only if this is mi.
5788      FIXME: Should have a better test for this.  */
5789   if (ui_out_is_mi_like_p (uiout))
5790     if (!part_of_multiple && b->hit_count == 0)
5791       ui_out_field_int (uiout, "times", b->hit_count);
5792
5793   if (!part_of_multiple && b->ignore_count)
5794     {
5795       annotate_field (8);
5796       ui_out_text (uiout, "\tignore next ");
5797       ui_out_field_int (uiout, "ignore", b->ignore_count);
5798       ui_out_text (uiout, " hits\n");
5799     }
5800
5801   /* Note that an enable count of 1 corresponds to "enable once"
5802      behavior, which is reported by the combination of enablement and
5803      disposition, so we don't need to mention it here.  */
5804   if (!part_of_multiple && b->enable_count > 1)
5805     {
5806       annotate_field (8);
5807       ui_out_text (uiout, "\tdisable after ");
5808       /* Tweak the wording to clarify that ignore and enable counts
5809          are distinct, and have additive effect.  */
5810       if (b->ignore_count)
5811         ui_out_text (uiout, "additional ");
5812       else
5813         ui_out_text (uiout, "next ");
5814       ui_out_field_int (uiout, "enable", b->enable_count);
5815       ui_out_text (uiout, " hits\n");
5816     }
5817
5818   if (!part_of_multiple && is_tracepoint (b))
5819     {
5820       struct tracepoint *tp = (struct tracepoint *) b;
5821
5822       if (tp->traceframe_usage)
5823         {
5824           ui_out_text (uiout, "\ttrace buffer usage ");
5825           ui_out_field_int (uiout, "traceframe-usage", tp->traceframe_usage);
5826           ui_out_text (uiout, " bytes\n");
5827         }
5828     }
5829   
5830   l = b->commands ? b->commands->commands : NULL;
5831   if (!part_of_multiple && l)
5832     {
5833       struct cleanup *script_chain;
5834
5835       annotate_field (9);
5836       script_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "script");
5837       print_command_lines (uiout, l, 4);
5838       do_cleanups (script_chain);
5839     }
5840
5841   if (is_tracepoint (b))
5842     {
5843       struct tracepoint *t = (struct tracepoint *) b;
5844
5845       if (!part_of_multiple && t->pass_count)
5846         {
5847           annotate_field (10);
5848           ui_out_text (uiout, "\tpass count ");
5849           ui_out_field_int (uiout, "pass", t->pass_count);
5850           ui_out_text (uiout, " \n");
5851         }
5852     }
5853
5854   if (ui_out_is_mi_like_p (uiout) && !part_of_multiple)
5855     {
5856       if (is_watchpoint (b))
5857         {
5858           struct watchpoint *w = (struct watchpoint *) b;
5859
5860           ui_out_field_string (uiout, "original-location", w->exp_string);
5861         }
5862       else if (b->addr_string)
5863         ui_out_field_string (uiout, "original-location", b->addr_string);
5864     }
5865 }
5866
5867 static void
5868 print_one_breakpoint (struct breakpoint *b,
5869                       struct bp_location **last_loc, 
5870                       int allflag)
5871 {
5872   struct cleanup *bkpt_chain;
5873   struct ui_out *uiout = current_uiout;
5874
5875   bkpt_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "bkpt");
5876
5877   print_one_breakpoint_location (b, NULL, 0, last_loc, allflag);
5878   do_cleanups (bkpt_chain);
5879
5880   /* If this breakpoint has custom print function,
5881      it's already printed.  Otherwise, print individual
5882      locations, if any.  */
5883   if (b->ops == NULL || b->ops->print_one == NULL)
5884     {
5885       /* If breakpoint has a single location that is disabled, we
5886          print it as if it had several locations, since otherwise it's
5887          hard to represent "breakpoint enabled, location disabled"
5888          situation.
5889
5890          Note that while hardware watchpoints have several locations
5891          internally, that's not a property exposed to user.  */
5892       if (b->loc 
5893           && !is_hardware_watchpoint (b)
5894           && (b->loc->next || !b->loc->enabled))
5895         {
5896           struct bp_location *loc;
5897           int n = 1;
5898
5899           for (loc = b->loc; loc; loc = loc->next, ++n)
5900             {
5901               struct cleanup *inner2 =
5902                 make_cleanup_ui_out_tuple_begin_end (uiout, NULL);
5903               print_one_breakpoint_location (b, loc, n, last_loc, allflag);
5904               do_cleanups (inner2);
5905             }
5906         }
5907     }
5908 }
5909
5910 static int
5911 breakpoint_address_bits (struct breakpoint *b)
5912 {
5913   int print_address_bits = 0;
5914   struct bp_location *loc;
5915
5916   for (loc = b->loc; loc; loc = loc->next)
5917     {
5918       int addr_bit;
5919
5920       /* Software watchpoints that aren't watching memory don't have
5921          an address to print.  */
5922       if (b->type == bp_watchpoint && loc->watchpoint_type == -1)
5923         continue;
5924
5925       addr_bit = gdbarch_addr_bit (loc->gdbarch);
5926       if (addr_bit > print_address_bits)
5927         print_address_bits = addr_bit;
5928     }
5929
5930   return print_address_bits;
5931 }
5932
5933 struct captured_breakpoint_query_args
5934   {
5935     int bnum;
5936   };
5937
5938 static int
5939 do_captured_breakpoint_query (struct ui_out *uiout, void *data)
5940 {
5941   struct captured_breakpoint_query_args *args = data;
5942   struct breakpoint *b;
5943   struct bp_location *dummy_loc = NULL;
5944
5945   ALL_BREAKPOINTS (b)
5946     {
5947       if (args->bnum == b->number)
5948         {
5949           print_one_breakpoint (b, &dummy_loc, 0);
5950           return GDB_RC_OK;
5951         }
5952     }
5953   return GDB_RC_NONE;
5954 }
5955
5956 enum gdb_rc
5957 gdb_breakpoint_query (struct ui_out *uiout, int bnum, 
5958                       char **error_message)
5959 {
5960   struct captured_breakpoint_query_args args;
5961
5962   args.bnum = bnum;
5963   /* For the moment we don't trust print_one_breakpoint() to not throw
5964      an error.  */
5965   if (catch_exceptions_with_msg (uiout, do_captured_breakpoint_query, &args,
5966                                  error_message, RETURN_MASK_ALL) < 0)
5967     return GDB_RC_FAIL;
5968   else
5969     return GDB_RC_OK;
5970 }
5971
5972 /* Return true if this breakpoint was set by the user, false if it is
5973    internal or momentary.  */
5974
5975 int
5976 user_breakpoint_p (struct breakpoint *b)
5977 {
5978   return b->number > 0;
5979 }
5980
5981 /* Print information on user settable breakpoint (watchpoint, etc)
5982    number BNUM.  If BNUM is -1 print all user-settable breakpoints.
5983    If ALLFLAG is non-zero, include non-user-settable breakpoints.  If
5984    FILTER is non-NULL, call it on each breakpoint and only include the
5985    ones for which it returns non-zero.  Return the total number of
5986    breakpoints listed.  */
5987
5988 static int
5989 breakpoint_1 (char *args, int allflag, 
5990               int (*filter) (const struct breakpoint *))
5991 {
5992   struct breakpoint *b;
5993   struct bp_location *last_loc = NULL;
5994   int nr_printable_breakpoints;
5995   struct cleanup *bkpttbl_chain;
5996   struct value_print_options opts;
5997   int print_address_bits = 0;
5998   int print_type_col_width = 14;
5999   struct ui_out *uiout = current_uiout;
6000
6001   get_user_print_options (&opts);
6002
6003   /* Compute the number of rows in the table, as well as the size
6004      required for address fields.  */
6005   nr_printable_breakpoints = 0;
6006   ALL_BREAKPOINTS (b)
6007     {
6008       /* If we have a filter, only list the breakpoints it accepts.  */
6009       if (filter && !filter (b))
6010         continue;
6011
6012       /* If we have an "args" string, it is a list of breakpoints to 
6013          accept.  Skip the others.  */
6014       if (args != NULL && *args != '\0')
6015         {
6016           if (allflag && parse_and_eval_long (args) != b->number)
6017             continue;
6018           if (!allflag && !number_is_in_list (args, b->number))
6019             continue;
6020         }
6021
6022       if (allflag || user_breakpoint_p (b))
6023         {
6024           int addr_bit, type_len;
6025
6026           addr_bit = breakpoint_address_bits (b);
6027           if (addr_bit > print_address_bits)
6028             print_address_bits = addr_bit;
6029
6030           type_len = strlen (bptype_string (b->type));
6031           if (type_len > print_type_col_width)
6032             print_type_col_width = type_len;
6033
6034           nr_printable_breakpoints++;
6035         }
6036     }
6037
6038   if (opts.addressprint)
6039     bkpttbl_chain 
6040       = make_cleanup_ui_out_table_begin_end (uiout, 6,
6041                                              nr_printable_breakpoints,
6042                                              "BreakpointTable");
6043   else
6044     bkpttbl_chain 
6045       = make_cleanup_ui_out_table_begin_end (uiout, 5,
6046                                              nr_printable_breakpoints,
6047                                              "BreakpointTable");
6048
6049   if (nr_printable_breakpoints > 0)
6050     annotate_breakpoints_headers ();
6051   if (nr_printable_breakpoints > 0)
6052     annotate_field (0);
6053   ui_out_table_header (uiout, 7, ui_left, "number", "Num");     /* 1 */
6054   if (nr_printable_breakpoints > 0)
6055     annotate_field (1);
6056   ui_out_table_header (uiout, print_type_col_width, ui_left,
6057                        "type", "Type");                         /* 2 */
6058   if (nr_printable_breakpoints > 0)
6059     annotate_field (2);
6060   ui_out_table_header (uiout, 4, ui_left, "disp", "Disp");      /* 3 */
6061   if (nr_printable_breakpoints > 0)
6062     annotate_field (3);
6063   ui_out_table_header (uiout, 3, ui_left, "enabled", "Enb");    /* 4 */
6064   if (opts.addressprint)
6065     {
6066       if (nr_printable_breakpoints > 0)
6067         annotate_field (4);
6068       if (print_address_bits <= 32)
6069         ui_out_table_header (uiout, 10, ui_left, 
6070                              "addr", "Address");                /* 5 */
6071       else
6072         ui_out_table_header (uiout, 18, ui_left, 
6073                              "addr", "Address");                /* 5 */
6074     }
6075   if (nr_printable_breakpoints > 0)
6076     annotate_field (5);
6077   ui_out_table_header (uiout, 40, ui_noalign, "what", "What");  /* 6 */
6078   ui_out_table_body (uiout);
6079   if (nr_printable_breakpoints > 0)
6080     annotate_breakpoints_table ();
6081
6082   ALL_BREAKPOINTS (b)
6083     {
6084       QUIT;
6085       /* If we have a filter, only list the breakpoints it accepts.  */
6086       if (filter && !filter (b))
6087         continue;
6088
6089       /* If we have an "args" string, it is a list of breakpoints to 
6090          accept.  Skip the others.  */
6091
6092       if (args != NULL && *args != '\0')
6093         {
6094           if (allflag)  /* maintenance info breakpoint */
6095             {
6096               if (parse_and_eval_long (args) != b->number)
6097                 continue;
6098             }
6099           else          /* all others */
6100             {
6101               if (!number_is_in_list (args, b->number))
6102                 continue;
6103             }
6104         }
6105       /* We only print out user settable breakpoints unless the
6106          allflag is set.  */
6107       if (allflag || user_breakpoint_p (b))
6108         print_one_breakpoint (b, &last_loc, allflag);
6109     }
6110
6111   do_cleanups (bkpttbl_chain);
6112
6113   if (nr_printable_breakpoints == 0)
6114     {
6115       /* If there's a filter, let the caller decide how to report
6116          empty list.  */
6117       if (!filter)
6118         {
6119           if (args == NULL || *args == '\0')
6120             ui_out_message (uiout, 0, "No breakpoints or watchpoints.\n");
6121           else
6122             ui_out_message (uiout, 0, 
6123                             "No breakpoint or watchpoint matching '%s'.\n",
6124                             args);
6125         }
6126     }
6127   else
6128     {
6129       if (last_loc && !server_command)
6130         set_next_address (last_loc->gdbarch, last_loc->address);
6131     }
6132
6133   /* FIXME?  Should this be moved up so that it is only called when
6134      there have been breakpoints? */
6135   annotate_breakpoints_table_end ();
6136
6137   return nr_printable_breakpoints;
6138 }
6139
6140 /* Display the value of default-collect in a way that is generally
6141    compatible with the breakpoint list.  */
6142
6143 static void
6144 default_collect_info (void)
6145 {
6146   struct ui_out *uiout = current_uiout;
6147
6148   /* If it has no value (which is frequently the case), say nothing; a
6149      message like "No default-collect." gets in user's face when it's
6150      not wanted.  */
6151   if (!*default_collect)
6152     return;
6153
6154   /* The following phrase lines up nicely with per-tracepoint collect
6155      actions.  */
6156   ui_out_text (uiout, "default collect ");
6157   ui_out_field_string (uiout, "default-collect", default_collect);
6158   ui_out_text (uiout, " \n");
6159 }
6160   
6161 static void
6162 breakpoints_info (char *args, int from_tty)
6163 {
6164   breakpoint_1 (args, 0, NULL);
6165
6166   default_collect_info ();
6167 }
6168
6169 static void
6170 watchpoints_info (char *args, int from_tty)
6171 {
6172   int num_printed = breakpoint_1 (args, 0, is_watchpoint);
6173   struct ui_out *uiout = current_uiout;
6174
6175   if (num_printed == 0)
6176     {
6177       if (args == NULL || *args == '\0')
6178         ui_out_message (uiout, 0, "No watchpoints.\n");
6179       else
6180         ui_out_message (uiout, 0, "No watchpoint matching '%s'.\n", args);
6181     }
6182 }
6183
6184 static void
6185 maintenance_info_breakpoints (char *args, int from_tty)
6186 {
6187   breakpoint_1 (args, 1, NULL);
6188
6189   default_collect_info ();
6190 }
6191
6192 static int
6193 breakpoint_has_pc (struct breakpoint *b,
6194                    struct program_space *pspace,
6195                    CORE_ADDR pc, struct obj_section *section)
6196 {
6197   struct bp_location *bl = b->loc;
6198
6199   for (; bl; bl = bl->next)
6200     {
6201       if (bl->pspace == pspace
6202           && bl->address == pc
6203           && (!overlay_debugging || bl->section == section))
6204         return 1;         
6205     }
6206   return 0;
6207 }
6208
6209 /* Print a message describing any user-breakpoints set at PC.  This
6210    concerns with logical breakpoints, so we match program spaces, not
6211    address spaces.  */
6212
6213 static void
6214 describe_other_breakpoints (struct gdbarch *gdbarch,
6215                             struct program_space *pspace, CORE_ADDR pc,
6216                             struct obj_section *section, int thread)
6217 {
6218   int others = 0;
6219   struct breakpoint *b;
6220
6221   ALL_BREAKPOINTS (b)
6222     others += (user_breakpoint_p (b)
6223                && breakpoint_has_pc (b, pspace, pc, section));
6224   if (others > 0)
6225     {
6226       if (others == 1)
6227         printf_filtered (_("Note: breakpoint "));
6228       else /* if (others == ???) */
6229         printf_filtered (_("Note: breakpoints "));
6230       ALL_BREAKPOINTS (b)
6231         if (user_breakpoint_p (b) && breakpoint_has_pc (b, pspace, pc, section))
6232           {
6233             others--;
6234             printf_filtered ("%d", b->number);
6235             if (b->thread == -1 && thread != -1)
6236               printf_filtered (" (all threads)");
6237             else if (b->thread != -1)
6238               printf_filtered (" (thread %d)", b->thread);
6239             printf_filtered ("%s%s ",
6240                              ((b->enable_state == bp_disabled
6241                                || b->enable_state == bp_call_disabled)
6242                               ? " (disabled)"
6243                               : b->enable_state == bp_permanent 
6244                               ? " (permanent)"
6245                               : ""),
6246                              (others > 1) ? "," 
6247                              : ((others == 1) ? " and" : ""));
6248           }
6249       printf_filtered (_("also set at pc "));
6250       fputs_filtered (paddress (gdbarch, pc), gdb_stdout);
6251       printf_filtered (".\n");
6252     }
6253 }
6254 \f
6255
6256 /* Return true iff it is meaningful to use the address member of
6257    BPT.  For some breakpoint types, the address member is irrelevant
6258    and it makes no sense to attempt to compare it to other addresses
6259    (or use it for any other purpose either).
6260
6261    More specifically, each of the following breakpoint types will
6262    always have a zero valued address and we don't want to mark
6263    breakpoints of any of these types to be a duplicate of an actual
6264    breakpoint at address zero:
6265
6266       bp_watchpoint
6267       bp_catchpoint
6268
6269 */
6270
6271 static int
6272 breakpoint_address_is_meaningful (struct breakpoint *bpt)
6273 {
6274   enum bptype type = bpt->type;
6275
6276   return (type != bp_watchpoint && type != bp_catchpoint);
6277 }
6278
6279 /* Assuming LOC1 and LOC2's owners are hardware watchpoints, returns
6280    true if LOC1 and LOC2 represent the same watchpoint location.  */
6281
6282 static int
6283 watchpoint_locations_match (struct bp_location *loc1, 
6284                             struct bp_location *loc2)
6285 {
6286   struct watchpoint *w1 = (struct watchpoint *) loc1->owner;
6287   struct watchpoint *w2 = (struct watchpoint *) loc2->owner;
6288
6289   /* Both of them must exist.  */
6290   gdb_assert (w1 != NULL);
6291   gdb_assert (w2 != NULL);
6292
6293   /* If the target can evaluate the condition expression in hardware,
6294      then we we need to insert both watchpoints even if they are at
6295      the same place.  Otherwise the watchpoint will only trigger when
6296      the condition of whichever watchpoint was inserted evaluates to
6297      true, not giving a chance for GDB to check the condition of the
6298      other watchpoint.  */
6299   if ((w1->cond_exp
6300        && target_can_accel_watchpoint_condition (loc1->address, 
6301                                                  loc1->length,
6302                                                  loc1->watchpoint_type,
6303                                                  w1->cond_exp))
6304       || (w2->cond_exp
6305           && target_can_accel_watchpoint_condition (loc2->address, 
6306                                                     loc2->length,
6307                                                     loc2->watchpoint_type,
6308                                                     w2->cond_exp)))
6309     return 0;
6310
6311   /* Note that this checks the owner's type, not the location's.  In
6312      case the target does not support read watchpoints, but does
6313      support access watchpoints, we'll have bp_read_watchpoint
6314      watchpoints with hw_access locations.  Those should be considered
6315      duplicates of hw_read locations.  The hw_read locations will
6316      become hw_access locations later.  */
6317   return (loc1->owner->type == loc2->owner->type
6318           && loc1->pspace->aspace == loc2->pspace->aspace
6319           && loc1->address == loc2->address
6320           && loc1->length == loc2->length);
6321 }
6322
6323 /* Returns true if {ASPACE1,ADDR1} and {ASPACE2,ADDR2} represent the
6324    same breakpoint location.  In most targets, this can only be true
6325    if ASPACE1 matches ASPACE2.  On targets that have global
6326    breakpoints, the address space doesn't really matter.  */
6327
6328 static int
6329 breakpoint_address_match (struct address_space *aspace1, CORE_ADDR addr1,
6330                           struct address_space *aspace2, CORE_ADDR addr2)
6331 {
6332   return ((gdbarch_has_global_breakpoints (target_gdbarch)
6333            || aspace1 == aspace2)
6334           && addr1 == addr2);
6335 }
6336
6337 /* Returns true if {ASPACE2,ADDR2} falls within the range determined by
6338    {ASPACE1,ADDR1,LEN1}.  In most targets, this can only be true if ASPACE1
6339    matches ASPACE2.  On targets that have global breakpoints, the address
6340    space doesn't really matter.  */
6341
6342 static int
6343 breakpoint_address_match_range (struct address_space *aspace1, CORE_ADDR addr1,
6344                                 int len1, struct address_space *aspace2,
6345                                 CORE_ADDR addr2)
6346 {
6347   return ((gdbarch_has_global_breakpoints (target_gdbarch)
6348            || aspace1 == aspace2)
6349           && addr2 >= addr1 && addr2 < addr1 + len1);
6350 }
6351
6352 /* Returns true if {ASPACE,ADDR} matches the breakpoint BL.  BL may be
6353    a ranged breakpoint.  In most targets, a match happens only if ASPACE
6354    matches the breakpoint's address space.  On targets that have global
6355    breakpoints, the address space doesn't really matter.  */
6356
6357 static int
6358 breakpoint_location_address_match (struct bp_location *bl,
6359                                    struct address_space *aspace,
6360                                    CORE_ADDR addr)
6361 {
6362   return (breakpoint_address_match (bl->pspace->aspace, bl->address,
6363                                     aspace, addr)
6364           || (bl->length
6365               && breakpoint_address_match_range (bl->pspace->aspace,
6366                                                  bl->address, bl->length,
6367                                                  aspace, addr)));
6368 }
6369
6370 /* If LOC1 and LOC2's owners are not tracepoints, returns false directly.
6371    Then, if LOC1 and LOC2 represent the same tracepoint location, returns
6372    true, otherwise returns false.  */
6373
6374 static int
6375 tracepoint_locations_match (struct bp_location *loc1,
6376                             struct bp_location *loc2)
6377 {
6378   if (is_tracepoint (loc1->owner) && is_tracepoint (loc2->owner))
6379     /* Since tracepoint locations are never duplicated with others', tracepoint
6380        locations at the same address of different tracepoints are regarded as
6381        different locations.  */
6382     return (loc1->address == loc2->address && loc1->owner == loc2->owner);
6383   else
6384     return 0;
6385 }
6386
6387 /* Assuming LOC1 and LOC2's types' have meaningful target addresses
6388    (breakpoint_address_is_meaningful), returns true if LOC1 and LOC2
6389    represent the same location.  */
6390
6391 static int
6392 breakpoint_locations_match (struct bp_location *loc1, 
6393                             struct bp_location *loc2)
6394 {
6395   int hw_point1, hw_point2;
6396
6397   /* Both of them must not be in moribund_locations.  */
6398   gdb_assert (loc1->owner != NULL);
6399   gdb_assert (loc2->owner != NULL);
6400
6401   hw_point1 = is_hardware_watchpoint (loc1->owner);
6402   hw_point2 = is_hardware_watchpoint (loc2->owner);
6403
6404   if (hw_point1 != hw_point2)
6405     return 0;
6406   else if (hw_point1)
6407     return watchpoint_locations_match (loc1, loc2);
6408   else if (is_tracepoint (loc1->owner) || is_tracepoint (loc2->owner))
6409     return tracepoint_locations_match (loc1, loc2);
6410   else
6411     /* We compare bp_location.length in order to cover ranged breakpoints.  */
6412     return (breakpoint_address_match (loc1->pspace->aspace, loc1->address,
6413                                      loc2->pspace->aspace, loc2->address)
6414             && loc1->length == loc2->length);
6415 }
6416
6417 static void
6418 breakpoint_adjustment_warning (CORE_ADDR from_addr, CORE_ADDR to_addr,
6419                                int bnum, int have_bnum)
6420 {
6421   /* The longest string possibly returned by hex_string_custom
6422      is 50 chars.  These must be at least that big for safety.  */
6423   char astr1[64];
6424   char astr2[64];
6425
6426   strcpy (astr1, hex_string_custom ((unsigned long) from_addr, 8));
6427   strcpy (astr2, hex_string_custom ((unsigned long) to_addr, 8));
6428   if (have_bnum)
6429     warning (_("Breakpoint %d address previously adjusted from %s to %s."),
6430              bnum, astr1, astr2);
6431   else
6432     warning (_("Breakpoint address adjusted from %s to %s."), astr1, astr2);
6433 }
6434
6435 /* Adjust a breakpoint's address to account for architectural
6436    constraints on breakpoint placement.  Return the adjusted address.
6437    Note: Very few targets require this kind of adjustment.  For most
6438    targets, this function is simply the identity function.  */
6439
6440 static CORE_ADDR
6441 adjust_breakpoint_address (struct gdbarch *gdbarch,
6442                            CORE_ADDR bpaddr, enum bptype bptype)
6443 {
6444   if (!gdbarch_adjust_breakpoint_address_p (gdbarch))
6445     {
6446       /* Very few targets need any kind of breakpoint adjustment.  */
6447       return bpaddr;
6448     }
6449   else if (bptype == bp_watchpoint
6450            || bptype == bp_hardware_watchpoint
6451            || bptype == bp_read_watchpoint
6452            || bptype == bp_access_watchpoint
6453            || bptype == bp_catchpoint)
6454     {
6455       /* Watchpoints and the various bp_catch_* eventpoints should not
6456          have their addresses modified.  */
6457       return bpaddr;
6458     }
6459   else
6460     {
6461       CORE_ADDR adjusted_bpaddr;
6462
6463       /* Some targets have architectural constraints on the placement
6464          of breakpoint instructions.  Obtain the adjusted address.  */
6465       adjusted_bpaddr = gdbarch_adjust_breakpoint_address (gdbarch, bpaddr);
6466
6467       /* An adjusted breakpoint address can significantly alter
6468          a user's expectations.  Print a warning if an adjustment
6469          is required.  */
6470       if (adjusted_bpaddr != bpaddr)
6471         breakpoint_adjustment_warning (bpaddr, adjusted_bpaddr, 0, 0);
6472
6473       return adjusted_bpaddr;
6474     }
6475 }
6476
6477 void
6478 init_bp_location (struct bp_location *loc, const struct bp_location_ops *ops,
6479                   struct breakpoint *owner)
6480 {
6481   memset (loc, 0, sizeof (*loc));
6482
6483   gdb_assert (ops != NULL);
6484
6485   loc->ops = ops;
6486   loc->owner = owner;
6487   loc->cond = NULL;
6488   loc->cond_bytecode = NULL;
6489   loc->shlib_disabled = 0;
6490   loc->enabled = 1;
6491
6492   switch (owner->type)
6493     {
6494     case bp_breakpoint:
6495     case bp_until:
6496     case bp_finish:
6497     case bp_longjmp:
6498     case bp_longjmp_resume:
6499     case bp_longjmp_call_dummy:
6500     case bp_exception:
6501     case bp_exception_resume:
6502     case bp_step_resume:
6503     case bp_hp_step_resume:
6504     case bp_watchpoint_scope:
6505     case bp_call_dummy:
6506     case bp_std_terminate:
6507     case bp_shlib_event:
6508     case bp_thread_event:
6509     case bp_overlay_event:
6510     case bp_jit_event:
6511     case bp_longjmp_master:
6512     case bp_std_terminate_master:
6513     case bp_exception_master:
6514     case bp_gnu_ifunc_resolver:
6515     case bp_gnu_ifunc_resolver_return:
6516     case bp_dprintf:
6517       loc->loc_type = bp_loc_software_breakpoint;
6518       mark_breakpoint_location_modified (loc);
6519       break;
6520     case bp_hardware_breakpoint:
6521       loc->loc_type = bp_loc_hardware_breakpoint;
6522       mark_breakpoint_location_modified (loc);
6523       break;
6524     case bp_hardware_watchpoint:
6525     case bp_read_watchpoint:
6526     case bp_access_watchpoint:
6527       loc->loc_type = bp_loc_hardware_watchpoint;
6528       break;
6529     case bp_watchpoint:
6530     case bp_catchpoint:
6531     case bp_tracepoint:
6532     case bp_fast_tracepoint:
6533     case bp_static_tracepoint:
6534       loc->loc_type = bp_loc_other;
6535       break;
6536     default:
6537       internal_error (__FILE__, __LINE__, _("unknown breakpoint type"));
6538     }
6539
6540   loc->refc = 1;
6541 }
6542
6543 /* Allocate a struct bp_location.  */
6544
6545 static struct bp_location *
6546 allocate_bp_location (struct breakpoint *bpt)
6547 {
6548   return bpt->ops->allocate_location (bpt);
6549 }
6550
6551 static void
6552 free_bp_location (struct bp_location *loc)
6553 {
6554   loc->ops->dtor (loc);
6555   xfree (loc);
6556 }
6557
6558 /* Increment reference count.  */
6559
6560 static void
6561 incref_bp_location (struct bp_location *bl)
6562 {
6563   ++bl->refc;
6564 }
6565
6566 /* Decrement reference count.  If the reference count reaches 0,
6567    destroy the bp_location.  Sets *BLP to NULL.  */
6568
6569 static void
6570 decref_bp_location (struct bp_location **blp)
6571 {
6572   gdb_assert ((*blp)->refc > 0);
6573
6574   if (--(*blp)->refc == 0)
6575     free_bp_location (*blp);
6576   *blp = NULL;
6577 }
6578
6579 /* Add breakpoint B at the end of the global breakpoint chain.  */
6580
6581 static void
6582 add_to_breakpoint_chain (struct breakpoint *b)
6583 {
6584   struct breakpoint *b1;
6585
6586   /* Add this breakpoint to the end of the chain so that a list of
6587      breakpoints will come out in order of increasing numbers.  */
6588
6589   b1 = breakpoint_chain;
6590   if (b1 == 0)
6591     breakpoint_chain = b;
6592   else
6593     {
6594       while (b1->next)
6595         b1 = b1->next;
6596       b1->next = b;
6597     }
6598 }
6599
6600 /* Initializes breakpoint B with type BPTYPE and no locations yet.  */
6601
6602 static void
6603 init_raw_breakpoint_without_location (struct breakpoint *b,
6604                                       struct gdbarch *gdbarch,
6605                                       enum bptype bptype,
6606                                       const struct breakpoint_ops *ops)
6607 {
6608   memset (b, 0, sizeof (*b));
6609
6610   gdb_assert (ops != NULL);
6611
6612   b->ops = ops;
6613   b->type = bptype;
6614   b->gdbarch = gdbarch;
6615   b->language = current_language->la_language;
6616   b->input_radix = input_radix;
6617   b->thread = -1;
6618   b->enable_state = bp_enabled;
6619   b->next = 0;
6620   b->silent = 0;
6621   b->ignore_count = 0;
6622   b->commands = NULL;
6623   b->frame_id = null_frame_id;
6624   b->condition_not_parsed = 0;
6625   b->py_bp_object = NULL;
6626   b->related_breakpoint = b;
6627 }
6628
6629 /* Helper to set_raw_breakpoint below.  Creates a breakpoint
6630    that has type BPTYPE and has no locations as yet.  */
6631
6632 static struct breakpoint *
6633 set_raw_breakpoint_without_location (struct gdbarch *gdbarch,
6634                                      enum bptype bptype,
6635                                      const struct breakpoint_ops *ops)
6636 {
6637   struct breakpoint *b = XNEW (struct breakpoint);
6638
6639   init_raw_breakpoint_without_location (b, gdbarch, bptype, ops);
6640   add_to_breakpoint_chain (b);
6641   return b;
6642 }
6643
6644 /* Initialize loc->function_name.  EXPLICIT_LOC says no indirect function
6645    resolutions should be made as the user specified the location explicitly
6646    enough.  */
6647
6648 static void
6649 set_breakpoint_location_function (struct bp_location *loc, int explicit_loc)
6650 {
6651   gdb_assert (loc->owner != NULL);
6652
6653   if (loc->owner->type == bp_breakpoint
6654       || loc->owner->type == bp_hardware_breakpoint
6655       || is_tracepoint (loc->owner))
6656     {
6657       int is_gnu_ifunc;
6658       const char *function_name;
6659       CORE_ADDR func_addr;
6660
6661       find_pc_partial_function_gnu_ifunc (loc->address, &function_name,
6662                                           &func_addr, NULL, &is_gnu_ifunc);
6663
6664       if (is_gnu_ifunc && !explicit_loc)
6665         {
6666           struct breakpoint *b = loc->owner;
6667
6668           gdb_assert (loc->pspace == current_program_space);
6669           if (gnu_ifunc_resolve_name (function_name,
6670                                       &loc->requested_address))
6671             {
6672               /* Recalculate ADDRESS based on new REQUESTED_ADDRESS.  */
6673               loc->address = adjust_breakpoint_address (loc->gdbarch,
6674                                                         loc->requested_address,
6675                                                         b->type);
6676             }
6677           else if (b->type == bp_breakpoint && b->loc == loc
6678                    && loc->next == NULL && b->related_breakpoint == b)
6679             {
6680               /* Create only the whole new breakpoint of this type but do not
6681                  mess more complicated breakpoints with multiple locations.  */
6682               b->type = bp_gnu_ifunc_resolver;
6683               /* Remember the resolver's address for use by the return
6684                  breakpoint.  */
6685               loc->related_address = func_addr;
6686             }
6687         }
6688
6689       if (function_name)
6690         loc->function_name = xstrdup (function_name);
6691     }
6692 }
6693
6694 /* Attempt to determine architecture of location identified by SAL.  */
6695 struct gdbarch *
6696 get_sal_arch (struct symtab_and_line sal)
6697 {
6698   if (sal.section)
6699     return get_objfile_arch (sal.section->objfile);
6700   if (sal.symtab)
6701     return get_objfile_arch (sal.symtab->objfile);
6702
6703   return NULL;
6704 }
6705
6706 /* Low level routine for partially initializing a breakpoint of type
6707    BPTYPE.  The newly created breakpoint's address, section, source
6708    file name, and line number are provided by SAL.
6709
6710    It is expected that the caller will complete the initialization of
6711    the newly created breakpoint struct as well as output any status
6712    information regarding the creation of a new breakpoint.  */
6713
6714 static void
6715 init_raw_breakpoint (struct breakpoint *b, struct gdbarch *gdbarch,
6716                      struct symtab_and_line sal, enum bptype bptype,
6717                      const struct breakpoint_ops *ops)
6718 {
6719   init_raw_breakpoint_without_location (b, gdbarch, bptype, ops);
6720
6721   add_location_to_breakpoint (b, &sal);
6722
6723   if (bptype != bp_catchpoint)
6724     gdb_assert (sal.pspace != NULL);
6725
6726   /* Store the program space that was used to set the breakpoint,
6727      except for ordinary breakpoints, which are independent of the
6728      program space.  */
6729   if (bptype != bp_breakpoint && bptype != bp_hardware_breakpoint)
6730     b->pspace = sal.pspace;
6731
6732   breakpoints_changed ();
6733 }
6734
6735 /* set_raw_breakpoint is a low level routine for allocating and
6736    partially initializing a breakpoint of type BPTYPE.  The newly
6737    created breakpoint's address, section, source file name, and line
6738    number are provided by SAL.  The newly created and partially
6739    initialized breakpoint is added to the breakpoint chain and
6740    is also returned as the value of this function.
6741
6742    It is expected that the caller will complete the initialization of
6743    the newly created breakpoint struct as well as output any status
6744    information regarding the creation of a new breakpoint.  In
6745    particular, set_raw_breakpoint does NOT set the breakpoint
6746    number!  Care should be taken to not allow an error to occur
6747    prior to completing the initialization of the breakpoint.  If this
6748    should happen, a bogus breakpoint will be left on the chain.  */
6749
6750 struct breakpoint *
6751 set_raw_breakpoint (struct gdbarch *gdbarch,
6752                     struct symtab_and_line sal, enum bptype bptype,
6753                     const struct breakpoint_ops *ops)
6754 {
6755   struct breakpoint *b = XNEW (struct breakpoint);
6756
6757   init_raw_breakpoint (b, gdbarch, sal, bptype, ops);
6758   add_to_breakpoint_chain (b);
6759   return b;
6760 }
6761
6762
6763 /* Note that the breakpoint object B describes a permanent breakpoint
6764    instruction, hard-wired into the inferior's code.  */
6765 void
6766 make_breakpoint_permanent (struct breakpoint *b)
6767 {
6768   struct bp_location *bl;
6769
6770   b->enable_state = bp_permanent;
6771
6772   /* By definition, permanent breakpoints are already present in the
6773      code.  Mark all locations as inserted.  For now,
6774      make_breakpoint_permanent is called in just one place, so it's
6775      hard to say if it's reasonable to have permanent breakpoint with
6776      multiple locations or not, but it's easy to implement.  */
6777   for (bl = b->loc; bl; bl = bl->next)
6778     bl->inserted = 1;
6779 }
6780
6781 /* Call this routine when stepping and nexting to enable a breakpoint
6782    if we do a longjmp() or 'throw' in TP.  FRAME is the frame which
6783    initiated the operation.  */
6784
6785 void
6786 set_longjmp_breakpoint (struct thread_info *tp, struct frame_id frame)
6787 {
6788   struct breakpoint *b, *b_tmp;
6789   int thread = tp->num;
6790
6791   /* To avoid having to rescan all objfile symbols at every step,
6792      we maintain a list of continually-inserted but always disabled
6793      longjmp "master" breakpoints.  Here, we simply create momentary
6794      clones of those and enable them for the requested thread.  */
6795   ALL_BREAKPOINTS_SAFE (b, b_tmp)
6796     if (b->pspace == current_program_space
6797         && (b->type == bp_longjmp_master
6798             || b->type == bp_exception_master))
6799       {
6800         enum bptype type = b->type == bp_longjmp_master ? bp_longjmp : bp_exception;
6801         struct breakpoint *clone;
6802
6803         /* longjmp_breakpoint_ops ensures INITIATING_FRAME is cleared again
6804            after their removal.  */
6805         clone = momentary_breakpoint_from_master (b, type,
6806                                                   &longjmp_breakpoint_ops);
6807         clone->thread = thread;
6808       }
6809
6810   tp->initiating_frame = frame;
6811 }
6812
6813 /* Delete all longjmp breakpoints from THREAD.  */
6814 void
6815 delete_longjmp_breakpoint (int thread)
6816 {
6817   struct breakpoint *b, *b_tmp;
6818
6819   ALL_BREAKPOINTS_SAFE (b, b_tmp)
6820     if (b->type == bp_longjmp || b->type == bp_exception)
6821       {
6822         if (b->thread == thread)
6823           delete_breakpoint (b);
6824       }
6825 }
6826
6827 void
6828 delete_longjmp_breakpoint_at_next_stop (int thread)
6829 {
6830   struct breakpoint *b, *b_tmp;
6831
6832   ALL_BREAKPOINTS_SAFE (b, b_tmp)
6833     if (b->type == bp_longjmp || b->type == bp_exception)
6834       {
6835         if (b->thread == thread)
6836           b->disposition = disp_del_at_next_stop;
6837       }
6838 }
6839
6840 /* Place breakpoints of type bp_longjmp_call_dummy to catch longjmp for
6841    INFERIOR_PTID thread.  Chain them all by RELATED_BREAKPOINT and return
6842    pointer to any of them.  Return NULL if this system cannot place longjmp
6843    breakpoints.  */
6844
6845 struct breakpoint *
6846 set_longjmp_breakpoint_for_call_dummy (void)
6847 {
6848   struct breakpoint *b, *retval = NULL;
6849
6850   ALL_BREAKPOINTS (b)
6851     if (b->pspace == current_program_space && b->type == bp_longjmp_master)
6852       {
6853         struct breakpoint *new_b;
6854
6855         new_b = momentary_breakpoint_from_master (b, bp_longjmp_call_dummy,
6856                                                   &momentary_breakpoint_ops);
6857         new_b->thread = pid_to_thread_id (inferior_ptid);
6858
6859         /* Link NEW_B into the chain of RETVAL breakpoints.  */
6860
6861         gdb_assert (new_b->related_breakpoint == new_b);
6862         if (retval == NULL)
6863           retval = new_b;
6864         new_b->related_breakpoint = retval;
6865         while (retval->related_breakpoint != new_b->related_breakpoint)
6866           retval = retval->related_breakpoint;
6867         retval->related_breakpoint = new_b;
6868       }
6869
6870   return retval;
6871 }
6872
6873 /* Verify all existing dummy frames and their associated breakpoints for
6874    THREAD.  Remove those which can no longer be found in the current frame
6875    stack.
6876
6877    You should call this function only at places where it is safe to currently
6878    unwind the whole stack.  Failed stack unwind would discard live dummy
6879    frames.  */
6880
6881 void
6882 check_longjmp_breakpoint_for_call_dummy (int thread)
6883 {
6884   struct breakpoint *b, *b_tmp;
6885
6886   ALL_BREAKPOINTS_SAFE (b, b_tmp)
6887     if (b->type == bp_longjmp_call_dummy && b->thread == thread)
6888       {
6889         struct breakpoint *dummy_b = b->related_breakpoint;
6890
6891         while (dummy_b != b && dummy_b->type != bp_call_dummy)
6892           dummy_b = dummy_b->related_breakpoint;
6893         if (dummy_b->type != bp_call_dummy
6894             || frame_find_by_id (dummy_b->frame_id) != NULL)
6895           continue;
6896         
6897         dummy_frame_discard (dummy_b->frame_id);
6898
6899         while (b->related_breakpoint != b)
6900           {
6901             if (b_tmp == b->related_breakpoint)
6902               b_tmp = b->related_breakpoint->next;
6903             delete_breakpoint (b->related_breakpoint);
6904           }
6905         delete_breakpoint (b);
6906       }
6907 }
6908
6909 void
6910 enable_overlay_breakpoints (void)
6911 {
6912   struct breakpoint *b;
6913
6914   ALL_BREAKPOINTS (b)
6915     if (b->type == bp_overlay_event)
6916     {
6917       b->enable_state = bp_enabled;
6918       update_global_location_list (1);
6919       overlay_events_enabled = 1;
6920     }
6921 }
6922
6923 void
6924 disable_overlay_breakpoints (void)
6925 {
6926   struct breakpoint *b;
6927
6928   ALL_BREAKPOINTS (b)
6929     if (b->type == bp_overlay_event)
6930     {
6931       b->enable_state = bp_disabled;
6932       update_global_location_list (0);
6933       overlay_events_enabled = 0;
6934     }
6935 }
6936
6937 /* Set an active std::terminate breakpoint for each std::terminate
6938    master breakpoint.  */
6939 void
6940 set_std_terminate_breakpoint (void)
6941 {
6942   struct breakpoint *b, *b_tmp;
6943
6944   ALL_BREAKPOINTS_SAFE (b, b_tmp)
6945     if (b->pspace == current_program_space
6946         && b->type == bp_std_terminate_master)
6947       {
6948         momentary_breakpoint_from_master (b, bp_std_terminate,
6949                                           &momentary_breakpoint_ops);
6950       }
6951 }
6952
6953 /* Delete all the std::terminate breakpoints.  */
6954 void
6955 delete_std_terminate_breakpoint (void)
6956 {
6957   struct breakpoint *b, *b_tmp;
6958
6959   ALL_BREAKPOINTS_SAFE (b, b_tmp)
6960     if (b->type == bp_std_terminate)
6961       delete_breakpoint (b);
6962 }
6963
6964 struct breakpoint *
6965 create_thread_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
6966 {
6967   struct breakpoint *b;
6968
6969   b = create_internal_breakpoint (gdbarch, address, bp_thread_event,
6970                                   &internal_breakpoint_ops);
6971
6972   b->enable_state = bp_enabled;
6973   /* addr_string has to be used or breakpoint_re_set will delete me.  */
6974   b->addr_string
6975     = xstrprintf ("*%s", paddress (b->loc->gdbarch, b->loc->address));
6976
6977   update_global_location_list_nothrow (1);
6978
6979   return b;
6980 }
6981
6982 void
6983 remove_thread_event_breakpoints (void)
6984 {
6985   struct breakpoint *b, *b_tmp;
6986
6987   ALL_BREAKPOINTS_SAFE (b, b_tmp)
6988     if (b->type == bp_thread_event
6989         && b->loc->pspace == current_program_space)
6990       delete_breakpoint (b);
6991 }
6992
6993 struct lang_and_radix
6994   {
6995     enum language lang;
6996     int radix;
6997   };
6998
6999 /* Create a breakpoint for JIT code registration and unregistration.  */
7000
7001 struct breakpoint *
7002 create_jit_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7003 {
7004   struct breakpoint *b;
7005
7006   b = create_internal_breakpoint (gdbarch, address, bp_jit_event,
7007                                   &internal_breakpoint_ops);
7008   update_global_location_list_nothrow (1);
7009   return b;
7010 }
7011
7012 /* Remove JIT code registration and unregistration breakpoint(s).  */
7013
7014 void
7015 remove_jit_event_breakpoints (void)
7016 {
7017   struct breakpoint *b, *b_tmp;
7018
7019   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7020     if (b->type == bp_jit_event
7021         && b->loc->pspace == current_program_space)
7022       delete_breakpoint (b);
7023 }
7024
7025 void
7026 remove_solib_event_breakpoints (void)
7027 {
7028   struct breakpoint *b, *b_tmp;
7029
7030   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7031     if (b->type == bp_shlib_event
7032         && b->loc->pspace == current_program_space)
7033       delete_breakpoint (b);
7034 }
7035
7036 struct breakpoint *
7037 create_solib_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7038 {
7039   struct breakpoint *b;
7040
7041   b = create_internal_breakpoint (gdbarch, address, bp_shlib_event,
7042                                   &internal_breakpoint_ops);
7043   update_global_location_list_nothrow (1);
7044   return b;
7045 }
7046
7047 /* Disable any breakpoints that are on code in shared libraries.  Only
7048    apply to enabled breakpoints, disabled ones can just stay disabled.  */
7049
7050 void
7051 disable_breakpoints_in_shlibs (void)
7052 {
7053   struct bp_location *loc, **locp_tmp;
7054
7055   ALL_BP_LOCATIONS (loc, locp_tmp)
7056   {
7057     /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
7058     struct breakpoint *b = loc->owner;
7059
7060     /* We apply the check to all breakpoints, including disabled for
7061        those with loc->duplicate set.  This is so that when breakpoint
7062        becomes enabled, or the duplicate is removed, gdb will try to
7063        insert all breakpoints.  If we don't set shlib_disabled here,
7064        we'll try to insert those breakpoints and fail.  */
7065     if (((b->type == bp_breakpoint)
7066          || (b->type == bp_jit_event)
7067          || (b->type == bp_hardware_breakpoint)
7068          || (is_tracepoint (b)))
7069         && loc->pspace == current_program_space
7070         && !loc->shlib_disabled
7071 #ifdef PC_SOLIB
7072         && PC_SOLIB (loc->address)
7073 #else
7074         && solib_name_from_address (loc->pspace, loc->address)
7075 #endif
7076         )
7077       {
7078         loc->shlib_disabled = 1;
7079       }
7080   }
7081 }
7082
7083 /* Disable any breakpoints and tracepoints that are in an unloaded shared
7084    library.  Only apply to enabled breakpoints, disabled ones can just stay
7085    disabled.  */
7086
7087 static void
7088 disable_breakpoints_in_unloaded_shlib (struct so_list *solib)
7089 {
7090   struct bp_location *loc, **locp_tmp;
7091   int disabled_shlib_breaks = 0;
7092
7093   /* SunOS a.out shared libraries are always mapped, so do not
7094      disable breakpoints; they will only be reported as unloaded
7095      through clear_solib when GDB discards its shared library
7096      list.  See clear_solib for more information.  */
7097   if (exec_bfd != NULL
7098       && bfd_get_flavour (exec_bfd) == bfd_target_aout_flavour)
7099     return;
7100
7101   ALL_BP_LOCATIONS (loc, locp_tmp)
7102   {
7103     /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
7104     struct breakpoint *b = loc->owner;
7105
7106     if (solib->pspace == loc->pspace
7107         && !loc->shlib_disabled
7108         && (((b->type == bp_breakpoint
7109               || b->type == bp_jit_event
7110               || b->type == bp_hardware_breakpoint)
7111              && (loc->loc_type == bp_loc_hardware_breakpoint
7112                  || loc->loc_type == bp_loc_software_breakpoint))
7113             || is_tracepoint (b))
7114         && solib_contains_address_p (solib, loc->address))
7115       {
7116         loc->shlib_disabled = 1;
7117         /* At this point, we cannot rely on remove_breakpoint
7118            succeeding so we must mark the breakpoint as not inserted
7119            to prevent future errors occurring in remove_breakpoints.  */
7120         loc->inserted = 0;
7121
7122         /* This may cause duplicate notifications for the same breakpoint.  */
7123         observer_notify_breakpoint_modified (b);
7124
7125         if (!disabled_shlib_breaks)
7126           {
7127             target_terminal_ours_for_output ();
7128             warning (_("Temporarily disabling breakpoints "
7129                        "for unloaded shared library \"%s\""),
7130                      solib->so_name);
7131           }
7132         disabled_shlib_breaks = 1;
7133       }
7134   }
7135 }
7136
7137 /* FORK & VFORK catchpoints.  */
7138
7139 /* An instance of this type is used to represent a fork or vfork
7140    catchpoint.  It includes a "struct breakpoint" as a kind of base
7141    class; users downcast to "struct breakpoint *" when needed.  A
7142    breakpoint is really of this type iff its ops pointer points to
7143    CATCH_FORK_BREAKPOINT_OPS.  */
7144
7145 struct fork_catchpoint
7146 {
7147   /* The base class.  */
7148   struct breakpoint base;
7149
7150   /* Process id of a child process whose forking triggered this
7151      catchpoint.  This field is only valid immediately after this
7152      catchpoint has triggered.  */
7153   ptid_t forked_inferior_pid;
7154 };
7155
7156 /* Implement the "insert" breakpoint_ops method for fork
7157    catchpoints.  */
7158
7159 static int
7160 insert_catch_fork (struct bp_location *bl)
7161 {
7162   return target_insert_fork_catchpoint (PIDGET (inferior_ptid));
7163 }
7164
7165 /* Implement the "remove" breakpoint_ops method for fork
7166    catchpoints.  */
7167
7168 static int
7169 remove_catch_fork (struct bp_location *bl)
7170 {
7171   return target_remove_fork_catchpoint (PIDGET (inferior_ptid));
7172 }
7173
7174 /* Implement the "breakpoint_hit" breakpoint_ops method for fork
7175    catchpoints.  */
7176
7177 static int
7178 breakpoint_hit_catch_fork (const struct bp_location *bl,
7179                            struct address_space *aspace, CORE_ADDR bp_addr,
7180                            const struct target_waitstatus *ws)
7181 {
7182   struct fork_catchpoint *c = (struct fork_catchpoint *) bl->owner;
7183
7184   if (ws->kind != TARGET_WAITKIND_FORKED)
7185     return 0;
7186
7187   c->forked_inferior_pid = ws->value.related_pid;
7188   return 1;
7189 }
7190
7191 /* Implement the "print_it" breakpoint_ops method for fork
7192    catchpoints.  */
7193
7194 static enum print_stop_action
7195 print_it_catch_fork (bpstat bs)
7196 {
7197   struct ui_out *uiout = current_uiout;
7198   struct breakpoint *b = bs->breakpoint_at;
7199   struct fork_catchpoint *c = (struct fork_catchpoint *) bs->breakpoint_at;
7200
7201   annotate_catchpoint (b->number);
7202   if (b->disposition == disp_del)
7203     ui_out_text (uiout, "\nTemporary catchpoint ");
7204   else
7205     ui_out_text (uiout, "\nCatchpoint ");
7206   if (ui_out_is_mi_like_p (uiout))
7207     {
7208       ui_out_field_string (uiout, "reason",
7209                            async_reason_lookup (EXEC_ASYNC_FORK));
7210       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
7211     }
7212   ui_out_field_int (uiout, "bkptno", b->number);
7213   ui_out_text (uiout, " (forked process ");
7214   ui_out_field_int (uiout, "newpid", ptid_get_pid (c->forked_inferior_pid));
7215   ui_out_text (uiout, "), ");
7216   return PRINT_SRC_AND_LOC;
7217 }
7218
7219 /* Implement the "print_one" breakpoint_ops method for fork
7220    catchpoints.  */
7221
7222 static void
7223 print_one_catch_fork (struct breakpoint *b, struct bp_location **last_loc)
7224 {
7225   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
7226   struct value_print_options opts;
7227   struct ui_out *uiout = current_uiout;
7228
7229   get_user_print_options (&opts);
7230
7231   /* Field 4, the address, is omitted (which makes the columns not
7232      line up too nicely with the headers, but the effect is relatively
7233      readable).  */
7234   if (opts.addressprint)
7235     ui_out_field_skip (uiout, "addr");
7236   annotate_field (5);
7237   ui_out_text (uiout, "fork");
7238   if (!ptid_equal (c->forked_inferior_pid, null_ptid))
7239     {
7240       ui_out_text (uiout, ", process ");
7241       ui_out_field_int (uiout, "what",
7242                         ptid_get_pid (c->forked_inferior_pid));
7243       ui_out_spaces (uiout, 1);
7244     }
7245 }
7246
7247 /* Implement the "print_mention" breakpoint_ops method for fork
7248    catchpoints.  */
7249
7250 static void
7251 print_mention_catch_fork (struct breakpoint *b)
7252 {
7253   printf_filtered (_("Catchpoint %d (fork)"), b->number);
7254 }
7255
7256 /* Implement the "print_recreate" breakpoint_ops method for fork
7257    catchpoints.  */
7258
7259 static void
7260 print_recreate_catch_fork (struct breakpoint *b, struct ui_file *fp)
7261 {
7262   fprintf_unfiltered (fp, "catch fork");
7263   print_recreate_thread (b, fp);
7264 }
7265
7266 /* The breakpoint_ops structure to be used in fork catchpoints.  */
7267
7268 static struct breakpoint_ops catch_fork_breakpoint_ops;
7269
7270 /* Implement the "insert" breakpoint_ops method for vfork
7271    catchpoints.  */
7272
7273 static int
7274 insert_catch_vfork (struct bp_location *bl)
7275 {
7276   return target_insert_vfork_catchpoint (PIDGET (inferior_ptid));
7277 }
7278
7279 /* Implement the "remove" breakpoint_ops method for vfork
7280    catchpoints.  */
7281
7282 static int
7283 remove_catch_vfork (struct bp_location *bl)
7284 {
7285   return target_remove_vfork_catchpoint (PIDGET (inferior_ptid));
7286 }
7287
7288 /* Implement the "breakpoint_hit" breakpoint_ops method for vfork
7289    catchpoints.  */
7290
7291 static int
7292 breakpoint_hit_catch_vfork (const struct bp_location *bl,
7293                             struct address_space *aspace, CORE_ADDR bp_addr,
7294                             const struct target_waitstatus *ws)
7295 {
7296   struct fork_catchpoint *c = (struct fork_catchpoint *) bl->owner;
7297
7298   if (ws->kind != TARGET_WAITKIND_VFORKED)
7299     return 0;
7300
7301   c->forked_inferior_pid = ws->value.related_pid;
7302   return 1;
7303 }
7304
7305 /* Implement the "print_it" breakpoint_ops method for vfork
7306    catchpoints.  */
7307
7308 static enum print_stop_action
7309 print_it_catch_vfork (bpstat bs)
7310 {
7311   struct ui_out *uiout = current_uiout;
7312   struct breakpoint *b = bs->breakpoint_at;
7313   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
7314
7315   annotate_catchpoint (b->number);
7316   if (b->disposition == disp_del)
7317     ui_out_text (uiout, "\nTemporary catchpoint ");
7318   else
7319     ui_out_text (uiout, "\nCatchpoint ");
7320   if (ui_out_is_mi_like_p (uiout))
7321     {
7322       ui_out_field_string (uiout, "reason",
7323                            async_reason_lookup (EXEC_ASYNC_VFORK));
7324       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
7325     }
7326   ui_out_field_int (uiout, "bkptno", b->number);
7327   ui_out_text (uiout, " (vforked process ");
7328   ui_out_field_int (uiout, "newpid", ptid_get_pid (c->forked_inferior_pid));
7329   ui_out_text (uiout, "), ");
7330   return PRINT_SRC_AND_LOC;
7331 }
7332
7333 /* Implement the "print_one" breakpoint_ops method for vfork
7334    catchpoints.  */
7335
7336 static void
7337 print_one_catch_vfork (struct breakpoint *b, struct bp_location **last_loc)
7338 {
7339   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
7340   struct value_print_options opts;
7341   struct ui_out *uiout = current_uiout;
7342
7343   get_user_print_options (&opts);
7344   /* Field 4, the address, is omitted (which makes the columns not
7345      line up too nicely with the headers, but the effect is relatively
7346      readable).  */
7347   if (opts.addressprint)
7348     ui_out_field_skip (uiout, "addr");
7349   annotate_field (5);
7350   ui_out_text (uiout, "vfork");
7351   if (!ptid_equal (c->forked_inferior_pid, null_ptid))
7352     {
7353       ui_out_text (uiout, ", process ");
7354       ui_out_field_int (uiout, "what",
7355                         ptid_get_pid (c->forked_inferior_pid));
7356       ui_out_spaces (uiout, 1);
7357     }
7358 }
7359
7360 /* Implement the "print_mention" breakpoint_ops method for vfork
7361    catchpoints.  */
7362
7363 static void
7364 print_mention_catch_vfork (struct breakpoint *b)
7365 {
7366   printf_filtered (_("Catchpoint %d (vfork)"), b->number);
7367 }
7368
7369 /* Implement the "print_recreate" breakpoint_ops method for vfork
7370    catchpoints.  */
7371
7372 static void
7373 print_recreate_catch_vfork (struct breakpoint *b, struct ui_file *fp)
7374 {
7375   fprintf_unfiltered (fp, "catch vfork");
7376   print_recreate_thread (b, fp);
7377 }
7378
7379 /* The breakpoint_ops structure to be used in vfork catchpoints.  */
7380
7381 static struct breakpoint_ops catch_vfork_breakpoint_ops;
7382
7383 /* An instance of this type is used to represent an solib catchpoint.
7384    It includes a "struct breakpoint" as a kind of base class; users
7385    downcast to "struct breakpoint *" when needed.  A breakpoint is
7386    really of this type iff its ops pointer points to
7387    CATCH_SOLIB_BREAKPOINT_OPS.  */
7388
7389 struct solib_catchpoint
7390 {
7391   /* The base class.  */
7392   struct breakpoint base;
7393
7394   /* True for "catch load", false for "catch unload".  */
7395   unsigned char is_load;
7396
7397   /* Regular expression to match, if any.  COMPILED is only valid when
7398      REGEX is non-NULL.  */
7399   char *regex;
7400   regex_t compiled;
7401 };
7402
7403 static void
7404 dtor_catch_solib (struct breakpoint *b)
7405 {
7406   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
7407
7408   if (self->regex)
7409     regfree (&self->compiled);
7410   xfree (self->regex);
7411
7412   base_breakpoint_ops.dtor (b);
7413 }
7414
7415 static int
7416 insert_catch_solib (struct bp_location *ignore)
7417 {
7418   return 0;
7419 }
7420
7421 static int
7422 remove_catch_solib (struct bp_location *ignore)
7423 {
7424   return 0;
7425 }
7426
7427 static int
7428 breakpoint_hit_catch_solib (const struct bp_location *bl,
7429                             struct address_space *aspace,
7430                             CORE_ADDR bp_addr,
7431                             const struct target_waitstatus *ws)
7432 {
7433   struct solib_catchpoint *self = (struct solib_catchpoint *) bl->owner;
7434   struct breakpoint *other;
7435
7436   if (ws->kind == TARGET_WAITKIND_LOADED)
7437     return 1;
7438
7439   ALL_BREAKPOINTS (other)
7440   {
7441     struct bp_location *other_bl;
7442
7443     if (other == bl->owner)
7444       continue;
7445
7446     if (other->type != bp_shlib_event)
7447       continue;
7448
7449     if (self->base.pspace != NULL && other->pspace != self->base.pspace)
7450       continue;
7451
7452     for (other_bl = other->loc; other_bl != NULL; other_bl = other_bl->next)
7453       {
7454         if (other->ops->breakpoint_hit (other_bl, aspace, bp_addr, ws))
7455           return 1;
7456       }
7457   }
7458
7459   return 0;
7460 }
7461
7462 static void
7463 check_status_catch_solib (struct bpstats *bs)
7464 {
7465   struct solib_catchpoint *self
7466     = (struct solib_catchpoint *) bs->breakpoint_at;
7467   int ix;
7468
7469   if (self->is_load)
7470     {
7471       struct so_list *iter;
7472
7473       for (ix = 0;
7474            VEC_iterate (so_list_ptr, current_program_space->added_solibs,
7475                         ix, iter);
7476            ++ix)
7477         {
7478           if (!self->regex
7479               || regexec (&self->compiled, iter->so_name, 0, NULL, 0) == 0)
7480             return;
7481         }
7482     }
7483   else
7484     {
7485       char *iter;
7486
7487       for (ix = 0;
7488            VEC_iterate (char_ptr, current_program_space->deleted_solibs,
7489                         ix, iter);
7490            ++ix)
7491         {
7492           if (!self->regex
7493               || regexec (&self->compiled, iter, 0, NULL, 0) == 0)
7494             return;
7495         }
7496     }
7497
7498   bs->stop = 0;
7499   bs->print_it = print_it_noop;
7500 }
7501
7502 static enum print_stop_action
7503 print_it_catch_solib (bpstat bs)
7504 {
7505   struct breakpoint *b = bs->breakpoint_at;
7506   struct ui_out *uiout = current_uiout;
7507
7508   annotate_catchpoint (b->number);
7509   if (b->disposition == disp_del)
7510     ui_out_text (uiout, "\nTemporary catchpoint ");
7511   else
7512     ui_out_text (uiout, "\nCatchpoint ");
7513   ui_out_field_int (uiout, "bkptno", b->number);
7514   ui_out_text (uiout, "\n");
7515   if (ui_out_is_mi_like_p (uiout))
7516     ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
7517   print_solib_event (1);
7518   return PRINT_SRC_AND_LOC;
7519 }
7520
7521 static void
7522 print_one_catch_solib (struct breakpoint *b, struct bp_location **locs)
7523 {
7524   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
7525   struct value_print_options opts;
7526   struct ui_out *uiout = current_uiout;
7527   char *msg;
7528
7529   get_user_print_options (&opts);
7530   /* Field 4, the address, is omitted (which makes the columns not
7531      line up too nicely with the headers, but the effect is relatively
7532      readable).  */
7533   if (opts.addressprint)
7534     {
7535       annotate_field (4);
7536       ui_out_field_skip (uiout, "addr");
7537     }
7538
7539   annotate_field (5);
7540   if (self->is_load)
7541     {
7542       if (self->regex)
7543         msg = xstrprintf (_("load of library matching %s"), self->regex);
7544       else
7545         msg = xstrdup (_("load of library"));
7546     }
7547   else
7548     {
7549       if (self->regex)
7550         msg = xstrprintf (_("unload of library matching %s"), self->regex);
7551       else
7552         msg = xstrdup (_("unload of library"));
7553     }
7554   ui_out_field_string (uiout, "what", msg);
7555   xfree (msg);
7556 }
7557
7558 static void
7559 print_mention_catch_solib (struct breakpoint *b)
7560 {
7561   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
7562
7563   printf_filtered (_("Catchpoint %d (%s)"), b->number,
7564                    self->is_load ? "load" : "unload");
7565 }
7566
7567 static void
7568 print_recreate_catch_solib (struct breakpoint *b, struct ui_file *fp)
7569 {
7570   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
7571
7572   fprintf_unfiltered (fp, "%s %s",
7573                       b->disposition == disp_del ? "tcatch" : "catch",
7574                       self->is_load ? "load" : "unload");
7575   if (self->regex)
7576     fprintf_unfiltered (fp, " %s", self->regex);
7577   fprintf_unfiltered (fp, "\n");
7578 }
7579
7580 static struct breakpoint_ops catch_solib_breakpoint_ops;
7581
7582 /* A helper function that does all the work for "catch load" and
7583    "catch unload".  */
7584
7585 static void
7586 catch_load_or_unload (char *arg, int from_tty, int is_load,
7587                       struct cmd_list_element *command)
7588 {
7589   struct solib_catchpoint *c;
7590   struct gdbarch *gdbarch = get_current_arch ();
7591   int tempflag;
7592   struct cleanup *cleanup;
7593
7594   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
7595
7596   if (!arg)
7597     arg = "";
7598   arg = skip_spaces (arg);
7599
7600   c = XCNEW (struct solib_catchpoint);
7601   cleanup = make_cleanup (xfree, c);
7602
7603   if (*arg != '\0')
7604     {
7605       int errcode;
7606
7607       errcode = regcomp (&c->compiled, arg, REG_NOSUB);
7608       if (errcode != 0)
7609         {
7610           char *err = get_regcomp_error (errcode, &c->compiled);
7611
7612           make_cleanup (xfree, err);
7613           error (_("Invalid regexp (%s): %s"), err, arg);
7614         }
7615       c->regex = xstrdup (arg);
7616     }
7617
7618   c->is_load = is_load;
7619   init_catchpoint (&c->base, gdbarch, tempflag, NULL,
7620                    &catch_solib_breakpoint_ops);
7621
7622   discard_cleanups (cleanup);
7623   install_breakpoint (0, &c->base, 1);
7624 }
7625
7626 static void
7627 catch_load_command_1 (char *arg, int from_tty,
7628                       struct cmd_list_element *command)
7629 {
7630   catch_load_or_unload (arg, from_tty, 1, command);
7631 }
7632
7633 static void
7634 catch_unload_command_1 (char *arg, int from_tty,
7635                         struct cmd_list_element *command)
7636 {
7637   catch_load_or_unload (arg, from_tty, 0, command);
7638 }
7639
7640 DEF_VEC_I(int);
7641
7642 /* An instance of this type is used to represent a syscall catchpoint.
7643    It includes a "struct breakpoint" as a kind of base class; users
7644    downcast to "struct breakpoint *" when needed.  A breakpoint is
7645    really of this type iff its ops pointer points to
7646    CATCH_SYSCALL_BREAKPOINT_OPS.  */
7647
7648 struct syscall_catchpoint
7649 {
7650   /* The base class.  */
7651   struct breakpoint base;
7652
7653   /* Syscall numbers used for the 'catch syscall' feature.  If no
7654      syscall has been specified for filtering, its value is NULL.
7655      Otherwise, it holds a list of all syscalls to be caught.  The
7656      list elements are allocated with xmalloc.  */
7657   VEC(int) *syscalls_to_be_caught;
7658 };
7659
7660 /* Implement the "dtor" breakpoint_ops method for syscall
7661    catchpoints.  */
7662
7663 static void
7664 dtor_catch_syscall (struct breakpoint *b)
7665 {
7666   struct syscall_catchpoint *c = (struct syscall_catchpoint *) b;
7667
7668   VEC_free (int, c->syscalls_to_be_caught);
7669
7670   base_breakpoint_ops.dtor (b);
7671 }
7672
7673 static const struct inferior_data *catch_syscall_inferior_data = NULL;
7674
7675 struct catch_syscall_inferior_data
7676 {
7677   /* We keep a count of the number of times the user has requested a
7678      particular syscall to be tracked, and pass this information to the
7679      target.  This lets capable targets implement filtering directly.  */
7680
7681   /* Number of times that "any" syscall is requested.  */
7682   int any_syscall_count;
7683
7684   /* Count of each system call.  */
7685   VEC(int) *syscalls_counts;
7686
7687   /* This counts all syscall catch requests, so we can readily determine
7688      if any catching is necessary.  */
7689   int total_syscalls_count;
7690 };
7691
7692 static struct catch_syscall_inferior_data*
7693 get_catch_syscall_inferior_data (struct inferior *inf)
7694 {
7695   struct catch_syscall_inferior_data *inf_data;
7696
7697   inf_data = inferior_data (inf, catch_syscall_inferior_data);
7698   if (inf_data == NULL)
7699     {
7700       inf_data = XZALLOC (struct catch_syscall_inferior_data);
7701       set_inferior_data (inf, catch_syscall_inferior_data, inf_data);
7702     }
7703
7704   return inf_data;
7705 }
7706
7707 static void
7708 catch_syscall_inferior_data_cleanup (struct inferior *inf, void *arg)
7709 {
7710   xfree (arg);
7711 }
7712
7713
7714 /* Implement the "insert" breakpoint_ops method for syscall
7715    catchpoints.  */
7716
7717 static int
7718 insert_catch_syscall (struct bp_location *bl)
7719 {
7720   struct syscall_catchpoint *c = (struct syscall_catchpoint *) bl->owner;
7721   struct inferior *inf = current_inferior ();
7722   struct catch_syscall_inferior_data *inf_data
7723     = get_catch_syscall_inferior_data (inf);
7724
7725   ++inf_data->total_syscalls_count;
7726   if (!c->syscalls_to_be_caught)
7727     ++inf_data->any_syscall_count;
7728   else
7729     {
7730       int i, iter;
7731
7732       for (i = 0;
7733            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
7734            i++)
7735         {
7736           int elem;
7737
7738           if (iter >= VEC_length (int, inf_data->syscalls_counts))
7739             {
7740               int old_size = VEC_length (int, inf_data->syscalls_counts);
7741               uintptr_t vec_addr_offset
7742                 = old_size * ((uintptr_t) sizeof (int));
7743               uintptr_t vec_addr;
7744               VEC_safe_grow (int, inf_data->syscalls_counts, iter + 1);
7745               vec_addr = ((uintptr_t) VEC_address (int,
7746                                                   inf_data->syscalls_counts)
7747                           + vec_addr_offset);
7748               memset ((void *) vec_addr, 0,
7749                       (iter + 1 - old_size) * sizeof (int));
7750             }
7751           elem = VEC_index (int, inf_data->syscalls_counts, iter);
7752           VEC_replace (int, inf_data->syscalls_counts, iter, ++elem);
7753         }
7754     }
7755
7756   return target_set_syscall_catchpoint (PIDGET (inferior_ptid),
7757                                         inf_data->total_syscalls_count != 0,
7758                                         inf_data->any_syscall_count,
7759                                         VEC_length (int,
7760                                                     inf_data->syscalls_counts),
7761                                         VEC_address (int,
7762                                                      inf_data->syscalls_counts));
7763 }
7764
7765 /* Implement the "remove" breakpoint_ops method for syscall
7766    catchpoints.  */
7767
7768 static int
7769 remove_catch_syscall (struct bp_location *bl)
7770 {
7771   struct syscall_catchpoint *c = (struct syscall_catchpoint *) bl->owner;
7772   struct inferior *inf = current_inferior ();
7773   struct catch_syscall_inferior_data *inf_data
7774     = get_catch_syscall_inferior_data (inf);
7775
7776   --inf_data->total_syscalls_count;
7777   if (!c->syscalls_to_be_caught)
7778     --inf_data->any_syscall_count;
7779   else
7780     {
7781       int i, iter;
7782
7783       for (i = 0;
7784            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
7785            i++)
7786         {
7787           int elem;
7788           if (iter >= VEC_length (int, inf_data->syscalls_counts))
7789             /* Shouldn't happen.  */
7790             continue;
7791           elem = VEC_index (int, inf_data->syscalls_counts, iter);
7792           VEC_replace (int, inf_data->syscalls_counts, iter, --elem);
7793         }
7794     }
7795
7796   return target_set_syscall_catchpoint (PIDGET (inferior_ptid),
7797                                         inf_data->total_syscalls_count != 0,
7798                                         inf_data->any_syscall_count,
7799                                         VEC_length (int,
7800                                                     inf_data->syscalls_counts),
7801                                         VEC_address (int,
7802                                                      inf_data->syscalls_counts));
7803 }
7804
7805 /* Implement the "breakpoint_hit" breakpoint_ops method for syscall
7806    catchpoints.  */
7807
7808 static int
7809 breakpoint_hit_catch_syscall (const struct bp_location *bl,
7810                               struct address_space *aspace, CORE_ADDR bp_addr,
7811                               const struct target_waitstatus *ws)
7812 {
7813   /* We must check if we are catching specific syscalls in this
7814      breakpoint.  If we are, then we must guarantee that the called
7815      syscall is the same syscall we are catching.  */
7816   int syscall_number = 0;
7817   const struct syscall_catchpoint *c
7818     = (const struct syscall_catchpoint *) bl->owner;
7819
7820   if (ws->kind != TARGET_WAITKIND_SYSCALL_ENTRY
7821       && ws->kind != TARGET_WAITKIND_SYSCALL_RETURN)
7822     return 0;
7823
7824   syscall_number = ws->value.syscall_number;
7825
7826   /* Now, checking if the syscall is the same.  */
7827   if (c->syscalls_to_be_caught)
7828     {
7829       int i, iter;
7830
7831       for (i = 0;
7832            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
7833            i++)
7834         if (syscall_number == iter)
7835           break;
7836       /* Not the same.  */
7837       if (!iter)
7838         return 0;
7839     }
7840
7841   return 1;
7842 }
7843
7844 /* Implement the "print_it" breakpoint_ops method for syscall
7845    catchpoints.  */
7846
7847 static enum print_stop_action
7848 print_it_catch_syscall (bpstat bs)
7849 {
7850   struct ui_out *uiout = current_uiout;
7851   struct breakpoint *b = bs->breakpoint_at;
7852   /* These are needed because we want to know in which state a
7853      syscall is.  It can be in the TARGET_WAITKIND_SYSCALL_ENTRY
7854      or TARGET_WAITKIND_SYSCALL_RETURN, and depending on it we
7855      must print "called syscall" or "returned from syscall".  */
7856   ptid_t ptid;
7857   struct target_waitstatus last;
7858   struct syscall s;
7859
7860   get_last_target_status (&ptid, &last);
7861
7862   get_syscall_by_number (last.value.syscall_number, &s);
7863
7864   annotate_catchpoint (b->number);
7865
7866   if (b->disposition == disp_del)
7867     ui_out_text (uiout, "\nTemporary catchpoint ");
7868   else
7869     ui_out_text (uiout, "\nCatchpoint ");
7870   if (ui_out_is_mi_like_p (uiout))
7871     {
7872       ui_out_field_string (uiout, "reason",
7873                            async_reason_lookup (last.kind == TARGET_WAITKIND_SYSCALL_ENTRY
7874                                                 ? EXEC_ASYNC_SYSCALL_ENTRY
7875                                                 : EXEC_ASYNC_SYSCALL_RETURN));
7876       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
7877     }
7878   ui_out_field_int (uiout, "bkptno", b->number);
7879
7880   if (last.kind == TARGET_WAITKIND_SYSCALL_ENTRY)
7881     ui_out_text (uiout, " (call to syscall ");
7882   else
7883     ui_out_text (uiout, " (returned from syscall ");
7884
7885   if (s.name == NULL || ui_out_is_mi_like_p (uiout))
7886     ui_out_field_int (uiout, "syscall-number", last.value.syscall_number);
7887   if (s.name != NULL)
7888     ui_out_field_string (uiout, "syscall-name", s.name);
7889
7890   ui_out_text (uiout, "), ");
7891
7892   return PRINT_SRC_AND_LOC;
7893 }
7894
7895 /* Implement the "print_one" breakpoint_ops method for syscall
7896    catchpoints.  */
7897
7898 static void
7899 print_one_catch_syscall (struct breakpoint *b,
7900                          struct bp_location **last_loc)
7901 {
7902   struct syscall_catchpoint *c = (struct syscall_catchpoint *) b;
7903   struct value_print_options opts;
7904   struct ui_out *uiout = current_uiout;
7905
7906   get_user_print_options (&opts);
7907   /* Field 4, the address, is omitted (which makes the columns not
7908      line up too nicely with the headers, but the effect is relatively
7909      readable).  */
7910   if (opts.addressprint)
7911     ui_out_field_skip (uiout, "addr");
7912   annotate_field (5);
7913
7914   if (c->syscalls_to_be_caught
7915       && VEC_length (int, c->syscalls_to_be_caught) > 1)
7916     ui_out_text (uiout, "syscalls \"");
7917   else
7918     ui_out_text (uiout, "syscall \"");
7919
7920   if (c->syscalls_to_be_caught)
7921     {
7922       int i, iter;
7923       char *text = xstrprintf ("%s", "");
7924
7925       for (i = 0;
7926            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
7927            i++)
7928         {
7929           char *x = text;
7930           struct syscall s;
7931           get_syscall_by_number (iter, &s);
7932
7933           if (s.name != NULL)
7934             text = xstrprintf ("%s%s, ", text, s.name);
7935           else
7936             text = xstrprintf ("%s%d, ", text, iter);
7937
7938           /* We have to xfree the last 'text' (now stored at 'x')
7939              because xstrprintf dynamically allocates new space for it
7940              on every call.  */
7941           xfree (x);
7942         }
7943       /* Remove the last comma.  */
7944       text[strlen (text) - 2] = '\0';
7945       ui_out_field_string (uiout, "what", text);
7946     }
7947   else
7948     ui_out_field_string (uiout, "what", "<any syscall>");
7949   ui_out_text (uiout, "\" ");
7950 }
7951
7952 /* Implement the "print_mention" breakpoint_ops method for syscall
7953    catchpoints.  */
7954
7955 static void
7956 print_mention_catch_syscall (struct breakpoint *b)
7957 {
7958   struct syscall_catchpoint *c = (struct syscall_catchpoint *) b;
7959
7960   if (c->syscalls_to_be_caught)
7961     {
7962       int i, iter;
7963
7964       if (VEC_length (int, c->syscalls_to_be_caught) > 1)
7965         printf_filtered (_("Catchpoint %d (syscalls"), b->number);
7966       else
7967         printf_filtered (_("Catchpoint %d (syscall"), b->number);
7968
7969       for (i = 0;
7970            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
7971            i++)
7972         {
7973           struct syscall s;
7974           get_syscall_by_number (iter, &s);
7975
7976           if (s.name)
7977             printf_filtered (" '%s' [%d]", s.name, s.number);
7978           else
7979             printf_filtered (" %d", s.number);
7980         }
7981       printf_filtered (")");
7982     }
7983   else
7984     printf_filtered (_("Catchpoint %d (any syscall)"),
7985                      b->number);
7986 }
7987
7988 /* Implement the "print_recreate" breakpoint_ops method for syscall
7989    catchpoints.  */
7990
7991 static void
7992 print_recreate_catch_syscall (struct breakpoint *b, struct ui_file *fp)
7993 {
7994   struct syscall_catchpoint *c = (struct syscall_catchpoint *) b;
7995
7996   fprintf_unfiltered (fp, "catch syscall");
7997
7998   if (c->syscalls_to_be_caught)
7999     {
8000       int i, iter;
8001
8002       for (i = 0;
8003            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
8004            i++)
8005         {
8006           struct syscall s;
8007
8008           get_syscall_by_number (iter, &s);
8009           if (s.name)
8010             fprintf_unfiltered (fp, " %s", s.name);
8011           else
8012             fprintf_unfiltered (fp, " %d", s.number);
8013         }
8014     }
8015   print_recreate_thread (b, fp);
8016 }
8017
8018 /* The breakpoint_ops structure to be used in syscall catchpoints.  */
8019
8020 static struct breakpoint_ops catch_syscall_breakpoint_ops;
8021
8022 /* Returns non-zero if 'b' is a syscall catchpoint.  */
8023
8024 static int
8025 syscall_catchpoint_p (struct breakpoint *b)
8026 {
8027   return (b->ops == &catch_syscall_breakpoint_ops);
8028 }
8029
8030 /* Initialize a new breakpoint of the bp_catchpoint kind.  If TEMPFLAG
8031    is non-zero, then make the breakpoint temporary.  If COND_STRING is
8032    not NULL, then store it in the breakpoint.  OPS, if not NULL, is
8033    the breakpoint_ops structure associated to the catchpoint.  */
8034
8035 static void
8036 init_catchpoint (struct breakpoint *b,
8037                  struct gdbarch *gdbarch, int tempflag,
8038                  char *cond_string,
8039                  const struct breakpoint_ops *ops)
8040 {
8041   struct symtab_and_line sal;
8042
8043   init_sal (&sal);
8044   sal.pspace = current_program_space;
8045
8046   init_raw_breakpoint (b, gdbarch, sal, bp_catchpoint, ops);
8047
8048   b->cond_string = (cond_string == NULL) ? NULL : xstrdup (cond_string);
8049   b->disposition = tempflag ? disp_del : disp_donttouch;
8050 }
8051
8052 void
8053 install_breakpoint (int internal, struct breakpoint *b, int update_gll)
8054 {
8055   add_to_breakpoint_chain (b);
8056   set_breakpoint_number (internal, b);
8057   if (!internal)
8058     mention (b);
8059   observer_notify_breakpoint_created (b);
8060
8061   if (update_gll)
8062     update_global_location_list (1);
8063 }
8064
8065 static void
8066 create_fork_vfork_event_catchpoint (struct gdbarch *gdbarch,
8067                                     int tempflag, char *cond_string,
8068                                     const struct breakpoint_ops *ops)
8069 {
8070   struct fork_catchpoint *c = XNEW (struct fork_catchpoint);
8071
8072   init_catchpoint (&c->base, gdbarch, tempflag, cond_string, ops);
8073
8074   c->forked_inferior_pid = null_ptid;
8075
8076   install_breakpoint (0, &c->base, 1);
8077 }
8078
8079 /* Exec catchpoints.  */
8080
8081 /* An instance of this type is used to represent an exec catchpoint.
8082    It includes a "struct breakpoint" as a kind of base class; users
8083    downcast to "struct breakpoint *" when needed.  A breakpoint is
8084    really of this type iff its ops pointer points to
8085    CATCH_EXEC_BREAKPOINT_OPS.  */
8086
8087 struct exec_catchpoint
8088 {
8089   /* The base class.  */
8090   struct breakpoint base;
8091
8092   /* Filename of a program whose exec triggered this catchpoint.
8093      This field is only valid immediately after this catchpoint has
8094      triggered.  */
8095   char *exec_pathname;
8096 };
8097
8098 /* Implement the "dtor" breakpoint_ops method for exec
8099    catchpoints.  */
8100
8101 static void
8102 dtor_catch_exec (struct breakpoint *b)
8103 {
8104   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
8105
8106   xfree (c->exec_pathname);
8107
8108   base_breakpoint_ops.dtor (b);
8109 }
8110
8111 static int
8112 insert_catch_exec (struct bp_location *bl)
8113 {
8114   return target_insert_exec_catchpoint (PIDGET (inferior_ptid));
8115 }
8116
8117 static int
8118 remove_catch_exec (struct bp_location *bl)
8119 {
8120   return target_remove_exec_catchpoint (PIDGET (inferior_ptid));
8121 }
8122
8123 static int
8124 breakpoint_hit_catch_exec (const struct bp_location *bl,
8125                            struct address_space *aspace, CORE_ADDR bp_addr,
8126                            const struct target_waitstatus *ws)
8127 {
8128   struct exec_catchpoint *c = (struct exec_catchpoint *) bl->owner;
8129
8130   if (ws->kind != TARGET_WAITKIND_EXECD)
8131     return 0;
8132
8133   c->exec_pathname = xstrdup (ws->value.execd_pathname);
8134   return 1;
8135 }
8136
8137 static enum print_stop_action
8138 print_it_catch_exec (bpstat bs)
8139 {
8140   struct ui_out *uiout = current_uiout;
8141   struct breakpoint *b = bs->breakpoint_at;
8142   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
8143
8144   annotate_catchpoint (b->number);
8145   if (b->disposition == disp_del)
8146     ui_out_text (uiout, "\nTemporary catchpoint ");
8147   else
8148     ui_out_text (uiout, "\nCatchpoint ");
8149   if (ui_out_is_mi_like_p (uiout))
8150     {
8151       ui_out_field_string (uiout, "reason",
8152                            async_reason_lookup (EXEC_ASYNC_EXEC));
8153       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
8154     }
8155   ui_out_field_int (uiout, "bkptno", b->number);
8156   ui_out_text (uiout, " (exec'd ");
8157   ui_out_field_string (uiout, "new-exec", c->exec_pathname);
8158   ui_out_text (uiout, "), ");
8159
8160   return PRINT_SRC_AND_LOC;
8161 }
8162
8163 static void
8164 print_one_catch_exec (struct breakpoint *b, struct bp_location **last_loc)
8165 {
8166   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
8167   struct value_print_options opts;
8168   struct ui_out *uiout = current_uiout;
8169
8170   get_user_print_options (&opts);
8171
8172   /* Field 4, the address, is omitted (which makes the columns
8173      not line up too nicely with the headers, but the effect
8174      is relatively readable).  */
8175   if (opts.addressprint)
8176     ui_out_field_skip (uiout, "addr");
8177   annotate_field (5);
8178   ui_out_text (uiout, "exec");
8179   if (c->exec_pathname != NULL)
8180     {
8181       ui_out_text (uiout, ", program \"");
8182       ui_out_field_string (uiout, "what", c->exec_pathname);
8183       ui_out_text (uiout, "\" ");
8184     }
8185 }
8186
8187 static void
8188 print_mention_catch_exec (struct breakpoint *b)
8189 {
8190   printf_filtered (_("Catchpoint %d (exec)"), b->number);
8191 }
8192
8193 /* Implement the "print_recreate" breakpoint_ops method for exec
8194    catchpoints.  */
8195
8196 static void
8197 print_recreate_catch_exec (struct breakpoint *b, struct ui_file *fp)
8198 {
8199   fprintf_unfiltered (fp, "catch exec");
8200   print_recreate_thread (b, fp);
8201 }
8202
8203 static struct breakpoint_ops catch_exec_breakpoint_ops;
8204
8205 static void
8206 create_syscall_event_catchpoint (int tempflag, VEC(int) *filter,
8207                                  const struct breakpoint_ops *ops)
8208 {
8209   struct syscall_catchpoint *c;
8210   struct gdbarch *gdbarch = get_current_arch ();
8211
8212   c = XNEW (struct syscall_catchpoint);
8213   init_catchpoint (&c->base, gdbarch, tempflag, NULL, ops);
8214   c->syscalls_to_be_caught = filter;
8215
8216   install_breakpoint (0, &c->base, 1);
8217 }
8218
8219 static int
8220 hw_breakpoint_used_count (void)
8221 {
8222   int i = 0;
8223   struct breakpoint *b;
8224   struct bp_location *bl;
8225
8226   ALL_BREAKPOINTS (b)
8227   {
8228     if (b->type == bp_hardware_breakpoint && breakpoint_enabled (b))
8229       for (bl = b->loc; bl; bl = bl->next)
8230         {
8231           /* Special types of hardware breakpoints may use more than
8232              one register.  */
8233           i += b->ops->resources_needed (bl);
8234         }
8235   }
8236
8237   return i;
8238 }
8239
8240 /* Returns the resources B would use if it were a hardware
8241    watchpoint.  */
8242
8243 static int
8244 hw_watchpoint_use_count (struct breakpoint *b)
8245 {
8246   int i = 0;
8247   struct bp_location *bl;
8248
8249   if (!breakpoint_enabled (b))
8250     return 0;
8251
8252   for (bl = b->loc; bl; bl = bl->next)
8253     {
8254       /* Special types of hardware watchpoints may use more than
8255          one register.  */
8256       i += b->ops->resources_needed (bl);
8257     }
8258
8259   return i;
8260 }
8261
8262 /* Returns the sum the used resources of all hardware watchpoints of
8263    type TYPE in the breakpoints list.  Also returns in OTHER_TYPE_USED
8264    the sum of the used resources of all hardware watchpoints of other
8265    types _not_ TYPE.  */
8266
8267 static int
8268 hw_watchpoint_used_count_others (struct breakpoint *except,
8269                                  enum bptype type, int *other_type_used)
8270 {
8271   int i = 0;
8272   struct breakpoint *b;
8273
8274   *other_type_used = 0;
8275   ALL_BREAKPOINTS (b)
8276     {
8277       if (b == except)
8278         continue;
8279       if (!breakpoint_enabled (b))
8280         continue;
8281
8282       if (b->type == type)
8283         i += hw_watchpoint_use_count (b);
8284       else if (is_hardware_watchpoint (b))
8285         *other_type_used = 1;
8286     }
8287
8288   return i;
8289 }
8290
8291 void
8292 disable_watchpoints_before_interactive_call_start (void)
8293 {
8294   struct breakpoint *b;
8295
8296   ALL_BREAKPOINTS (b)
8297   {
8298     if (is_watchpoint (b) && breakpoint_enabled (b))
8299       {
8300         b->enable_state = bp_call_disabled;
8301         update_global_location_list (0);
8302       }
8303   }
8304 }
8305
8306 void
8307 enable_watchpoints_after_interactive_call_stop (void)
8308 {
8309   struct breakpoint *b;
8310
8311   ALL_BREAKPOINTS (b)
8312   {
8313     if (is_watchpoint (b) && b->enable_state == bp_call_disabled)
8314       {
8315         b->enable_state = bp_enabled;
8316         update_global_location_list (1);
8317       }
8318   }
8319 }
8320
8321 void
8322 disable_breakpoints_before_startup (void)
8323 {
8324   current_program_space->executing_startup = 1;
8325   update_global_location_list (0);
8326 }
8327
8328 void
8329 enable_breakpoints_after_startup (void)
8330 {
8331   current_program_space->executing_startup = 0;
8332   breakpoint_re_set ();
8333 }
8334
8335
8336 /* Set a breakpoint that will evaporate an end of command
8337    at address specified by SAL.
8338    Restrict it to frame FRAME if FRAME is nonzero.  */
8339
8340 struct breakpoint *
8341 set_momentary_breakpoint (struct gdbarch *gdbarch, struct symtab_and_line sal,
8342                           struct frame_id frame_id, enum bptype type)
8343 {
8344   struct breakpoint *b;
8345
8346   /* If FRAME_ID is valid, it should be a real frame, not an inlined
8347      one.  */
8348   gdb_assert (!frame_id_inlined_p (frame_id));
8349
8350   b = set_raw_breakpoint (gdbarch, sal, type, &momentary_breakpoint_ops);
8351   b->enable_state = bp_enabled;
8352   b->disposition = disp_donttouch;
8353   b->frame_id = frame_id;
8354
8355   /* If we're debugging a multi-threaded program, then we want
8356      momentary breakpoints to be active in only a single thread of
8357      control.  */
8358   if (in_thread_list (inferior_ptid))
8359     b->thread = pid_to_thread_id (inferior_ptid);
8360
8361   update_global_location_list_nothrow (1);
8362
8363   return b;
8364 }
8365
8366 /* Make a momentary breakpoint based on the master breakpoint ORIG.
8367    The new breakpoint will have type TYPE, and use OPS as it
8368    breakpoint_ops.  */
8369
8370 static struct breakpoint *
8371 momentary_breakpoint_from_master (struct breakpoint *orig,
8372                                   enum bptype type,
8373                                   const struct breakpoint_ops *ops)
8374 {
8375   struct breakpoint *copy;
8376
8377   copy = set_raw_breakpoint_without_location (orig->gdbarch, type, ops);
8378   copy->loc = allocate_bp_location (copy);
8379   set_breakpoint_location_function (copy->loc, 1);
8380
8381   copy->loc->gdbarch = orig->loc->gdbarch;
8382   copy->loc->requested_address = orig->loc->requested_address;
8383   copy->loc->address = orig->loc->address;
8384   copy->loc->section = orig->loc->section;
8385   copy->loc->pspace = orig->loc->pspace;
8386   copy->loc->probe = orig->loc->probe;
8387
8388   if (orig->loc->source_file != NULL)
8389     copy->loc->source_file = xstrdup (orig->loc->source_file);
8390
8391   copy->loc->line_number = orig->loc->line_number;
8392   copy->frame_id = orig->frame_id;
8393   copy->thread = orig->thread;
8394   copy->pspace = orig->pspace;
8395
8396   copy->enable_state = bp_enabled;
8397   copy->disposition = disp_donttouch;
8398   copy->number = internal_breakpoint_number--;
8399
8400   update_global_location_list_nothrow (0);
8401   return copy;
8402 }
8403
8404 /* Make a deep copy of momentary breakpoint ORIG.  Returns NULL if
8405    ORIG is NULL.  */
8406
8407 struct breakpoint *
8408 clone_momentary_breakpoint (struct breakpoint *orig)
8409 {
8410   /* If there's nothing to clone, then return nothing.  */
8411   if (orig == NULL)
8412     return NULL;
8413
8414   return momentary_breakpoint_from_master (orig, orig->type, orig->ops);
8415 }
8416
8417 struct breakpoint *
8418 set_momentary_breakpoint_at_pc (struct gdbarch *gdbarch, CORE_ADDR pc,
8419                                 enum bptype type)
8420 {
8421   struct symtab_and_line sal;
8422
8423   sal = find_pc_line (pc, 0);
8424   sal.pc = pc;
8425   sal.section = find_pc_overlay (pc);
8426   sal.explicit_pc = 1;
8427
8428   return set_momentary_breakpoint (gdbarch, sal, null_frame_id, type);
8429 }
8430 \f
8431
8432 /* Tell the user we have just set a breakpoint B.  */
8433
8434 static void
8435 mention (struct breakpoint *b)
8436 {
8437   b->ops->print_mention (b);
8438   if (ui_out_is_mi_like_p (current_uiout))
8439     return;
8440   printf_filtered ("\n");
8441 }
8442 \f
8443
8444 static struct bp_location *
8445 add_location_to_breakpoint (struct breakpoint *b,
8446                             const struct symtab_and_line *sal)
8447 {
8448   struct bp_location *loc, **tmp;
8449   CORE_ADDR adjusted_address;
8450   struct gdbarch *loc_gdbarch = get_sal_arch (*sal);
8451
8452   if (loc_gdbarch == NULL)
8453     loc_gdbarch = b->gdbarch;
8454
8455   /* Adjust the breakpoint's address prior to allocating a location.
8456      Once we call allocate_bp_location(), that mostly uninitialized
8457      location will be placed on the location chain.  Adjustment of the
8458      breakpoint may cause target_read_memory() to be called and we do
8459      not want its scan of the location chain to find a breakpoint and
8460      location that's only been partially initialized.  */
8461   adjusted_address = adjust_breakpoint_address (loc_gdbarch,
8462                                                 sal->pc, b->type);
8463
8464   loc = allocate_bp_location (b);
8465   for (tmp = &(b->loc); *tmp != NULL; tmp = &((*tmp)->next))
8466     ;
8467   *tmp = loc;
8468
8469   loc->requested_address = sal->pc;
8470   loc->address = adjusted_address;
8471   loc->pspace = sal->pspace;
8472   loc->probe = sal->probe;
8473   gdb_assert (loc->pspace != NULL);
8474   loc->section = sal->section;
8475   loc->gdbarch = loc_gdbarch;
8476
8477   if (sal->symtab != NULL)
8478     loc->source_file = xstrdup (sal->symtab->filename);
8479   loc->line_number = sal->line;
8480
8481   set_breakpoint_location_function (loc,
8482                                     sal->explicit_pc || sal->explicit_line);
8483   return loc;
8484 }
8485 \f
8486
8487 /* Return 1 if LOC is pointing to a permanent breakpoint, 
8488    return 0 otherwise.  */
8489
8490 static int
8491 bp_loc_is_permanent (struct bp_location *loc)
8492 {
8493   int len;
8494   CORE_ADDR addr;
8495   const gdb_byte *bpoint;
8496   gdb_byte *target_mem;
8497   struct cleanup *cleanup;
8498   int retval = 0;
8499
8500   gdb_assert (loc != NULL);
8501
8502   addr = loc->address;
8503   bpoint = gdbarch_breakpoint_from_pc (loc->gdbarch, &addr, &len);
8504
8505   /* Software breakpoints unsupported?  */
8506   if (bpoint == NULL)
8507     return 0;
8508
8509   target_mem = alloca (len);
8510
8511   /* Enable the automatic memory restoration from breakpoints while
8512      we read the memory.  Otherwise we could say about our temporary
8513      breakpoints they are permanent.  */
8514   cleanup = save_current_space_and_thread ();
8515
8516   switch_to_program_space_and_thread (loc->pspace);
8517   make_show_memory_breakpoints_cleanup (0);
8518
8519   if (target_read_memory (loc->address, target_mem, len) == 0
8520       && memcmp (target_mem, bpoint, len) == 0)
8521     retval = 1;
8522
8523   do_cleanups (cleanup);
8524
8525   return retval;
8526 }
8527
8528 /* The style in which to perform a dynamic printf.  This is a user
8529    option because different output options have different tradeoffs;
8530    if GDB does the printing, there is better error handling if there
8531    is a problem with any of the arguments, but using an inferior
8532    function lets you have special-purpose printers and sending of
8533    output to the same place as compiled-in print functions.  (Future
8534    styles may include the ability to do a target-side printf.)  */
8535
8536 static const char dprintf_style_gdb[] = "gdb";
8537 static const char dprintf_style_call[] = "call";
8538 static const char *const dprintf_style_enums[] = {
8539   dprintf_style_gdb,
8540   dprintf_style_call,
8541   NULL
8542 };
8543 static const char *dprintf_style = dprintf_style_gdb;
8544
8545 /* The function to use for dynamic printf if the preferred style is to
8546    call into the inferior.  The value is simply a string that is
8547    copied into the command, so it can be anything that GDB can
8548    evaluate to a callable address, not necessarily a function name.  */
8549
8550 static char *dprintf_function = "";
8551
8552 /* The channel to use for dynamic printf if the preferred style is to
8553    call into the inferior; if a nonempty string, it will be passed to
8554    the call as the first argument, with the format string as the
8555    second.  As with the dprintf function, this can be anything that
8556    GDB knows how to evaluate, so in addition to common choices like
8557    "stderr", this could be an app-specific expression like
8558    "mystreams[curlogger]".  */
8559
8560 static char *dprintf_channel = "";
8561
8562 /* Build a command list for the dprintf corresponding to the current
8563    settings of the dprintf style options.  */
8564
8565 static void
8566 update_dprintf_command_list (struct breakpoint *b)
8567 {
8568   char *dprintf_args = b->extra_string;
8569   char *printf_line = NULL;
8570
8571   if (!dprintf_args)
8572     return;
8573
8574   dprintf_args = skip_spaces (dprintf_args);
8575
8576   /* Allow a comma, as it may have terminated a location, but don't
8577      insist on it.  */
8578   if (*dprintf_args == ',')
8579     ++dprintf_args;
8580   dprintf_args = skip_spaces (dprintf_args);
8581
8582   if (*dprintf_args != '"')
8583     error (_("Bad format string, missing '\"'."));
8584
8585   if (strcmp (dprintf_style, "gdb") == 0)
8586     printf_line = xstrprintf ("printf %s", dprintf_args);
8587   else if (strcmp (dprintf_style, "call") == 0)
8588     {
8589       if (!dprintf_function)
8590         error (_("No function supplied for dprintf call"));
8591
8592       if (dprintf_channel && strlen (dprintf_channel) > 0)
8593         printf_line = xstrprintf ("call (void) %s (%s,%s)",
8594                                   dprintf_function,
8595                                   dprintf_channel,
8596                                   dprintf_args);
8597       else
8598         printf_line = xstrprintf ("call (void) %s (%s)",
8599                                   dprintf_function,
8600                                   dprintf_args);
8601     }
8602   else
8603     internal_error (__FILE__, __LINE__,
8604                     _("Invalid dprintf style."));
8605
8606   /* Manufacture a printf/continue sequence.  */
8607   if (printf_line)
8608     {
8609       struct command_line *printf_cmd_line, *cont_cmd_line = NULL;
8610
8611       cont_cmd_line = xmalloc (sizeof (struct command_line));
8612       cont_cmd_line->control_type = simple_control;
8613       cont_cmd_line->body_count = 0;
8614       cont_cmd_line->body_list = NULL;
8615       cont_cmd_line->next = NULL;
8616       cont_cmd_line->line = xstrdup ("continue");
8617
8618       printf_cmd_line = xmalloc (sizeof (struct command_line));
8619       printf_cmd_line->control_type = simple_control;
8620       printf_cmd_line->body_count = 0;
8621       printf_cmd_line->body_list = NULL;
8622       printf_cmd_line->next = cont_cmd_line;
8623       printf_cmd_line->line = printf_line;
8624
8625       breakpoint_set_commands (b, printf_cmd_line);
8626     }
8627 }
8628
8629 /* Update all dprintf commands, making their command lists reflect
8630    current style settings.  */
8631
8632 static void
8633 update_dprintf_commands (char *args, int from_tty,
8634                          struct cmd_list_element *c)
8635 {
8636   struct breakpoint *b;
8637
8638   ALL_BREAKPOINTS (b)
8639     {
8640       if (b->type == bp_dprintf)
8641         update_dprintf_command_list (b);
8642     }
8643 }
8644
8645 /* Create a breakpoint with SAL as location.  Use ADDR_STRING
8646    as textual description of the location, and COND_STRING
8647    as condition expression.  */
8648
8649 static void
8650 init_breakpoint_sal (struct breakpoint *b, struct gdbarch *gdbarch,
8651                      struct symtabs_and_lines sals, char *addr_string,
8652                      char *filter, char *cond_string,
8653                      char *extra_string,
8654                      enum bptype type, enum bpdisp disposition,
8655                      int thread, int task, int ignore_count,
8656                      const struct breakpoint_ops *ops, int from_tty,
8657                      int enabled, int internal, unsigned flags,
8658                      int display_canonical)
8659 {
8660   int i;
8661
8662   if (type == bp_hardware_breakpoint)
8663     {
8664       int target_resources_ok;
8665
8666       i = hw_breakpoint_used_count ();
8667       target_resources_ok =
8668         target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
8669                                             i + 1, 0);
8670       if (target_resources_ok == 0)
8671         error (_("No hardware breakpoint support in the target."));
8672       else if (target_resources_ok < 0)
8673         error (_("Hardware breakpoints used exceeds limit."));
8674     }
8675
8676   gdb_assert (sals.nelts > 0);
8677
8678   for (i = 0; i < sals.nelts; ++i)
8679     {
8680       struct symtab_and_line sal = sals.sals[i];
8681       struct bp_location *loc;
8682
8683       if (from_tty)
8684         {
8685           struct gdbarch *loc_gdbarch = get_sal_arch (sal);
8686           if (!loc_gdbarch)
8687             loc_gdbarch = gdbarch;
8688
8689           describe_other_breakpoints (loc_gdbarch,
8690                                       sal.pspace, sal.pc, sal.section, thread);
8691         }
8692
8693       if (i == 0)
8694         {
8695           init_raw_breakpoint (b, gdbarch, sal, type, ops);
8696           b->thread = thread;
8697           b->task = task;
8698
8699           b->cond_string = cond_string;
8700           b->extra_string = extra_string;
8701           b->ignore_count = ignore_count;
8702           b->enable_state = enabled ? bp_enabled : bp_disabled;
8703           b->disposition = disposition;
8704
8705           if ((flags & CREATE_BREAKPOINT_FLAGS_INSERTED) != 0)
8706             b->loc->inserted = 1;
8707
8708           if (type == bp_static_tracepoint)
8709             {
8710               struct tracepoint *t = (struct tracepoint *) b;
8711               struct static_tracepoint_marker marker;
8712
8713               if (strace_marker_p (b))
8714                 {
8715                   /* We already know the marker exists, otherwise, we
8716                      wouldn't see a sal for it.  */
8717                   char *p = &addr_string[3];
8718                   char *endp;
8719                   char *marker_str;
8720
8721                   p = skip_spaces (p);
8722
8723                   endp = skip_to_space (p);
8724
8725                   marker_str = savestring (p, endp - p);
8726                   t->static_trace_marker_id = marker_str;
8727
8728                   printf_filtered (_("Probed static tracepoint "
8729                                      "marker \"%s\"\n"),
8730                                    t->static_trace_marker_id);
8731                 }
8732               else if (target_static_tracepoint_marker_at (sal.pc, &marker))
8733                 {
8734                   t->static_trace_marker_id = xstrdup (marker.str_id);
8735                   release_static_tracepoint_marker (&marker);
8736
8737                   printf_filtered (_("Probed static tracepoint "
8738                                      "marker \"%s\"\n"),
8739                                    t->static_trace_marker_id);
8740                 }
8741               else
8742                 warning (_("Couldn't determine the static "
8743                            "tracepoint marker to probe"));
8744             }
8745
8746           loc = b->loc;
8747         }
8748       else
8749         {
8750           loc = add_location_to_breakpoint (b, &sal);
8751           if ((flags & CREATE_BREAKPOINT_FLAGS_INSERTED) != 0)
8752             loc->inserted = 1;
8753         }
8754
8755       if (bp_loc_is_permanent (loc))
8756         make_breakpoint_permanent (b);
8757
8758       if (b->cond_string)
8759         {
8760           char *arg = b->cond_string;
8761           loc->cond = parse_exp_1 (&arg, loc->address,
8762                                    block_for_pc (loc->address), 0);
8763           if (*arg)
8764               error (_("Garbage '%s' follows condition"), arg);
8765         }
8766
8767       /* Dynamic printf requires and uses additional arguments on the
8768          command line, otherwise it's an error.  */
8769       if (type == bp_dprintf)
8770         {
8771           if (b->extra_string)
8772             update_dprintf_command_list (b);
8773           else
8774             error (_("Format string required"));
8775         }
8776       else if (b->extra_string)
8777         error (_("Garbage '%s' at end of command"), b->extra_string);
8778     }
8779
8780   b->display_canonical = display_canonical;
8781   if (addr_string)
8782     b->addr_string = addr_string;
8783   else
8784     /* addr_string has to be used or breakpoint_re_set will delete
8785        me.  */
8786     b->addr_string
8787       = xstrprintf ("*%s", paddress (b->loc->gdbarch, b->loc->address));
8788   b->filter = filter;
8789 }
8790
8791 static void
8792 create_breakpoint_sal (struct gdbarch *gdbarch,
8793                        struct symtabs_and_lines sals, char *addr_string,
8794                        char *filter, char *cond_string,
8795                        char *extra_string,
8796                        enum bptype type, enum bpdisp disposition,
8797                        int thread, int task, int ignore_count,
8798                        const struct breakpoint_ops *ops, int from_tty,
8799                        int enabled, int internal, unsigned flags,
8800                        int display_canonical)
8801 {
8802   struct breakpoint *b;
8803   struct cleanup *old_chain;
8804
8805   if (is_tracepoint_type (type))
8806     {
8807       struct tracepoint *t;
8808
8809       t = XCNEW (struct tracepoint);
8810       b = &t->base;
8811     }
8812   else
8813     b = XNEW (struct breakpoint);
8814
8815   old_chain = make_cleanup (xfree, b);
8816
8817   init_breakpoint_sal (b, gdbarch,
8818                        sals, addr_string,
8819                        filter, cond_string, extra_string,
8820                        type, disposition,
8821                        thread, task, ignore_count,
8822                        ops, from_tty,
8823                        enabled, internal, flags,
8824                        display_canonical);
8825   discard_cleanups (old_chain);
8826
8827   install_breakpoint (internal, b, 0);
8828 }
8829
8830 /* Add SALS.nelts breakpoints to the breakpoint table.  For each
8831    SALS.sal[i] breakpoint, include the corresponding ADDR_STRING[i]
8832    value.  COND_STRING, if not NULL, specified the condition to be
8833    used for all breakpoints.  Essentially the only case where
8834    SALS.nelts is not 1 is when we set a breakpoint on an overloaded
8835    function.  In that case, it's still not possible to specify
8836    separate conditions for different overloaded functions, so
8837    we take just a single condition string.
8838    
8839    NOTE: If the function succeeds, the caller is expected to cleanup
8840    the arrays ADDR_STRING, COND_STRING, and SALS (but not the
8841    array contents).  If the function fails (error() is called), the
8842    caller is expected to cleanups both the ADDR_STRING, COND_STRING,
8843    COND and SALS arrays and each of those arrays contents.  */
8844
8845 static void
8846 create_breakpoints_sal (struct gdbarch *gdbarch,
8847                         struct linespec_result *canonical,
8848                         char *cond_string, char *extra_string,
8849                         enum bptype type, enum bpdisp disposition,
8850                         int thread, int task, int ignore_count,
8851                         const struct breakpoint_ops *ops, int from_tty,
8852                         int enabled, int internal, unsigned flags)
8853 {
8854   int i;
8855   struct linespec_sals *lsal;
8856
8857   if (canonical->pre_expanded)
8858     gdb_assert (VEC_length (linespec_sals, canonical->sals) == 1);
8859
8860   for (i = 0; VEC_iterate (linespec_sals, canonical->sals, i, lsal); ++i)
8861     {
8862       /* Note that 'addr_string' can be NULL in the case of a plain
8863          'break', without arguments.  */
8864       char *addr_string = (canonical->addr_string
8865                            ? xstrdup (canonical->addr_string)
8866                            : NULL);
8867       char *filter_string = lsal->canonical ? xstrdup (lsal->canonical) : NULL;
8868       struct cleanup *inner = make_cleanup (xfree, addr_string);
8869
8870       make_cleanup (xfree, filter_string);
8871       create_breakpoint_sal (gdbarch, lsal->sals,
8872                              addr_string,
8873                              filter_string,
8874                              cond_string, extra_string,
8875                              type, disposition,
8876                              thread, task, ignore_count, ops,
8877                              from_tty, enabled, internal, flags,
8878                              canonical->special_display);
8879       discard_cleanups (inner);
8880     }
8881 }
8882
8883 /* Parse ADDRESS which is assumed to be a SAL specification possibly
8884    followed by conditionals.  On return, SALS contains an array of SAL
8885    addresses found.  ADDR_STRING contains a vector of (canonical)
8886    address strings.  ADDRESS points to the end of the SAL.
8887
8888    The array and the line spec strings are allocated on the heap, it is
8889    the caller's responsibility to free them.  */
8890
8891 static void
8892 parse_breakpoint_sals (char **address,
8893                        struct linespec_result *canonical)
8894 {
8895   char *addr_start = *address;
8896
8897   /* If no arg given, or if first arg is 'if ', use the default
8898      breakpoint.  */
8899   if ((*address) == NULL
8900       || (strncmp ((*address), "if", 2) == 0 && isspace ((*address)[2])))
8901     {
8902       /* The last displayed codepoint, if it's valid, is our default breakpoint
8903          address.  */
8904       if (last_displayed_sal_is_valid ())
8905         {
8906           struct linespec_sals lsal;
8907           struct symtab_and_line sal;
8908
8909           init_sal (&sal);              /* Initialize to zeroes.  */
8910           lsal.sals.sals = (struct symtab_and_line *)
8911             xmalloc (sizeof (struct symtab_and_line));
8912
8913           /* Set sal's pspace, pc, symtab, and line to the values
8914              corresponding to the last call to print_frame_info.  */
8915           get_last_displayed_sal (&sal);
8916           sal.section = find_pc_overlay (sal.pc);
8917
8918           /* "break" without arguments is equivalent to "break *PC"
8919              where PC is the last displayed codepoint's address.  So
8920              make sure to set sal.explicit_pc to prevent GDB from
8921              trying to expand the list of sals to include all other
8922              instances with the same symtab and line.  */
8923           sal.explicit_pc = 1;
8924
8925           lsal.sals.sals[0] = sal;
8926           lsal.sals.nelts = 1;
8927           lsal.canonical = NULL;
8928
8929           VEC_safe_push (linespec_sals, canonical->sals, &lsal);
8930         }
8931       else
8932         error (_("No default breakpoint address now."));
8933     }
8934   else
8935     {
8936       struct symtab_and_line cursal = get_current_source_symtab_and_line ();
8937
8938       /* Force almost all breakpoints to be in terms of the
8939          current_source_symtab (which is decode_line_1's default).
8940          This should produce the results we want almost all of the
8941          time while leaving default_breakpoint_* alone.
8942
8943          ObjC: However, don't match an Objective-C method name which
8944          may have a '+' or '-' succeeded by a '['.  */
8945       if (last_displayed_sal_is_valid ()
8946           && (!cursal.symtab
8947               || ((strchr ("+-", (*address)[0]) != NULL)
8948                   && ((*address)[1] != '['))))
8949         decode_line_full (address, DECODE_LINE_FUNFIRSTLINE,
8950                           get_last_displayed_symtab (),
8951                           get_last_displayed_line (),
8952                           canonical, NULL, NULL);
8953       else
8954         decode_line_full (address, DECODE_LINE_FUNFIRSTLINE,
8955                           cursal.symtab, cursal.line, canonical, NULL, NULL);
8956     }
8957 }
8958
8959
8960 /* Convert each SAL into a real PC.  Verify that the PC can be
8961    inserted as a breakpoint.  If it can't throw an error.  */
8962
8963 static void
8964 breakpoint_sals_to_pc (struct symtabs_and_lines *sals)
8965 {    
8966   int i;
8967
8968   for (i = 0; i < sals->nelts; i++)
8969     resolve_sal_pc (&sals->sals[i]);
8970 }
8971
8972 /* Fast tracepoints may have restrictions on valid locations.  For
8973    instance, a fast tracepoint using a jump instead of a trap will
8974    likely have to overwrite more bytes than a trap would, and so can
8975    only be placed where the instruction is longer than the jump, or a
8976    multi-instruction sequence does not have a jump into the middle of
8977    it, etc.  */
8978
8979 static void
8980 check_fast_tracepoint_sals (struct gdbarch *gdbarch,
8981                             struct symtabs_and_lines *sals)
8982 {
8983   int i, rslt;
8984   struct symtab_and_line *sal;
8985   char *msg;
8986   struct cleanup *old_chain;
8987
8988   for (i = 0; i < sals->nelts; i++)
8989     {
8990       struct gdbarch *sarch;
8991
8992       sal = &sals->sals[i];
8993
8994       sarch = get_sal_arch (*sal);
8995       /* We fall back to GDBARCH if there is no architecture
8996          associated with SAL.  */
8997       if (sarch == NULL)
8998         sarch = gdbarch;
8999       rslt = gdbarch_fast_tracepoint_valid_at (sarch, sal->pc,
9000                                                NULL, &msg);
9001       old_chain = make_cleanup (xfree, msg);
9002
9003       if (!rslt)
9004         error (_("May not have a fast tracepoint at 0x%s%s"),
9005                paddress (sarch, sal->pc), (msg ? msg : ""));
9006
9007       do_cleanups (old_chain);
9008     }
9009 }
9010
9011 /* Given TOK, a string specification of condition and thread, as
9012    accepted by the 'break' command, extract the condition
9013    string and thread number and set *COND_STRING and *THREAD.
9014    PC identifies the context at which the condition should be parsed.
9015    If no condition is found, *COND_STRING is set to NULL.
9016    If no thread is found, *THREAD is set to -1.  */
9017
9018 static void
9019 find_condition_and_thread (char *tok, CORE_ADDR pc,
9020                            char **cond_string, int *thread, int *task,
9021                            char **rest)
9022 {
9023   *cond_string = NULL;
9024   *thread = -1;
9025   while (tok && *tok)
9026     {
9027       char *end_tok;
9028       int toklen;
9029       char *cond_start = NULL;
9030       char *cond_end = NULL;
9031
9032       tok = skip_spaces (tok);
9033
9034       if ((*tok == '"' || *tok == ',') && rest)
9035         {
9036           *rest = savestring (tok, strlen (tok));
9037           return;
9038         }
9039
9040       end_tok = skip_to_space (tok);
9041
9042       toklen = end_tok - tok;
9043
9044       if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
9045         {
9046           struct expression *expr;
9047
9048           tok = cond_start = end_tok + 1;
9049           expr = parse_exp_1 (&tok, pc, block_for_pc (pc), 0);
9050           xfree (expr);
9051           cond_end = tok;
9052           *cond_string = savestring (cond_start, cond_end - cond_start);
9053         }
9054       else if (toklen >= 1 && strncmp (tok, "thread", toklen) == 0)
9055         {
9056           char *tmptok;
9057
9058           tok = end_tok + 1;
9059           tmptok = tok;
9060           *thread = strtol (tok, &tok, 0);
9061           if (tok == tmptok)
9062             error (_("Junk after thread keyword."));
9063           if (!valid_thread_id (*thread))
9064             error (_("Unknown thread %d."), *thread);
9065         }
9066       else if (toklen >= 1 && strncmp (tok, "task", toklen) == 0)
9067         {
9068           char *tmptok;
9069
9070           tok = end_tok + 1;
9071           tmptok = tok;
9072           *task = strtol (tok, &tok, 0);
9073           if (tok == tmptok)
9074             error (_("Junk after task keyword."));
9075           if (!valid_task_id (*task))
9076             error (_("Unknown task %d."), *task);
9077         }
9078       else if (rest)
9079         {
9080           *rest = savestring (tok, strlen (tok));
9081           return;
9082         }
9083       else
9084         error (_("Junk at end of arguments."));
9085     }
9086 }
9087
9088 /* Decode a static tracepoint marker spec.  */
9089
9090 static struct symtabs_and_lines
9091 decode_static_tracepoint_spec (char **arg_p)
9092 {
9093   VEC(static_tracepoint_marker_p) *markers = NULL;
9094   struct symtabs_and_lines sals;
9095   struct cleanup *old_chain;
9096   char *p = &(*arg_p)[3];
9097   char *endp;
9098   char *marker_str;
9099   int i;
9100
9101   p = skip_spaces (p);
9102
9103   endp = skip_to_space (p);
9104
9105   marker_str = savestring (p, endp - p);
9106   old_chain = make_cleanup (xfree, marker_str);
9107
9108   markers = target_static_tracepoint_markers_by_strid (marker_str);
9109   if (VEC_empty(static_tracepoint_marker_p, markers))
9110     error (_("No known static tracepoint marker named %s"), marker_str);
9111
9112   sals.nelts = VEC_length(static_tracepoint_marker_p, markers);
9113   sals.sals = xmalloc (sizeof *sals.sals * sals.nelts);
9114
9115   for (i = 0; i < sals.nelts; i++)
9116     {
9117       struct static_tracepoint_marker *marker;
9118
9119       marker = VEC_index (static_tracepoint_marker_p, markers, i);
9120
9121       init_sal (&sals.sals[i]);
9122
9123       sals.sals[i] = find_pc_line (marker->address, 0);
9124       sals.sals[i].pc = marker->address;
9125
9126       release_static_tracepoint_marker (marker);
9127     }
9128
9129   do_cleanups (old_chain);
9130
9131   *arg_p = endp;
9132   return sals;
9133 }
9134
9135 /* Set a breakpoint.  This function is shared between CLI and MI
9136    functions for setting a breakpoint.  This function has two major
9137    modes of operations, selected by the PARSE_CONDITION_AND_THREAD
9138    parameter.  If non-zero, the function will parse arg, extracting
9139    breakpoint location, address and thread.  Otherwise, ARG is just
9140    the location of breakpoint, with condition and thread specified by
9141    the COND_STRING and THREAD parameters.  If INTERNAL is non-zero,
9142    the breakpoint number will be allocated from the internal
9143    breakpoint count.  Returns true if any breakpoint was created;
9144    false otherwise.  */
9145
9146 int
9147 create_breakpoint (struct gdbarch *gdbarch,
9148                    char *arg, char *cond_string,
9149                    int thread, char *extra_string,
9150                    int parse_condition_and_thread,
9151                    int tempflag, enum bptype type_wanted,
9152                    int ignore_count,
9153                    enum auto_boolean pending_break_support,
9154                    const struct breakpoint_ops *ops,
9155                    int from_tty, int enabled, int internal,
9156                    unsigned flags)
9157 {
9158   volatile struct gdb_exception e;
9159   char *copy_arg = NULL;
9160   char *addr_start = arg;
9161   struct linespec_result canonical;
9162   struct cleanup *old_chain;
9163   struct cleanup *bkpt_chain = NULL;
9164   int pending = 0;
9165   int task = 0;
9166   int prev_bkpt_count = breakpoint_count;
9167
9168   gdb_assert (ops != NULL);
9169
9170   init_linespec_result (&canonical);
9171
9172   TRY_CATCH (e, RETURN_MASK_ALL)
9173     {
9174       ops->create_sals_from_address (&arg, &canonical, type_wanted,
9175                                      addr_start, &copy_arg);
9176     }
9177
9178   /* If caller is interested in rc value from parse, set value.  */
9179   switch (e.reason)
9180     {
9181     case GDB_NO_ERROR:
9182       if (VEC_empty (linespec_sals, canonical.sals))
9183         return 0;
9184       break;
9185     case RETURN_ERROR:
9186       switch (e.error)
9187         {
9188         case NOT_FOUND_ERROR:
9189
9190           /* If pending breakpoint support is turned off, throw
9191              error.  */
9192
9193           if (pending_break_support == AUTO_BOOLEAN_FALSE)
9194             throw_exception (e);
9195
9196           exception_print (gdb_stderr, e);
9197
9198           /* If pending breakpoint support is auto query and the user
9199              selects no, then simply return the error code.  */
9200           if (pending_break_support == AUTO_BOOLEAN_AUTO
9201               && !nquery (_("Make %s pending on future shared library load? "),
9202                           bptype_string (type_wanted)))
9203             return 0;
9204
9205           /* At this point, either the user was queried about setting
9206              a pending breakpoint and selected yes, or pending
9207              breakpoint behavior is on and thus a pending breakpoint
9208              is defaulted on behalf of the user.  */
9209           {
9210             struct linespec_sals lsal;
9211
9212             copy_arg = xstrdup (addr_start);
9213             lsal.canonical = xstrdup (copy_arg);
9214             lsal.sals.nelts = 1;
9215             lsal.sals.sals = XNEW (struct symtab_and_line);
9216             init_sal (&lsal.sals.sals[0]);
9217             pending = 1;
9218             VEC_safe_push (linespec_sals, canonical.sals, &lsal);
9219           }
9220           break;
9221         default:
9222           throw_exception (e);
9223         }
9224       break;
9225     default:
9226       throw_exception (e);
9227     }
9228
9229   /* Create a chain of things that always need to be cleaned up.  */
9230   old_chain = make_cleanup_destroy_linespec_result (&canonical);
9231
9232   /* ----------------------------- SNIP -----------------------------
9233      Anything added to the cleanup chain beyond this point is assumed
9234      to be part of a breakpoint.  If the breakpoint create succeeds
9235      then the memory is not reclaimed.  */
9236   bkpt_chain = make_cleanup (null_cleanup, 0);
9237
9238   /* Resolve all line numbers to PC's and verify that the addresses
9239      are ok for the target.  */
9240   if (!pending)
9241     {
9242       int ix;
9243       struct linespec_sals *iter;
9244
9245       for (ix = 0; VEC_iterate (linespec_sals, canonical.sals, ix, iter); ++ix)
9246         breakpoint_sals_to_pc (&iter->sals);
9247     }
9248
9249   /* Fast tracepoints may have additional restrictions on location.  */
9250   if (!pending && type_wanted == bp_fast_tracepoint)
9251     {
9252       int ix;
9253       struct linespec_sals *iter;
9254
9255       for (ix = 0; VEC_iterate (linespec_sals, canonical.sals, ix, iter); ++ix)
9256         check_fast_tracepoint_sals (gdbarch, &iter->sals);
9257     }
9258
9259   /* Verify that condition can be parsed, before setting any
9260      breakpoints.  Allocate a separate condition expression for each
9261      breakpoint.  */
9262   if (!pending)
9263     {
9264       struct linespec_sals *lsal;
9265
9266       lsal = VEC_index (linespec_sals, canonical.sals, 0);
9267
9268       if (parse_condition_and_thread)
9269         {
9270             char *rest;
9271             /* Here we only parse 'arg' to separate condition
9272                from thread number, so parsing in context of first
9273                sal is OK.  When setting the breakpoint we'll 
9274                re-parse it in context of each sal.  */
9275             cond_string = NULL;
9276             thread = -1;
9277             rest = NULL;
9278             find_condition_and_thread (arg, lsal->sals.sals[0].pc, &cond_string,
9279                                        &thread, &task, &rest);
9280             if (cond_string)
9281                 make_cleanup (xfree, cond_string);
9282             if (rest)
9283               make_cleanup (xfree, rest);
9284             if (rest)
9285               extra_string = rest;
9286         }
9287       else
9288         {
9289             /* Create a private copy of condition string.  */
9290             if (cond_string)
9291             {
9292                 cond_string = xstrdup (cond_string);
9293                 make_cleanup (xfree, cond_string);
9294             }
9295             /* Create a private copy of any extra string.  */
9296             if (extra_string)
9297               {
9298                 extra_string = xstrdup (extra_string);
9299                 make_cleanup (xfree, extra_string);
9300               }
9301         }
9302
9303       ops->create_breakpoints_sal (gdbarch, &canonical, lsal,
9304                                    cond_string, extra_string, type_wanted,
9305                                    tempflag ? disp_del : disp_donttouch,
9306                                    thread, task, ignore_count, ops,
9307                                    from_tty, enabled, internal, flags);
9308     }
9309   else
9310     {
9311       struct breakpoint *b;
9312
9313       make_cleanup (xfree, copy_arg);
9314
9315       if (is_tracepoint_type (type_wanted))
9316         {
9317           struct tracepoint *t;
9318
9319           t = XCNEW (struct tracepoint);
9320           b = &t->base;
9321         }
9322       else
9323         b = XNEW (struct breakpoint);
9324
9325       init_raw_breakpoint_without_location (b, gdbarch, type_wanted, ops);
9326
9327       b->addr_string = copy_arg;
9328       b->cond_string = NULL;
9329       b->extra_string = NULL;
9330       b->ignore_count = ignore_count;
9331       b->disposition = tempflag ? disp_del : disp_donttouch;
9332       b->condition_not_parsed = 1;
9333       b->enable_state = enabled ? bp_enabled : bp_disabled;
9334       if ((type_wanted != bp_breakpoint
9335            && type_wanted != bp_hardware_breakpoint) || thread != -1)
9336         b->pspace = current_program_space;
9337
9338       install_breakpoint (internal, b, 0);
9339     }
9340   
9341   if (VEC_length (linespec_sals, canonical.sals) > 1)
9342     {
9343       warning (_("Multiple breakpoints were set.\nUse the "
9344                  "\"delete\" command to delete unwanted breakpoints."));
9345       prev_breakpoint_count = prev_bkpt_count;
9346     }
9347
9348   /* That's it.  Discard the cleanups for data inserted into the
9349      breakpoint.  */
9350   discard_cleanups (bkpt_chain);
9351   /* But cleanup everything else.  */
9352   do_cleanups (old_chain);
9353
9354   /* error call may happen here - have BKPT_CHAIN already discarded.  */
9355   update_global_location_list (1);
9356
9357   return 1;
9358 }
9359
9360 /* Set a breakpoint.
9361    ARG is a string describing breakpoint address,
9362    condition, and thread.
9363    FLAG specifies if a breakpoint is hardware on,
9364    and if breakpoint is temporary, using BP_HARDWARE_FLAG
9365    and BP_TEMPFLAG.  */
9366
9367 static void
9368 break_command_1 (char *arg, int flag, int from_tty)
9369 {
9370   int tempflag = flag & BP_TEMPFLAG;
9371   enum bptype type_wanted = (flag & BP_HARDWAREFLAG
9372                              ? bp_hardware_breakpoint
9373                              : bp_breakpoint);
9374   struct breakpoint_ops *ops;
9375   const char *arg_cp = arg;
9376
9377   /* Matching breakpoints on probes.  */
9378   if (arg && probe_linespec_to_ops (&arg_cp) != NULL)
9379     ops = &bkpt_probe_breakpoint_ops;
9380   else
9381     ops = &bkpt_breakpoint_ops;
9382
9383   create_breakpoint (get_current_arch (),
9384                      arg,
9385                      NULL, 0, NULL, 1 /* parse arg */,
9386                      tempflag, type_wanted,
9387                      0 /* Ignore count */,
9388                      pending_break_support,
9389                      ops,
9390                      from_tty,
9391                      1 /* enabled */,
9392                      0 /* internal */,
9393                      0);
9394 }
9395
9396 /* Helper function for break_command_1 and disassemble_command.  */
9397
9398 void
9399 resolve_sal_pc (struct symtab_and_line *sal)
9400 {
9401   CORE_ADDR pc;
9402
9403   if (sal->pc == 0 && sal->symtab != NULL)
9404     {
9405       if (!find_line_pc (sal->symtab, sal->line, &pc))
9406         error (_("No line %d in file \"%s\"."),
9407                sal->line, sal->symtab->filename);
9408       sal->pc = pc;
9409
9410       /* If this SAL corresponds to a breakpoint inserted using a line
9411          number, then skip the function prologue if necessary.  */
9412       if (sal->explicit_line)
9413         skip_prologue_sal (sal);
9414     }
9415
9416   if (sal->section == 0 && sal->symtab != NULL)
9417     {
9418       struct blockvector *bv;
9419       struct block *b;
9420       struct symbol *sym;
9421
9422       bv = blockvector_for_pc_sect (sal->pc, 0, &b, sal->symtab);
9423       if (bv != NULL)
9424         {
9425           sym = block_linkage_function (b);
9426           if (sym != NULL)
9427             {
9428               fixup_symbol_section (sym, sal->symtab->objfile);
9429               sal->section = SYMBOL_OBJ_SECTION (sym);
9430             }
9431           else
9432             {
9433               /* It really is worthwhile to have the section, so we'll
9434                  just have to look harder. This case can be executed
9435                  if we have line numbers but no functions (as can
9436                  happen in assembly source).  */
9437
9438               struct minimal_symbol *msym;
9439               struct cleanup *old_chain = save_current_space_and_thread ();
9440
9441               switch_to_program_space_and_thread (sal->pspace);
9442
9443               msym = lookup_minimal_symbol_by_pc (sal->pc);
9444               if (msym)
9445                 sal->section = SYMBOL_OBJ_SECTION (msym);
9446
9447               do_cleanups (old_chain);
9448             }
9449         }
9450     }
9451 }
9452
9453 void
9454 break_command (char *arg, int from_tty)
9455 {
9456   break_command_1 (arg, 0, from_tty);
9457 }
9458
9459 void
9460 tbreak_command (char *arg, int from_tty)
9461 {
9462   break_command_1 (arg, BP_TEMPFLAG, from_tty);
9463 }
9464
9465 static void
9466 hbreak_command (char *arg, int from_tty)
9467 {
9468   break_command_1 (arg, BP_HARDWAREFLAG, from_tty);
9469 }
9470
9471 static void
9472 thbreak_command (char *arg, int from_tty)
9473 {
9474   break_command_1 (arg, (BP_TEMPFLAG | BP_HARDWAREFLAG), from_tty);
9475 }
9476
9477 static void
9478 stop_command (char *arg, int from_tty)
9479 {
9480   printf_filtered (_("Specify the type of breakpoint to set.\n\
9481 Usage: stop in <function | address>\n\
9482        stop at <line>\n"));
9483 }
9484
9485 static void
9486 stopin_command (char *arg, int from_tty)
9487 {
9488   int badInput = 0;
9489
9490   if (arg == (char *) NULL)
9491     badInput = 1;
9492   else if (*arg != '*')
9493     {
9494       char *argptr = arg;
9495       int hasColon = 0;
9496
9497       /* Look for a ':'.  If this is a line number specification, then
9498          say it is bad, otherwise, it should be an address or
9499          function/method name.  */
9500       while (*argptr && !hasColon)
9501         {
9502           hasColon = (*argptr == ':');
9503           argptr++;
9504         }
9505
9506       if (hasColon)
9507         badInput = (*argptr != ':');    /* Not a class::method */
9508       else
9509         badInput = isdigit (*arg);      /* a simple line number */
9510     }
9511
9512   if (badInput)
9513     printf_filtered (_("Usage: stop in <function | address>\n"));
9514   else
9515     break_command_1 (arg, 0, from_tty);
9516 }
9517
9518 static void
9519 stopat_command (char *arg, int from_tty)
9520 {
9521   int badInput = 0;
9522
9523   if (arg == (char *) NULL || *arg == '*')      /* no line number */
9524     badInput = 1;
9525   else
9526     {
9527       char *argptr = arg;
9528       int hasColon = 0;
9529
9530       /* Look for a ':'.  If there is a '::' then get out, otherwise
9531          it is probably a line number.  */
9532       while (*argptr && !hasColon)
9533         {
9534           hasColon = (*argptr == ':');
9535           argptr++;
9536         }
9537
9538       if (hasColon)
9539         badInput = (*argptr == ':');    /* we have class::method */
9540       else
9541         badInput = !isdigit (*arg);     /* not a line number */
9542     }
9543
9544   if (badInput)
9545     printf_filtered (_("Usage: stop at <line>\n"));
9546   else
9547     break_command_1 (arg, 0, from_tty);
9548 }
9549
9550 void dprintf_command (char *arg, int from_tty);
9551
9552 /* The dynamic printf command is mostly like a regular breakpoint, but
9553    with a prewired command list consisting of a single output command,
9554    built from extra arguments supplied on the dprintf command
9555    line.  */
9556
9557 void
9558 dprintf_command (char *arg, int from_tty)
9559 {
9560   create_breakpoint (get_current_arch (),
9561                      arg,
9562                      NULL, 0, NULL, 1 /* parse arg */,
9563                      0, bp_dprintf,
9564                      0 /* Ignore count */,
9565                      pending_break_support,
9566                      &dprintf_breakpoint_ops,
9567                      from_tty,
9568                      1 /* enabled */,
9569                      0 /* internal */,
9570                      0);
9571 }
9572
9573 /* Implement the "breakpoint_hit" breakpoint_ops method for
9574    ranged breakpoints.  */
9575
9576 static int
9577 breakpoint_hit_ranged_breakpoint (const struct bp_location *bl,
9578                                   struct address_space *aspace,
9579                                   CORE_ADDR bp_addr,
9580                                   const struct target_waitstatus *ws)
9581 {
9582   if (ws->kind != TARGET_WAITKIND_STOPPED
9583       || ws->value.sig != GDB_SIGNAL_TRAP)
9584     return 0;
9585
9586   return breakpoint_address_match_range (bl->pspace->aspace, bl->address,
9587                                          bl->length, aspace, bp_addr);
9588 }
9589
9590 /* Implement the "resources_needed" breakpoint_ops method for
9591    ranged breakpoints.  */
9592
9593 static int
9594 resources_needed_ranged_breakpoint (const struct bp_location *bl)
9595 {
9596   return target_ranged_break_num_registers ();
9597 }
9598
9599 /* Implement the "print_it" breakpoint_ops method for
9600    ranged breakpoints.  */
9601
9602 static enum print_stop_action
9603 print_it_ranged_breakpoint (bpstat bs)
9604 {
9605   struct breakpoint *b = bs->breakpoint_at;
9606   struct bp_location *bl = b->loc;
9607   struct ui_out *uiout = current_uiout;
9608
9609   gdb_assert (b->type == bp_hardware_breakpoint);
9610
9611   /* Ranged breakpoints have only one location.  */
9612   gdb_assert (bl && bl->next == NULL);
9613
9614   annotate_breakpoint (b->number);
9615   if (b->disposition == disp_del)
9616     ui_out_text (uiout, "\nTemporary ranged breakpoint ");
9617   else
9618     ui_out_text (uiout, "\nRanged breakpoint ");
9619   if (ui_out_is_mi_like_p (uiout))
9620     {
9621       ui_out_field_string (uiout, "reason",
9622                       async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
9623       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
9624     }
9625   ui_out_field_int (uiout, "bkptno", b->number);
9626   ui_out_text (uiout, ", ");
9627
9628   return PRINT_SRC_AND_LOC;
9629 }
9630
9631 /* Implement the "print_one" breakpoint_ops method for
9632    ranged breakpoints.  */
9633
9634 static void
9635 print_one_ranged_breakpoint (struct breakpoint *b,
9636                              struct bp_location **last_loc)
9637 {
9638   struct bp_location *bl = b->loc;
9639   struct value_print_options opts;
9640   struct ui_out *uiout = current_uiout;
9641
9642   /* Ranged breakpoints have only one location.  */
9643   gdb_assert (bl && bl->next == NULL);
9644
9645   get_user_print_options (&opts);
9646
9647   if (opts.addressprint)
9648     /* We don't print the address range here, it will be printed later
9649        by print_one_detail_ranged_breakpoint.  */
9650     ui_out_field_skip (uiout, "addr");
9651   annotate_field (5);
9652   print_breakpoint_location (b, bl);
9653   *last_loc = bl;
9654 }
9655
9656 /* Implement the "print_one_detail" breakpoint_ops method for
9657    ranged breakpoints.  */
9658
9659 static void
9660 print_one_detail_ranged_breakpoint (const struct breakpoint *b,
9661                                     struct ui_out *uiout)
9662 {
9663   CORE_ADDR address_start, address_end;
9664   struct bp_location *bl = b->loc;
9665   struct ui_file *stb = mem_fileopen ();
9666   struct cleanup *cleanup = make_cleanup_ui_file_delete (stb);
9667
9668   gdb_assert (bl);
9669
9670   address_start = bl->address;
9671   address_end = address_start + bl->length - 1;
9672
9673   ui_out_text (uiout, "\taddress range: ");
9674   fprintf_unfiltered (stb, "[%s, %s]",
9675                       print_core_address (bl->gdbarch, address_start),
9676                       print_core_address (bl->gdbarch, address_end));
9677   ui_out_field_stream (uiout, "addr", stb);
9678   ui_out_text (uiout, "\n");
9679
9680   do_cleanups (cleanup);
9681 }
9682
9683 /* Implement the "print_mention" breakpoint_ops method for
9684    ranged breakpoints.  */
9685
9686 static void
9687 print_mention_ranged_breakpoint (struct breakpoint *b)
9688 {
9689   struct bp_location *bl = b->loc;
9690   struct ui_out *uiout = current_uiout;
9691
9692   gdb_assert (bl);
9693   gdb_assert (b->type == bp_hardware_breakpoint);
9694
9695   if (ui_out_is_mi_like_p (uiout))
9696     return;
9697
9698   printf_filtered (_("Hardware assisted ranged breakpoint %d from %s to %s."),
9699                    b->number, paddress (bl->gdbarch, bl->address),
9700                    paddress (bl->gdbarch, bl->address + bl->length - 1));
9701 }
9702
9703 /* Implement the "print_recreate" breakpoint_ops method for
9704    ranged breakpoints.  */
9705
9706 static void
9707 print_recreate_ranged_breakpoint (struct breakpoint *b, struct ui_file *fp)
9708 {
9709   fprintf_unfiltered (fp, "break-range %s, %s", b->addr_string,
9710                       b->addr_string_range_end);
9711   print_recreate_thread (b, fp);
9712 }
9713
9714 /* The breakpoint_ops structure to be used in ranged breakpoints.  */
9715
9716 static struct breakpoint_ops ranged_breakpoint_ops;
9717
9718 /* Find the address where the end of the breakpoint range should be
9719    placed, given the SAL of the end of the range.  This is so that if
9720    the user provides a line number, the end of the range is set to the
9721    last instruction of the given line.  */
9722
9723 static CORE_ADDR
9724 find_breakpoint_range_end (struct symtab_and_line sal)
9725 {
9726   CORE_ADDR end;
9727
9728   /* If the user provided a PC value, use it.  Otherwise,
9729      find the address of the end of the given location.  */
9730   if (sal.explicit_pc)
9731     end = sal.pc;
9732   else
9733     {
9734       int ret;
9735       CORE_ADDR start;
9736
9737       ret = find_line_pc_range (sal, &start, &end);
9738       if (!ret)
9739         error (_("Could not find location of the end of the range."));
9740
9741       /* find_line_pc_range returns the start of the next line.  */
9742       end--;
9743     }
9744
9745   return end;
9746 }
9747
9748 /* Implement the "break-range" CLI command.  */
9749
9750 static void
9751 break_range_command (char *arg, int from_tty)
9752 {
9753   char *arg_start, *addr_string_start, *addr_string_end;
9754   struct linespec_result canonical_start, canonical_end;
9755   int bp_count, can_use_bp, length;
9756   CORE_ADDR end;
9757   struct breakpoint *b;
9758   struct symtab_and_line sal_start, sal_end;
9759   struct cleanup *cleanup_bkpt;
9760   struct linespec_sals *lsal_start, *lsal_end;
9761
9762   /* We don't support software ranged breakpoints.  */
9763   if (target_ranged_break_num_registers () < 0)
9764     error (_("This target does not support hardware ranged breakpoints."));
9765
9766   bp_count = hw_breakpoint_used_count ();
9767   bp_count += target_ranged_break_num_registers ();
9768   can_use_bp = target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
9769                                                    bp_count, 0);
9770   if (can_use_bp < 0)
9771     error (_("Hardware breakpoints used exceeds limit."));
9772
9773   arg = skip_spaces (arg);
9774   if (arg == NULL || arg[0] == '\0')
9775     error(_("No address range specified."));
9776
9777   init_linespec_result (&canonical_start);
9778
9779   arg_start = arg;
9780   parse_breakpoint_sals (&arg, &canonical_start);
9781
9782   cleanup_bkpt = make_cleanup_destroy_linespec_result (&canonical_start);
9783
9784   if (arg[0] != ',')
9785     error (_("Too few arguments."));
9786   else if (VEC_empty (linespec_sals, canonical_start.sals))
9787     error (_("Could not find location of the beginning of the range."));
9788
9789   lsal_start = VEC_index (linespec_sals, canonical_start.sals, 0);
9790
9791   if (VEC_length (linespec_sals, canonical_start.sals) > 1
9792       || lsal_start->sals.nelts != 1)
9793     error (_("Cannot create a ranged breakpoint with multiple locations."));
9794
9795   sal_start = lsal_start->sals.sals[0];
9796   addr_string_start = savestring (arg_start, arg - arg_start);
9797   make_cleanup (xfree, addr_string_start);
9798
9799   arg++;        /* Skip the comma.  */
9800   arg = skip_spaces (arg);
9801
9802   /* Parse the end location.  */
9803
9804   init_linespec_result (&canonical_end);
9805   arg_start = arg;
9806
9807   /* We call decode_line_full directly here instead of using
9808      parse_breakpoint_sals because we need to specify the start location's
9809      symtab and line as the default symtab and line for the end of the
9810      range.  This makes it possible to have ranges like "foo.c:27, +14",
9811      where +14 means 14 lines from the start location.  */
9812   decode_line_full (&arg, DECODE_LINE_FUNFIRSTLINE,
9813                     sal_start.symtab, sal_start.line,
9814                     &canonical_end, NULL, NULL);
9815
9816   make_cleanup_destroy_linespec_result (&canonical_end);
9817
9818   if (VEC_empty (linespec_sals, canonical_end.sals))
9819     error (_("Could not find location of the end of the range."));
9820
9821   lsal_end = VEC_index (linespec_sals, canonical_end.sals, 0);
9822   if (VEC_length (linespec_sals, canonical_end.sals) > 1
9823       || lsal_end->sals.nelts != 1)
9824     error (_("Cannot create a ranged breakpoint with multiple locations."));
9825
9826   sal_end = lsal_end->sals.sals[0];
9827   addr_string_end = savestring (arg_start, arg - arg_start);
9828   make_cleanup (xfree, addr_string_end);
9829
9830   end = find_breakpoint_range_end (sal_end);
9831   if (sal_start.pc > end)
9832     error (_("Invalid address range, end precedes start."));
9833
9834   length = end - sal_start.pc + 1;
9835   if (length < 0)
9836     /* Length overflowed.  */
9837     error (_("Address range too large."));
9838   else if (length == 1)
9839     {
9840       /* This range is simple enough to be handled by
9841          the `hbreak' command.  */
9842       hbreak_command (addr_string_start, 1);
9843
9844       do_cleanups (cleanup_bkpt);
9845
9846       return;
9847     }
9848
9849   /* Now set up the breakpoint.  */
9850   b = set_raw_breakpoint (get_current_arch (), sal_start,
9851                           bp_hardware_breakpoint, &ranged_breakpoint_ops);
9852   set_breakpoint_count (breakpoint_count + 1);
9853   b->number = breakpoint_count;
9854   b->disposition = disp_donttouch;
9855   b->addr_string = xstrdup (addr_string_start);
9856   b->addr_string_range_end = xstrdup (addr_string_end);
9857   b->loc->length = length;
9858
9859   do_cleanups (cleanup_bkpt);
9860
9861   mention (b);
9862   observer_notify_breakpoint_created (b);
9863   update_global_location_list (1);
9864 }
9865
9866 /*  Return non-zero if EXP is verified as constant.  Returned zero
9867     means EXP is variable.  Also the constant detection may fail for
9868     some constant expressions and in such case still falsely return
9869     zero.  */
9870
9871 static int
9872 watchpoint_exp_is_const (const struct expression *exp)
9873 {
9874   int i = exp->nelts;
9875
9876   while (i > 0)
9877     {
9878       int oplenp, argsp;
9879
9880       /* We are only interested in the descriptor of each element.  */
9881       operator_length (exp, i, &oplenp, &argsp);
9882       i -= oplenp;
9883
9884       switch (exp->elts[i].opcode)
9885         {
9886         case BINOP_ADD:
9887         case BINOP_SUB:
9888         case BINOP_MUL:
9889         case BINOP_DIV:
9890         case BINOP_REM:
9891         case BINOP_MOD:
9892         case BINOP_LSH:
9893         case BINOP_RSH:
9894         case BINOP_LOGICAL_AND:
9895         case BINOP_LOGICAL_OR:
9896         case BINOP_BITWISE_AND:
9897         case BINOP_BITWISE_IOR:
9898         case BINOP_BITWISE_XOR:
9899         case BINOP_EQUAL:
9900         case BINOP_NOTEQUAL:
9901         case BINOP_LESS:
9902         case BINOP_GTR:
9903         case BINOP_LEQ:
9904         case BINOP_GEQ:
9905         case BINOP_REPEAT:
9906         case BINOP_COMMA:
9907         case BINOP_EXP:
9908         case BINOP_MIN:
9909         case BINOP_MAX:
9910         case BINOP_INTDIV:
9911         case BINOP_CONCAT:
9912         case BINOP_IN:
9913         case BINOP_RANGE:
9914         case TERNOP_COND:
9915         case TERNOP_SLICE:
9916         case TERNOP_SLICE_COUNT:
9917
9918         case OP_LONG:
9919         case OP_DOUBLE:
9920         case OP_DECFLOAT:
9921         case OP_LAST:
9922         case OP_COMPLEX:
9923         case OP_STRING:
9924         case OP_BITSTRING:
9925         case OP_ARRAY:
9926         case OP_TYPE:
9927         case OP_NAME:
9928         case OP_OBJC_NSSTRING:
9929
9930         case UNOP_NEG:
9931         case UNOP_LOGICAL_NOT:
9932         case UNOP_COMPLEMENT:
9933         case UNOP_ADDR:
9934         case UNOP_HIGH:
9935         case UNOP_CAST:
9936           /* Unary, binary and ternary operators: We have to check
9937              their operands.  If they are constant, then so is the
9938              result of that operation.  For instance, if A and B are
9939              determined to be constants, then so is "A + B".
9940
9941              UNOP_IND is one exception to the rule above, because the
9942              value of *ADDR is not necessarily a constant, even when
9943              ADDR is.  */
9944           break;
9945
9946         case OP_VAR_VALUE:
9947           /* Check whether the associated symbol is a constant.
9948
9949              We use SYMBOL_CLASS rather than TYPE_CONST because it's
9950              possible that a buggy compiler could mark a variable as
9951              constant even when it is not, and TYPE_CONST would return
9952              true in this case, while SYMBOL_CLASS wouldn't.
9953
9954              We also have to check for function symbols because they
9955              are always constant.  */
9956           {
9957             struct symbol *s = exp->elts[i + 2].symbol;
9958
9959             if (SYMBOL_CLASS (s) != LOC_BLOCK
9960                 && SYMBOL_CLASS (s) != LOC_CONST
9961                 && SYMBOL_CLASS (s) != LOC_CONST_BYTES)
9962               return 0;
9963             break;
9964           }
9965
9966         /* The default action is to return 0 because we are using
9967            the optimistic approach here: If we don't know something,
9968            then it is not a constant.  */
9969         default:
9970           return 0;
9971         }
9972     }
9973
9974   return 1;
9975 }
9976
9977 /* Implement the "dtor" breakpoint_ops method for watchpoints.  */
9978
9979 static void
9980 dtor_watchpoint (struct breakpoint *self)
9981 {
9982   struct watchpoint *w = (struct watchpoint *) self;
9983
9984   xfree (w->cond_exp);
9985   xfree (w->exp);
9986   xfree (w->exp_string);
9987   xfree (w->exp_string_reparse);
9988   value_free (w->val);
9989
9990   base_breakpoint_ops.dtor (self);
9991 }
9992
9993 /* Implement the "re_set" breakpoint_ops method for watchpoints.  */
9994
9995 static void
9996 re_set_watchpoint (struct breakpoint *b)
9997 {
9998   struct watchpoint *w = (struct watchpoint *) b;
9999
10000   /* Watchpoint can be either on expression using entirely global
10001      variables, or it can be on local variables.
10002
10003      Watchpoints of the first kind are never auto-deleted, and even
10004      persist across program restarts.  Since they can use variables
10005      from shared libraries, we need to reparse expression as libraries
10006      are loaded and unloaded.
10007
10008      Watchpoints on local variables can also change meaning as result
10009      of solib event.  For example, if a watchpoint uses both a local
10010      and a global variables in expression, it's a local watchpoint,
10011      but unloading of a shared library will make the expression
10012      invalid.  This is not a very common use case, but we still
10013      re-evaluate expression, to avoid surprises to the user.
10014
10015      Note that for local watchpoints, we re-evaluate it only if
10016      watchpoints frame id is still valid.  If it's not, it means the
10017      watchpoint is out of scope and will be deleted soon.  In fact,
10018      I'm not sure we'll ever be called in this case.
10019
10020      If a local watchpoint's frame id is still valid, then
10021      w->exp_valid_block is likewise valid, and we can safely use it.
10022
10023      Don't do anything about disabled watchpoints, since they will be
10024      reevaluated again when enabled.  */
10025   update_watchpoint (w, 1 /* reparse */);
10026 }
10027
10028 /* Implement the "insert" breakpoint_ops method for hardware watchpoints.  */
10029
10030 static int
10031 insert_watchpoint (struct bp_location *bl)
10032 {
10033   struct watchpoint *w = (struct watchpoint *) bl->owner;
10034   int length = w->exact ? 1 : bl->length;
10035
10036   return target_insert_watchpoint (bl->address, length, bl->watchpoint_type,
10037                                    w->cond_exp);
10038 }
10039
10040 /* Implement the "remove" breakpoint_ops method for hardware watchpoints.  */
10041
10042 static int
10043 remove_watchpoint (struct bp_location *bl)
10044 {
10045   struct watchpoint *w = (struct watchpoint *) bl->owner;
10046   int length = w->exact ? 1 : bl->length;
10047
10048   return target_remove_watchpoint (bl->address, length, bl->watchpoint_type,
10049                                    w->cond_exp);
10050 }
10051
10052 static int
10053 breakpoint_hit_watchpoint (const struct bp_location *bl,
10054                            struct address_space *aspace, CORE_ADDR bp_addr,
10055                            const struct target_waitstatus *ws)
10056 {
10057   struct breakpoint *b = bl->owner;
10058   struct watchpoint *w = (struct watchpoint *) b;
10059
10060   /* Continuable hardware watchpoints are treated as non-existent if the
10061      reason we stopped wasn't a hardware watchpoint (we didn't stop on
10062      some data address).  Otherwise gdb won't stop on a break instruction
10063      in the code (not from a breakpoint) when a hardware watchpoint has
10064      been defined.  Also skip watchpoints which we know did not trigger
10065      (did not match the data address).  */
10066   if (is_hardware_watchpoint (b)
10067       && w->watchpoint_triggered == watch_triggered_no)
10068     return 0;
10069
10070   return 1;
10071 }
10072
10073 static void
10074 check_status_watchpoint (bpstat bs)
10075 {
10076   gdb_assert (is_watchpoint (bs->breakpoint_at));
10077
10078   bpstat_check_watchpoint (bs);
10079 }
10080
10081 /* Implement the "resources_needed" breakpoint_ops method for
10082    hardware watchpoints.  */
10083
10084 static int
10085 resources_needed_watchpoint (const struct bp_location *bl)
10086 {
10087   struct watchpoint *w = (struct watchpoint *) bl->owner;
10088   int length = w->exact? 1 : bl->length;
10089
10090   return target_region_ok_for_hw_watchpoint (bl->address, length);
10091 }
10092
10093 /* Implement the "works_in_software_mode" breakpoint_ops method for
10094    hardware watchpoints.  */
10095
10096 static int
10097 works_in_software_mode_watchpoint (const struct breakpoint *b)
10098 {
10099   /* Read and access watchpoints only work with hardware support.  */
10100   return b->type == bp_watchpoint || b->type == bp_hardware_watchpoint;
10101 }
10102
10103 static enum print_stop_action
10104 print_it_watchpoint (bpstat bs)
10105 {
10106   struct cleanup *old_chain;
10107   struct breakpoint *b;
10108   const struct bp_location *bl;
10109   struct ui_file *stb;
10110   enum print_stop_action result;
10111   struct watchpoint *w;
10112   struct ui_out *uiout = current_uiout;
10113
10114   gdb_assert (bs->bp_location_at != NULL);
10115
10116   bl = bs->bp_location_at;
10117   b = bs->breakpoint_at;
10118   w = (struct watchpoint *) b;
10119
10120   stb = mem_fileopen ();
10121   old_chain = make_cleanup_ui_file_delete (stb);
10122
10123   switch (b->type)
10124     {
10125     case bp_watchpoint:
10126     case bp_hardware_watchpoint:
10127       annotate_watchpoint (b->number);
10128       if (ui_out_is_mi_like_p (uiout))
10129         ui_out_field_string
10130           (uiout, "reason",
10131            async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
10132       mention (b);
10133       make_cleanup_ui_out_tuple_begin_end (uiout, "value");
10134       ui_out_text (uiout, "\nOld value = ");
10135       watchpoint_value_print (bs->old_val, stb);
10136       ui_out_field_stream (uiout, "old", stb);
10137       ui_out_text (uiout, "\nNew value = ");
10138       watchpoint_value_print (w->val, stb);
10139       ui_out_field_stream (uiout, "new", stb);
10140       ui_out_text (uiout, "\n");
10141       /* More than one watchpoint may have been triggered.  */
10142       result = PRINT_UNKNOWN;
10143       break;
10144
10145     case bp_read_watchpoint:
10146       if (ui_out_is_mi_like_p (uiout))
10147         ui_out_field_string
10148           (uiout, "reason",
10149            async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
10150       mention (b);
10151       make_cleanup_ui_out_tuple_begin_end (uiout, "value");
10152       ui_out_text (uiout, "\nValue = ");
10153       watchpoint_value_print (w->val, stb);
10154       ui_out_field_stream (uiout, "value", stb);
10155       ui_out_text (uiout, "\n");
10156       result = PRINT_UNKNOWN;
10157       break;
10158
10159     case bp_access_watchpoint:
10160       if (bs->old_val != NULL)
10161         {
10162           annotate_watchpoint (b->number);
10163           if (ui_out_is_mi_like_p (uiout))
10164             ui_out_field_string
10165               (uiout, "reason",
10166                async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10167           mention (b);
10168           make_cleanup_ui_out_tuple_begin_end (uiout, "value");
10169           ui_out_text (uiout, "\nOld value = ");
10170           watchpoint_value_print (bs->old_val, stb);
10171           ui_out_field_stream (uiout, "old", stb);
10172           ui_out_text (uiout, "\nNew value = ");
10173         }
10174       else
10175         {
10176           mention (b);
10177           if (ui_out_is_mi_like_p (uiout))
10178             ui_out_field_string
10179               (uiout, "reason",
10180                async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10181           make_cleanup_ui_out_tuple_begin_end (uiout, "value");
10182           ui_out_text (uiout, "\nValue = ");
10183         }
10184       watchpoint_value_print (w->val, stb);
10185       ui_out_field_stream (uiout, "new", stb);
10186       ui_out_text (uiout, "\n");
10187       result = PRINT_UNKNOWN;
10188       break;
10189     default:
10190       result = PRINT_UNKNOWN;
10191     }
10192
10193   do_cleanups (old_chain);
10194   return result;
10195 }
10196
10197 /* Implement the "print_mention" breakpoint_ops method for hardware
10198    watchpoints.  */
10199
10200 static void
10201 print_mention_watchpoint (struct breakpoint *b)
10202 {
10203   struct cleanup *ui_out_chain;
10204   struct watchpoint *w = (struct watchpoint *) b;
10205   struct ui_out *uiout = current_uiout;
10206
10207   switch (b->type)
10208     {
10209     case bp_watchpoint:
10210       ui_out_text (uiout, "Watchpoint ");
10211       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "wpt");
10212       break;
10213     case bp_hardware_watchpoint:
10214       ui_out_text (uiout, "Hardware watchpoint ");
10215       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "wpt");
10216       break;
10217     case bp_read_watchpoint:
10218       ui_out_text (uiout, "Hardware read watchpoint ");
10219       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-rwpt");
10220       break;
10221     case bp_access_watchpoint:
10222       ui_out_text (uiout, "Hardware access (read/write) watchpoint ");
10223       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-awpt");
10224       break;
10225     default:
10226       internal_error (__FILE__, __LINE__,
10227                       _("Invalid hardware watchpoint type."));
10228     }
10229
10230   ui_out_field_int (uiout, "number", b->number);
10231   ui_out_text (uiout, ": ");
10232   ui_out_field_string (uiout, "exp", w->exp_string);
10233   do_cleanups (ui_out_chain);
10234 }
10235
10236 /* Implement the "print_recreate" breakpoint_ops method for
10237    watchpoints.  */
10238
10239 static void
10240 print_recreate_watchpoint (struct breakpoint *b, struct ui_file *fp)
10241 {
10242   struct watchpoint *w = (struct watchpoint *) b;
10243
10244   switch (b->type)
10245     {
10246     case bp_watchpoint:
10247     case bp_hardware_watchpoint:
10248       fprintf_unfiltered (fp, "watch");
10249       break;
10250     case bp_read_watchpoint:
10251       fprintf_unfiltered (fp, "rwatch");
10252       break;
10253     case bp_access_watchpoint:
10254       fprintf_unfiltered (fp, "awatch");
10255       break;
10256     default:
10257       internal_error (__FILE__, __LINE__,
10258                       _("Invalid watchpoint type."));
10259     }
10260
10261   fprintf_unfiltered (fp, " %s", w->exp_string);
10262   print_recreate_thread (b, fp);
10263 }
10264
10265 /* The breakpoint_ops structure to be used in hardware watchpoints.  */
10266
10267 static struct breakpoint_ops watchpoint_breakpoint_ops;
10268
10269 /* Implement the "insert" breakpoint_ops method for
10270    masked hardware watchpoints.  */
10271
10272 static int
10273 insert_masked_watchpoint (struct bp_location *bl)
10274 {
10275   struct watchpoint *w = (struct watchpoint *) bl->owner;
10276
10277   return target_insert_mask_watchpoint (bl->address, w->hw_wp_mask,
10278                                         bl->watchpoint_type);
10279 }
10280
10281 /* Implement the "remove" breakpoint_ops method for
10282    masked hardware watchpoints.  */
10283
10284 static int
10285 remove_masked_watchpoint (struct bp_location *bl)
10286 {
10287   struct watchpoint *w = (struct watchpoint *) bl->owner;
10288
10289   return target_remove_mask_watchpoint (bl->address, w->hw_wp_mask,
10290                                         bl->watchpoint_type);
10291 }
10292
10293 /* Implement the "resources_needed" breakpoint_ops method for
10294    masked hardware watchpoints.  */
10295
10296 static int
10297 resources_needed_masked_watchpoint (const struct bp_location *bl)
10298 {
10299   struct watchpoint *w = (struct watchpoint *) bl->owner;
10300
10301   return target_masked_watch_num_registers (bl->address, w->hw_wp_mask);
10302 }
10303
10304 /* Implement the "works_in_software_mode" breakpoint_ops method for
10305    masked hardware watchpoints.  */
10306
10307 static int
10308 works_in_software_mode_masked_watchpoint (const struct breakpoint *b)
10309 {
10310   return 0;
10311 }
10312
10313 /* Implement the "print_it" breakpoint_ops method for
10314    masked hardware watchpoints.  */
10315
10316 static enum print_stop_action
10317 print_it_masked_watchpoint (bpstat bs)
10318 {
10319   struct breakpoint *b = bs->breakpoint_at;
10320   struct ui_out *uiout = current_uiout;
10321
10322   /* Masked watchpoints have only one location.  */
10323   gdb_assert (b->loc && b->loc->next == NULL);
10324
10325   switch (b->type)
10326     {
10327     case bp_hardware_watchpoint:
10328       annotate_watchpoint (b->number);
10329       if (ui_out_is_mi_like_p (uiout))
10330         ui_out_field_string
10331           (uiout, "reason",
10332            async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
10333       break;
10334
10335     case bp_read_watchpoint:
10336       if (ui_out_is_mi_like_p (uiout))
10337         ui_out_field_string
10338           (uiout, "reason",
10339            async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
10340       break;
10341
10342     case bp_access_watchpoint:
10343       if (ui_out_is_mi_like_p (uiout))
10344         ui_out_field_string
10345           (uiout, "reason",
10346            async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10347       break;
10348     default:
10349       internal_error (__FILE__, __LINE__,
10350                       _("Invalid hardware watchpoint type."));
10351     }
10352
10353   mention (b);
10354   ui_out_text (uiout, _("\n\
10355 Check the underlying instruction at PC for the memory\n\
10356 address and value which triggered this watchpoint.\n"));
10357   ui_out_text (uiout, "\n");
10358
10359   /* More than one watchpoint may have been triggered.  */
10360   return PRINT_UNKNOWN;
10361 }
10362
10363 /* Implement the "print_one_detail" breakpoint_ops method for
10364    masked hardware watchpoints.  */
10365
10366 static void
10367 print_one_detail_masked_watchpoint (const struct breakpoint *b,
10368                                     struct ui_out *uiout)
10369 {
10370   struct watchpoint *w = (struct watchpoint *) b;
10371
10372   /* Masked watchpoints have only one location.  */
10373   gdb_assert (b->loc && b->loc->next == NULL);
10374
10375   ui_out_text (uiout, "\tmask ");
10376   ui_out_field_core_addr (uiout, "mask", b->loc->gdbarch, w->hw_wp_mask);
10377   ui_out_text (uiout, "\n");
10378 }
10379
10380 /* Implement the "print_mention" breakpoint_ops method for
10381    masked hardware watchpoints.  */
10382
10383 static void
10384 print_mention_masked_watchpoint (struct breakpoint *b)
10385 {
10386   struct watchpoint *w = (struct watchpoint *) b;
10387   struct ui_out *uiout = current_uiout;
10388   struct cleanup *ui_out_chain;
10389
10390   switch (b->type)
10391     {
10392     case bp_hardware_watchpoint:
10393       ui_out_text (uiout, "Masked hardware watchpoint ");
10394       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "wpt");
10395       break;
10396     case bp_read_watchpoint:
10397       ui_out_text (uiout, "Masked hardware read watchpoint ");
10398       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-rwpt");
10399       break;
10400     case bp_access_watchpoint:
10401       ui_out_text (uiout, "Masked hardware access (read/write) watchpoint ");
10402       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-awpt");
10403       break;
10404     default:
10405       internal_error (__FILE__, __LINE__,
10406                       _("Invalid hardware watchpoint type."));
10407     }
10408
10409   ui_out_field_int (uiout, "number", b->number);
10410   ui_out_text (uiout, ": ");
10411   ui_out_field_string (uiout, "exp", w->exp_string);
10412   do_cleanups (ui_out_chain);
10413 }
10414
10415 /* Implement the "print_recreate" breakpoint_ops method for
10416    masked hardware watchpoints.  */
10417
10418 static void
10419 print_recreate_masked_watchpoint (struct breakpoint *b, struct ui_file *fp)
10420 {
10421   struct watchpoint *w = (struct watchpoint *) b;
10422   char tmp[40];
10423
10424   switch (b->type)
10425     {
10426     case bp_hardware_watchpoint:
10427       fprintf_unfiltered (fp, "watch");
10428       break;
10429     case bp_read_watchpoint:
10430       fprintf_unfiltered (fp, "rwatch");
10431       break;
10432     case bp_access_watchpoint:
10433       fprintf_unfiltered (fp, "awatch");
10434       break;
10435     default:
10436       internal_error (__FILE__, __LINE__,
10437                       _("Invalid hardware watchpoint type."));
10438     }
10439
10440   sprintf_vma (tmp, w->hw_wp_mask);
10441   fprintf_unfiltered (fp, " %s mask 0x%s", w->exp_string, tmp);
10442   print_recreate_thread (b, fp);
10443 }
10444
10445 /* The breakpoint_ops structure to be used in masked hardware watchpoints.  */
10446
10447 static struct breakpoint_ops masked_watchpoint_breakpoint_ops;
10448
10449 /* Tell whether the given watchpoint is a masked hardware watchpoint.  */
10450
10451 static int
10452 is_masked_watchpoint (const struct breakpoint *b)
10453 {
10454   return b->ops == &masked_watchpoint_breakpoint_ops;
10455 }
10456
10457 /* accessflag:  hw_write:  watch write, 
10458                 hw_read:   watch read, 
10459                 hw_access: watch access (read or write) */
10460 static void
10461 watch_command_1 (char *arg, int accessflag, int from_tty,
10462                  int just_location, int internal)
10463 {
10464   volatile struct gdb_exception e;
10465   struct breakpoint *b, *scope_breakpoint = NULL;
10466   struct expression *exp;
10467   struct block *exp_valid_block = NULL, *cond_exp_valid_block = NULL;
10468   struct value *val, *mark, *result;
10469   struct frame_info *frame;
10470   char *exp_start = NULL;
10471   char *exp_end = NULL;
10472   char *tok, *end_tok;
10473   int toklen = -1;
10474   char *cond_start = NULL;
10475   char *cond_end = NULL;
10476   enum bptype bp_type;
10477   int thread = -1;
10478   int pc = 0;
10479   /* Flag to indicate whether we are going to use masks for
10480      the hardware watchpoint.  */
10481   int use_mask = 0;
10482   CORE_ADDR mask = 0;
10483   struct watchpoint *w;
10484
10485   /* Make sure that we actually have parameters to parse.  */
10486   if (arg != NULL && arg[0] != '\0')
10487     {
10488       char *value_start;
10489
10490       /* Look for "parameter value" pairs at the end
10491          of the arguments string.  */
10492       for (tok = arg + strlen (arg) - 1; tok > arg; tok--)
10493         {
10494           /* Skip whitespace at the end of the argument list.  */
10495           while (tok > arg && (*tok == ' ' || *tok == '\t'))
10496             tok--;
10497
10498           /* Find the beginning of the last token.
10499              This is the value of the parameter.  */
10500           while (tok > arg && (*tok != ' ' && *tok != '\t'))
10501             tok--;
10502           value_start = tok + 1;
10503
10504           /* Skip whitespace.  */
10505           while (tok > arg && (*tok == ' ' || *tok == '\t'))
10506             tok--;
10507
10508           end_tok = tok;
10509
10510           /* Find the beginning of the second to last token.
10511              This is the parameter itself.  */
10512           while (tok > arg && (*tok != ' ' && *tok != '\t'))
10513             tok--;
10514           tok++;
10515           toklen = end_tok - tok + 1;
10516
10517           if (toklen == 6 && !strncmp (tok, "thread", 6))
10518             {
10519               /* At this point we've found a "thread" token, which means
10520                  the user is trying to set a watchpoint that triggers
10521                  only in a specific thread.  */
10522               char *endp;
10523
10524               if (thread != -1)
10525                 error(_("You can specify only one thread."));
10526
10527               /* Extract the thread ID from the next token.  */
10528               thread = strtol (value_start, &endp, 0);
10529
10530               /* Check if the user provided a valid numeric value for the
10531                  thread ID.  */
10532               if (*endp != ' ' && *endp != '\t' && *endp != '\0')
10533                 error (_("Invalid thread ID specification %s."), value_start);
10534
10535               /* Check if the thread actually exists.  */
10536               if (!valid_thread_id (thread))
10537                 error (_("Unknown thread %d."), thread);
10538             }
10539           else if (toklen == 4 && !strncmp (tok, "mask", 4))
10540             {
10541               /* We've found a "mask" token, which means the user wants to
10542                  create a hardware watchpoint that is going to have the mask
10543                  facility.  */
10544               struct value *mask_value, *mark;
10545
10546               if (use_mask)
10547                 error(_("You can specify only one mask."));
10548
10549               use_mask = just_location = 1;
10550
10551               mark = value_mark ();
10552               mask_value = parse_to_comma_and_eval (&value_start);
10553               mask = value_as_address (mask_value);
10554               value_free_to_mark (mark);
10555             }
10556           else
10557             /* We didn't recognize what we found.  We should stop here.  */
10558             break;
10559
10560           /* Truncate the string and get rid of the "parameter value" pair before
10561              the arguments string is parsed by the parse_exp_1 function.  */
10562           *tok = '\0';
10563         }
10564     }
10565
10566   /* Parse the rest of the arguments.  */
10567   innermost_block = NULL;
10568   exp_start = arg;
10569   exp = parse_exp_1 (&arg, 0, 0, 0);
10570   exp_end = arg;
10571   /* Remove trailing whitespace from the expression before saving it.
10572      This makes the eventual display of the expression string a bit
10573      prettier.  */
10574   while (exp_end > exp_start && (exp_end[-1] == ' ' || exp_end[-1] == '\t'))
10575     --exp_end;
10576
10577   /* Checking if the expression is not constant.  */
10578   if (watchpoint_exp_is_const (exp))
10579     {
10580       int len;
10581
10582       len = exp_end - exp_start;
10583       while (len > 0 && isspace (exp_start[len - 1]))
10584         len--;
10585       error (_("Cannot watch constant value `%.*s'."), len, exp_start);
10586     }
10587
10588   exp_valid_block = innermost_block;
10589   mark = value_mark ();
10590   fetch_subexp_value (exp, &pc, &val, &result, NULL);
10591
10592   if (just_location)
10593     {
10594       int ret;
10595
10596       exp_valid_block = NULL;
10597       val = value_addr (result);
10598       release_value (val);
10599       value_free_to_mark (mark);
10600
10601       if (use_mask)
10602         {
10603           ret = target_masked_watch_num_registers (value_as_address (val),
10604                                                    mask);
10605           if (ret == -1)
10606             error (_("This target does not support masked watchpoints."));
10607           else if (ret == -2)
10608             error (_("Invalid mask or memory region."));
10609         }
10610     }
10611   else if (val != NULL)
10612     release_value (val);
10613
10614   tok = skip_spaces (arg);
10615   end_tok = skip_to_space (tok);
10616
10617   toklen = end_tok - tok;
10618   if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
10619     {
10620       struct expression *cond;
10621
10622       innermost_block = NULL;
10623       tok = cond_start = end_tok + 1;
10624       cond = parse_exp_1 (&tok, 0, 0, 0);
10625
10626       /* The watchpoint expression may not be local, but the condition
10627          may still be.  E.g.: `watch global if local > 0'.  */
10628       cond_exp_valid_block = innermost_block;
10629
10630       xfree (cond);
10631       cond_end = tok;
10632     }
10633   if (*tok)
10634     error (_("Junk at end of command."));
10635
10636   if (accessflag == hw_read)
10637     bp_type = bp_read_watchpoint;
10638   else if (accessflag == hw_access)
10639     bp_type = bp_access_watchpoint;
10640   else
10641     bp_type = bp_hardware_watchpoint;
10642
10643   frame = block_innermost_frame (exp_valid_block);
10644
10645   /* If the expression is "local", then set up a "watchpoint scope"
10646      breakpoint at the point where we've left the scope of the watchpoint
10647      expression.  Create the scope breakpoint before the watchpoint, so
10648      that we will encounter it first in bpstat_stop_status.  */
10649   if (exp_valid_block && frame)
10650     {
10651       if (frame_id_p (frame_unwind_caller_id (frame)))
10652         {
10653           scope_breakpoint
10654             = create_internal_breakpoint (frame_unwind_caller_arch (frame),
10655                                           frame_unwind_caller_pc (frame),
10656                                           bp_watchpoint_scope,
10657                                           &momentary_breakpoint_ops);
10658
10659           scope_breakpoint->enable_state = bp_enabled;
10660
10661           /* Automatically delete the breakpoint when it hits.  */
10662           scope_breakpoint->disposition = disp_del;
10663
10664           /* Only break in the proper frame (help with recursion).  */
10665           scope_breakpoint->frame_id = frame_unwind_caller_id (frame);
10666
10667           /* Set the address at which we will stop.  */
10668           scope_breakpoint->loc->gdbarch
10669             = frame_unwind_caller_arch (frame);
10670           scope_breakpoint->loc->requested_address
10671             = frame_unwind_caller_pc (frame);
10672           scope_breakpoint->loc->address
10673             = adjust_breakpoint_address (scope_breakpoint->loc->gdbarch,
10674                                          scope_breakpoint->loc->requested_address,
10675                                          scope_breakpoint->type);
10676         }
10677     }
10678
10679   /* Now set up the breakpoint.  */
10680
10681   w = XCNEW (struct watchpoint);
10682   b = &w->base;
10683   if (use_mask)
10684     init_raw_breakpoint_without_location (b, NULL, bp_type,
10685                                           &masked_watchpoint_breakpoint_ops);
10686   else
10687     init_raw_breakpoint_without_location (b, NULL, bp_type,
10688                                           &watchpoint_breakpoint_ops);
10689   b->thread = thread;
10690   b->disposition = disp_donttouch;
10691   b->pspace = current_program_space;
10692   w->exp = exp;
10693   w->exp_valid_block = exp_valid_block;
10694   w->cond_exp_valid_block = cond_exp_valid_block;
10695   if (just_location)
10696     {
10697       struct type *t = value_type (val);
10698       CORE_ADDR addr = value_as_address (val);
10699       char *name;
10700
10701       t = check_typedef (TYPE_TARGET_TYPE (check_typedef (t)));
10702       name = type_to_string (t);
10703
10704       w->exp_string_reparse = xstrprintf ("* (%s *) %s", name,
10705                                           core_addr_to_string (addr));
10706       xfree (name);
10707
10708       w->exp_string = xstrprintf ("-location %.*s",
10709                                   (int) (exp_end - exp_start), exp_start);
10710
10711       /* The above expression is in C.  */
10712       b->language = language_c;
10713     }
10714   else
10715     w->exp_string = savestring (exp_start, exp_end - exp_start);
10716
10717   if (use_mask)
10718     {
10719       w->hw_wp_mask = mask;
10720     }
10721   else
10722     {
10723       w->val = val;
10724       w->val_valid = 1;
10725     }
10726
10727   if (cond_start)
10728     b->cond_string = savestring (cond_start, cond_end - cond_start);
10729   else
10730     b->cond_string = 0;
10731
10732   if (frame)
10733     {
10734       w->watchpoint_frame = get_frame_id (frame);
10735       w->watchpoint_thread = inferior_ptid;
10736     }
10737   else
10738     {
10739       w->watchpoint_frame = null_frame_id;
10740       w->watchpoint_thread = null_ptid;
10741     }
10742
10743   if (scope_breakpoint != NULL)
10744     {
10745       /* The scope breakpoint is related to the watchpoint.  We will
10746          need to act on them together.  */
10747       b->related_breakpoint = scope_breakpoint;
10748       scope_breakpoint->related_breakpoint = b;
10749     }
10750
10751   if (!just_location)
10752     value_free_to_mark (mark);
10753
10754   TRY_CATCH (e, RETURN_MASK_ALL)
10755     {
10756       /* Finally update the new watchpoint.  This creates the locations
10757          that should be inserted.  */
10758       update_watchpoint (w, 1);
10759     }
10760   if (e.reason < 0)
10761     {
10762       delete_breakpoint (b);
10763       throw_exception (e);
10764     }
10765
10766   install_breakpoint (internal, b, 1);
10767 }
10768
10769 /* Return count of debug registers needed to watch the given expression.
10770    If the watchpoint cannot be handled in hardware return zero.  */
10771
10772 static int
10773 can_use_hardware_watchpoint (struct value *v)
10774 {
10775   int found_memory_cnt = 0;
10776   struct value *head = v;
10777
10778   /* Did the user specifically forbid us to use hardware watchpoints? */
10779   if (!can_use_hw_watchpoints)
10780     return 0;
10781
10782   /* Make sure that the value of the expression depends only upon
10783      memory contents, and values computed from them within GDB.  If we
10784      find any register references or function calls, we can't use a
10785      hardware watchpoint.
10786
10787      The idea here is that evaluating an expression generates a series
10788      of values, one holding the value of every subexpression.  (The
10789      expression a*b+c has five subexpressions: a, b, a*b, c, and
10790      a*b+c.)  GDB's values hold almost enough information to establish
10791      the criteria given above --- they identify memory lvalues,
10792      register lvalues, computed values, etcetera.  So we can evaluate
10793      the expression, and then scan the chain of values that leaves
10794      behind to decide whether we can detect any possible change to the
10795      expression's final value using only hardware watchpoints.
10796
10797      However, I don't think that the values returned by inferior
10798      function calls are special in any way.  So this function may not
10799      notice that an expression involving an inferior function call
10800      can't be watched with hardware watchpoints.  FIXME.  */
10801   for (; v; v = value_next (v))
10802     {
10803       if (VALUE_LVAL (v) == lval_memory)
10804         {
10805           if (v != head && value_lazy (v))
10806             /* A lazy memory lvalue in the chain is one that GDB never
10807                needed to fetch; we either just used its address (e.g.,
10808                `a' in `a.b') or we never needed it at all (e.g., `a'
10809                in `a,b').  This doesn't apply to HEAD; if that is
10810                lazy then it was not readable, but watch it anyway.  */
10811             ;
10812           else
10813             {
10814               /* Ahh, memory we actually used!  Check if we can cover
10815                  it with hardware watchpoints.  */
10816               struct type *vtype = check_typedef (value_type (v));
10817
10818               /* We only watch structs and arrays if user asked for it
10819                  explicitly, never if they just happen to appear in a
10820                  middle of some value chain.  */
10821               if (v == head
10822                   || (TYPE_CODE (vtype) != TYPE_CODE_STRUCT
10823                       && TYPE_CODE (vtype) != TYPE_CODE_ARRAY))
10824                 {
10825                   CORE_ADDR vaddr = value_address (v);
10826                   int len;
10827                   int num_regs;
10828
10829                   len = (target_exact_watchpoints
10830                          && is_scalar_type_recursive (vtype))?
10831                     1 : TYPE_LENGTH (value_type (v));
10832
10833                   num_regs = target_region_ok_for_hw_watchpoint (vaddr, len);
10834                   if (!num_regs)
10835                     return 0;
10836                   else
10837                     found_memory_cnt += num_regs;
10838                 }
10839             }
10840         }
10841       else if (VALUE_LVAL (v) != not_lval
10842                && deprecated_value_modifiable (v) == 0)
10843         return 0;       /* These are values from the history (e.g., $1).  */
10844       else if (VALUE_LVAL (v) == lval_register)
10845         return 0;       /* Cannot watch a register with a HW watchpoint.  */
10846     }
10847
10848   /* The expression itself looks suitable for using a hardware
10849      watchpoint, but give the target machine a chance to reject it.  */
10850   return found_memory_cnt;
10851 }
10852
10853 void
10854 watch_command_wrapper (char *arg, int from_tty, int internal)
10855 {
10856   watch_command_1 (arg, hw_write, from_tty, 0, internal);
10857 }
10858
10859 /* A helper function that looks for an argument at the start of a
10860    string.  The argument must also either be at the end of the string,
10861    or be followed by whitespace.  Returns 1 if it finds the argument,
10862    0 otherwise.  If the argument is found, it updates *STR.  */
10863
10864 static int
10865 check_for_argument (char **str, char *arg, int arg_len)
10866 {
10867   if (strncmp (*str, arg, arg_len) == 0
10868       && ((*str)[arg_len] == '\0' || isspace ((*str)[arg_len])))
10869     {
10870       *str += arg_len;
10871       return 1;
10872     }
10873   return 0;
10874 }
10875
10876 /* A helper function that looks for the "-location" argument and then
10877    calls watch_command_1.  */
10878
10879 static void
10880 watch_maybe_just_location (char *arg, int accessflag, int from_tty)
10881 {
10882   int just_location = 0;
10883
10884   if (arg
10885       && (check_for_argument (&arg, "-location", sizeof ("-location") - 1)
10886           || check_for_argument (&arg, "-l", sizeof ("-l") - 1)))
10887     {
10888       arg = skip_spaces (arg);
10889       just_location = 1;
10890     }
10891
10892   watch_command_1 (arg, accessflag, from_tty, just_location, 0);
10893 }
10894
10895 static void
10896 watch_command (char *arg, int from_tty)
10897 {
10898   watch_maybe_just_location (arg, hw_write, from_tty);
10899 }
10900
10901 void
10902 rwatch_command_wrapper (char *arg, int from_tty, int internal)
10903 {
10904   watch_command_1 (arg, hw_read, from_tty, 0, internal);
10905 }
10906
10907 static void
10908 rwatch_command (char *arg, int from_tty)
10909 {
10910   watch_maybe_just_location (arg, hw_read, from_tty);
10911 }
10912
10913 void
10914 awatch_command_wrapper (char *arg, int from_tty, int internal)
10915 {
10916   watch_command_1 (arg, hw_access, from_tty, 0, internal);
10917 }
10918
10919 static void
10920 awatch_command (char *arg, int from_tty)
10921 {
10922   watch_maybe_just_location (arg, hw_access, from_tty);
10923 }
10924 \f
10925
10926 /* Helper routines for the until_command routine in infcmd.c.  Here
10927    because it uses the mechanisms of breakpoints.  */
10928
10929 struct until_break_command_continuation_args
10930 {
10931   struct breakpoint *breakpoint;
10932   struct breakpoint *breakpoint2;
10933   int thread_num;
10934 };
10935
10936 /* This function is called by fetch_inferior_event via the
10937    cmd_continuation pointer, to complete the until command.  It takes
10938    care of cleaning up the temporary breakpoints set up by the until
10939    command.  */
10940 static void
10941 until_break_command_continuation (void *arg, int err)
10942 {
10943   struct until_break_command_continuation_args *a = arg;
10944
10945   delete_breakpoint (a->breakpoint);
10946   if (a->breakpoint2)
10947     delete_breakpoint (a->breakpoint2);
10948   delete_longjmp_breakpoint (a->thread_num);
10949 }
10950
10951 void
10952 until_break_command (char *arg, int from_tty, int anywhere)
10953 {
10954   struct symtabs_and_lines sals;
10955   struct symtab_and_line sal;
10956   struct frame_info *frame;
10957   struct gdbarch *frame_gdbarch;
10958   struct frame_id stack_frame_id;
10959   struct frame_id caller_frame_id;
10960   struct breakpoint *breakpoint;
10961   struct breakpoint *breakpoint2 = NULL;
10962   struct cleanup *old_chain;
10963   int thread;
10964   struct thread_info *tp;
10965
10966   clear_proceed_status ();
10967
10968   /* Set a breakpoint where the user wants it and at return from
10969      this function.  */
10970
10971   if (last_displayed_sal_is_valid ())
10972     sals = decode_line_1 (&arg, DECODE_LINE_FUNFIRSTLINE,
10973                           get_last_displayed_symtab (),
10974                           get_last_displayed_line ());
10975   else
10976     sals = decode_line_1 (&arg, DECODE_LINE_FUNFIRSTLINE,
10977                           (struct symtab *) NULL, 0);
10978
10979   if (sals.nelts != 1)
10980     error (_("Couldn't get information on specified line."));
10981
10982   sal = sals.sals[0];
10983   xfree (sals.sals);    /* malloc'd, so freed.  */
10984
10985   if (*arg)
10986     error (_("Junk at end of arguments."));
10987
10988   resolve_sal_pc (&sal);
10989
10990   tp = inferior_thread ();
10991   thread = tp->num;
10992
10993   old_chain = make_cleanup (null_cleanup, NULL);
10994
10995   /* Note linespec handling above invalidates the frame chain.
10996      Installing a breakpoint also invalidates the frame chain (as it
10997      may need to switch threads), so do any frame handling before
10998      that.  */
10999
11000   frame = get_selected_frame (NULL);
11001   frame_gdbarch = get_frame_arch (frame);
11002   stack_frame_id = get_stack_frame_id (frame);
11003   caller_frame_id = frame_unwind_caller_id (frame);
11004
11005   /* Keep within the current frame, or in frames called by the current
11006      one.  */
11007
11008   if (frame_id_p (caller_frame_id))
11009     {
11010       struct symtab_and_line sal2;
11011
11012       sal2 = find_pc_line (frame_unwind_caller_pc (frame), 0);
11013       sal2.pc = frame_unwind_caller_pc (frame);
11014       breakpoint2 = set_momentary_breakpoint (frame_unwind_caller_arch (frame),
11015                                               sal2,
11016                                               caller_frame_id,
11017                                               bp_until);
11018       make_cleanup_delete_breakpoint (breakpoint2);
11019
11020       set_longjmp_breakpoint (tp, caller_frame_id);
11021       make_cleanup (delete_longjmp_breakpoint_cleanup, &thread);
11022     }
11023
11024   /* set_momentary_breakpoint could invalidate FRAME.  */
11025   frame = NULL;
11026
11027   if (anywhere)
11028     /* If the user told us to continue until a specified location,
11029        we don't specify a frame at which we need to stop.  */
11030     breakpoint = set_momentary_breakpoint (frame_gdbarch, sal,
11031                                            null_frame_id, bp_until);
11032   else
11033     /* Otherwise, specify the selected frame, because we want to stop
11034        only at the very same frame.  */
11035     breakpoint = set_momentary_breakpoint (frame_gdbarch, sal,
11036                                            stack_frame_id, bp_until);
11037   make_cleanup_delete_breakpoint (breakpoint);
11038
11039   proceed (-1, GDB_SIGNAL_DEFAULT, 0);
11040
11041   /* If we are running asynchronously, and proceed call above has
11042      actually managed to start the target, arrange for breakpoints to
11043      be deleted when the target stops.  Otherwise, we're already
11044      stopped and delete breakpoints via cleanup chain.  */
11045
11046   if (target_can_async_p () && is_running (inferior_ptid))
11047     {
11048       struct until_break_command_continuation_args *args;
11049       args = xmalloc (sizeof (*args));
11050
11051       args->breakpoint = breakpoint;
11052       args->breakpoint2 = breakpoint2;
11053       args->thread_num = thread;
11054
11055       discard_cleanups (old_chain);
11056       add_continuation (inferior_thread (),
11057                         until_break_command_continuation, args,
11058                         xfree);
11059     }
11060   else
11061     do_cleanups (old_chain);
11062 }
11063
11064 /* This function attempts to parse an optional "if <cond>" clause
11065    from the arg string.  If one is not found, it returns NULL.
11066
11067    Else, it returns a pointer to the condition string.  (It does not
11068    attempt to evaluate the string against a particular block.)  And,
11069    it updates arg to point to the first character following the parsed
11070    if clause in the arg string.  */
11071
11072 static char *
11073 ep_parse_optional_if_clause (char **arg)
11074 {
11075   char *cond_string;
11076
11077   if (((*arg)[0] != 'i') || ((*arg)[1] != 'f') || !isspace ((*arg)[2]))
11078     return NULL;
11079
11080   /* Skip the "if" keyword.  */
11081   (*arg) += 2;
11082
11083   /* Skip any extra leading whitespace, and record the start of the
11084      condition string.  */
11085   *arg = skip_spaces (*arg);
11086   cond_string = *arg;
11087
11088   /* Assume that the condition occupies the remainder of the arg
11089      string.  */
11090   (*arg) += strlen (cond_string);
11091
11092   return cond_string;
11093 }
11094
11095 /* Commands to deal with catching events, such as signals, exceptions,
11096    process start/exit, etc.  */
11097
11098 typedef enum
11099 {
11100   catch_fork_temporary, catch_vfork_temporary,
11101   catch_fork_permanent, catch_vfork_permanent
11102 }
11103 catch_fork_kind;
11104
11105 static void
11106 catch_fork_command_1 (char *arg, int from_tty, 
11107                       struct cmd_list_element *command)
11108 {
11109   struct gdbarch *gdbarch = get_current_arch ();
11110   char *cond_string = NULL;
11111   catch_fork_kind fork_kind;
11112   int tempflag;
11113
11114   fork_kind = (catch_fork_kind) (uintptr_t) get_cmd_context (command);
11115   tempflag = (fork_kind == catch_fork_temporary
11116               || fork_kind == catch_vfork_temporary);
11117
11118   if (!arg)
11119     arg = "";
11120   arg = skip_spaces (arg);
11121
11122   /* The allowed syntax is:
11123      catch [v]fork
11124      catch [v]fork if <cond>
11125
11126      First, check if there's an if clause.  */
11127   cond_string = ep_parse_optional_if_clause (&arg);
11128
11129   if ((*arg != '\0') && !isspace (*arg))
11130     error (_("Junk at end of arguments."));
11131
11132   /* If this target supports it, create a fork or vfork catchpoint
11133      and enable reporting of such events.  */
11134   switch (fork_kind)
11135     {
11136     case catch_fork_temporary:
11137     case catch_fork_permanent:
11138       create_fork_vfork_event_catchpoint (gdbarch, tempflag, cond_string,
11139                                           &catch_fork_breakpoint_ops);
11140       break;
11141     case catch_vfork_temporary:
11142     case catch_vfork_permanent:
11143       create_fork_vfork_event_catchpoint (gdbarch, tempflag, cond_string,
11144                                           &catch_vfork_breakpoint_ops);
11145       break;
11146     default:
11147       error (_("unsupported or unknown fork kind; cannot catch it"));
11148       break;
11149     }
11150 }
11151
11152 static void
11153 catch_exec_command_1 (char *arg, int from_tty, 
11154                       struct cmd_list_element *command)
11155 {
11156   struct exec_catchpoint *c;
11157   struct gdbarch *gdbarch = get_current_arch ();
11158   int tempflag;
11159   char *cond_string = NULL;
11160
11161   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
11162
11163   if (!arg)
11164     arg = "";
11165   arg = skip_spaces (arg);
11166
11167   /* The allowed syntax is:
11168      catch exec
11169      catch exec if <cond>
11170
11171      First, check if there's an if clause.  */
11172   cond_string = ep_parse_optional_if_clause (&arg);
11173
11174   if ((*arg != '\0') && !isspace (*arg))
11175     error (_("Junk at end of arguments."));
11176
11177   c = XNEW (struct exec_catchpoint);
11178   init_catchpoint (&c->base, gdbarch, tempflag, cond_string,
11179                    &catch_exec_breakpoint_ops);
11180   c->exec_pathname = NULL;
11181
11182   install_breakpoint (0, &c->base, 1);
11183 }
11184
11185 static enum print_stop_action
11186 print_it_exception_catchpoint (bpstat bs)
11187 {
11188   struct ui_out *uiout = current_uiout;
11189   struct breakpoint *b = bs->breakpoint_at;
11190   int bp_temp, bp_throw;
11191
11192   annotate_catchpoint (b->number);
11193
11194   bp_throw = strstr (b->addr_string, "throw") != NULL;
11195   if (b->loc->address != b->loc->requested_address)
11196     breakpoint_adjustment_warning (b->loc->requested_address,
11197                                    b->loc->address,
11198                                    b->number, 1);
11199   bp_temp = b->disposition == disp_del;
11200   ui_out_text (uiout, 
11201                bp_temp ? "Temporary catchpoint "
11202                        : "Catchpoint ");
11203   if (!ui_out_is_mi_like_p (uiout))
11204     ui_out_field_int (uiout, "bkptno", b->number);
11205   ui_out_text (uiout,
11206                bp_throw ? " (exception thrown), "
11207                         : " (exception caught), ");
11208   if (ui_out_is_mi_like_p (uiout))
11209     {
11210       ui_out_field_string (uiout, "reason", 
11211                            async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
11212       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
11213       ui_out_field_int (uiout, "bkptno", b->number);
11214     }
11215   return PRINT_SRC_AND_LOC;
11216 }
11217
11218 static void
11219 print_one_exception_catchpoint (struct breakpoint *b, 
11220                                 struct bp_location **last_loc)
11221 {
11222   struct value_print_options opts;
11223   struct ui_out *uiout = current_uiout;
11224
11225   get_user_print_options (&opts);
11226   if (opts.addressprint)
11227     {
11228       annotate_field (4);
11229       if (b->loc == NULL || b->loc->shlib_disabled)
11230         ui_out_field_string (uiout, "addr", "<PENDING>");
11231       else
11232         ui_out_field_core_addr (uiout, "addr",
11233                                 b->loc->gdbarch, b->loc->address);
11234     }
11235   annotate_field (5);
11236   if (b->loc)
11237     *last_loc = b->loc;
11238   if (strstr (b->addr_string, "throw") != NULL)
11239     ui_out_field_string (uiout, "what", "exception throw");
11240   else
11241     ui_out_field_string (uiout, "what", "exception catch");
11242 }
11243
11244 static void
11245 print_mention_exception_catchpoint (struct breakpoint *b)
11246 {
11247   struct ui_out *uiout = current_uiout;
11248   int bp_temp;
11249   int bp_throw;
11250
11251   bp_temp = b->disposition == disp_del;
11252   bp_throw = strstr (b->addr_string, "throw") != NULL;
11253   ui_out_text (uiout, bp_temp ? _("Temporary catchpoint ")
11254                               : _("Catchpoint "));
11255   ui_out_field_int (uiout, "bkptno", b->number);
11256   ui_out_text (uiout, bp_throw ? _(" (throw)")
11257                                : _(" (catch)"));
11258 }
11259
11260 /* Implement the "print_recreate" breakpoint_ops method for throw and
11261    catch catchpoints.  */
11262
11263 static void
11264 print_recreate_exception_catchpoint (struct breakpoint *b, 
11265                                      struct ui_file *fp)
11266 {
11267   int bp_temp;
11268   int bp_throw;
11269
11270   bp_temp = b->disposition == disp_del;
11271   bp_throw = strstr (b->addr_string, "throw") != NULL;
11272   fprintf_unfiltered (fp, bp_temp ? "tcatch " : "catch ");
11273   fprintf_unfiltered (fp, bp_throw ? "throw" : "catch");
11274   print_recreate_thread (b, fp);
11275 }
11276
11277 static struct breakpoint_ops gnu_v3_exception_catchpoint_ops;
11278
11279 static int
11280 handle_gnu_v3_exceptions (int tempflag, char *cond_string,
11281                           enum exception_event_kind ex_event, int from_tty)
11282 {
11283   char *trigger_func_name;
11284  
11285   if (ex_event == EX_EVENT_CATCH)
11286     trigger_func_name = "__cxa_begin_catch";
11287   else
11288     trigger_func_name = "__cxa_throw";
11289
11290   create_breakpoint (get_current_arch (),
11291                      trigger_func_name, cond_string, -1, NULL,
11292                      0 /* condition and thread are valid.  */,
11293                      tempflag, bp_breakpoint,
11294                      0,
11295                      AUTO_BOOLEAN_TRUE /* pending */,
11296                      &gnu_v3_exception_catchpoint_ops, from_tty,
11297                      1 /* enabled */,
11298                      0 /* internal */,
11299                      0);
11300
11301   return 1;
11302 }
11303
11304 /* Deal with "catch catch" and "catch throw" commands.  */
11305
11306 static void
11307 catch_exception_command_1 (enum exception_event_kind ex_event, char *arg,
11308                            int tempflag, int from_tty)
11309 {
11310   char *cond_string = NULL;
11311
11312   if (!arg)
11313     arg = "";
11314   arg = skip_spaces (arg);
11315
11316   cond_string = ep_parse_optional_if_clause (&arg);
11317
11318   if ((*arg != '\0') && !isspace (*arg))
11319     error (_("Junk at end of arguments."));
11320
11321   if (ex_event != EX_EVENT_THROW
11322       && ex_event != EX_EVENT_CATCH)
11323     error (_("Unsupported or unknown exception event; cannot catch it"));
11324
11325   if (handle_gnu_v3_exceptions (tempflag, cond_string, ex_event, from_tty))
11326     return;
11327
11328   warning (_("Unsupported with this platform/compiler combination."));
11329 }
11330
11331 /* Implementation of "catch catch" command.  */
11332
11333 static void
11334 catch_catch_command (char *arg, int from_tty, struct cmd_list_element *command)
11335 {
11336   int tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
11337
11338   catch_exception_command_1 (EX_EVENT_CATCH, arg, tempflag, from_tty);
11339 }
11340
11341 /* Implementation of "catch throw" command.  */
11342
11343 static void
11344 catch_throw_command (char *arg, int from_tty, struct cmd_list_element *command)
11345 {
11346   int tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
11347
11348   catch_exception_command_1 (EX_EVENT_THROW, arg, tempflag, from_tty);
11349 }
11350
11351 void
11352 init_ada_exception_breakpoint (struct breakpoint *b,
11353                                struct gdbarch *gdbarch,
11354                                struct symtab_and_line sal,
11355                                char *addr_string,
11356                                const struct breakpoint_ops *ops,
11357                                int tempflag,
11358                                int from_tty)
11359 {
11360   if (from_tty)
11361     {
11362       struct gdbarch *loc_gdbarch = get_sal_arch (sal);
11363       if (!loc_gdbarch)
11364         loc_gdbarch = gdbarch;
11365
11366       describe_other_breakpoints (loc_gdbarch,
11367                                   sal.pspace, sal.pc, sal.section, -1);
11368       /* FIXME: brobecker/2006-12-28: Actually, re-implement a special
11369          version for exception catchpoints, because two catchpoints
11370          used for different exception names will use the same address.
11371          In this case, a "breakpoint ... also set at..." warning is
11372          unproductive.  Besides, the warning phrasing is also a bit
11373          inappropriate, we should use the word catchpoint, and tell
11374          the user what type of catchpoint it is.  The above is good
11375          enough for now, though.  */
11376     }
11377
11378   init_raw_breakpoint (b, gdbarch, sal, bp_breakpoint, ops);
11379
11380   b->enable_state = bp_enabled;
11381   b->disposition = tempflag ? disp_del : disp_donttouch;
11382   b->addr_string = addr_string;
11383   b->language = language_ada;
11384 }
11385
11386 /* Splits the argument using space as delimiter.  Returns an xmalloc'd
11387    filter list, or NULL if no filtering is required.  */
11388 static VEC(int) *
11389 catch_syscall_split_args (char *arg)
11390 {
11391   VEC(int) *result = NULL;
11392   struct cleanup *cleanup = make_cleanup (VEC_cleanup (int), &result);
11393
11394   while (*arg != '\0')
11395     {
11396       int i, syscall_number;
11397       char *endptr;
11398       char cur_name[128];
11399       struct syscall s;
11400
11401       /* Skip whitespace.  */
11402       while (isspace (*arg))
11403         arg++;
11404
11405       for (i = 0; i < 127 && arg[i] && !isspace (arg[i]); ++i)
11406         cur_name[i] = arg[i];
11407       cur_name[i] = '\0';
11408       arg += i;
11409
11410       /* Check if the user provided a syscall name or a number.  */
11411       syscall_number = (int) strtol (cur_name, &endptr, 0);
11412       if (*endptr == '\0')
11413         get_syscall_by_number (syscall_number, &s);
11414       else
11415         {
11416           /* We have a name.  Let's check if it's valid and convert it
11417              to a number.  */
11418           get_syscall_by_name (cur_name, &s);
11419
11420           if (s.number == UNKNOWN_SYSCALL)
11421             /* Here we have to issue an error instead of a warning,
11422                because GDB cannot do anything useful if there's no
11423                syscall number to be caught.  */
11424             error (_("Unknown syscall name '%s'."), cur_name);
11425         }
11426
11427       /* Ok, it's valid.  */
11428       VEC_safe_push (int, result, s.number);
11429     }
11430
11431   discard_cleanups (cleanup);
11432   return result;
11433 }
11434
11435 /* Implement the "catch syscall" command.  */
11436
11437 static void
11438 catch_syscall_command_1 (char *arg, int from_tty, 
11439                          struct cmd_list_element *command)
11440 {
11441   int tempflag;
11442   VEC(int) *filter;
11443   struct syscall s;
11444   struct gdbarch *gdbarch = get_current_arch ();
11445
11446   /* Checking if the feature if supported.  */
11447   if (gdbarch_get_syscall_number_p (gdbarch) == 0)
11448     error (_("The feature 'catch syscall' is not supported on \
11449 this architecture yet."));
11450
11451   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
11452
11453   arg = skip_spaces (arg);
11454
11455   /* We need to do this first "dummy" translation in order
11456      to get the syscall XML file loaded or, most important,
11457      to display a warning to the user if there's no XML file
11458      for his/her architecture.  */
11459   get_syscall_by_number (0, &s);
11460
11461   /* The allowed syntax is:
11462      catch syscall
11463      catch syscall <name | number> [<name | number> ... <name | number>]
11464
11465      Let's check if there's a syscall name.  */
11466
11467   if (arg != NULL)
11468     filter = catch_syscall_split_args (arg);
11469   else
11470     filter = NULL;
11471
11472   create_syscall_event_catchpoint (tempflag, filter,
11473                                    &catch_syscall_breakpoint_ops);
11474 }
11475
11476 static void
11477 catch_command (char *arg, int from_tty)
11478 {
11479   error (_("Catch requires an event name."));
11480 }
11481 \f
11482
11483 static void
11484 tcatch_command (char *arg, int from_tty)
11485 {
11486   error (_("Catch requires an event name."));
11487 }
11488
11489 /* A qsort comparison function that sorts breakpoints in order.  */
11490
11491 static int
11492 compare_breakpoints (const void *a, const void *b)
11493 {
11494   const breakpoint_p *ba = a;
11495   uintptr_t ua = (uintptr_t) *ba;
11496   const breakpoint_p *bb = b;
11497   uintptr_t ub = (uintptr_t) *bb;
11498
11499   if ((*ba)->number < (*bb)->number)
11500     return -1;
11501   else if ((*ba)->number > (*bb)->number)
11502     return 1;
11503
11504   /* Now sort by address, in case we see, e..g, two breakpoints with
11505      the number 0.  */
11506   if (ua < ub)
11507     return -1;
11508   return ub > ub ? 1 : 0;
11509 }
11510
11511 /* Delete breakpoints by address or line.  */
11512
11513 static void
11514 clear_command (char *arg, int from_tty)
11515 {
11516   struct breakpoint *b, *prev;
11517   VEC(breakpoint_p) *found = 0;
11518   int ix;
11519   int default_match;
11520   struct symtabs_and_lines sals;
11521   struct symtab_and_line sal;
11522   int i;
11523   struct cleanup *cleanups = make_cleanup (null_cleanup, NULL);
11524
11525   if (arg)
11526     {
11527       sals = decode_line_with_current_source (arg,
11528                                               (DECODE_LINE_FUNFIRSTLINE
11529                                                | DECODE_LINE_LIST_MODE));
11530       default_match = 0;
11531     }
11532   else
11533     {
11534       sals.sals = (struct symtab_and_line *)
11535         xmalloc (sizeof (struct symtab_and_line));
11536       make_cleanup (xfree, sals.sals);
11537       init_sal (&sal);          /* Initialize to zeroes.  */
11538
11539       /* Set sal's line, symtab, pc, and pspace to the values
11540          corresponding to the last call to print_frame_info.  If the
11541          codepoint is not valid, this will set all the fields to 0.  */
11542       get_last_displayed_sal (&sal);
11543       if (sal.symtab == 0)
11544         error (_("No source file specified."));
11545
11546       sals.sals[0] = sal;
11547       sals.nelts = 1;
11548
11549       default_match = 1;
11550     }
11551
11552   /* We don't call resolve_sal_pc here.  That's not as bad as it
11553      seems, because all existing breakpoints typically have both
11554      file/line and pc set.  So, if clear is given file/line, we can
11555      match this to existing breakpoint without obtaining pc at all.
11556
11557      We only support clearing given the address explicitly 
11558      present in breakpoint table.  Say, we've set breakpoint 
11559      at file:line.  There were several PC values for that file:line,
11560      due to optimization, all in one block.
11561
11562      We've picked one PC value.  If "clear" is issued with another
11563      PC corresponding to the same file:line, the breakpoint won't
11564      be cleared.  We probably can still clear the breakpoint, but 
11565      since the other PC value is never presented to user, user
11566      can only find it by guessing, and it does not seem important
11567      to support that.  */
11568
11569   /* For each line spec given, delete bps which correspond to it.  Do
11570      it in two passes, solely to preserve the current behavior that
11571      from_tty is forced true if we delete more than one
11572      breakpoint.  */
11573
11574   found = NULL;
11575   make_cleanup (VEC_cleanup (breakpoint_p), &found);
11576   for (i = 0; i < sals.nelts; i++)
11577     {
11578       int is_abs, sal_name_len;
11579
11580       /* If exact pc given, clear bpts at that pc.
11581          If line given (pc == 0), clear all bpts on specified line.
11582          If defaulting, clear all bpts on default line
11583          or at default pc.
11584
11585          defaulting    sal.pc != 0    tests to do
11586
11587          0              1             pc
11588          1              1             pc _and_ line
11589          0              0             line
11590          1              0             <can't happen> */
11591
11592       sal = sals.sals[i];
11593       is_abs = sal.symtab == NULL ? 1 : IS_ABSOLUTE_PATH (sal.symtab->filename);
11594       sal_name_len = is_abs ? 0 : strlen (sal.symtab->filename);
11595
11596       /* Find all matching breakpoints and add them to 'found'.  */
11597       ALL_BREAKPOINTS (b)
11598         {
11599           int match = 0;
11600           /* Are we going to delete b?  */
11601           if (b->type != bp_none && !is_watchpoint (b))
11602             {
11603               struct bp_location *loc = b->loc;
11604               for (; loc; loc = loc->next)
11605                 {
11606                   /* If the user specified file:line, don't allow a PC
11607                      match.  This matches historical gdb behavior.  */
11608                   int pc_match = (!sal.explicit_line
11609                                   && sal.pc
11610                                   && (loc->pspace == sal.pspace)
11611                                   && (loc->address == sal.pc)
11612                                   && (!section_is_overlay (loc->section)
11613                                       || loc->section == sal.section));
11614                   int line_match = 0;
11615
11616                   if ((default_match || sal.explicit_line)
11617                       && loc->source_file != NULL
11618                       && sal.symtab != NULL
11619                       && sal.pspace == loc->pspace
11620                       && loc->line_number == sal.line)
11621                     {
11622                       if (filename_cmp (loc->source_file,
11623                                         sal.symtab->filename) == 0)
11624                         line_match = 1;
11625                       else if (!IS_ABSOLUTE_PATH (sal.symtab->filename)
11626                                && compare_filenames_for_search (loc->source_file,
11627                                                                 sal.symtab->filename,
11628                                                                 sal_name_len))
11629                         line_match = 1;
11630                     }
11631
11632                   if (pc_match || line_match)
11633                     {
11634                       match = 1;
11635                       break;
11636                     }
11637                 }
11638             }
11639
11640           if (match)
11641             VEC_safe_push(breakpoint_p, found, b);
11642         }
11643     }
11644
11645   /* Now go thru the 'found' chain and delete them.  */
11646   if (VEC_empty(breakpoint_p, found))
11647     {
11648       if (arg)
11649         error (_("No breakpoint at %s."), arg);
11650       else
11651         error (_("No breakpoint at this line."));
11652     }
11653
11654   /* Remove duplicates from the vec.  */
11655   qsort (VEC_address (breakpoint_p, found),
11656          VEC_length (breakpoint_p, found),
11657          sizeof (breakpoint_p),
11658          compare_breakpoints);
11659   prev = VEC_index (breakpoint_p, found, 0);
11660   for (ix = 1; VEC_iterate (breakpoint_p, found, ix, b); ++ix)
11661     {
11662       if (b == prev)
11663         {
11664           VEC_ordered_remove (breakpoint_p, found, ix);
11665           --ix;
11666         }
11667     }
11668
11669   if (VEC_length(breakpoint_p, found) > 1)
11670     from_tty = 1;       /* Always report if deleted more than one.  */
11671   if (from_tty)
11672     {
11673       if (VEC_length(breakpoint_p, found) == 1)
11674         printf_unfiltered (_("Deleted breakpoint "));
11675       else
11676         printf_unfiltered (_("Deleted breakpoints "));
11677     }
11678   breakpoints_changed ();
11679
11680   for (ix = 0; VEC_iterate(breakpoint_p, found, ix, b); ix++)
11681     {
11682       if (from_tty)
11683         printf_unfiltered ("%d ", b->number);
11684       delete_breakpoint (b);
11685     }
11686   if (from_tty)
11687     putchar_unfiltered ('\n');
11688
11689   do_cleanups (cleanups);
11690 }
11691 \f
11692 /* Delete breakpoint in BS if they are `delete' breakpoints and
11693    all breakpoints that are marked for deletion, whether hit or not.
11694    This is called after any breakpoint is hit, or after errors.  */
11695
11696 void
11697 breakpoint_auto_delete (bpstat bs)
11698 {
11699   struct breakpoint *b, *b_tmp;
11700
11701   for (; bs; bs = bs->next)
11702     if (bs->breakpoint_at
11703         && bs->breakpoint_at->disposition == disp_del
11704         && bs->stop)
11705       delete_breakpoint (bs->breakpoint_at);
11706
11707   ALL_BREAKPOINTS_SAFE (b, b_tmp)
11708   {
11709     if (b->disposition == disp_del_at_next_stop)
11710       delete_breakpoint (b);
11711   }
11712 }
11713
11714 /* A comparison function for bp_location AP and BP being interfaced to
11715    qsort.  Sort elements primarily by their ADDRESS (no matter what
11716    does breakpoint_address_is_meaningful say for its OWNER),
11717    secondarily by ordering first bp_permanent OWNERed elements and
11718    terciarily just ensuring the array is sorted stable way despite
11719    qsort being an unstable algorithm.  */
11720
11721 static int
11722 bp_location_compare (const void *ap, const void *bp)
11723 {
11724   struct bp_location *a = *(void **) ap;
11725   struct bp_location *b = *(void **) bp;
11726   /* A and B come from existing breakpoints having non-NULL OWNER.  */
11727   int a_perm = a->owner->enable_state == bp_permanent;
11728   int b_perm = b->owner->enable_state == bp_permanent;
11729
11730   if (a->address != b->address)
11731     return (a->address > b->address) - (a->address < b->address);
11732
11733   /* Sort locations at the same address by their pspace number, keeping
11734      locations of the same inferior (in a multi-inferior environment)
11735      grouped.  */
11736
11737   if (a->pspace->num != b->pspace->num)
11738     return ((a->pspace->num > b->pspace->num)
11739             - (a->pspace->num < b->pspace->num));
11740
11741   /* Sort permanent breakpoints first.  */
11742   if (a_perm != b_perm)
11743     return (a_perm < b_perm) - (a_perm > b_perm);
11744
11745   /* Make the internal GDB representation stable across GDB runs
11746      where A and B memory inside GDB can differ.  Breakpoint locations of
11747      the same type at the same address can be sorted in arbitrary order.  */
11748
11749   if (a->owner->number != b->owner->number)
11750     return ((a->owner->number > b->owner->number)
11751             - (a->owner->number < b->owner->number));
11752
11753   return (a > b) - (a < b);
11754 }
11755
11756 /* Set bp_location_placed_address_before_address_max and
11757    bp_location_shadow_len_after_address_max according to the current
11758    content of the bp_location array.  */
11759
11760 static void
11761 bp_location_target_extensions_update (void)
11762 {
11763   struct bp_location *bl, **blp_tmp;
11764
11765   bp_location_placed_address_before_address_max = 0;
11766   bp_location_shadow_len_after_address_max = 0;
11767
11768   ALL_BP_LOCATIONS (bl, blp_tmp)
11769     {
11770       CORE_ADDR start, end, addr;
11771
11772       if (!bp_location_has_shadow (bl))
11773         continue;
11774
11775       start = bl->target_info.placed_address;
11776       end = start + bl->target_info.shadow_len;
11777
11778       gdb_assert (bl->address >= start);
11779       addr = bl->address - start;
11780       if (addr > bp_location_placed_address_before_address_max)
11781         bp_location_placed_address_before_address_max = addr;
11782
11783       /* Zero SHADOW_LEN would not pass bp_location_has_shadow.  */
11784
11785       gdb_assert (bl->address < end);
11786       addr = end - bl->address;
11787       if (addr > bp_location_shadow_len_after_address_max)
11788         bp_location_shadow_len_after_address_max = addr;
11789     }
11790 }
11791
11792 /* Download tracepoint locations if they haven't been.  */
11793
11794 static void
11795 download_tracepoint_locations (void)
11796 {
11797   struct bp_location *bl, **blp_tmp;
11798   struct cleanup *old_chain;
11799
11800   if (!target_can_download_tracepoint ())
11801     return;
11802
11803   old_chain = save_current_space_and_thread ();
11804
11805   ALL_BP_LOCATIONS (bl, blp_tmp)
11806     {
11807       struct tracepoint *t;
11808
11809       if (!is_tracepoint (bl->owner))
11810         continue;
11811
11812       if ((bl->owner->type == bp_fast_tracepoint
11813            ? !may_insert_fast_tracepoints
11814            : !may_insert_tracepoints))
11815         continue;
11816
11817       /* In tracepoint, locations are _never_ duplicated, so
11818          should_be_inserted is equivalent to
11819          unduplicated_should_be_inserted.  */
11820       if (!should_be_inserted (bl) || bl->inserted)
11821         continue;
11822
11823       switch_to_program_space_and_thread (bl->pspace);
11824
11825       target_download_tracepoint (bl);
11826
11827       bl->inserted = 1;
11828       t = (struct tracepoint *) bl->owner;
11829       t->number_on_target = bl->owner->number;
11830     }
11831
11832   do_cleanups (old_chain);
11833 }
11834
11835 /* Swap the insertion/duplication state between two locations.  */
11836
11837 static void
11838 swap_insertion (struct bp_location *left, struct bp_location *right)
11839 {
11840   const int left_inserted = left->inserted;
11841   const int left_duplicate = left->duplicate;
11842   const int left_needs_update = left->needs_update;
11843   const struct bp_target_info left_target_info = left->target_info;
11844
11845   /* Locations of tracepoints can never be duplicated.  */
11846   if (is_tracepoint (left->owner))
11847     gdb_assert (!left->duplicate);
11848   if (is_tracepoint (right->owner))
11849     gdb_assert (!right->duplicate);
11850
11851   left->inserted = right->inserted;
11852   left->duplicate = right->duplicate;
11853   left->needs_update = right->needs_update;
11854   left->target_info = right->target_info;
11855   right->inserted = left_inserted;
11856   right->duplicate = left_duplicate;
11857   right->needs_update = left_needs_update;
11858   right->target_info = left_target_info;
11859 }
11860
11861 /* Force the re-insertion of the locations at ADDRESS.  This is called
11862    once a new/deleted/modified duplicate location is found and we are evaluating
11863    conditions on the target's side.  Such conditions need to be updated on
11864    the target.  */
11865
11866 static void
11867 force_breakpoint_reinsertion (struct bp_location *bl)
11868 {
11869   struct bp_location **locp = NULL, **loc2p;
11870   struct bp_location *loc;
11871   CORE_ADDR address = 0;
11872   int pspace_num;
11873
11874   address = bl->address;
11875   pspace_num = bl->pspace->num;
11876
11877   /* This is only meaningful if the target is
11878      evaluating conditions and if the user has
11879      opted for condition evaluation on the target's
11880      side.  */
11881   if (gdb_evaluates_breakpoint_condition_p ()
11882       || !target_supports_evaluation_of_breakpoint_conditions ())
11883     return;
11884
11885   /* Flag all breakpoint locations with this address and
11886      the same program space as the location
11887      as "its condition has changed".  We need to
11888      update the conditions on the target's side.  */
11889   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, address)
11890     {
11891       loc = *loc2p;
11892
11893       if (!is_breakpoint (loc->owner)
11894           || pspace_num != loc->pspace->num)
11895         continue;
11896
11897       /* Flag the location appropriately.  We use a different state to
11898          let everyone know that we already updated the set of locations
11899          with addr bl->address and program space bl->pspace.  This is so
11900          we don't have to keep calling these functions just to mark locations
11901          that have already been marked.  */
11902       loc->condition_changed = condition_updated;
11903
11904       /* Free the agent expression bytecode as well.  We will compute
11905          it later on.  */
11906       if (loc->cond_bytecode)
11907         {
11908           free_agent_expr (loc->cond_bytecode);
11909           loc->cond_bytecode = NULL;
11910         }
11911     }
11912 }
11913
11914 /* If SHOULD_INSERT is false, do not insert any breakpoint locations
11915    into the inferior, only remove already-inserted locations that no
11916    longer should be inserted.  Functions that delete a breakpoint or
11917    breakpoints should pass false, so that deleting a breakpoint
11918    doesn't have the side effect of inserting the locations of other
11919    breakpoints that are marked not-inserted, but should_be_inserted
11920    returns true on them.
11921
11922    This behaviour is useful is situations close to tear-down -- e.g.,
11923    after an exec, while the target still has execution, but breakpoint
11924    shadows of the previous executable image should *NOT* be restored
11925    to the new image; or before detaching, where the target still has
11926    execution and wants to delete breakpoints from GDB's lists, and all
11927    breakpoints had already been removed from the inferior.  */
11928
11929 static void
11930 update_global_location_list (int should_insert)
11931 {
11932   struct breakpoint *b;
11933   struct bp_location **locp, *loc;
11934   struct cleanup *cleanups;
11935   /* Last breakpoint location address that was marked for update.  */
11936   CORE_ADDR last_addr = 0;
11937   /* Last breakpoint location program space that was marked for update.  */
11938   int last_pspace_num = -1;
11939
11940   /* Used in the duplicates detection below.  When iterating over all
11941      bp_locations, points to the first bp_location of a given address.
11942      Breakpoints and watchpoints of different types are never
11943      duplicates of each other.  Keep one pointer for each type of
11944      breakpoint/watchpoint, so we only need to loop over all locations
11945      once.  */
11946   struct bp_location *bp_loc_first;  /* breakpoint */
11947   struct bp_location *wp_loc_first;  /* hardware watchpoint */
11948   struct bp_location *awp_loc_first; /* access watchpoint */
11949   struct bp_location *rwp_loc_first; /* read watchpoint */
11950
11951   /* Saved former bp_location array which we compare against the newly
11952      built bp_location from the current state of ALL_BREAKPOINTS.  */
11953   struct bp_location **old_location, **old_locp;
11954   unsigned old_location_count;
11955
11956   old_location = bp_location;
11957   old_location_count = bp_location_count;
11958   bp_location = NULL;
11959   bp_location_count = 0;
11960   cleanups = make_cleanup (xfree, old_location);
11961
11962   ALL_BREAKPOINTS (b)
11963     for (loc = b->loc; loc; loc = loc->next)
11964       bp_location_count++;
11965
11966   bp_location = xmalloc (sizeof (*bp_location) * bp_location_count);
11967   locp = bp_location;
11968   ALL_BREAKPOINTS (b)
11969     for (loc = b->loc; loc; loc = loc->next)
11970       *locp++ = loc;
11971   qsort (bp_location, bp_location_count, sizeof (*bp_location),
11972          bp_location_compare);
11973
11974   bp_location_target_extensions_update ();
11975
11976   /* Identify bp_location instances that are no longer present in the
11977      new list, and therefore should be freed.  Note that it's not
11978      necessary that those locations should be removed from inferior --
11979      if there's another location at the same address (previously
11980      marked as duplicate), we don't need to remove/insert the
11981      location.
11982      
11983      LOCP is kept in sync with OLD_LOCP, each pointing to the current
11984      and former bp_location array state respectively.  */
11985
11986   locp = bp_location;
11987   for (old_locp = old_location; old_locp < old_location + old_location_count;
11988        old_locp++)
11989     {
11990       struct bp_location *old_loc = *old_locp;
11991       struct bp_location **loc2p;
11992
11993       /* Tells if 'old_loc' is found among the new locations.  If
11994          not, we have to free it.  */
11995       int found_object = 0;
11996       /* Tells if the location should remain inserted in the target.  */
11997       int keep_in_target = 0;
11998       int removed = 0;
11999
12000       /* Skip LOCP entries which will definitely never be needed.
12001          Stop either at or being the one matching OLD_LOC.  */
12002       while (locp < bp_location + bp_location_count
12003              && (*locp)->address < old_loc->address)
12004         locp++;
12005
12006       for (loc2p = locp;
12007            (loc2p < bp_location + bp_location_count
12008             && (*loc2p)->address == old_loc->address);
12009            loc2p++)
12010         {
12011           /* Check if this is a new/duplicated location or a duplicated
12012              location that had its condition modified.  If so, we want to send
12013              its condition to the target if evaluation of conditions is taking
12014              place there.  */
12015           if ((*loc2p)->condition_changed == condition_modified
12016               && (last_addr != old_loc->address
12017                   || last_pspace_num != old_loc->pspace->num))
12018             {
12019               force_breakpoint_reinsertion (*loc2p);
12020               last_pspace_num = old_loc->pspace->num;
12021             }
12022
12023           if (*loc2p == old_loc)
12024             found_object = 1;
12025         }
12026
12027       /* We have already handled this address, update it so that we don't
12028          have to go through updates again.  */
12029       last_addr = old_loc->address;
12030
12031       /* Target-side condition evaluation: Handle deleted locations.  */
12032       if (!found_object)
12033         force_breakpoint_reinsertion (old_loc);
12034
12035       /* If this location is no longer present, and inserted, look if
12036          there's maybe a new location at the same address.  If so,
12037          mark that one inserted, and don't remove this one.  This is
12038          needed so that we don't have a time window where a breakpoint
12039          at certain location is not inserted.  */
12040
12041       if (old_loc->inserted)
12042         {
12043           /* If the location is inserted now, we might have to remove
12044              it.  */
12045
12046           if (found_object && should_be_inserted (old_loc))
12047             {
12048               /* The location is still present in the location list,
12049                  and still should be inserted.  Don't do anything.  */
12050               keep_in_target = 1;
12051             }
12052           else
12053             {
12054               /* This location still exists, but it won't be kept in the
12055                  target since it may have been disabled.  We proceed to
12056                  remove its target-side condition.  */
12057
12058               /* The location is either no longer present, or got
12059                  disabled.  See if there's another location at the
12060                  same address, in which case we don't need to remove
12061                  this one from the target.  */
12062
12063               /* OLD_LOC comes from existing struct breakpoint.  */
12064               if (breakpoint_address_is_meaningful (old_loc->owner))
12065                 {
12066                   for (loc2p = locp;
12067                        (loc2p < bp_location + bp_location_count
12068                         && (*loc2p)->address == old_loc->address);
12069                        loc2p++)
12070                     {
12071                       struct bp_location *loc2 = *loc2p;
12072
12073                       if (breakpoint_locations_match (loc2, old_loc))
12074                         {
12075                           /* Read watchpoint locations are switched to
12076                              access watchpoints, if the former are not
12077                              supported, but the latter are.  */
12078                           if (is_hardware_watchpoint (old_loc->owner))
12079                             {
12080                               gdb_assert (is_hardware_watchpoint (loc2->owner));
12081                               loc2->watchpoint_type = old_loc->watchpoint_type;
12082                             }
12083
12084                           /* loc2 is a duplicated location. We need to check
12085                              if it should be inserted in case it will be
12086                              unduplicated.  */
12087                           if (loc2 != old_loc
12088                               && unduplicated_should_be_inserted (loc2))
12089                             {
12090                               swap_insertion (old_loc, loc2);
12091                               keep_in_target = 1;
12092                               break;
12093                             }
12094                         }
12095                     }
12096                 }
12097             }
12098
12099           if (!keep_in_target)
12100             {
12101               if (remove_breakpoint (old_loc, mark_uninserted))
12102                 {
12103                   /* This is just about all we can do.  We could keep
12104                      this location on the global list, and try to
12105                      remove it next time, but there's no particular
12106                      reason why we will succeed next time.
12107                      
12108                      Note that at this point, old_loc->owner is still
12109                      valid, as delete_breakpoint frees the breakpoint
12110                      only after calling us.  */
12111                   printf_filtered (_("warning: Error removing "
12112                                      "breakpoint %d\n"), 
12113                                    old_loc->owner->number);
12114                 }
12115               removed = 1;
12116             }
12117         }
12118
12119       if (!found_object)
12120         {
12121           if (removed && non_stop
12122               && breakpoint_address_is_meaningful (old_loc->owner)
12123               && !is_hardware_watchpoint (old_loc->owner))
12124             {
12125               /* This location was removed from the target.  In
12126                  non-stop mode, a race condition is possible where
12127                  we've removed a breakpoint, but stop events for that
12128                  breakpoint are already queued and will arrive later.
12129                  We apply an heuristic to be able to distinguish such
12130                  SIGTRAPs from other random SIGTRAPs: we keep this
12131                  breakpoint location for a bit, and will retire it
12132                  after we see some number of events.  The theory here
12133                  is that reporting of events should, "on the average",
12134                  be fair, so after a while we'll see events from all
12135                  threads that have anything of interest, and no longer
12136                  need to keep this breakpoint location around.  We
12137                  don't hold locations forever so to reduce chances of
12138                  mistaking a non-breakpoint SIGTRAP for a breakpoint
12139                  SIGTRAP.
12140
12141                  The heuristic failing can be disastrous on
12142                  decr_pc_after_break targets.
12143
12144                  On decr_pc_after_break targets, like e.g., x86-linux,
12145                  if we fail to recognize a late breakpoint SIGTRAP,
12146                  because events_till_retirement has reached 0 too
12147                  soon, we'll fail to do the PC adjustment, and report
12148                  a random SIGTRAP to the user.  When the user resumes
12149                  the inferior, it will most likely immediately crash
12150                  with SIGILL/SIGBUS/SIGSEGV, or worse, get silently
12151                  corrupted, because of being resumed e.g., in the
12152                  middle of a multi-byte instruction, or skipped a
12153                  one-byte instruction.  This was actually seen happen
12154                  on native x86-linux, and should be less rare on
12155                  targets that do not support new thread events, like
12156                  remote, due to the heuristic depending on
12157                  thread_count.
12158
12159                  Mistaking a random SIGTRAP for a breakpoint trap
12160                  causes similar symptoms (PC adjustment applied when
12161                  it shouldn't), but then again, playing with SIGTRAPs
12162                  behind the debugger's back is asking for trouble.
12163
12164                  Since hardware watchpoint traps are always
12165                  distinguishable from other traps, so we don't need to
12166                  apply keep hardware watchpoint moribund locations
12167                  around.  We simply always ignore hardware watchpoint
12168                  traps we can no longer explain.  */
12169
12170               old_loc->events_till_retirement = 3 * (thread_count () + 1);
12171               old_loc->owner = NULL;
12172
12173               VEC_safe_push (bp_location_p, moribund_locations, old_loc);
12174             }
12175           else
12176             {
12177               old_loc->owner = NULL;
12178               decref_bp_location (&old_loc);
12179             }
12180         }
12181     }
12182
12183   /* Rescan breakpoints at the same address and section, marking the
12184      first one as "first" and any others as "duplicates".  This is so
12185      that the bpt instruction is only inserted once.  If we have a
12186      permanent breakpoint at the same place as BPT, make that one the
12187      official one, and the rest as duplicates.  Permanent breakpoints
12188      are sorted first for the same address.
12189
12190      Do the same for hardware watchpoints, but also considering the
12191      watchpoint's type (regular/access/read) and length.  */
12192
12193   bp_loc_first = NULL;
12194   wp_loc_first = NULL;
12195   awp_loc_first = NULL;
12196   rwp_loc_first = NULL;
12197   ALL_BP_LOCATIONS (loc, locp)
12198     {
12199       /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always
12200          non-NULL.  */
12201       struct bp_location **loc_first_p;
12202       b = loc->owner;
12203
12204       if (!should_be_inserted (loc)
12205           || !breakpoint_address_is_meaningful (b)
12206           /* Don't detect duplicate for tracepoint locations because they are
12207            never duplicated.  See the comments in field `duplicate' of
12208            `struct bp_location'.  */
12209           || is_tracepoint (b))
12210         {
12211           /* Clear the condition modification flag.  */
12212           loc->condition_changed = condition_unchanged;
12213           continue;
12214         }
12215
12216       /* Permanent breakpoint should always be inserted.  */
12217       if (b->enable_state == bp_permanent && ! loc->inserted)
12218         internal_error (__FILE__, __LINE__,
12219                         _("allegedly permanent breakpoint is not "
12220                         "actually inserted"));
12221
12222       if (b->type == bp_hardware_watchpoint)
12223         loc_first_p = &wp_loc_first;
12224       else if (b->type == bp_read_watchpoint)
12225         loc_first_p = &rwp_loc_first;
12226       else if (b->type == bp_access_watchpoint)
12227         loc_first_p = &awp_loc_first;
12228       else
12229         loc_first_p = &bp_loc_first;
12230
12231       if (*loc_first_p == NULL
12232           || (overlay_debugging && loc->section != (*loc_first_p)->section)
12233           || !breakpoint_locations_match (loc, *loc_first_p))
12234         {
12235           *loc_first_p = loc;
12236           loc->duplicate = 0;
12237
12238           if (is_breakpoint (loc->owner) && loc->condition_changed)
12239             {
12240               loc->needs_update = 1;
12241               /* Clear the condition modification flag.  */
12242               loc->condition_changed = condition_unchanged;
12243             }
12244           continue;
12245         }
12246
12247
12248       /* This and the above ensure the invariant that the first location
12249          is not duplicated, and is the inserted one.
12250          All following are marked as duplicated, and are not inserted.  */
12251       if (loc->inserted)
12252         swap_insertion (loc, *loc_first_p);
12253       loc->duplicate = 1;
12254
12255       /* Clear the condition modification flag.  */
12256       loc->condition_changed = condition_unchanged;
12257
12258       if ((*loc_first_p)->owner->enable_state == bp_permanent && loc->inserted
12259           && b->enable_state != bp_permanent)
12260         internal_error (__FILE__, __LINE__,
12261                         _("another breakpoint was inserted on top of "
12262                         "a permanent breakpoint"));
12263     }
12264
12265   if (breakpoints_always_inserted_mode ()
12266       && (have_live_inferiors ()
12267           || (gdbarch_has_global_breakpoints (target_gdbarch))))
12268     {
12269       if (should_insert)
12270         insert_breakpoint_locations ();
12271       else
12272         {
12273           /* Though should_insert is false, we may need to update conditions
12274              on the target's side if it is evaluating such conditions.  We
12275              only update conditions for locations that are marked
12276              "needs_update".  */
12277           update_inserted_breakpoint_locations ();
12278         }
12279     }
12280
12281   if (should_insert)
12282     download_tracepoint_locations ();
12283
12284   do_cleanups (cleanups);
12285 }
12286
12287 void
12288 breakpoint_retire_moribund (void)
12289 {
12290   struct bp_location *loc;
12291   int ix;
12292
12293   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
12294     if (--(loc->events_till_retirement) == 0)
12295       {
12296         decref_bp_location (&loc);
12297         VEC_unordered_remove (bp_location_p, moribund_locations, ix);
12298         --ix;
12299       }
12300 }
12301
12302 static void
12303 update_global_location_list_nothrow (int inserting)
12304 {
12305   volatile struct gdb_exception e;
12306
12307   TRY_CATCH (e, RETURN_MASK_ERROR)
12308     update_global_location_list (inserting);
12309 }
12310
12311 /* Clear BKP from a BPS.  */
12312
12313 static void
12314 bpstat_remove_bp_location (bpstat bps, struct breakpoint *bpt)
12315 {
12316   bpstat bs;
12317
12318   for (bs = bps; bs; bs = bs->next)
12319     if (bs->breakpoint_at == bpt)
12320       {
12321         bs->breakpoint_at = NULL;
12322         bs->old_val = NULL;
12323         /* bs->commands will be freed later.  */
12324       }
12325 }
12326
12327 /* Callback for iterate_over_threads.  */
12328 static int
12329 bpstat_remove_breakpoint_callback (struct thread_info *th, void *data)
12330 {
12331   struct breakpoint *bpt = data;
12332
12333   bpstat_remove_bp_location (th->control.stop_bpstat, bpt);
12334   return 0;
12335 }
12336
12337 /* Helper for breakpoint and tracepoint breakpoint_ops->mention
12338    callbacks.  */
12339
12340 static void
12341 say_where (struct breakpoint *b)
12342 {
12343   struct ui_out *uiout = current_uiout;
12344   struct value_print_options opts;
12345
12346   get_user_print_options (&opts);
12347
12348   /* i18n: cagney/2005-02-11: Below needs to be merged into a
12349      single string.  */
12350   if (b->loc == NULL)
12351     {
12352       printf_filtered (_(" (%s) pending."), b->addr_string);
12353     }
12354   else
12355     {
12356       if (opts.addressprint || b->loc->source_file == NULL)
12357         {
12358           printf_filtered (" at ");
12359           fputs_filtered (paddress (b->loc->gdbarch, b->loc->address),
12360                           gdb_stdout);
12361         }
12362       if (b->loc->source_file)
12363         {
12364           /* If there is a single location, we can print the location
12365              more nicely.  */
12366           if (b->loc->next == NULL)
12367             printf_filtered (": file %s, line %d.",
12368                              b->loc->source_file, b->loc->line_number);
12369           else
12370             /* This is not ideal, but each location may have a
12371                different file name, and this at least reflects the
12372                real situation somewhat.  */
12373             printf_filtered (": %s.", b->addr_string);
12374         }
12375
12376       if (b->loc->next)
12377         {
12378           struct bp_location *loc = b->loc;
12379           int n = 0;
12380           for (; loc; loc = loc->next)
12381             ++n;
12382           printf_filtered (" (%d locations)", n);
12383         }
12384     }
12385 }
12386
12387 /* Default bp_location_ops methods.  */
12388
12389 static void
12390 bp_location_dtor (struct bp_location *self)
12391 {
12392   xfree (self->cond);
12393   if (self->cond_bytecode)
12394     free_agent_expr (self->cond_bytecode);
12395   xfree (self->function_name);
12396   xfree (self->source_file);
12397 }
12398
12399 static const struct bp_location_ops bp_location_ops =
12400 {
12401   bp_location_dtor
12402 };
12403
12404 /* Default breakpoint_ops methods all breakpoint_ops ultimately
12405    inherit from.  */
12406
12407 static void
12408 base_breakpoint_dtor (struct breakpoint *self)
12409 {
12410   decref_counted_command_line (&self->commands);
12411   xfree (self->cond_string);
12412   xfree (self->addr_string);
12413   xfree (self->filter);
12414   xfree (self->addr_string_range_end);
12415 }
12416
12417 static struct bp_location *
12418 base_breakpoint_allocate_location (struct breakpoint *self)
12419 {
12420   struct bp_location *loc;
12421
12422   loc = XNEW (struct bp_location);
12423   init_bp_location (loc, &bp_location_ops, self);
12424   return loc;
12425 }
12426
12427 static void
12428 base_breakpoint_re_set (struct breakpoint *b)
12429 {
12430   /* Nothing to re-set. */
12431 }
12432
12433 #define internal_error_pure_virtual_called() \
12434   gdb_assert_not_reached ("pure virtual function called")
12435
12436 static int
12437 base_breakpoint_insert_location (struct bp_location *bl)
12438 {
12439   internal_error_pure_virtual_called ();
12440 }
12441
12442 static int
12443 base_breakpoint_remove_location (struct bp_location *bl)
12444 {
12445   internal_error_pure_virtual_called ();
12446 }
12447
12448 static int
12449 base_breakpoint_breakpoint_hit (const struct bp_location *bl,
12450                                 struct address_space *aspace,
12451                                 CORE_ADDR bp_addr,
12452                                 const struct target_waitstatus *ws)
12453 {
12454   internal_error_pure_virtual_called ();
12455 }
12456
12457 static void
12458 base_breakpoint_check_status (bpstat bs)
12459 {
12460   /* Always stop.   */
12461 }
12462
12463 /* A "works_in_software_mode" breakpoint_ops method that just internal
12464    errors.  */
12465
12466 static int
12467 base_breakpoint_works_in_software_mode (const struct breakpoint *b)
12468 {
12469   internal_error_pure_virtual_called ();
12470 }
12471
12472 /* A "resources_needed" breakpoint_ops method that just internal
12473    errors.  */
12474
12475 static int
12476 base_breakpoint_resources_needed (const struct bp_location *bl)
12477 {
12478   internal_error_pure_virtual_called ();
12479 }
12480
12481 static enum print_stop_action
12482 base_breakpoint_print_it (bpstat bs)
12483 {
12484   internal_error_pure_virtual_called ();
12485 }
12486
12487 static void
12488 base_breakpoint_print_one_detail (const struct breakpoint *self,
12489                                   struct ui_out *uiout)
12490 {
12491   /* nothing */
12492 }
12493
12494 static void
12495 base_breakpoint_print_mention (struct breakpoint *b)
12496 {
12497   internal_error_pure_virtual_called ();
12498 }
12499
12500 static void
12501 base_breakpoint_print_recreate (struct breakpoint *b, struct ui_file *fp)
12502 {
12503   internal_error_pure_virtual_called ();
12504 }
12505
12506 static void
12507 base_breakpoint_create_sals_from_address (char **arg,
12508                                           struct linespec_result *canonical,
12509                                           enum bptype type_wanted,
12510                                           char *addr_start,
12511                                           char **copy_arg)
12512 {
12513   internal_error_pure_virtual_called ();
12514 }
12515
12516 static void
12517 base_breakpoint_create_breakpoints_sal (struct gdbarch *gdbarch,
12518                                         struct linespec_result *c,
12519                                         struct linespec_sals *lsal,
12520                                         char *cond_string,
12521                                         char *extra_string,
12522                                         enum bptype type_wanted,
12523                                         enum bpdisp disposition,
12524                                         int thread,
12525                                         int task, int ignore_count,
12526                                         const struct breakpoint_ops *o,
12527                                         int from_tty, int enabled,
12528                                         int internal, unsigned flags)
12529 {
12530   internal_error_pure_virtual_called ();
12531 }
12532
12533 static void
12534 base_breakpoint_decode_linespec (struct breakpoint *b, char **s,
12535                                  struct symtabs_and_lines *sals)
12536 {
12537   internal_error_pure_virtual_called ();
12538 }
12539
12540 static struct breakpoint_ops base_breakpoint_ops =
12541 {
12542   base_breakpoint_dtor,
12543   base_breakpoint_allocate_location,
12544   base_breakpoint_re_set,
12545   base_breakpoint_insert_location,
12546   base_breakpoint_remove_location,
12547   base_breakpoint_breakpoint_hit,
12548   base_breakpoint_check_status,
12549   base_breakpoint_resources_needed,
12550   base_breakpoint_works_in_software_mode,
12551   base_breakpoint_print_it,
12552   NULL,
12553   base_breakpoint_print_one_detail,
12554   base_breakpoint_print_mention,
12555   base_breakpoint_print_recreate,
12556   base_breakpoint_create_sals_from_address,
12557   base_breakpoint_create_breakpoints_sal,
12558   base_breakpoint_decode_linespec,
12559 };
12560
12561 /* Default breakpoint_ops methods.  */
12562
12563 static void
12564 bkpt_re_set (struct breakpoint *b)
12565 {
12566   /* FIXME: is this still reachable?  */
12567   if (b->addr_string == NULL)
12568     {
12569       /* Anything without a string can't be re-set.  */
12570       delete_breakpoint (b);
12571       return;
12572     }
12573
12574   breakpoint_re_set_default (b);
12575 }
12576
12577 static int
12578 bkpt_insert_location (struct bp_location *bl)
12579 {
12580   if (bl->loc_type == bp_loc_hardware_breakpoint)
12581     return target_insert_hw_breakpoint (bl->gdbarch,
12582                                         &bl->target_info);
12583   else
12584     return target_insert_breakpoint (bl->gdbarch,
12585                                      &bl->target_info);
12586 }
12587
12588 static int
12589 bkpt_remove_location (struct bp_location *bl)
12590 {
12591   if (bl->loc_type == bp_loc_hardware_breakpoint)
12592     return target_remove_hw_breakpoint (bl->gdbarch, &bl->target_info);
12593   else
12594     return target_remove_breakpoint (bl->gdbarch, &bl->target_info);
12595 }
12596
12597 static int
12598 bkpt_breakpoint_hit (const struct bp_location *bl,
12599                      struct address_space *aspace, CORE_ADDR bp_addr,
12600                      const struct target_waitstatus *ws)
12601 {
12602   struct breakpoint *b = bl->owner;
12603
12604   if (ws->kind != TARGET_WAITKIND_STOPPED
12605       || ws->value.sig != GDB_SIGNAL_TRAP)
12606     return 0;
12607
12608   if (!breakpoint_address_match (bl->pspace->aspace, bl->address,
12609                                  aspace, bp_addr))
12610     return 0;
12611
12612   if (overlay_debugging         /* unmapped overlay section */
12613       && section_is_overlay (bl->section)
12614       && !section_is_mapped (bl->section))
12615     return 0;
12616
12617   return 1;
12618 }
12619
12620 static int
12621 bkpt_resources_needed (const struct bp_location *bl)
12622 {
12623   gdb_assert (bl->owner->type == bp_hardware_breakpoint);
12624
12625   return 1;
12626 }
12627
12628 static enum print_stop_action
12629 bkpt_print_it (bpstat bs)
12630 {
12631   struct breakpoint *b;
12632   const struct bp_location *bl;
12633   int bp_temp;
12634   struct ui_out *uiout = current_uiout;
12635
12636   gdb_assert (bs->bp_location_at != NULL);
12637
12638   bl = bs->bp_location_at;
12639   b = bs->breakpoint_at;
12640
12641   bp_temp = b->disposition == disp_del;
12642   if (bl->address != bl->requested_address)
12643     breakpoint_adjustment_warning (bl->requested_address,
12644                                    bl->address,
12645                                    b->number, 1);
12646   annotate_breakpoint (b->number);
12647   if (bp_temp)
12648     ui_out_text (uiout, "\nTemporary breakpoint ");
12649   else
12650     ui_out_text (uiout, "\nBreakpoint ");
12651   if (ui_out_is_mi_like_p (uiout))
12652     {
12653       ui_out_field_string (uiout, "reason",
12654                            async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
12655       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
12656     }
12657   ui_out_field_int (uiout, "bkptno", b->number);
12658   ui_out_text (uiout, ", ");
12659
12660   return PRINT_SRC_AND_LOC;
12661 }
12662
12663 static void
12664 bkpt_print_mention (struct breakpoint *b)
12665 {
12666   if (ui_out_is_mi_like_p (current_uiout))
12667     return;
12668
12669   switch (b->type)
12670     {
12671     case bp_breakpoint:
12672     case bp_gnu_ifunc_resolver:
12673       if (b->disposition == disp_del)
12674         printf_filtered (_("Temporary breakpoint"));
12675       else
12676         printf_filtered (_("Breakpoint"));
12677       printf_filtered (_(" %d"), b->number);
12678       if (b->type == bp_gnu_ifunc_resolver)
12679         printf_filtered (_(" at gnu-indirect-function resolver"));
12680       break;
12681     case bp_hardware_breakpoint:
12682       printf_filtered (_("Hardware assisted breakpoint %d"), b->number);
12683       break;
12684     case bp_dprintf:
12685       printf_filtered (_("Dprintf %d"), b->number);
12686       break;
12687     }
12688
12689   say_where (b);
12690 }
12691
12692 static void
12693 bkpt_print_recreate (struct breakpoint *tp, struct ui_file *fp)
12694 {
12695   if (tp->type == bp_breakpoint && tp->disposition == disp_del)
12696     fprintf_unfiltered (fp, "tbreak");
12697   else if (tp->type == bp_breakpoint)
12698     fprintf_unfiltered (fp, "break");
12699   else if (tp->type == bp_hardware_breakpoint
12700            && tp->disposition == disp_del)
12701     fprintf_unfiltered (fp, "thbreak");
12702   else if (tp->type == bp_hardware_breakpoint)
12703     fprintf_unfiltered (fp, "hbreak");
12704   else
12705     internal_error (__FILE__, __LINE__,
12706                     _("unhandled breakpoint type %d"), (int) tp->type);
12707
12708   fprintf_unfiltered (fp, " %s", tp->addr_string);
12709   print_recreate_thread (tp, fp);
12710 }
12711
12712 static void
12713 bkpt_create_sals_from_address (char **arg,
12714                                struct linespec_result *canonical,
12715                                enum bptype type_wanted,
12716                                char *addr_start, char **copy_arg)
12717 {
12718   create_sals_from_address_default (arg, canonical, type_wanted,
12719                                     addr_start, copy_arg);
12720 }
12721
12722 static void
12723 bkpt_create_breakpoints_sal (struct gdbarch *gdbarch,
12724                              struct linespec_result *canonical,
12725                              struct linespec_sals *lsal,
12726                              char *cond_string,
12727                              char *extra_string,
12728                              enum bptype type_wanted,
12729                              enum bpdisp disposition,
12730                              int thread,
12731                              int task, int ignore_count,
12732                              const struct breakpoint_ops *ops,
12733                              int from_tty, int enabled,
12734                              int internal, unsigned flags)
12735 {
12736   create_breakpoints_sal_default (gdbarch, canonical, lsal,
12737                                   cond_string, extra_string,
12738                                   type_wanted,
12739                                   disposition, thread, task,
12740                                   ignore_count, ops, from_tty,
12741                                   enabled, internal, flags);
12742 }
12743
12744 static void
12745 bkpt_decode_linespec (struct breakpoint *b, char **s,
12746                       struct symtabs_and_lines *sals)
12747 {
12748   decode_linespec_default (b, s, sals);
12749 }
12750
12751 /* Virtual table for internal breakpoints.  */
12752
12753 static void
12754 internal_bkpt_re_set (struct breakpoint *b)
12755 {
12756   switch (b->type)
12757     {
12758       /* Delete overlay event and longjmp master breakpoints; they
12759          will be reset later by breakpoint_re_set.  */
12760     case bp_overlay_event:
12761     case bp_longjmp_master:
12762     case bp_std_terminate_master:
12763     case bp_exception_master:
12764       delete_breakpoint (b);
12765       break;
12766
12767       /* This breakpoint is special, it's set up when the inferior
12768          starts and we really don't want to touch it.  */
12769     case bp_shlib_event:
12770
12771       /* Like bp_shlib_event, this breakpoint type is special.  Once
12772          it is set up, we do not want to touch it.  */
12773     case bp_thread_event:
12774       break;
12775     }
12776 }
12777
12778 static void
12779 internal_bkpt_check_status (bpstat bs)
12780 {
12781   if (bs->breakpoint_at->type == bp_shlib_event)
12782     {
12783       /* If requested, stop when the dynamic linker notifies GDB of
12784          events.  This allows the user to get control and place
12785          breakpoints in initializer routines for dynamically loaded
12786          objects (among other things).  */
12787       bs->stop = stop_on_solib_events;
12788       bs->print = stop_on_solib_events;
12789     }
12790   else
12791     bs->stop = 0;
12792 }
12793
12794 static enum print_stop_action
12795 internal_bkpt_print_it (bpstat bs)
12796 {
12797   struct ui_out *uiout = current_uiout;
12798   struct breakpoint *b;
12799
12800   b = bs->breakpoint_at;
12801
12802   switch (b->type)
12803     {
12804     case bp_shlib_event:
12805       /* Did we stop because the user set the stop_on_solib_events
12806          variable?  (If so, we report this as a generic, "Stopped due
12807          to shlib event" message.) */
12808       print_solib_event (0);
12809       break;
12810
12811     case bp_thread_event:
12812       /* Not sure how we will get here.
12813          GDB should not stop for these breakpoints.  */
12814       printf_filtered (_("Thread Event Breakpoint: gdb should not stop!\n"));
12815       break;
12816
12817     case bp_overlay_event:
12818       /* By analogy with the thread event, GDB should not stop for these.  */
12819       printf_filtered (_("Overlay Event Breakpoint: gdb should not stop!\n"));
12820       break;
12821
12822     case bp_longjmp_master:
12823       /* These should never be enabled.  */
12824       printf_filtered (_("Longjmp Master Breakpoint: gdb should not stop!\n"));
12825       break;
12826
12827     case bp_std_terminate_master:
12828       /* These should never be enabled.  */
12829       printf_filtered (_("std::terminate Master Breakpoint: "
12830                          "gdb should not stop!\n"));
12831       break;
12832
12833     case bp_exception_master:
12834       /* These should never be enabled.  */
12835       printf_filtered (_("Exception Master Breakpoint: "
12836                          "gdb should not stop!\n"));
12837       break;
12838     }
12839
12840   return PRINT_NOTHING;
12841 }
12842
12843 static void
12844 internal_bkpt_print_mention (struct breakpoint *b)
12845 {
12846   /* Nothing to mention.  These breakpoints are internal.  */
12847 }
12848
12849 /* Virtual table for momentary breakpoints  */
12850
12851 static void
12852 momentary_bkpt_re_set (struct breakpoint *b)
12853 {
12854   /* Keep temporary breakpoints, which can be encountered when we step
12855      over a dlopen call and SOLIB_ADD is resetting the breakpoints.
12856      Otherwise these should have been blown away via the cleanup chain
12857      or by breakpoint_init_inferior when we rerun the executable.  */
12858 }
12859
12860 static void
12861 momentary_bkpt_check_status (bpstat bs)
12862 {
12863   /* Nothing.  The point of these breakpoints is causing a stop.  */
12864 }
12865
12866 static enum print_stop_action
12867 momentary_bkpt_print_it (bpstat bs)
12868 {
12869   struct ui_out *uiout = current_uiout;
12870
12871   if (ui_out_is_mi_like_p (uiout))
12872     {
12873       struct breakpoint *b = bs->breakpoint_at;
12874
12875       switch (b->type)
12876         {
12877         case bp_finish:
12878           ui_out_field_string
12879             (uiout, "reason",
12880              async_reason_lookup (EXEC_ASYNC_FUNCTION_FINISHED));
12881           break;
12882
12883         case bp_until:
12884           ui_out_field_string
12885             (uiout, "reason",
12886              async_reason_lookup (EXEC_ASYNC_LOCATION_REACHED));
12887           break;
12888         }
12889     }
12890
12891   return PRINT_UNKNOWN;
12892 }
12893
12894 static void
12895 momentary_bkpt_print_mention (struct breakpoint *b)
12896 {
12897   /* Nothing to mention.  These breakpoints are internal.  */
12898 }
12899
12900 /* Ensure INITIATING_FRAME is cleared when no such breakpoint exists.
12901
12902    It gets cleared already on the removal of the first one of such placed
12903    breakpoints.  This is OK as they get all removed altogether.  */
12904
12905 static void
12906 longjmp_bkpt_dtor (struct breakpoint *self)
12907 {
12908   struct thread_info *tp = find_thread_id (self->thread);
12909
12910   if (tp)
12911     tp->initiating_frame = null_frame_id;
12912
12913   momentary_breakpoint_ops.dtor (self);
12914 }
12915
12916 /* Specific methods for probe breakpoints.  */
12917
12918 static int
12919 bkpt_probe_insert_location (struct bp_location *bl)
12920 {
12921   int v = bkpt_insert_location (bl);
12922
12923   if (v == 0)
12924     {
12925       /* The insertion was successful, now let's set the probe's semaphore
12926          if needed.  */
12927       bl->probe->pops->set_semaphore (bl->probe, bl->gdbarch);
12928     }
12929
12930   return v;
12931 }
12932
12933 static int
12934 bkpt_probe_remove_location (struct bp_location *bl)
12935 {
12936   /* Let's clear the semaphore before removing the location.  */
12937   bl->probe->pops->clear_semaphore (bl->probe, bl->gdbarch);
12938
12939   return bkpt_remove_location (bl);
12940 }
12941
12942 static void
12943 bkpt_probe_create_sals_from_address (char **arg,
12944                                      struct linespec_result *canonical,
12945                                      enum bptype type_wanted,
12946                                      char *addr_start, char **copy_arg)
12947 {
12948   struct linespec_sals lsal;
12949
12950   lsal.sals = parse_probes (arg, canonical);
12951
12952   *copy_arg = xstrdup (canonical->addr_string);
12953   lsal.canonical = xstrdup (*copy_arg);
12954
12955   VEC_safe_push (linespec_sals, canonical->sals, &lsal);
12956 }
12957
12958 static void
12959 bkpt_probe_decode_linespec (struct breakpoint *b, char **s,
12960                             struct symtabs_and_lines *sals)
12961 {
12962   *sals = parse_probes (s, NULL);
12963   if (!sals->sals)
12964     error (_("probe not found"));
12965 }
12966
12967 /* The breakpoint_ops structure to be used in tracepoints.  */
12968
12969 static void
12970 tracepoint_re_set (struct breakpoint *b)
12971 {
12972   breakpoint_re_set_default (b);
12973 }
12974
12975 static int
12976 tracepoint_breakpoint_hit (const struct bp_location *bl,
12977                            struct address_space *aspace, CORE_ADDR bp_addr,
12978                            const struct target_waitstatus *ws)
12979 {
12980   /* By definition, the inferior does not report stops at
12981      tracepoints.  */
12982   return 0;
12983 }
12984
12985 static void
12986 tracepoint_print_one_detail (const struct breakpoint *self,
12987                              struct ui_out *uiout)
12988 {
12989   struct tracepoint *tp = (struct tracepoint *) self;
12990   if (tp->static_trace_marker_id)
12991     {
12992       gdb_assert (self->type == bp_static_tracepoint);
12993
12994       ui_out_text (uiout, "\tmarker id is ");
12995       ui_out_field_string (uiout, "static-tracepoint-marker-string-id",
12996                            tp->static_trace_marker_id);
12997       ui_out_text (uiout, "\n");
12998     }
12999 }
13000
13001 static void
13002 tracepoint_print_mention (struct breakpoint *b)
13003 {
13004   if (ui_out_is_mi_like_p (current_uiout))
13005     return;
13006
13007   switch (b->type)
13008     {
13009     case bp_tracepoint:
13010       printf_filtered (_("Tracepoint"));
13011       printf_filtered (_(" %d"), b->number);
13012       break;
13013     case bp_fast_tracepoint:
13014       printf_filtered (_("Fast tracepoint"));
13015       printf_filtered (_(" %d"), b->number);
13016       break;
13017     case bp_static_tracepoint:
13018       printf_filtered (_("Static tracepoint"));
13019       printf_filtered (_(" %d"), b->number);
13020       break;
13021     default:
13022       internal_error (__FILE__, __LINE__,
13023                       _("unhandled tracepoint type %d"), (int) b->type);
13024     }
13025
13026   say_where (b);
13027 }
13028
13029 static void
13030 tracepoint_print_recreate (struct breakpoint *self, struct ui_file *fp)
13031 {
13032   struct tracepoint *tp = (struct tracepoint *) self;
13033
13034   if (self->type == bp_fast_tracepoint)
13035     fprintf_unfiltered (fp, "ftrace");
13036   if (self->type == bp_static_tracepoint)
13037     fprintf_unfiltered (fp, "strace");
13038   else if (self->type == bp_tracepoint)
13039     fprintf_unfiltered (fp, "trace");
13040   else
13041     internal_error (__FILE__, __LINE__,
13042                     _("unhandled tracepoint type %d"), (int) self->type);
13043
13044   fprintf_unfiltered (fp, " %s", self->addr_string);
13045   print_recreate_thread (self, fp);
13046
13047   if (tp->pass_count)
13048     fprintf_unfiltered (fp, "  passcount %d\n", tp->pass_count);
13049 }
13050
13051 static void
13052 tracepoint_create_sals_from_address (char **arg,
13053                                      struct linespec_result *canonical,
13054                                      enum bptype type_wanted,
13055                                      char *addr_start, char **copy_arg)
13056 {
13057   create_sals_from_address_default (arg, canonical, type_wanted,
13058                                     addr_start, copy_arg);
13059 }
13060
13061 static void
13062 tracepoint_create_breakpoints_sal (struct gdbarch *gdbarch,
13063                                    struct linespec_result *canonical,
13064                                    struct linespec_sals *lsal,
13065                                    char *cond_string,
13066                                    char *extra_string,
13067                                    enum bptype type_wanted,
13068                                    enum bpdisp disposition,
13069                                    int thread,
13070                                    int task, int ignore_count,
13071                                    const struct breakpoint_ops *ops,
13072                                    int from_tty, int enabled,
13073                                    int internal, unsigned flags)
13074 {
13075   create_breakpoints_sal_default (gdbarch, canonical, lsal,
13076                                   cond_string, extra_string,
13077                                   type_wanted,
13078                                   disposition, thread, task,
13079                                   ignore_count, ops, from_tty,
13080                                   enabled, internal, flags);
13081 }
13082
13083 static void
13084 tracepoint_decode_linespec (struct breakpoint *b, char **s,
13085                             struct symtabs_and_lines *sals)
13086 {
13087   decode_linespec_default (b, s, sals);
13088 }
13089
13090 struct breakpoint_ops tracepoint_breakpoint_ops;
13091
13092 /* The breakpoint_ops structure to be use on tracepoints placed in a
13093    static probe.  */
13094
13095 static void
13096 tracepoint_probe_create_sals_from_address (char **arg,
13097                                            struct linespec_result *canonical,
13098                                            enum bptype type_wanted,
13099                                            char *addr_start, char **copy_arg)
13100 {
13101   /* We use the same method for breakpoint on probes.  */
13102   bkpt_probe_create_sals_from_address (arg, canonical, type_wanted,
13103                                        addr_start, copy_arg);
13104 }
13105
13106 static void
13107 tracepoint_probe_decode_linespec (struct breakpoint *b, char **s,
13108                                   struct symtabs_and_lines *sals)
13109 {
13110   /* We use the same method for breakpoint on probes.  */
13111   bkpt_probe_decode_linespec (b, s, sals);
13112 }
13113
13114 static struct breakpoint_ops tracepoint_probe_breakpoint_ops;
13115
13116 /* The breakpoint_ops structure to be used on static tracepoints with
13117    markers (`-m').  */
13118
13119 static void
13120 strace_marker_create_sals_from_address (char **arg,
13121                                         struct linespec_result *canonical,
13122                                         enum bptype type_wanted,
13123                                         char *addr_start, char **copy_arg)
13124 {
13125   struct linespec_sals lsal;
13126
13127   lsal.sals = decode_static_tracepoint_spec (arg);
13128
13129   *copy_arg = savestring (addr_start, *arg - addr_start);
13130
13131   canonical->addr_string = xstrdup (*copy_arg);
13132   lsal.canonical = xstrdup (*copy_arg);
13133   VEC_safe_push (linespec_sals, canonical->sals, &lsal);
13134 }
13135
13136 static void
13137 strace_marker_create_breakpoints_sal (struct gdbarch *gdbarch,
13138                                       struct linespec_result *canonical,
13139                                       struct linespec_sals *lsal,
13140                                       char *cond_string,
13141                                       char *extra_string,
13142                                       enum bptype type_wanted,
13143                                       enum bpdisp disposition,
13144                                       int thread,
13145                                       int task, int ignore_count,
13146                                       const struct breakpoint_ops *ops,
13147                                       int from_tty, int enabled,
13148                                       int internal, unsigned flags)
13149 {
13150   int i;
13151
13152   /* If the user is creating a static tracepoint by marker id
13153      (strace -m MARKER_ID), then store the sals index, so that
13154      breakpoint_re_set can try to match up which of the newly
13155      found markers corresponds to this one, and, don't try to
13156      expand multiple locations for each sal, given than SALS
13157      already should contain all sals for MARKER_ID.  */
13158
13159   for (i = 0; i < lsal->sals.nelts; ++i)
13160     {
13161       struct symtabs_and_lines expanded;
13162       struct tracepoint *tp;
13163       struct cleanup *old_chain;
13164       char *addr_string;
13165
13166       expanded.nelts = 1;
13167       expanded.sals = &lsal->sals.sals[i];
13168
13169       addr_string = xstrdup (canonical->addr_string);
13170       old_chain = make_cleanup (xfree, addr_string);
13171
13172       tp = XCNEW (struct tracepoint);
13173       init_breakpoint_sal (&tp->base, gdbarch, expanded,
13174                            addr_string, NULL,
13175                            cond_string, extra_string,
13176                            type_wanted, disposition,
13177                            thread, task, ignore_count, ops,
13178                            from_tty, enabled, internal, flags,
13179                            canonical->special_display);
13180       /* Given that its possible to have multiple markers with
13181          the same string id, if the user is creating a static
13182          tracepoint by marker id ("strace -m MARKER_ID"), then
13183          store the sals index, so that breakpoint_re_set can
13184          try to match up which of the newly found markers
13185          corresponds to this one  */
13186       tp->static_trace_marker_id_idx = i;
13187
13188       install_breakpoint (internal, &tp->base, 0);
13189
13190       discard_cleanups (old_chain);
13191     }
13192 }
13193
13194 static void
13195 strace_marker_decode_linespec (struct breakpoint *b, char **s,
13196                                struct symtabs_and_lines *sals)
13197 {
13198   struct tracepoint *tp = (struct tracepoint *) b;
13199
13200   *sals = decode_static_tracepoint_spec (s);
13201   if (sals->nelts > tp->static_trace_marker_id_idx)
13202     {
13203       sals->sals[0] = sals->sals[tp->static_trace_marker_id_idx];
13204       sals->nelts = 1;
13205     }
13206   else
13207     error (_("marker %s not found"), tp->static_trace_marker_id);
13208 }
13209
13210 static struct breakpoint_ops strace_marker_breakpoint_ops;
13211
13212 static int
13213 strace_marker_p (struct breakpoint *b)
13214 {
13215   return b->ops == &strace_marker_breakpoint_ops;
13216 }
13217
13218 /* Delete a breakpoint and clean up all traces of it in the data
13219    structures.  */
13220
13221 void
13222 delete_breakpoint (struct breakpoint *bpt)
13223 {
13224   struct breakpoint *b;
13225
13226   gdb_assert (bpt != NULL);
13227
13228   /* Has this bp already been deleted?  This can happen because
13229      multiple lists can hold pointers to bp's.  bpstat lists are
13230      especial culprits.
13231
13232      One example of this happening is a watchpoint's scope bp.  When
13233      the scope bp triggers, we notice that the watchpoint is out of
13234      scope, and delete it.  We also delete its scope bp.  But the
13235      scope bp is marked "auto-deleting", and is already on a bpstat.
13236      That bpstat is then checked for auto-deleting bp's, which are
13237      deleted.
13238
13239      A real solution to this problem might involve reference counts in
13240      bp's, and/or giving them pointers back to their referencing
13241      bpstat's, and teaching delete_breakpoint to only free a bp's
13242      storage when no more references were extent.  A cheaper bandaid
13243      was chosen.  */
13244   if (bpt->type == bp_none)
13245     return;
13246
13247   /* At least avoid this stale reference until the reference counting
13248      of breakpoints gets resolved.  */
13249   if (bpt->related_breakpoint != bpt)
13250     {
13251       struct breakpoint *related;
13252       struct watchpoint *w;
13253
13254       if (bpt->type == bp_watchpoint_scope)
13255         w = (struct watchpoint *) bpt->related_breakpoint;
13256       else if (bpt->related_breakpoint->type == bp_watchpoint_scope)
13257         w = (struct watchpoint *) bpt;
13258       else
13259         w = NULL;
13260       if (w != NULL)
13261         watchpoint_del_at_next_stop (w);
13262
13263       /* Unlink bpt from the bpt->related_breakpoint ring.  */
13264       for (related = bpt; related->related_breakpoint != bpt;
13265            related = related->related_breakpoint);
13266       related->related_breakpoint = bpt->related_breakpoint;
13267       bpt->related_breakpoint = bpt;
13268     }
13269
13270   /* watch_command_1 creates a watchpoint but only sets its number if
13271      update_watchpoint succeeds in creating its bp_locations.  If there's
13272      a problem in that process, we'll be asked to delete the half-created
13273      watchpoint.  In that case, don't announce the deletion.  */
13274   if (bpt->number)
13275     observer_notify_breakpoint_deleted (bpt);
13276
13277   if (breakpoint_chain == bpt)
13278     breakpoint_chain = bpt->next;
13279
13280   ALL_BREAKPOINTS (b)
13281     if (b->next == bpt)
13282     {
13283       b->next = bpt->next;
13284       break;
13285     }
13286
13287   /* Be sure no bpstat's are pointing at the breakpoint after it's
13288      been freed.  */
13289   /* FIXME, how can we find all bpstat's?  We just check stop_bpstat
13290      in all threads for now.  Note that we cannot just remove bpstats
13291      pointing at bpt from the stop_bpstat list entirely, as breakpoint
13292      commands are associated with the bpstat; if we remove it here,
13293      then the later call to bpstat_do_actions (&stop_bpstat); in
13294      event-top.c won't do anything, and temporary breakpoints with
13295      commands won't work.  */
13296
13297   iterate_over_threads (bpstat_remove_breakpoint_callback, bpt);
13298
13299   /* Now that breakpoint is removed from breakpoint list, update the
13300      global location list.  This will remove locations that used to
13301      belong to this breakpoint.  Do this before freeing the breakpoint
13302      itself, since remove_breakpoint looks at location's owner.  It
13303      might be better design to have location completely
13304      self-contained, but it's not the case now.  */
13305   update_global_location_list (0);
13306
13307   bpt->ops->dtor (bpt);
13308   /* On the chance that someone will soon try again to delete this
13309      same bp, we mark it as deleted before freeing its storage.  */
13310   bpt->type = bp_none;
13311   xfree (bpt);
13312 }
13313
13314 static void
13315 do_delete_breakpoint_cleanup (void *b)
13316 {
13317   delete_breakpoint (b);
13318 }
13319
13320 struct cleanup *
13321 make_cleanup_delete_breakpoint (struct breakpoint *b)
13322 {
13323   return make_cleanup (do_delete_breakpoint_cleanup, b);
13324 }
13325
13326 /* Iterator function to call a user-provided callback function once
13327    for each of B and its related breakpoints.  */
13328
13329 static void
13330 iterate_over_related_breakpoints (struct breakpoint *b,
13331                                   void (*function) (struct breakpoint *,
13332                                                     void *),
13333                                   void *data)
13334 {
13335   struct breakpoint *related;
13336
13337   related = b;
13338   do
13339     {
13340       struct breakpoint *next;
13341
13342       /* FUNCTION may delete RELATED.  */
13343       next = related->related_breakpoint;
13344
13345       if (next == related)
13346         {
13347           /* RELATED is the last ring entry.  */
13348           function (related, data);
13349
13350           /* FUNCTION may have deleted it, so we'd never reach back to
13351              B.  There's nothing left to do anyway, so just break
13352              out.  */
13353           break;
13354         }
13355       else
13356         function (related, data);
13357
13358       related = next;
13359     }
13360   while (related != b);
13361 }
13362
13363 static void
13364 do_delete_breakpoint (struct breakpoint *b, void *ignore)
13365 {
13366   delete_breakpoint (b);
13367 }
13368
13369 /* A callback for map_breakpoint_numbers that calls
13370    delete_breakpoint.  */
13371
13372 static void
13373 do_map_delete_breakpoint (struct breakpoint *b, void *ignore)
13374 {
13375   iterate_over_related_breakpoints (b, do_delete_breakpoint, NULL);
13376 }
13377
13378 void
13379 delete_command (char *arg, int from_tty)
13380 {
13381   struct breakpoint *b, *b_tmp;
13382
13383   dont_repeat ();
13384
13385   if (arg == 0)
13386     {
13387       int breaks_to_delete = 0;
13388
13389       /* Delete all breakpoints if no argument.  Do not delete
13390          internal breakpoints, these have to be deleted with an
13391          explicit breakpoint number argument.  */
13392       ALL_BREAKPOINTS (b)
13393         if (user_breakpoint_p (b))
13394           {
13395             breaks_to_delete = 1;
13396             break;
13397           }
13398
13399       /* Ask user only if there are some breakpoints to delete.  */
13400       if (!from_tty
13401           || (breaks_to_delete && query (_("Delete all breakpoints? "))))
13402         {
13403           ALL_BREAKPOINTS_SAFE (b, b_tmp)
13404             if (user_breakpoint_p (b))
13405               delete_breakpoint (b);
13406         }
13407     }
13408   else
13409     map_breakpoint_numbers (arg, do_map_delete_breakpoint, NULL);
13410 }
13411
13412 static int
13413 all_locations_are_pending (struct bp_location *loc)
13414 {
13415   for (; loc; loc = loc->next)
13416     if (!loc->shlib_disabled
13417         && !loc->pspace->executing_startup)
13418       return 0;
13419   return 1;
13420 }
13421
13422 /* Subroutine of update_breakpoint_locations to simplify it.
13423    Return non-zero if multiple fns in list LOC have the same name.
13424    Null names are ignored.  */
13425
13426 static int
13427 ambiguous_names_p (struct bp_location *loc)
13428 {
13429   struct bp_location *l;
13430   htab_t htab = htab_create_alloc (13, htab_hash_string,
13431                                    (int (*) (const void *, 
13432                                              const void *)) streq,
13433                                    NULL, xcalloc, xfree);
13434
13435   for (l = loc; l != NULL; l = l->next)
13436     {
13437       const char **slot;
13438       const char *name = l->function_name;
13439
13440       /* Allow for some names to be NULL, ignore them.  */
13441       if (name == NULL)
13442         continue;
13443
13444       slot = (const char **) htab_find_slot (htab, (const void *) name,
13445                                              INSERT);
13446       /* NOTE: We can assume slot != NULL here because xcalloc never
13447          returns NULL.  */
13448       if (*slot != NULL)
13449         {
13450           htab_delete (htab);
13451           return 1;
13452         }
13453       *slot = name;
13454     }
13455
13456   htab_delete (htab);
13457   return 0;
13458 }
13459
13460 /* When symbols change, it probably means the sources changed as well,
13461    and it might mean the static tracepoint markers are no longer at
13462    the same address or line numbers they used to be at last we
13463    checked.  Losing your static tracepoints whenever you rebuild is
13464    undesirable.  This function tries to resync/rematch gdb static
13465    tracepoints with the markers on the target, for static tracepoints
13466    that have not been set by marker id.  Static tracepoint that have
13467    been set by marker id are reset by marker id in breakpoint_re_set.
13468    The heuristic is:
13469
13470    1) For a tracepoint set at a specific address, look for a marker at
13471    the old PC.  If one is found there, assume to be the same marker.
13472    If the name / string id of the marker found is different from the
13473    previous known name, assume that means the user renamed the marker
13474    in the sources, and output a warning.
13475
13476    2) For a tracepoint set at a given line number, look for a marker
13477    at the new address of the old line number.  If one is found there,
13478    assume to be the same marker.  If the name / string id of the
13479    marker found is different from the previous known name, assume that
13480    means the user renamed the marker in the sources, and output a
13481    warning.
13482
13483    3) If a marker is no longer found at the same address or line, it
13484    may mean the marker no longer exists.  But it may also just mean
13485    the code changed a bit.  Maybe the user added a few lines of code
13486    that made the marker move up or down (in line number terms).  Ask
13487    the target for info about the marker with the string id as we knew
13488    it.  If found, update line number and address in the matching
13489    static tracepoint.  This will get confused if there's more than one
13490    marker with the same ID (possible in UST, although unadvised
13491    precisely because it confuses tools).  */
13492
13493 static struct symtab_and_line
13494 update_static_tracepoint (struct breakpoint *b, struct symtab_and_line sal)
13495 {
13496   struct tracepoint *tp = (struct tracepoint *) b;
13497   struct static_tracepoint_marker marker;
13498   CORE_ADDR pc;
13499
13500   pc = sal.pc;
13501   if (sal.line)
13502     find_line_pc (sal.symtab, sal.line, &pc);
13503
13504   if (target_static_tracepoint_marker_at (pc, &marker))
13505     {
13506       if (strcmp (tp->static_trace_marker_id, marker.str_id) != 0)
13507         warning (_("static tracepoint %d changed probed marker from %s to %s"),
13508                  b->number,
13509                  tp->static_trace_marker_id, marker.str_id);
13510
13511       xfree (tp->static_trace_marker_id);
13512       tp->static_trace_marker_id = xstrdup (marker.str_id);
13513       release_static_tracepoint_marker (&marker);
13514
13515       return sal;
13516     }
13517
13518   /* Old marker wasn't found on target at lineno.  Try looking it up
13519      by string ID.  */
13520   if (!sal.explicit_pc
13521       && sal.line != 0
13522       && sal.symtab != NULL
13523       && tp->static_trace_marker_id != NULL)
13524     {
13525       VEC(static_tracepoint_marker_p) *markers;
13526
13527       markers
13528         = target_static_tracepoint_markers_by_strid (tp->static_trace_marker_id);
13529
13530       if (!VEC_empty(static_tracepoint_marker_p, markers))
13531         {
13532           struct symtab_and_line sal2;
13533           struct symbol *sym;
13534           struct static_tracepoint_marker *tpmarker;
13535           struct ui_out *uiout = current_uiout;
13536
13537           tpmarker = VEC_index (static_tracepoint_marker_p, markers, 0);
13538
13539           xfree (tp->static_trace_marker_id);
13540           tp->static_trace_marker_id = xstrdup (tpmarker->str_id);
13541
13542           warning (_("marker for static tracepoint %d (%s) not "
13543                      "found at previous line number"),
13544                    b->number, tp->static_trace_marker_id);
13545
13546           init_sal (&sal2);
13547
13548           sal2.pc = tpmarker->address;
13549
13550           sal2 = find_pc_line (tpmarker->address, 0);
13551           sym = find_pc_sect_function (tpmarker->address, NULL);
13552           ui_out_text (uiout, "Now in ");
13553           if (sym)
13554             {
13555               ui_out_field_string (uiout, "func",
13556                                    SYMBOL_PRINT_NAME (sym));
13557               ui_out_text (uiout, " at ");
13558             }
13559           ui_out_field_string (uiout, "file", sal2.symtab->filename);
13560           ui_out_text (uiout, ":");
13561
13562           if (ui_out_is_mi_like_p (uiout))
13563             {
13564               char *fullname = symtab_to_fullname (sal2.symtab);
13565
13566               if (fullname)
13567                 ui_out_field_string (uiout, "fullname", fullname);
13568             }
13569
13570           ui_out_field_int (uiout, "line", sal2.line);
13571           ui_out_text (uiout, "\n");
13572
13573           b->loc->line_number = sal2.line;
13574
13575           xfree (b->loc->source_file);
13576           if (sym)
13577             b->loc->source_file = xstrdup (sal2.symtab->filename);
13578           else
13579             b->loc->source_file = NULL;
13580
13581           xfree (b->addr_string);
13582           b->addr_string = xstrprintf ("%s:%d",
13583                                        sal2.symtab->filename,
13584                                        b->loc->line_number);
13585
13586           /* Might be nice to check if function changed, and warn if
13587              so.  */
13588
13589           release_static_tracepoint_marker (tpmarker);
13590         }
13591     }
13592   return sal;
13593 }
13594
13595 /* Returns 1 iff locations A and B are sufficiently same that
13596    we don't need to report breakpoint as changed.  */
13597
13598 static int
13599 locations_are_equal (struct bp_location *a, struct bp_location *b)
13600 {
13601   while (a && b)
13602     {
13603       if (a->address != b->address)
13604         return 0;
13605
13606       if (a->shlib_disabled != b->shlib_disabled)
13607         return 0;
13608
13609       if (a->enabled != b->enabled)
13610         return 0;
13611
13612       a = a->next;
13613       b = b->next;
13614     }
13615
13616   if ((a == NULL) != (b == NULL))
13617     return 0;
13618
13619   return 1;
13620 }
13621
13622 /* Create new breakpoint locations for B (a hardware or software breakpoint)
13623    based on SALS and SALS_END.  If SALS_END.NELTS is not zero, then B is
13624    a ranged breakpoint.  */
13625
13626 void
13627 update_breakpoint_locations (struct breakpoint *b,
13628                              struct symtabs_and_lines sals,
13629                              struct symtabs_and_lines sals_end)
13630 {
13631   int i;
13632   struct bp_location *existing_locations = b->loc;
13633
13634   if (sals_end.nelts != 0 && (sals.nelts != 1 || sals_end.nelts != 1))
13635     {
13636       /* Ranged breakpoints have only one start location and one end
13637          location.  */
13638       b->enable_state = bp_disabled;
13639       update_global_location_list (1);
13640       printf_unfiltered (_("Could not reset ranged breakpoint %d: "
13641                            "multiple locations found\n"),
13642                          b->number);
13643       return;
13644     }
13645
13646   /* If there's no new locations, and all existing locations are
13647      pending, don't do anything.  This optimizes the common case where
13648      all locations are in the same shared library, that was unloaded.
13649      We'd like to retain the location, so that when the library is
13650      loaded again, we don't loose the enabled/disabled status of the
13651      individual locations.  */
13652   if (all_locations_are_pending (existing_locations) && sals.nelts == 0)
13653     return;
13654
13655   b->loc = NULL;
13656
13657   for (i = 0; i < sals.nelts; ++i)
13658     {
13659       struct bp_location *new_loc;
13660
13661       switch_to_program_space_and_thread (sals.sals[i].pspace);
13662
13663       new_loc = add_location_to_breakpoint (b, &(sals.sals[i]));
13664
13665       /* Reparse conditions, they might contain references to the
13666          old symtab.  */
13667       if (b->cond_string != NULL)
13668         {
13669           char *s;
13670           volatile struct gdb_exception e;
13671
13672           s = b->cond_string;
13673           TRY_CATCH (e, RETURN_MASK_ERROR)
13674             {
13675               new_loc->cond = parse_exp_1 (&s, sals.sals[i].pc,
13676                                            block_for_pc (sals.sals[i].pc), 
13677                                            0);
13678             }
13679           if (e.reason < 0)
13680             {
13681               warning (_("failed to reevaluate condition "
13682                          "for breakpoint %d: %s"), 
13683                        b->number, e.message);
13684               new_loc->enabled = 0;
13685             }
13686         }
13687
13688       if (sals_end.nelts)
13689         {
13690           CORE_ADDR end = find_breakpoint_range_end (sals_end.sals[0]);
13691
13692           new_loc->length = end - sals.sals[0].pc + 1;
13693         }
13694     }
13695
13696   /* Update locations of permanent breakpoints.  */
13697   if (b->enable_state == bp_permanent)
13698     make_breakpoint_permanent (b);
13699
13700   /* If possible, carry over 'disable' status from existing
13701      breakpoints.  */
13702   {
13703     struct bp_location *e = existing_locations;
13704     /* If there are multiple breakpoints with the same function name,
13705        e.g. for inline functions, comparing function names won't work.
13706        Instead compare pc addresses; this is just a heuristic as things
13707        may have moved, but in practice it gives the correct answer
13708        often enough until a better solution is found.  */
13709     int have_ambiguous_names = ambiguous_names_p (b->loc);
13710
13711     for (; e; e = e->next)
13712       {
13713         if (!e->enabled && e->function_name)
13714           {
13715             struct bp_location *l = b->loc;
13716             if (have_ambiguous_names)
13717               {
13718                 for (; l; l = l->next)
13719                   if (breakpoint_locations_match (e, l))
13720                     {
13721                       l->enabled = 0;
13722                       break;
13723                     }
13724               }
13725             else
13726               {
13727                 for (; l; l = l->next)
13728                   if (l->function_name
13729                       && strcmp (e->function_name, l->function_name) == 0)
13730                     {
13731                       l->enabled = 0;
13732                       break;
13733                     }
13734               }
13735           }
13736       }
13737   }
13738
13739   if (!locations_are_equal (existing_locations, b->loc))
13740     observer_notify_breakpoint_modified (b);
13741
13742   update_global_location_list (1);
13743 }
13744
13745 /* Find the SaL locations corresponding to the given ADDR_STRING.
13746    On return, FOUND will be 1 if any SaL was found, zero otherwise.  */
13747
13748 static struct symtabs_and_lines
13749 addr_string_to_sals (struct breakpoint *b, char *addr_string, int *found)
13750 {
13751   char *s;
13752   struct symtabs_and_lines sals = {0};
13753   volatile struct gdb_exception e;
13754
13755   gdb_assert (b->ops != NULL);
13756   s = addr_string;
13757
13758   TRY_CATCH (e, RETURN_MASK_ERROR)
13759     {
13760       b->ops->decode_linespec (b, &s, &sals);
13761     }
13762   if (e.reason < 0)
13763     {
13764       int not_found_and_ok = 0;
13765       /* For pending breakpoints, it's expected that parsing will
13766          fail until the right shared library is loaded.  User has
13767          already told to create pending breakpoints and don't need
13768          extra messages.  If breakpoint is in bp_shlib_disabled
13769          state, then user already saw the message about that
13770          breakpoint being disabled, and don't want to see more
13771          errors.  */
13772       if (e.error == NOT_FOUND_ERROR
13773           && (b->condition_not_parsed 
13774               || (b->loc && b->loc->shlib_disabled)
13775               || (b->loc && b->loc->pspace->executing_startup)
13776               || b->enable_state == bp_disabled))
13777         not_found_and_ok = 1;
13778
13779       if (!not_found_and_ok)
13780         {
13781           /* We surely don't want to warn about the same breakpoint
13782              10 times.  One solution, implemented here, is disable
13783              the breakpoint on error.  Another solution would be to
13784              have separate 'warning emitted' flag.  Since this
13785              happens only when a binary has changed, I don't know
13786              which approach is better.  */
13787           b->enable_state = bp_disabled;
13788           throw_exception (e);
13789         }
13790     }
13791
13792   if (e.reason == 0 || e.error != NOT_FOUND_ERROR)
13793     {
13794       int i;
13795
13796       for (i = 0; i < sals.nelts; ++i)
13797         resolve_sal_pc (&sals.sals[i]);
13798       if (b->condition_not_parsed && s && s[0])
13799         {
13800           char *cond_string = 0;
13801           int thread = -1;
13802           int task = 0;
13803           char *extra_string = NULL;
13804
13805           find_condition_and_thread (s, sals.sals[0].pc,
13806                                      &cond_string, &thread, &task,
13807                                      &extra_string);
13808           if (cond_string)
13809             b->cond_string = cond_string;
13810           b->thread = thread;
13811           b->task = task;
13812           if (extra_string)
13813             b->extra_string = extra_string;
13814           b->condition_not_parsed = 0;
13815         }
13816
13817       if (b->type == bp_static_tracepoint && !strace_marker_p (b))
13818         sals.sals[0] = update_static_tracepoint (b, sals.sals[0]);
13819
13820       *found = 1;
13821     }
13822   else
13823     *found = 0;
13824
13825   return sals;
13826 }
13827
13828 /* The default re_set method, for typical hardware or software
13829    breakpoints.  Reevaluate the breakpoint and recreate its
13830    locations.  */
13831
13832 static void
13833 breakpoint_re_set_default (struct breakpoint *b)
13834 {
13835   int found;
13836   struct symtabs_and_lines sals, sals_end;
13837   struct symtabs_and_lines expanded = {0};
13838   struct symtabs_and_lines expanded_end = {0};
13839
13840   sals = addr_string_to_sals (b, b->addr_string, &found);
13841   if (found)
13842     {
13843       make_cleanup (xfree, sals.sals);
13844       expanded = sals;
13845     }
13846
13847   if (b->addr_string_range_end)
13848     {
13849       sals_end = addr_string_to_sals (b, b->addr_string_range_end, &found);
13850       if (found)
13851         {
13852           make_cleanup (xfree, sals_end.sals);
13853           expanded_end = sals_end;
13854         }
13855     }
13856
13857   update_breakpoint_locations (b, expanded, expanded_end);
13858 }
13859
13860 /* Default method for creating SALs from an address string.  It basically
13861    calls parse_breakpoint_sals.  Return 1 for success, zero for failure.  */
13862
13863 static void
13864 create_sals_from_address_default (char **arg,
13865                                   struct linespec_result *canonical,
13866                                   enum bptype type_wanted,
13867                                   char *addr_start, char **copy_arg)
13868 {
13869   parse_breakpoint_sals (arg, canonical);
13870 }
13871
13872 /* Call create_breakpoints_sal for the given arguments.  This is the default
13873    function for the `create_breakpoints_sal' method of
13874    breakpoint_ops.  */
13875
13876 static void
13877 create_breakpoints_sal_default (struct gdbarch *gdbarch,
13878                                 struct linespec_result *canonical,
13879                                 struct linespec_sals *lsal,
13880                                 char *cond_string,
13881                                 char *extra_string,
13882                                 enum bptype type_wanted,
13883                                 enum bpdisp disposition,
13884                                 int thread,
13885                                 int task, int ignore_count,
13886                                 const struct breakpoint_ops *ops,
13887                                 int from_tty, int enabled,
13888                                 int internal, unsigned flags)
13889 {
13890   create_breakpoints_sal (gdbarch, canonical, cond_string,
13891                           extra_string,
13892                           type_wanted, disposition,
13893                           thread, task, ignore_count, ops, from_tty,
13894                           enabled, internal, flags);
13895 }
13896
13897 /* Decode the line represented by S by calling decode_line_full.  This is the
13898    default function for the `decode_linespec' method of breakpoint_ops.  */
13899
13900 static void
13901 decode_linespec_default (struct breakpoint *b, char **s,
13902                          struct symtabs_and_lines *sals)
13903 {
13904   struct linespec_result canonical;
13905
13906   init_linespec_result (&canonical);
13907   decode_line_full (s, DECODE_LINE_FUNFIRSTLINE,
13908                     (struct symtab *) NULL, 0,
13909                     &canonical, multiple_symbols_all,
13910                     b->filter);
13911
13912   /* We should get 0 or 1 resulting SALs.  */
13913   gdb_assert (VEC_length (linespec_sals, canonical.sals) < 2);
13914
13915   if (VEC_length (linespec_sals, canonical.sals) > 0)
13916     {
13917       struct linespec_sals *lsal;
13918
13919       lsal = VEC_index (linespec_sals, canonical.sals, 0);
13920       *sals = lsal->sals;
13921       /* Arrange it so the destructor does not free the
13922          contents.  */
13923       lsal->sals.sals = NULL;
13924     }
13925
13926   destroy_linespec_result (&canonical);
13927 }
13928
13929 /* Prepare the global context for a re-set of breakpoint B.  */
13930
13931 static struct cleanup *
13932 prepare_re_set_context (struct breakpoint *b)
13933 {
13934   struct cleanup *cleanups;
13935
13936   input_radix = b->input_radix;
13937   cleanups = save_current_space_and_thread ();
13938   if (b->pspace != NULL)
13939     switch_to_program_space_and_thread (b->pspace);
13940   set_language (b->language);
13941
13942   return cleanups;
13943 }
13944
13945 /* Reset a breakpoint given it's struct breakpoint * BINT.
13946    The value we return ends up being the return value from catch_errors.
13947    Unused in this case.  */
13948
13949 static int
13950 breakpoint_re_set_one (void *bint)
13951 {
13952   /* Get past catch_errs.  */
13953   struct breakpoint *b = (struct breakpoint *) bint;
13954   struct cleanup *cleanups;
13955
13956   cleanups = prepare_re_set_context (b);
13957   b->ops->re_set (b);
13958   do_cleanups (cleanups);
13959   return 0;
13960 }
13961
13962 /* Re-set all breakpoints after symbols have been re-loaded.  */
13963 void
13964 breakpoint_re_set (void)
13965 {
13966   struct breakpoint *b, *b_tmp;
13967   enum language save_language;
13968   int save_input_radix;
13969   struct cleanup *old_chain;
13970
13971   save_language = current_language->la_language;
13972   save_input_radix = input_radix;
13973   old_chain = save_current_program_space ();
13974
13975   ALL_BREAKPOINTS_SAFE (b, b_tmp)
13976   {
13977     /* Format possible error msg.  */
13978     char *message = xstrprintf ("Error in re-setting breakpoint %d: ",
13979                                 b->number);
13980     struct cleanup *cleanups = make_cleanup (xfree, message);
13981     catch_errors (breakpoint_re_set_one, b, message, RETURN_MASK_ALL);
13982     do_cleanups (cleanups);
13983   }
13984   set_language (save_language);
13985   input_radix = save_input_radix;
13986
13987   jit_breakpoint_re_set ();
13988
13989   do_cleanups (old_chain);
13990
13991   create_overlay_event_breakpoint ();
13992   create_longjmp_master_breakpoint ();
13993   create_std_terminate_master_breakpoint ();
13994   create_exception_master_breakpoint ();
13995
13996   /* While we're at it, reset the skip list too.  */
13997   skip_re_set ();
13998 }
13999 \f
14000 /* Reset the thread number of this breakpoint:
14001
14002    - If the breakpoint is for all threads, leave it as-is.
14003    - Else, reset it to the current thread for inferior_ptid.  */
14004 void
14005 breakpoint_re_set_thread (struct breakpoint *b)
14006 {
14007   if (b->thread != -1)
14008     {
14009       if (in_thread_list (inferior_ptid))
14010         b->thread = pid_to_thread_id (inferior_ptid);
14011
14012       /* We're being called after following a fork.  The new fork is
14013          selected as current, and unless this was a vfork will have a
14014          different program space from the original thread.  Reset that
14015          as well.  */
14016       b->loc->pspace = current_program_space;
14017     }
14018 }
14019
14020 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
14021    If from_tty is nonzero, it prints a message to that effect,
14022    which ends with a period (no newline).  */
14023
14024 void
14025 set_ignore_count (int bptnum, int count, int from_tty)
14026 {
14027   struct breakpoint *b;
14028
14029   if (count < 0)
14030     count = 0;
14031
14032   ALL_BREAKPOINTS (b)
14033     if (b->number == bptnum)
14034     {
14035       if (is_tracepoint (b))
14036         {
14037           if (from_tty && count != 0)
14038             printf_filtered (_("Ignore count ignored for tracepoint %d."),
14039                              bptnum);
14040           return;
14041         }
14042       
14043       b->ignore_count = count;
14044       if (from_tty)
14045         {
14046           if (count == 0)
14047             printf_filtered (_("Will stop next time "
14048                                "breakpoint %d is reached."),
14049                              bptnum);
14050           else if (count == 1)
14051             printf_filtered (_("Will ignore next crossing of breakpoint %d."),
14052                              bptnum);
14053           else
14054             printf_filtered (_("Will ignore next %d "
14055                                "crossings of breakpoint %d."),
14056                              count, bptnum);
14057         }
14058       breakpoints_changed ();
14059       observer_notify_breakpoint_modified (b);
14060       return;
14061     }
14062
14063   error (_("No breakpoint number %d."), bptnum);
14064 }
14065
14066 /* Command to set ignore-count of breakpoint N to COUNT.  */
14067
14068 static void
14069 ignore_command (char *args, int from_tty)
14070 {
14071   char *p = args;
14072   int num;
14073
14074   if (p == 0)
14075     error_no_arg (_("a breakpoint number"));
14076
14077   num = get_number (&p);
14078   if (num == 0)
14079     error (_("bad breakpoint number: '%s'"), args);
14080   if (*p == 0)
14081     error (_("Second argument (specified ignore-count) is missing."));
14082
14083   set_ignore_count (num,
14084                     longest_to_int (value_as_long (parse_and_eval (p))),
14085                     from_tty);
14086   if (from_tty)
14087     printf_filtered ("\n");
14088 }
14089 \f
14090 /* Call FUNCTION on each of the breakpoints
14091    whose numbers are given in ARGS.  */
14092
14093 static void
14094 map_breakpoint_numbers (char *args, void (*function) (struct breakpoint *,
14095                                                       void *),
14096                         void *data)
14097 {
14098   int num;
14099   struct breakpoint *b, *tmp;
14100   int match;
14101   struct get_number_or_range_state state;
14102
14103   if (args == 0)
14104     error_no_arg (_("one or more breakpoint numbers"));
14105
14106   init_number_or_range (&state, args);
14107
14108   while (!state.finished)
14109     {
14110       char *p = state.string;
14111
14112       match = 0;
14113
14114       num = get_number_or_range (&state);
14115       if (num == 0)
14116         {
14117           warning (_("bad breakpoint number at or near '%s'"), p);
14118         }
14119       else
14120         {
14121           ALL_BREAKPOINTS_SAFE (b, tmp)
14122             if (b->number == num)
14123               {
14124                 match = 1;
14125                 function (b, data);
14126                 break;
14127               }
14128           if (match == 0)
14129             printf_unfiltered (_("No breakpoint number %d.\n"), num);
14130         }
14131     }
14132 }
14133
14134 static struct bp_location *
14135 find_location_by_number (char *number)
14136 {
14137   char *dot = strchr (number, '.');
14138   char *p1;
14139   int bp_num;
14140   int loc_num;
14141   struct breakpoint *b;
14142   struct bp_location *loc;  
14143
14144   *dot = '\0';
14145
14146   p1 = number;
14147   bp_num = get_number (&p1);
14148   if (bp_num == 0)
14149     error (_("Bad breakpoint number '%s'"), number);
14150
14151   ALL_BREAKPOINTS (b)
14152     if (b->number == bp_num)
14153       {
14154         break;
14155       }
14156
14157   if (!b || b->number != bp_num)
14158     error (_("Bad breakpoint number '%s'"), number);
14159   
14160   p1 = dot+1;
14161   loc_num = get_number (&p1);
14162   if (loc_num == 0)
14163     error (_("Bad breakpoint location number '%s'"), number);
14164
14165   --loc_num;
14166   loc = b->loc;
14167   for (;loc_num && loc; --loc_num, loc = loc->next)
14168     ;
14169   if (!loc)
14170     error (_("Bad breakpoint location number '%s'"), dot+1);
14171     
14172   return loc;  
14173 }
14174
14175
14176 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
14177    If from_tty is nonzero, it prints a message to that effect,
14178    which ends with a period (no newline).  */
14179
14180 void
14181 disable_breakpoint (struct breakpoint *bpt)
14182 {
14183   /* Never disable a watchpoint scope breakpoint; we want to
14184      hit them when we leave scope so we can delete both the
14185      watchpoint and its scope breakpoint at that time.  */
14186   if (bpt->type == bp_watchpoint_scope)
14187     return;
14188
14189   /* You can't disable permanent breakpoints.  */
14190   if (bpt->enable_state == bp_permanent)
14191     return;
14192
14193   bpt->enable_state = bp_disabled;
14194
14195   /* Mark breakpoint locations modified.  */
14196   mark_breakpoint_modified (bpt);
14197
14198   if (target_supports_enable_disable_tracepoint ()
14199       && current_trace_status ()->running && is_tracepoint (bpt))
14200     {
14201       struct bp_location *location;
14202      
14203       for (location = bpt->loc; location; location = location->next)
14204         target_disable_tracepoint (location);
14205     }
14206
14207   update_global_location_list (0);
14208
14209   observer_notify_breakpoint_modified (bpt);
14210 }
14211
14212 /* A callback for iterate_over_related_breakpoints.  */
14213
14214 static void
14215 do_disable_breakpoint (struct breakpoint *b, void *ignore)
14216 {
14217   disable_breakpoint (b);
14218 }
14219
14220 /* A callback for map_breakpoint_numbers that calls
14221    disable_breakpoint.  */
14222
14223 static void
14224 do_map_disable_breakpoint (struct breakpoint *b, void *ignore)
14225 {
14226   iterate_over_related_breakpoints (b, do_disable_breakpoint, NULL);
14227 }
14228
14229 static void
14230 disable_command (char *args, int from_tty)
14231 {
14232   if (args == 0)
14233     {
14234       struct breakpoint *bpt;
14235
14236       ALL_BREAKPOINTS (bpt)
14237         if (user_breakpoint_p (bpt))
14238           disable_breakpoint (bpt);
14239     }
14240   else if (strchr (args, '.'))
14241     {
14242       struct bp_location *loc = find_location_by_number (args);
14243       if (loc)
14244         {
14245           if (loc->enabled)
14246             {
14247               loc->enabled = 0;
14248               mark_breakpoint_location_modified (loc);
14249             }
14250           if (target_supports_enable_disable_tracepoint ()
14251               && current_trace_status ()->running && loc->owner
14252               && is_tracepoint (loc->owner))
14253             target_disable_tracepoint (loc);
14254         }
14255       update_global_location_list (0);
14256     }
14257   else
14258     map_breakpoint_numbers (args, do_map_disable_breakpoint, NULL);
14259 }
14260
14261 static void
14262 enable_breakpoint_disp (struct breakpoint *bpt, enum bpdisp disposition,
14263                         int count)
14264 {
14265   int target_resources_ok;
14266
14267   if (bpt->type == bp_hardware_breakpoint)
14268     {
14269       int i;
14270       i = hw_breakpoint_used_count ();
14271       target_resources_ok = 
14272         target_can_use_hardware_watchpoint (bp_hardware_breakpoint, 
14273                                             i + 1, 0);
14274       if (target_resources_ok == 0)
14275         error (_("No hardware breakpoint support in the target."));
14276       else if (target_resources_ok < 0)
14277         error (_("Hardware breakpoints used exceeds limit."));
14278     }
14279
14280   if (is_watchpoint (bpt))
14281     {
14282       /* Initialize it just to avoid a GCC false warning.  */
14283       enum enable_state orig_enable_state = 0;
14284       volatile struct gdb_exception e;
14285
14286       TRY_CATCH (e, RETURN_MASK_ALL)
14287         {
14288           struct watchpoint *w = (struct watchpoint *) bpt;
14289
14290           orig_enable_state = bpt->enable_state;
14291           bpt->enable_state = bp_enabled;
14292           update_watchpoint (w, 1 /* reparse */);
14293         }
14294       if (e.reason < 0)
14295         {
14296           bpt->enable_state = orig_enable_state;
14297           exception_fprintf (gdb_stderr, e, _("Cannot enable watchpoint %d: "),
14298                              bpt->number);
14299           return;
14300         }
14301     }
14302
14303   if (bpt->enable_state != bp_permanent)
14304     bpt->enable_state = bp_enabled;
14305
14306   bpt->enable_state = bp_enabled;
14307
14308   /* Mark breakpoint locations modified.  */
14309   mark_breakpoint_modified (bpt);
14310
14311   if (target_supports_enable_disable_tracepoint ()
14312       && current_trace_status ()->running && is_tracepoint (bpt))
14313     {
14314       struct bp_location *location;
14315
14316       for (location = bpt->loc; location; location = location->next)
14317         target_enable_tracepoint (location);
14318     }
14319
14320   bpt->disposition = disposition;
14321   bpt->enable_count = count;
14322   update_global_location_list (1);
14323   breakpoints_changed ();
14324   
14325   observer_notify_breakpoint_modified (bpt);
14326 }
14327
14328
14329 void
14330 enable_breakpoint (struct breakpoint *bpt)
14331 {
14332   enable_breakpoint_disp (bpt, bpt->disposition, 0);
14333 }
14334
14335 static void
14336 do_enable_breakpoint (struct breakpoint *bpt, void *arg)
14337 {
14338   enable_breakpoint (bpt);
14339 }
14340
14341 /* A callback for map_breakpoint_numbers that calls
14342    enable_breakpoint.  */
14343
14344 static void
14345 do_map_enable_breakpoint (struct breakpoint *b, void *ignore)
14346 {
14347   iterate_over_related_breakpoints (b, do_enable_breakpoint, NULL);
14348 }
14349
14350 /* The enable command enables the specified breakpoints (or all defined
14351    breakpoints) so they once again become (or continue to be) effective
14352    in stopping the inferior.  */
14353
14354 static void
14355 enable_command (char *args, int from_tty)
14356 {
14357   if (args == 0)
14358     {
14359       struct breakpoint *bpt;
14360
14361       ALL_BREAKPOINTS (bpt)
14362         if (user_breakpoint_p (bpt))
14363           enable_breakpoint (bpt);
14364     }
14365   else if (strchr (args, '.'))
14366     {
14367       struct bp_location *loc = find_location_by_number (args);
14368       if (loc)
14369         {
14370           if (!loc->enabled)
14371             {
14372               loc->enabled = 1;
14373               mark_breakpoint_location_modified (loc);
14374             }
14375           if (target_supports_enable_disable_tracepoint ()
14376               && current_trace_status ()->running && loc->owner
14377               && is_tracepoint (loc->owner))
14378             target_enable_tracepoint (loc);
14379         }
14380       update_global_location_list (1);
14381     }
14382   else
14383     map_breakpoint_numbers (args, do_map_enable_breakpoint, NULL);
14384 }
14385
14386 /* This struct packages up disposition data for application to multiple
14387    breakpoints.  */
14388
14389 struct disp_data
14390 {
14391   enum bpdisp disp;
14392   int count;
14393 };
14394
14395 static void
14396 do_enable_breakpoint_disp (struct breakpoint *bpt, void *arg)
14397 {
14398   struct disp_data disp_data = *(struct disp_data *) arg;
14399
14400   enable_breakpoint_disp (bpt, disp_data.disp, disp_data.count);
14401 }
14402
14403 static void
14404 do_map_enable_once_breakpoint (struct breakpoint *bpt, void *ignore)
14405 {
14406   struct disp_data disp = { disp_disable, 1 };
14407
14408   iterate_over_related_breakpoints (bpt, do_enable_breakpoint_disp, &disp);
14409 }
14410
14411 static void
14412 enable_once_command (char *args, int from_tty)
14413 {
14414   map_breakpoint_numbers (args, do_map_enable_once_breakpoint, NULL);
14415 }
14416
14417 static void
14418 do_map_enable_count_breakpoint (struct breakpoint *bpt, void *countptr)
14419 {
14420   struct disp_data disp = { disp_disable, *(int *) countptr };
14421
14422   iterate_over_related_breakpoints (bpt, do_enable_breakpoint_disp, &disp);
14423 }
14424
14425 static void
14426 enable_count_command (char *args, int from_tty)
14427 {
14428   int count = get_number (&args);
14429
14430   map_breakpoint_numbers (args, do_map_enable_count_breakpoint, &count);
14431 }
14432
14433 static void
14434 do_map_enable_delete_breakpoint (struct breakpoint *bpt, void *ignore)
14435 {
14436   struct disp_data disp = { disp_del, 1 };
14437
14438   iterate_over_related_breakpoints (bpt, do_enable_breakpoint_disp, &disp);
14439 }
14440
14441 static void
14442 enable_delete_command (char *args, int from_tty)
14443 {
14444   map_breakpoint_numbers (args, do_map_enable_delete_breakpoint, NULL);
14445 }
14446 \f
14447 static void
14448 set_breakpoint_cmd (char *args, int from_tty)
14449 {
14450 }
14451
14452 static void
14453 show_breakpoint_cmd (char *args, int from_tty)
14454 {
14455 }
14456
14457 /* Invalidate last known value of any hardware watchpoint if
14458    the memory which that value represents has been written to by
14459    GDB itself.  */
14460
14461 static void
14462 invalidate_bp_value_on_memory_change (CORE_ADDR addr, int len,
14463                                       const bfd_byte *data)
14464 {
14465   struct breakpoint *bp;
14466
14467   ALL_BREAKPOINTS (bp)
14468     if (bp->enable_state == bp_enabled
14469         && bp->type == bp_hardware_watchpoint)
14470       {
14471         struct watchpoint *wp = (struct watchpoint *) bp;
14472
14473         if (wp->val_valid && wp->val)
14474           {
14475             struct bp_location *loc;
14476
14477             for (loc = bp->loc; loc != NULL; loc = loc->next)
14478               if (loc->loc_type == bp_loc_hardware_watchpoint
14479                   && loc->address + loc->length > addr
14480                   && addr + len > loc->address)
14481                 {
14482                   value_free (wp->val);
14483                   wp->val = NULL;
14484                   wp->val_valid = 0;
14485                 }
14486           }
14487       }
14488 }
14489
14490 /* Create and insert a raw software breakpoint at PC.  Return an
14491    identifier, which should be used to remove the breakpoint later.
14492    In general, places which call this should be using something on the
14493    breakpoint chain instead; this function should be eliminated
14494    someday.  */
14495
14496 void *
14497 deprecated_insert_raw_breakpoint (struct gdbarch *gdbarch,
14498                                   struct address_space *aspace, CORE_ADDR pc)
14499 {
14500   struct bp_target_info *bp_tgt;
14501
14502   bp_tgt = XZALLOC (struct bp_target_info);
14503
14504   bp_tgt->placed_address_space = aspace;
14505   bp_tgt->placed_address = pc;
14506
14507   if (target_insert_breakpoint (gdbarch, bp_tgt) != 0)
14508     {
14509       /* Could not insert the breakpoint.  */
14510       xfree (bp_tgt);
14511       return NULL;
14512     }
14513
14514   return bp_tgt;
14515 }
14516
14517 /* Remove a breakpoint BP inserted by
14518    deprecated_insert_raw_breakpoint.  */
14519
14520 int
14521 deprecated_remove_raw_breakpoint (struct gdbarch *gdbarch, void *bp)
14522 {
14523   struct bp_target_info *bp_tgt = bp;
14524   int ret;
14525
14526   ret = target_remove_breakpoint (gdbarch, bp_tgt);
14527   xfree (bp_tgt);
14528
14529   return ret;
14530 }
14531
14532 /* One (or perhaps two) breakpoints used for software single
14533    stepping.  */
14534
14535 static void *single_step_breakpoints[2];
14536 static struct gdbarch *single_step_gdbarch[2];
14537
14538 /* Create and insert a breakpoint for software single step.  */
14539
14540 void
14541 insert_single_step_breakpoint (struct gdbarch *gdbarch,
14542                                struct address_space *aspace, 
14543                                CORE_ADDR next_pc)
14544 {
14545   void **bpt_p;
14546
14547   if (single_step_breakpoints[0] == NULL)
14548     {
14549       bpt_p = &single_step_breakpoints[0];
14550       single_step_gdbarch[0] = gdbarch;
14551     }
14552   else
14553     {
14554       gdb_assert (single_step_breakpoints[1] == NULL);
14555       bpt_p = &single_step_breakpoints[1];
14556       single_step_gdbarch[1] = gdbarch;
14557     }
14558
14559   /* NOTE drow/2006-04-11: A future improvement to this function would
14560      be to only create the breakpoints once, and actually put them on
14561      the breakpoint chain.  That would let us use set_raw_breakpoint.
14562      We could adjust the addresses each time they were needed.  Doing
14563      this requires corresponding changes elsewhere where single step
14564      breakpoints are handled, however.  So, for now, we use this.  */
14565
14566   *bpt_p = deprecated_insert_raw_breakpoint (gdbarch, aspace, next_pc);
14567   if (*bpt_p == NULL)
14568     error (_("Could not insert single-step breakpoint at %s"),
14569              paddress (gdbarch, next_pc));
14570 }
14571
14572 /* Check if the breakpoints used for software single stepping
14573    were inserted or not.  */
14574
14575 int
14576 single_step_breakpoints_inserted (void)
14577 {
14578   return (single_step_breakpoints[0] != NULL
14579           || single_step_breakpoints[1] != NULL);
14580 }
14581
14582 /* Remove and delete any breakpoints used for software single step.  */
14583
14584 void
14585 remove_single_step_breakpoints (void)
14586 {
14587   gdb_assert (single_step_breakpoints[0] != NULL);
14588
14589   /* See insert_single_step_breakpoint for more about this deprecated
14590      call.  */
14591   deprecated_remove_raw_breakpoint (single_step_gdbarch[0],
14592                                     single_step_breakpoints[0]);
14593   single_step_gdbarch[0] = NULL;
14594   single_step_breakpoints[0] = NULL;
14595
14596   if (single_step_breakpoints[1] != NULL)
14597     {
14598       deprecated_remove_raw_breakpoint (single_step_gdbarch[1],
14599                                         single_step_breakpoints[1]);
14600       single_step_gdbarch[1] = NULL;
14601       single_step_breakpoints[1] = NULL;
14602     }
14603 }
14604
14605 /* Delete software single step breakpoints without removing them from
14606    the inferior.  This is intended to be used if the inferior's address
14607    space where they were inserted is already gone, e.g. after exit or
14608    exec.  */
14609
14610 void
14611 cancel_single_step_breakpoints (void)
14612 {
14613   int i;
14614
14615   for (i = 0; i < 2; i++)
14616     if (single_step_breakpoints[i])
14617       {
14618         xfree (single_step_breakpoints[i]);
14619         single_step_breakpoints[i] = NULL;
14620         single_step_gdbarch[i] = NULL;
14621       }
14622 }
14623
14624 /* Detach software single-step breakpoints from INFERIOR_PTID without
14625    removing them.  */
14626
14627 static void
14628 detach_single_step_breakpoints (void)
14629 {
14630   int i;
14631
14632   for (i = 0; i < 2; i++)
14633     if (single_step_breakpoints[i])
14634       target_remove_breakpoint (single_step_gdbarch[i],
14635                                 single_step_breakpoints[i]);
14636 }
14637
14638 /* Check whether a software single-step breakpoint is inserted at
14639    PC.  */
14640
14641 static int
14642 single_step_breakpoint_inserted_here_p (struct address_space *aspace, 
14643                                         CORE_ADDR pc)
14644 {
14645   int i;
14646
14647   for (i = 0; i < 2; i++)
14648     {
14649       struct bp_target_info *bp_tgt = single_step_breakpoints[i];
14650       if (bp_tgt
14651           && breakpoint_address_match (bp_tgt->placed_address_space,
14652                                        bp_tgt->placed_address,
14653                                        aspace, pc))
14654         return 1;
14655     }
14656
14657   return 0;
14658 }
14659
14660 /* Returns 0 if 'bp' is NOT a syscall catchpoint,
14661    non-zero otherwise.  */
14662 static int
14663 is_syscall_catchpoint_enabled (struct breakpoint *bp)
14664 {
14665   if (syscall_catchpoint_p (bp)
14666       && bp->enable_state != bp_disabled
14667       && bp->enable_state != bp_call_disabled)
14668     return 1;
14669   else
14670     return 0;
14671 }
14672
14673 int
14674 catch_syscall_enabled (void)
14675 {
14676   struct catch_syscall_inferior_data *inf_data
14677     = get_catch_syscall_inferior_data (current_inferior ());
14678
14679   return inf_data->total_syscalls_count != 0;
14680 }
14681
14682 int
14683 catching_syscall_number (int syscall_number)
14684 {
14685   struct breakpoint *bp;
14686
14687   ALL_BREAKPOINTS (bp)
14688     if (is_syscall_catchpoint_enabled (bp))
14689       {
14690         struct syscall_catchpoint *c = (struct syscall_catchpoint *) bp;
14691
14692         if (c->syscalls_to_be_caught)
14693           {
14694             int i, iter;
14695             for (i = 0;
14696                  VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
14697                  i++)
14698               if (syscall_number == iter)
14699                 return 1;
14700           }
14701         else
14702           return 1;
14703       }
14704
14705   return 0;
14706 }
14707
14708 /* Complete syscall names.  Used by "catch syscall".  */
14709 static VEC (char_ptr) *
14710 catch_syscall_completer (struct cmd_list_element *cmd,
14711                          char *text, char *word)
14712 {
14713   const char **list = get_syscall_names ();
14714   VEC (char_ptr) *retlist
14715     = (list == NULL) ? NULL : complete_on_enum (list, text, word);
14716
14717   xfree (list);
14718   return retlist;
14719 }
14720
14721 /* Tracepoint-specific operations.  */
14722
14723 /* Set tracepoint count to NUM.  */
14724 static void
14725 set_tracepoint_count (int num)
14726 {
14727   tracepoint_count = num;
14728   set_internalvar_integer (lookup_internalvar ("tpnum"), num);
14729 }
14730
14731 static void
14732 trace_command (char *arg, int from_tty)
14733 {
14734   struct breakpoint_ops *ops;
14735   const char *arg_cp = arg;
14736
14737   if (arg && probe_linespec_to_ops (&arg_cp))
14738     ops = &tracepoint_probe_breakpoint_ops;
14739   else
14740     ops = &tracepoint_breakpoint_ops;
14741
14742   if (create_breakpoint (get_current_arch (),
14743                          arg,
14744                          NULL, 0, NULL, 1 /* parse arg */,
14745                          0 /* tempflag */,
14746                          bp_tracepoint /* type_wanted */,
14747                          0 /* Ignore count */,
14748                          pending_break_support,
14749                          ops,
14750                          from_tty,
14751                          1 /* enabled */,
14752                          0 /* internal */, 0))
14753     set_tracepoint_count (breakpoint_count);
14754 }
14755
14756 static void
14757 ftrace_command (char *arg, int from_tty)
14758 {
14759   if (create_breakpoint (get_current_arch (),
14760                          arg,
14761                          NULL, 0, NULL, 1 /* parse arg */,
14762                          0 /* tempflag */,
14763                          bp_fast_tracepoint /* type_wanted */,
14764                          0 /* Ignore count */,
14765                          pending_break_support,
14766                          &tracepoint_breakpoint_ops,
14767                          from_tty,
14768                          1 /* enabled */,
14769                          0 /* internal */, 0))
14770     set_tracepoint_count (breakpoint_count);
14771 }
14772
14773 /* strace command implementation.  Creates a static tracepoint.  */
14774
14775 static void
14776 strace_command (char *arg, int from_tty)
14777 {
14778   struct breakpoint_ops *ops;
14779
14780   /* Decide if we are dealing with a static tracepoint marker (`-m'),
14781      or with a normal static tracepoint.  */
14782   if (arg && strncmp (arg, "-m", 2) == 0 && isspace (arg[2]))
14783     ops = &strace_marker_breakpoint_ops;
14784   else
14785     ops = &tracepoint_breakpoint_ops;
14786
14787   if (create_breakpoint (get_current_arch (),
14788                          arg,
14789                          NULL, 0, NULL, 1 /* parse arg */,
14790                          0 /* tempflag */,
14791                          bp_static_tracepoint /* type_wanted */,
14792                          0 /* Ignore count */,
14793                          pending_break_support,
14794                          ops,
14795                          from_tty,
14796                          1 /* enabled */,
14797                          0 /* internal */, 0))
14798     set_tracepoint_count (breakpoint_count);
14799 }
14800
14801 /* Set up a fake reader function that gets command lines from a linked
14802    list that was acquired during tracepoint uploading.  */
14803
14804 static struct uploaded_tp *this_utp;
14805 static int next_cmd;
14806
14807 static char *
14808 read_uploaded_action (void)
14809 {
14810   char *rslt;
14811
14812   VEC_iterate (char_ptr, this_utp->cmd_strings, next_cmd, rslt);
14813
14814   next_cmd++;
14815
14816   return rslt;
14817 }
14818
14819 /* Given information about a tracepoint as recorded on a target (which
14820    can be either a live system or a trace file), attempt to create an
14821    equivalent GDB tracepoint.  This is not a reliable process, since
14822    the target does not necessarily have all the information used when
14823    the tracepoint was originally defined.  */
14824   
14825 struct tracepoint *
14826 create_tracepoint_from_upload (struct uploaded_tp *utp)
14827 {
14828   char *addr_str, small_buf[100];
14829   struct tracepoint *tp;
14830
14831   if (utp->at_string)
14832     addr_str = utp->at_string;
14833   else
14834     {
14835       /* In the absence of a source location, fall back to raw
14836          address.  Since there is no way to confirm that the address
14837          means the same thing as when the trace was started, warn the
14838          user.  */
14839       warning (_("Uploaded tracepoint %d has no "
14840                  "source location, using raw address"),
14841                utp->number);
14842       sprintf (small_buf, "*%s", hex_string (utp->addr));
14843       addr_str = small_buf;
14844     }
14845
14846   /* There's not much we can do with a sequence of bytecodes.  */
14847   if (utp->cond && !utp->cond_string)
14848     warning (_("Uploaded tracepoint %d condition "
14849                "has no source form, ignoring it"),
14850              utp->number);
14851
14852   if (!create_breakpoint (get_current_arch (),
14853                           addr_str,
14854                           utp->cond_string, -1, NULL,
14855                           0 /* parse cond/thread */,
14856                           0 /* tempflag */,
14857                           utp->type /* type_wanted */,
14858                           0 /* Ignore count */,
14859                           pending_break_support,
14860                           &tracepoint_breakpoint_ops,
14861                           0 /* from_tty */,
14862                           utp->enabled /* enabled */,
14863                           0 /* internal */,
14864                           CREATE_BREAKPOINT_FLAGS_INSERTED))
14865     return NULL;
14866
14867   set_tracepoint_count (breakpoint_count);
14868   
14869   /* Get the tracepoint we just created.  */
14870   tp = get_tracepoint (tracepoint_count);
14871   gdb_assert (tp != NULL);
14872
14873   if (utp->pass > 0)
14874     {
14875       sprintf (small_buf, "%d %d", utp->pass, tp->base.number);
14876
14877       trace_pass_command (small_buf, 0);
14878     }
14879
14880   /* If we have uploaded versions of the original commands, set up a
14881      special-purpose "reader" function and call the usual command line
14882      reader, then pass the result to the breakpoint command-setting
14883      function.  */
14884   if (!VEC_empty (char_ptr, utp->cmd_strings))
14885     {
14886       struct command_line *cmd_list;
14887
14888       this_utp = utp;
14889       next_cmd = 0;
14890
14891       cmd_list = read_command_lines_1 (read_uploaded_action, 1, NULL, NULL);
14892
14893       breakpoint_set_commands (&tp->base, cmd_list);
14894     }
14895   else if (!VEC_empty (char_ptr, utp->actions)
14896            || !VEC_empty (char_ptr, utp->step_actions))
14897     warning (_("Uploaded tracepoint %d actions "
14898                "have no source form, ignoring them"),
14899              utp->number);
14900
14901   /* Copy any status information that might be available.  */
14902   tp->base.hit_count = utp->hit_count;
14903   tp->traceframe_usage = utp->traceframe_usage;
14904
14905   return tp;
14906 }
14907   
14908 /* Print information on tracepoint number TPNUM_EXP, or all if
14909    omitted.  */
14910
14911 static void
14912 tracepoints_info (char *args, int from_tty)
14913 {
14914   struct ui_out *uiout = current_uiout;
14915   int num_printed;
14916
14917   num_printed = breakpoint_1 (args, 0, is_tracepoint);
14918
14919   if (num_printed == 0)
14920     {
14921       if (args == NULL || *args == '\0')
14922         ui_out_message (uiout, 0, "No tracepoints.\n");
14923       else
14924         ui_out_message (uiout, 0, "No tracepoint matching '%s'.\n", args);
14925     }
14926
14927   default_collect_info ();
14928 }
14929
14930 /* The 'enable trace' command enables tracepoints.
14931    Not supported by all targets.  */
14932 static void
14933 enable_trace_command (char *args, int from_tty)
14934 {
14935   enable_command (args, from_tty);
14936 }
14937
14938 /* The 'disable trace' command disables tracepoints.
14939    Not supported by all targets.  */
14940 static void
14941 disable_trace_command (char *args, int from_tty)
14942 {
14943   disable_command (args, from_tty);
14944 }
14945
14946 /* Remove a tracepoint (or all if no argument).  */
14947 static void
14948 delete_trace_command (char *arg, int from_tty)
14949 {
14950   struct breakpoint *b, *b_tmp;
14951
14952   dont_repeat ();
14953
14954   if (arg == 0)
14955     {
14956       int breaks_to_delete = 0;
14957
14958       /* Delete all breakpoints if no argument.
14959          Do not delete internal or call-dummy breakpoints, these
14960          have to be deleted with an explicit breakpoint number 
14961          argument.  */
14962       ALL_TRACEPOINTS (b)
14963         if (is_tracepoint (b) && user_breakpoint_p (b))
14964           {
14965             breaks_to_delete = 1;
14966             break;
14967           }
14968
14969       /* Ask user only if there are some breakpoints to delete.  */
14970       if (!from_tty
14971           || (breaks_to_delete && query (_("Delete all tracepoints? "))))
14972         {
14973           ALL_BREAKPOINTS_SAFE (b, b_tmp)
14974             if (is_tracepoint (b) && user_breakpoint_p (b))
14975               delete_breakpoint (b);
14976         }
14977     }
14978   else
14979     map_breakpoint_numbers (arg, do_map_delete_breakpoint, NULL);
14980 }
14981
14982 /* Helper function for trace_pass_command.  */
14983
14984 static void
14985 trace_pass_set_count (struct tracepoint *tp, int count, int from_tty)
14986 {
14987   tp->pass_count = count;
14988   observer_notify_tracepoint_modified (tp->base.number);
14989   if (from_tty)
14990     printf_filtered (_("Setting tracepoint %d's passcount to %d\n"),
14991                      tp->base.number, count);
14992 }
14993
14994 /* Set passcount for tracepoint.
14995
14996    First command argument is passcount, second is tracepoint number.
14997    If tracepoint number omitted, apply to most recently defined.
14998    Also accepts special argument "all".  */
14999
15000 static void
15001 trace_pass_command (char *args, int from_tty)
15002 {
15003   struct tracepoint *t1;
15004   unsigned int count;
15005
15006   if (args == 0 || *args == 0)
15007     error (_("passcount command requires an "
15008              "argument (count + optional TP num)"));
15009
15010   count = strtoul (args, &args, 10);    /* Count comes first, then TP num.  */
15011
15012   while (*args && isspace ((int) *args))
15013     args++;
15014
15015   if (*args && strncasecmp (args, "all", 3) == 0)
15016     {
15017       struct breakpoint *b;
15018
15019       args += 3;                        /* Skip special argument "all".  */
15020       if (*args)
15021         error (_("Junk at end of arguments."));
15022
15023       ALL_TRACEPOINTS (b)
15024       {
15025         t1 = (struct tracepoint *) b;
15026         trace_pass_set_count (t1, count, from_tty);
15027       }
15028     }
15029   else if (*args == '\0')
15030     {
15031       t1 = get_tracepoint_by_number (&args, NULL, 1);
15032       if (t1)
15033         trace_pass_set_count (t1, count, from_tty);
15034     }
15035   else
15036     {
15037       struct get_number_or_range_state state;
15038
15039       init_number_or_range (&state, args);
15040       while (!state.finished)
15041         {
15042           t1 = get_tracepoint_by_number (&args, &state, 1);
15043           if (t1)
15044             trace_pass_set_count (t1, count, from_tty);
15045         }
15046     }
15047 }
15048
15049 struct tracepoint *
15050 get_tracepoint (int num)
15051 {
15052   struct breakpoint *t;
15053
15054   ALL_TRACEPOINTS (t)
15055     if (t->number == num)
15056       return (struct tracepoint *) t;
15057
15058   return NULL;
15059 }
15060
15061 /* Find the tracepoint with the given target-side number (which may be
15062    different from the tracepoint number after disconnecting and
15063    reconnecting).  */
15064
15065 struct tracepoint *
15066 get_tracepoint_by_number_on_target (int num)
15067 {
15068   struct breakpoint *b;
15069
15070   ALL_TRACEPOINTS (b)
15071     {
15072       struct tracepoint *t = (struct tracepoint *) b;
15073
15074       if (t->number_on_target == num)
15075         return t;
15076     }
15077
15078   return NULL;
15079 }
15080
15081 /* Utility: parse a tracepoint number and look it up in the list.
15082    If STATE is not NULL, use, get_number_or_range_state and ignore ARG.
15083    If OPTIONAL_P is true, then if the argument is missing, the most
15084    recent tracepoint (tracepoint_count) is returned.  */
15085 struct tracepoint *
15086 get_tracepoint_by_number (char **arg,
15087                           struct get_number_or_range_state *state,
15088                           int optional_p)
15089 {
15090   extern int tracepoint_count;
15091   struct breakpoint *t;
15092   int tpnum;
15093   char *instring = arg == NULL ? NULL : *arg;
15094
15095   if (state)
15096     {
15097       gdb_assert (!state->finished);
15098       tpnum = get_number_or_range (state);
15099     }
15100   else if (arg == NULL || *arg == NULL || ! **arg)
15101     {
15102       if (optional_p)
15103         tpnum = tracepoint_count;
15104       else
15105         error_no_arg (_("tracepoint number"));
15106     }
15107   else
15108     tpnum = get_number (arg);
15109
15110   if (tpnum <= 0)
15111     {
15112       if (instring && *instring)
15113         printf_filtered (_("bad tracepoint number at or near '%s'\n"), 
15114                          instring);
15115       else
15116         printf_filtered (_("Tracepoint argument missing "
15117                            "and no previous tracepoint\n"));
15118       return NULL;
15119     }
15120
15121   ALL_TRACEPOINTS (t)
15122     if (t->number == tpnum)
15123     {
15124       return (struct tracepoint *) t;
15125     }
15126
15127   printf_unfiltered ("No tracepoint number %d.\n", tpnum);
15128   return NULL;
15129 }
15130
15131 void
15132 print_recreate_thread (struct breakpoint *b, struct ui_file *fp)
15133 {
15134   if (b->thread != -1)
15135     fprintf_unfiltered (fp, " thread %d", b->thread);
15136
15137   if (b->task != 0)
15138     fprintf_unfiltered (fp, " task %d", b->task);
15139
15140   fprintf_unfiltered (fp, "\n");
15141 }
15142
15143 /* Save information on user settable breakpoints (watchpoints, etc) to
15144    a new script file named FILENAME.  If FILTER is non-NULL, call it
15145    on each breakpoint and only include the ones for which it returns
15146    non-zero.  */
15147
15148 static void
15149 save_breakpoints (char *filename, int from_tty,
15150                   int (*filter) (const struct breakpoint *))
15151 {
15152   struct breakpoint *tp;
15153   int any = 0;
15154   char *pathname;
15155   struct cleanup *cleanup;
15156   struct ui_file *fp;
15157   int extra_trace_bits = 0;
15158
15159   if (filename == 0 || *filename == 0)
15160     error (_("Argument required (file name in which to save)"));
15161
15162   /* See if we have anything to save.  */
15163   ALL_BREAKPOINTS (tp)
15164   {
15165     /* Skip internal and momentary breakpoints.  */
15166     if (!user_breakpoint_p (tp))
15167       continue;
15168
15169     /* If we have a filter, only save the breakpoints it accepts.  */
15170     if (filter && !filter (tp))
15171       continue;
15172
15173     any = 1;
15174
15175     if (is_tracepoint (tp))
15176       {
15177         extra_trace_bits = 1;
15178
15179         /* We can stop searching.  */
15180         break;
15181       }
15182   }
15183
15184   if (!any)
15185     {
15186       warning (_("Nothing to save."));
15187       return;
15188     }
15189
15190   pathname = tilde_expand (filename);
15191   cleanup = make_cleanup (xfree, pathname);
15192   fp = gdb_fopen (pathname, "w");
15193   if (!fp)
15194     error (_("Unable to open file '%s' for saving (%s)"),
15195            filename, safe_strerror (errno));
15196   make_cleanup_ui_file_delete (fp);
15197
15198   if (extra_trace_bits)
15199     save_trace_state_variables (fp);
15200
15201   ALL_BREAKPOINTS (tp)
15202   {
15203     /* Skip internal and momentary breakpoints.  */
15204     if (!user_breakpoint_p (tp))
15205       continue;
15206
15207     /* If we have a filter, only save the breakpoints it accepts.  */
15208     if (filter && !filter (tp))
15209       continue;
15210
15211     tp->ops->print_recreate (tp, fp);
15212
15213     /* Note, we can't rely on tp->number for anything, as we can't
15214        assume the recreated breakpoint numbers will match.  Use $bpnum
15215        instead.  */
15216
15217     if (tp->cond_string)
15218       fprintf_unfiltered (fp, "  condition $bpnum %s\n", tp->cond_string);
15219
15220     if (tp->ignore_count)
15221       fprintf_unfiltered (fp, "  ignore $bpnum %d\n", tp->ignore_count);
15222
15223     if (tp->commands)
15224       {
15225         volatile struct gdb_exception ex;       
15226
15227         fprintf_unfiltered (fp, "  commands\n");
15228         
15229         ui_out_redirect (current_uiout, fp);
15230         TRY_CATCH (ex, RETURN_MASK_ALL)
15231           {
15232             print_command_lines (current_uiout, tp->commands->commands, 2);
15233           }
15234         ui_out_redirect (current_uiout, NULL);
15235
15236         if (ex.reason < 0)
15237           throw_exception (ex);
15238
15239         fprintf_unfiltered (fp, "  end\n");
15240       }
15241
15242     if (tp->enable_state == bp_disabled)
15243       fprintf_unfiltered (fp, "disable\n");
15244
15245     /* If this is a multi-location breakpoint, check if the locations
15246        should be individually disabled.  Watchpoint locations are
15247        special, and not user visible.  */
15248     if (!is_watchpoint (tp) && tp->loc && tp->loc->next)
15249       {
15250         struct bp_location *loc;
15251         int n = 1;
15252
15253         for (loc = tp->loc; loc != NULL; loc = loc->next, n++)
15254           if (!loc->enabled)
15255             fprintf_unfiltered (fp, "disable $bpnum.%d\n", n);
15256       }
15257   }
15258
15259   if (extra_trace_bits && *default_collect)
15260     fprintf_unfiltered (fp, "set default-collect %s\n", default_collect);
15261
15262   do_cleanups (cleanup);
15263   if (from_tty)
15264     printf_filtered (_("Saved to file '%s'.\n"), filename);
15265 }
15266
15267 /* The `save breakpoints' command.  */
15268
15269 static void
15270 save_breakpoints_command (char *args, int from_tty)
15271 {
15272   save_breakpoints (args, from_tty, NULL);
15273 }
15274
15275 /* The `save tracepoints' command.  */
15276
15277 static void
15278 save_tracepoints_command (char *args, int from_tty)
15279 {
15280   save_breakpoints (args, from_tty, is_tracepoint);
15281 }
15282
15283 /* Create a vector of all tracepoints.  */
15284
15285 VEC(breakpoint_p) *
15286 all_tracepoints (void)
15287 {
15288   VEC(breakpoint_p) *tp_vec = 0;
15289   struct breakpoint *tp;
15290
15291   ALL_TRACEPOINTS (tp)
15292   {
15293     VEC_safe_push (breakpoint_p, tp_vec, tp);
15294   }
15295
15296   return tp_vec;
15297 }
15298
15299 \f
15300 /* This help string is used for the break, hbreak, tbreak and thbreak
15301    commands.  It is defined as a macro to prevent duplication.
15302    COMMAND should be a string constant containing the name of the
15303    command.  */
15304 #define BREAK_ARGS_HELP(command) \
15305 command" [LOCATION] [thread THREADNUM] [if CONDITION]\n\
15306 LOCATION may be a line number, function name, or \"*\" and an address.\n\
15307 If a line number is specified, break at start of code for that line.\n\
15308 If a function is specified, break at start of code for that function.\n\
15309 If an address is specified, break at that exact address.\n\
15310 With no LOCATION, uses current execution address of the selected\n\
15311 stack frame.  This is useful for breaking on return to a stack frame.\n\
15312 \n\
15313 THREADNUM is the number from \"info threads\".\n\
15314 CONDITION is a boolean expression.\n\
15315 \n\
15316 Multiple breakpoints at one place are permitted, and useful if their\n\
15317 conditions are different.\n\
15318 \n\
15319 Do \"help breakpoints\" for info on other commands dealing with breakpoints."
15320
15321 /* List of subcommands for "catch".  */
15322 static struct cmd_list_element *catch_cmdlist;
15323
15324 /* List of subcommands for "tcatch".  */
15325 static struct cmd_list_element *tcatch_cmdlist;
15326
15327 void
15328 add_catch_command (char *name, char *docstring,
15329                    void (*sfunc) (char *args, int from_tty,
15330                                   struct cmd_list_element *command),
15331                    completer_ftype *completer,
15332                    void *user_data_catch,
15333                    void *user_data_tcatch)
15334 {
15335   struct cmd_list_element *command;
15336
15337   command = add_cmd (name, class_breakpoint, NULL, docstring,
15338                      &catch_cmdlist);
15339   set_cmd_sfunc (command, sfunc);
15340   set_cmd_context (command, user_data_catch);
15341   set_cmd_completer (command, completer);
15342
15343   command = add_cmd (name, class_breakpoint, NULL, docstring,
15344                      &tcatch_cmdlist);
15345   set_cmd_sfunc (command, sfunc);
15346   set_cmd_context (command, user_data_tcatch);
15347   set_cmd_completer (command, completer);
15348 }
15349
15350 static void
15351 clear_syscall_counts (struct inferior *inf)
15352 {
15353   struct catch_syscall_inferior_data *inf_data
15354     = get_catch_syscall_inferior_data (inf);
15355
15356   inf_data->total_syscalls_count = 0;
15357   inf_data->any_syscall_count = 0;
15358   VEC_free (int, inf_data->syscalls_counts);
15359 }
15360
15361 static void
15362 save_command (char *arg, int from_tty)
15363 {
15364   printf_unfiltered (_("\"save\" must be followed by "
15365                        "the name of a save subcommand.\n"));
15366   help_list (save_cmdlist, "save ", -1, gdb_stdout);
15367 }
15368
15369 struct breakpoint *
15370 iterate_over_breakpoints (int (*callback) (struct breakpoint *, void *),
15371                           void *data)
15372 {
15373   struct breakpoint *b, *b_tmp;
15374
15375   ALL_BREAKPOINTS_SAFE (b, b_tmp)
15376     {
15377       if ((*callback) (b, data))
15378         return b;
15379     }
15380
15381   return NULL;
15382 }
15383
15384 /* Zero if any of the breakpoint's locations could be a location where
15385    functions have been inlined, nonzero otherwise.  */
15386
15387 static int
15388 is_non_inline_function (struct breakpoint *b)
15389 {
15390   /* The shared library event breakpoint is set on the address of a
15391      non-inline function.  */
15392   if (b->type == bp_shlib_event)
15393     return 1;
15394
15395   return 0;
15396 }
15397
15398 /* Nonzero if the specified PC cannot be a location where functions
15399    have been inlined.  */
15400
15401 int
15402 pc_at_non_inline_function (struct address_space *aspace, CORE_ADDR pc,
15403                            const struct target_waitstatus *ws)
15404 {
15405   struct breakpoint *b;
15406   struct bp_location *bl;
15407
15408   ALL_BREAKPOINTS (b)
15409     {
15410       if (!is_non_inline_function (b))
15411         continue;
15412
15413       for (bl = b->loc; bl != NULL; bl = bl->next)
15414         {
15415           if (!bl->shlib_disabled
15416               && bpstat_check_location (bl, aspace, pc, ws))
15417             return 1;
15418         }
15419     }
15420
15421   return 0;
15422 }
15423
15424 void
15425 initialize_breakpoint_ops (void)
15426 {
15427   static int initialized = 0;
15428
15429   struct breakpoint_ops *ops;
15430
15431   if (initialized)
15432     return;
15433   initialized = 1;
15434
15435   /* The breakpoint_ops structure to be inherit by all kinds of
15436      breakpoints (real breakpoints, i.e., user "break" breakpoints,
15437      internal and momentary breakpoints, etc.).  */
15438   ops = &bkpt_base_breakpoint_ops;
15439   *ops = base_breakpoint_ops;
15440   ops->re_set = bkpt_re_set;
15441   ops->insert_location = bkpt_insert_location;
15442   ops->remove_location = bkpt_remove_location;
15443   ops->breakpoint_hit = bkpt_breakpoint_hit;
15444   ops->create_sals_from_address = bkpt_create_sals_from_address;
15445   ops->create_breakpoints_sal = bkpt_create_breakpoints_sal;
15446   ops->decode_linespec = bkpt_decode_linespec;
15447
15448   /* The breakpoint_ops structure to be used in regular breakpoints.  */
15449   ops = &bkpt_breakpoint_ops;
15450   *ops = bkpt_base_breakpoint_ops;
15451   ops->re_set = bkpt_re_set;
15452   ops->resources_needed = bkpt_resources_needed;
15453   ops->print_it = bkpt_print_it;
15454   ops->print_mention = bkpt_print_mention;
15455   ops->print_recreate = bkpt_print_recreate;
15456
15457   /* Ranged breakpoints.  */
15458   ops = &ranged_breakpoint_ops;
15459   *ops = bkpt_breakpoint_ops;
15460   ops->breakpoint_hit = breakpoint_hit_ranged_breakpoint;
15461   ops->resources_needed = resources_needed_ranged_breakpoint;
15462   ops->print_it = print_it_ranged_breakpoint;
15463   ops->print_one = print_one_ranged_breakpoint;
15464   ops->print_one_detail = print_one_detail_ranged_breakpoint;
15465   ops->print_mention = print_mention_ranged_breakpoint;
15466   ops->print_recreate = print_recreate_ranged_breakpoint;
15467
15468   /* Internal breakpoints.  */
15469   ops = &internal_breakpoint_ops;
15470   *ops = bkpt_base_breakpoint_ops;
15471   ops->re_set = internal_bkpt_re_set;
15472   ops->check_status = internal_bkpt_check_status;
15473   ops->print_it = internal_bkpt_print_it;
15474   ops->print_mention = internal_bkpt_print_mention;
15475
15476   /* Momentary breakpoints.  */
15477   ops = &momentary_breakpoint_ops;
15478   *ops = bkpt_base_breakpoint_ops;
15479   ops->re_set = momentary_bkpt_re_set;
15480   ops->check_status = momentary_bkpt_check_status;
15481   ops->print_it = momentary_bkpt_print_it;
15482   ops->print_mention = momentary_bkpt_print_mention;
15483
15484   /* Momentary breakpoints for bp_longjmp and bp_exception.  */
15485   ops = &longjmp_breakpoint_ops;
15486   *ops = momentary_breakpoint_ops;
15487   ops->dtor = longjmp_bkpt_dtor;
15488
15489   /* Probe breakpoints.  */
15490   ops = &bkpt_probe_breakpoint_ops;
15491   *ops = bkpt_breakpoint_ops;
15492   ops->insert_location = bkpt_probe_insert_location;
15493   ops->remove_location = bkpt_probe_remove_location;
15494   ops->create_sals_from_address = bkpt_probe_create_sals_from_address;
15495   ops->decode_linespec = bkpt_probe_decode_linespec;
15496
15497   /* GNU v3 exception catchpoints.  */
15498   ops = &gnu_v3_exception_catchpoint_ops;
15499   *ops = bkpt_breakpoint_ops;
15500   ops->print_it = print_it_exception_catchpoint;
15501   ops->print_one = print_one_exception_catchpoint;
15502   ops->print_mention = print_mention_exception_catchpoint;
15503   ops->print_recreate = print_recreate_exception_catchpoint;
15504
15505   /* Watchpoints.  */
15506   ops = &watchpoint_breakpoint_ops;
15507   *ops = base_breakpoint_ops;
15508   ops->dtor = dtor_watchpoint;
15509   ops->re_set = re_set_watchpoint;
15510   ops->insert_location = insert_watchpoint;
15511   ops->remove_location = remove_watchpoint;
15512   ops->breakpoint_hit = breakpoint_hit_watchpoint;
15513   ops->check_status = check_status_watchpoint;
15514   ops->resources_needed = resources_needed_watchpoint;
15515   ops->works_in_software_mode = works_in_software_mode_watchpoint;
15516   ops->print_it = print_it_watchpoint;
15517   ops->print_mention = print_mention_watchpoint;
15518   ops->print_recreate = print_recreate_watchpoint;
15519
15520   /* Masked watchpoints.  */
15521   ops = &masked_watchpoint_breakpoint_ops;
15522   *ops = watchpoint_breakpoint_ops;
15523   ops->insert_location = insert_masked_watchpoint;
15524   ops->remove_location = remove_masked_watchpoint;
15525   ops->resources_needed = resources_needed_masked_watchpoint;
15526   ops->works_in_software_mode = works_in_software_mode_masked_watchpoint;
15527   ops->print_it = print_it_masked_watchpoint;
15528   ops->print_one_detail = print_one_detail_masked_watchpoint;
15529   ops->print_mention = print_mention_masked_watchpoint;
15530   ops->print_recreate = print_recreate_masked_watchpoint;
15531
15532   /* Tracepoints.  */
15533   ops = &tracepoint_breakpoint_ops;
15534   *ops = base_breakpoint_ops;
15535   ops->re_set = tracepoint_re_set;
15536   ops->breakpoint_hit = tracepoint_breakpoint_hit;
15537   ops->print_one_detail = tracepoint_print_one_detail;
15538   ops->print_mention = tracepoint_print_mention;
15539   ops->print_recreate = tracepoint_print_recreate;
15540   ops->create_sals_from_address = tracepoint_create_sals_from_address;
15541   ops->create_breakpoints_sal = tracepoint_create_breakpoints_sal;
15542   ops->decode_linespec = tracepoint_decode_linespec;
15543
15544   /* Probe tracepoints.  */
15545   ops = &tracepoint_probe_breakpoint_ops;
15546   *ops = tracepoint_breakpoint_ops;
15547   ops->create_sals_from_address = tracepoint_probe_create_sals_from_address;
15548   ops->decode_linespec = tracepoint_probe_decode_linespec;
15549
15550   /* Static tracepoints with marker (`-m').  */
15551   ops = &strace_marker_breakpoint_ops;
15552   *ops = tracepoint_breakpoint_ops;
15553   ops->create_sals_from_address = strace_marker_create_sals_from_address;
15554   ops->create_breakpoints_sal = strace_marker_create_breakpoints_sal;
15555   ops->decode_linespec = strace_marker_decode_linespec;
15556
15557   /* Fork catchpoints.  */
15558   ops = &catch_fork_breakpoint_ops;
15559   *ops = base_breakpoint_ops;
15560   ops->insert_location = insert_catch_fork;
15561   ops->remove_location = remove_catch_fork;
15562   ops->breakpoint_hit = breakpoint_hit_catch_fork;
15563   ops->print_it = print_it_catch_fork;
15564   ops->print_one = print_one_catch_fork;
15565   ops->print_mention = print_mention_catch_fork;
15566   ops->print_recreate = print_recreate_catch_fork;
15567
15568   /* Vfork catchpoints.  */
15569   ops = &catch_vfork_breakpoint_ops;
15570   *ops = base_breakpoint_ops;
15571   ops->insert_location = insert_catch_vfork;
15572   ops->remove_location = remove_catch_vfork;
15573   ops->breakpoint_hit = breakpoint_hit_catch_vfork;
15574   ops->print_it = print_it_catch_vfork;
15575   ops->print_one = print_one_catch_vfork;
15576   ops->print_mention = print_mention_catch_vfork;
15577   ops->print_recreate = print_recreate_catch_vfork;
15578
15579   /* Exec catchpoints.  */
15580   ops = &catch_exec_breakpoint_ops;
15581   *ops = base_breakpoint_ops;
15582   ops->dtor = dtor_catch_exec;
15583   ops->insert_location = insert_catch_exec;
15584   ops->remove_location = remove_catch_exec;
15585   ops->breakpoint_hit = breakpoint_hit_catch_exec;
15586   ops->print_it = print_it_catch_exec;
15587   ops->print_one = print_one_catch_exec;
15588   ops->print_mention = print_mention_catch_exec;
15589   ops->print_recreate = print_recreate_catch_exec;
15590
15591   /* Syscall catchpoints.  */
15592   ops = &catch_syscall_breakpoint_ops;
15593   *ops = base_breakpoint_ops;
15594   ops->dtor = dtor_catch_syscall;
15595   ops->insert_location = insert_catch_syscall;
15596   ops->remove_location = remove_catch_syscall;
15597   ops->breakpoint_hit = breakpoint_hit_catch_syscall;
15598   ops->print_it = print_it_catch_syscall;
15599   ops->print_one = print_one_catch_syscall;
15600   ops->print_mention = print_mention_catch_syscall;
15601   ops->print_recreate = print_recreate_catch_syscall;
15602
15603   /* Solib-related catchpoints.  */
15604   ops = &catch_solib_breakpoint_ops;
15605   *ops = base_breakpoint_ops;
15606   ops->dtor = dtor_catch_solib;
15607   ops->insert_location = insert_catch_solib;
15608   ops->remove_location = remove_catch_solib;
15609   ops->breakpoint_hit = breakpoint_hit_catch_solib;
15610   ops->check_status = check_status_catch_solib;
15611   ops->print_it = print_it_catch_solib;
15612   ops->print_one = print_one_catch_solib;
15613   ops->print_mention = print_mention_catch_solib;
15614   ops->print_recreate = print_recreate_catch_solib;
15615
15616   ops = &dprintf_breakpoint_ops;
15617   *ops = bkpt_base_breakpoint_ops;
15618   ops->re_set = bkpt_re_set;
15619   ops->resources_needed = bkpt_resources_needed;
15620   ops->print_it = bkpt_print_it;
15621   ops->print_mention = bkpt_print_mention;
15622   ops->print_recreate = bkpt_print_recreate;
15623 }
15624
15625 void
15626 _initialize_breakpoint (void)
15627 {
15628   struct cmd_list_element *c;
15629
15630   initialize_breakpoint_ops ();
15631
15632   observer_attach_solib_unloaded (disable_breakpoints_in_unloaded_shlib);
15633   observer_attach_inferior_exit (clear_syscall_counts);
15634   observer_attach_memory_changed (invalidate_bp_value_on_memory_change);
15635
15636   breakpoint_objfile_key
15637     = register_objfile_data_with_cleanup (NULL, free_breakpoint_probes);
15638
15639   catch_syscall_inferior_data
15640     = register_inferior_data_with_cleanup (catch_syscall_inferior_data_cleanup);
15641
15642   breakpoint_chain = 0;
15643   /* Don't bother to call set_breakpoint_count.  $bpnum isn't useful
15644      before a breakpoint is set.  */
15645   breakpoint_count = 0;
15646
15647   tracepoint_count = 0;
15648
15649   add_com ("ignore", class_breakpoint, ignore_command, _("\
15650 Set ignore-count of breakpoint number N to COUNT.\n\
15651 Usage is `ignore N COUNT'."));
15652   if (xdb_commands)
15653     add_com_alias ("bc", "ignore", class_breakpoint, 1);
15654
15655   add_com ("commands", class_breakpoint, commands_command, _("\
15656 Set commands to be executed when a breakpoint is hit.\n\
15657 Give breakpoint number as argument after \"commands\".\n\
15658 With no argument, the targeted breakpoint is the last one set.\n\
15659 The commands themselves follow starting on the next line.\n\
15660 Type a line containing \"end\" to indicate the end of them.\n\
15661 Give \"silent\" as the first line to make the breakpoint silent;\n\
15662 then no output is printed when it is hit, except what the commands print."));
15663
15664   c = add_com ("condition", class_breakpoint, condition_command, _("\
15665 Specify breakpoint number N to break only if COND is true.\n\
15666 Usage is `condition N COND', where N is an integer and COND is an\n\
15667 expression to be evaluated whenever breakpoint N is reached."));
15668   set_cmd_completer (c, condition_completer);
15669
15670   c = add_com ("tbreak", class_breakpoint, tbreak_command, _("\
15671 Set a temporary breakpoint.\n\
15672 Like \"break\" except the breakpoint is only temporary,\n\
15673 so it will be deleted when hit.  Equivalent to \"break\" followed\n\
15674 by using \"enable delete\" on the breakpoint number.\n\
15675 \n"
15676 BREAK_ARGS_HELP ("tbreak")));
15677   set_cmd_completer (c, location_completer);
15678
15679   c = add_com ("hbreak", class_breakpoint, hbreak_command, _("\
15680 Set a hardware assisted breakpoint.\n\
15681 Like \"break\" except the breakpoint requires hardware support,\n\
15682 some target hardware may not have this support.\n\
15683 \n"
15684 BREAK_ARGS_HELP ("hbreak")));
15685   set_cmd_completer (c, location_completer);
15686
15687   c = add_com ("thbreak", class_breakpoint, thbreak_command, _("\
15688 Set a temporary hardware assisted breakpoint.\n\
15689 Like \"hbreak\" except the breakpoint is only temporary,\n\
15690 so it will be deleted when hit.\n\
15691 \n"
15692 BREAK_ARGS_HELP ("thbreak")));
15693   set_cmd_completer (c, location_completer);
15694
15695   add_prefix_cmd ("enable", class_breakpoint, enable_command, _("\
15696 Enable some breakpoints.\n\
15697 Give breakpoint numbers (separated by spaces) as arguments.\n\
15698 With no subcommand, breakpoints are enabled until you command otherwise.\n\
15699 This is used to cancel the effect of the \"disable\" command.\n\
15700 With a subcommand you can enable temporarily."),
15701                   &enablelist, "enable ", 1, &cmdlist);
15702   if (xdb_commands)
15703     add_com ("ab", class_breakpoint, enable_command, _("\
15704 Enable some breakpoints.\n\
15705 Give breakpoint numbers (separated by spaces) as arguments.\n\
15706 With no subcommand, breakpoints are enabled until you command otherwise.\n\
15707 This is used to cancel the effect of the \"disable\" command.\n\
15708 With a subcommand you can enable temporarily."));
15709
15710   add_com_alias ("en", "enable", class_breakpoint, 1);
15711
15712   add_prefix_cmd ("breakpoints", class_breakpoint, enable_command, _("\
15713 Enable some breakpoints.\n\
15714 Give breakpoint numbers (separated by spaces) as arguments.\n\
15715 This is used to cancel the effect of the \"disable\" command.\n\
15716 May be abbreviated to simply \"enable\".\n"),
15717                    &enablebreaklist, "enable breakpoints ", 1, &enablelist);
15718
15719   add_cmd ("once", no_class, enable_once_command, _("\
15720 Enable breakpoints for one hit.  Give breakpoint numbers.\n\
15721 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
15722            &enablebreaklist);
15723
15724   add_cmd ("delete", no_class, enable_delete_command, _("\
15725 Enable breakpoints and delete when hit.  Give breakpoint numbers.\n\
15726 If a breakpoint is hit while enabled in this fashion, it is deleted."),
15727            &enablebreaklist);
15728
15729   add_cmd ("count", no_class, enable_count_command, _("\
15730 Enable breakpoints for COUNT hits.  Give count and then breakpoint numbers.\n\
15731 If a breakpoint is hit while enabled in this fashion,\n\
15732 the count is decremented; when it reaches zero, the breakpoint is disabled."),
15733            &enablebreaklist);
15734
15735   add_cmd ("delete", no_class, enable_delete_command, _("\
15736 Enable breakpoints and delete when hit.  Give breakpoint numbers.\n\
15737 If a breakpoint is hit while enabled in this fashion, it is deleted."),
15738            &enablelist);
15739
15740   add_cmd ("once", no_class, enable_once_command, _("\
15741 Enable breakpoints for one hit.  Give breakpoint numbers.\n\
15742 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
15743            &enablelist);
15744
15745   add_cmd ("count", no_class, enable_count_command, _("\
15746 Enable breakpoints for COUNT hits.  Give count and then breakpoint numbers.\n\
15747 If a breakpoint is hit while enabled in this fashion,\n\
15748 the count is decremented; when it reaches zero, the breakpoint is disabled."),
15749            &enablelist);
15750
15751   add_prefix_cmd ("disable", class_breakpoint, disable_command, _("\
15752 Disable some breakpoints.\n\
15753 Arguments are breakpoint numbers with spaces in between.\n\
15754 To disable all breakpoints, give no argument.\n\
15755 A disabled breakpoint is not forgotten, but has no effect until re-enabled."),
15756                   &disablelist, "disable ", 1, &cmdlist);
15757   add_com_alias ("dis", "disable", class_breakpoint, 1);
15758   add_com_alias ("disa", "disable", class_breakpoint, 1);
15759   if (xdb_commands)
15760     add_com ("sb", class_breakpoint, disable_command, _("\
15761 Disable some breakpoints.\n\
15762 Arguments are breakpoint numbers with spaces in between.\n\
15763 To disable all breakpoints, give no argument.\n\
15764 A disabled breakpoint is not forgotten, but has no effect until re-enabled."));
15765
15766   add_cmd ("breakpoints", class_alias, disable_command, _("\
15767 Disable some breakpoints.\n\
15768 Arguments are breakpoint numbers with spaces in between.\n\
15769 To disable all breakpoints, give no argument.\n\
15770 A disabled breakpoint is not forgotten, but has no effect until re-enabled.\n\
15771 This command may be abbreviated \"disable\"."),
15772            &disablelist);
15773
15774   add_prefix_cmd ("delete", class_breakpoint, delete_command, _("\
15775 Delete some breakpoints or auto-display expressions.\n\
15776 Arguments are breakpoint numbers with spaces in between.\n\
15777 To delete all breakpoints, give no argument.\n\
15778 \n\
15779 Also a prefix command for deletion of other GDB objects.\n\
15780 The \"unset\" command is also an alias for \"delete\"."),
15781                   &deletelist, "delete ", 1, &cmdlist);
15782   add_com_alias ("d", "delete", class_breakpoint, 1);
15783   add_com_alias ("del", "delete", class_breakpoint, 1);
15784   if (xdb_commands)
15785     add_com ("db", class_breakpoint, delete_command, _("\
15786 Delete some breakpoints.\n\
15787 Arguments are breakpoint numbers with spaces in between.\n\
15788 To delete all breakpoints, give no argument.\n"));
15789
15790   add_cmd ("breakpoints", class_alias, delete_command, _("\
15791 Delete some breakpoints or auto-display expressions.\n\
15792 Arguments are breakpoint numbers with spaces in between.\n\
15793 To delete all breakpoints, give no argument.\n\
15794 This command may be abbreviated \"delete\"."),
15795            &deletelist);
15796
15797   add_com ("clear", class_breakpoint, clear_command, _("\
15798 Clear breakpoint at specified line or function.\n\
15799 Argument may be line number, function name, or \"*\" and an address.\n\
15800 If line number is specified, all breakpoints in that line are cleared.\n\
15801 If function is specified, breakpoints at beginning of function are cleared.\n\
15802 If an address is specified, breakpoints at that address are cleared.\n\
15803 \n\
15804 With no argument, clears all breakpoints in the line that the selected frame\n\
15805 is executing in.\n\
15806 \n\
15807 See also the \"delete\" command which clears breakpoints by number."));
15808   add_com_alias ("cl", "clear", class_breakpoint, 1);
15809
15810   c = add_com ("break", class_breakpoint, break_command, _("\
15811 Set breakpoint at specified line or function.\n"
15812 BREAK_ARGS_HELP ("break")));
15813   set_cmd_completer (c, location_completer);
15814
15815   add_com_alias ("b", "break", class_run, 1);
15816   add_com_alias ("br", "break", class_run, 1);
15817   add_com_alias ("bre", "break", class_run, 1);
15818   add_com_alias ("brea", "break", class_run, 1);
15819
15820   if (xdb_commands)
15821    add_com_alias ("ba", "break", class_breakpoint, 1);
15822
15823   if (dbx_commands)
15824     {
15825       add_abbrev_prefix_cmd ("stop", class_breakpoint, stop_command, _("\
15826 Break in function/address or break at a line in the current file."),
15827                              &stoplist, "stop ", 1, &cmdlist);
15828       add_cmd ("in", class_breakpoint, stopin_command,
15829                _("Break in function or address."), &stoplist);
15830       add_cmd ("at", class_breakpoint, stopat_command,
15831                _("Break at a line in the current file."), &stoplist);
15832       add_com ("status", class_info, breakpoints_info, _("\
15833 Status of user-settable breakpoints, or breakpoint number NUMBER.\n\
15834 The \"Type\" column indicates one of:\n\
15835 \tbreakpoint     - normal breakpoint\n\
15836 \twatchpoint     - watchpoint\n\
15837 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
15838 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
15839 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
15840 address and file/line number respectively.\n\
15841 \n\
15842 Convenience variable \"$_\" and default examine address for \"x\"\n\
15843 are set to the address of the last breakpoint listed unless the command\n\
15844 is prefixed with \"server \".\n\n\
15845 Convenience variable \"$bpnum\" contains the number of the last\n\
15846 breakpoint set."));
15847     }
15848
15849   add_info ("breakpoints", breakpoints_info, _("\
15850 Status of specified breakpoints (all user-settable breakpoints if no argument).\n\
15851 The \"Type\" column indicates one of:\n\
15852 \tbreakpoint     - normal breakpoint\n\
15853 \twatchpoint     - watchpoint\n\
15854 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
15855 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
15856 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
15857 address and file/line number respectively.\n\
15858 \n\
15859 Convenience variable \"$_\" and default examine address for \"x\"\n\
15860 are set to the address of the last breakpoint listed unless the command\n\
15861 is prefixed with \"server \".\n\n\
15862 Convenience variable \"$bpnum\" contains the number of the last\n\
15863 breakpoint set."));
15864
15865   add_info_alias ("b", "breakpoints", 1);
15866
15867   if (xdb_commands)
15868     add_com ("lb", class_breakpoint, breakpoints_info, _("\
15869 Status of user-settable breakpoints, or breakpoint number NUMBER.\n\
15870 The \"Type\" column indicates one of:\n\
15871 \tbreakpoint     - normal breakpoint\n\
15872 \twatchpoint     - watchpoint\n\
15873 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
15874 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
15875 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
15876 address and file/line number respectively.\n\
15877 \n\
15878 Convenience variable \"$_\" and default examine address for \"x\"\n\
15879 are set to the address of the last breakpoint listed unless the command\n\
15880 is prefixed with \"server \".\n\n\
15881 Convenience variable \"$bpnum\" contains the number of the last\n\
15882 breakpoint set."));
15883
15884   add_cmd ("breakpoints", class_maintenance, maintenance_info_breakpoints, _("\
15885 Status of all breakpoints, or breakpoint number NUMBER.\n\
15886 The \"Type\" column indicates one of:\n\
15887 \tbreakpoint     - normal breakpoint\n\
15888 \twatchpoint     - watchpoint\n\
15889 \tlongjmp        - internal breakpoint used to step through longjmp()\n\
15890 \tlongjmp resume - internal breakpoint at the target of longjmp()\n\
15891 \tuntil          - internal breakpoint used by the \"until\" command\n\
15892 \tfinish         - internal breakpoint used by the \"finish\" command\n\
15893 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
15894 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
15895 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
15896 address and file/line number respectively.\n\
15897 \n\
15898 Convenience variable \"$_\" and default examine address for \"x\"\n\
15899 are set to the address of the last breakpoint listed unless the command\n\
15900 is prefixed with \"server \".\n\n\
15901 Convenience variable \"$bpnum\" contains the number of the last\n\
15902 breakpoint set."),
15903            &maintenanceinfolist);
15904
15905   add_prefix_cmd ("catch", class_breakpoint, catch_command, _("\
15906 Set catchpoints to catch events."),
15907                   &catch_cmdlist, "catch ",
15908                   0/*allow-unknown*/, &cmdlist);
15909
15910   add_prefix_cmd ("tcatch", class_breakpoint, tcatch_command, _("\
15911 Set temporary catchpoints to catch events."),
15912                   &tcatch_cmdlist, "tcatch ",
15913                   0/*allow-unknown*/, &cmdlist);
15914
15915   /* Add catch and tcatch sub-commands.  */
15916   add_catch_command ("catch", _("\
15917 Catch an exception, when caught."),
15918                      catch_catch_command,
15919                      NULL,
15920                      CATCH_PERMANENT,
15921                      CATCH_TEMPORARY);
15922   add_catch_command ("throw", _("\
15923 Catch an exception, when thrown."),
15924                      catch_throw_command,
15925                      NULL,
15926                      CATCH_PERMANENT,
15927                      CATCH_TEMPORARY);
15928   add_catch_command ("fork", _("Catch calls to fork."),
15929                      catch_fork_command_1,
15930                      NULL,
15931                      (void *) (uintptr_t) catch_fork_permanent,
15932                      (void *) (uintptr_t) catch_fork_temporary);
15933   add_catch_command ("vfork", _("Catch calls to vfork."),
15934                      catch_fork_command_1,
15935                      NULL,
15936                      (void *) (uintptr_t) catch_vfork_permanent,
15937                      (void *) (uintptr_t) catch_vfork_temporary);
15938   add_catch_command ("exec", _("Catch calls to exec."),
15939                      catch_exec_command_1,
15940                      NULL,
15941                      CATCH_PERMANENT,
15942                      CATCH_TEMPORARY);
15943   add_catch_command ("load", _("Catch loads of shared libraries.\n\
15944 Usage: catch load [REGEX]\n\
15945 If REGEX is given, only stop for libraries matching the regular expression."),
15946                      catch_load_command_1,
15947                      NULL,
15948                      CATCH_PERMANENT,
15949                      CATCH_TEMPORARY);
15950   add_catch_command ("unload", _("Catch unloads of shared libraries.\n\
15951 Usage: catch unload [REGEX]\n\
15952 If REGEX is given, only stop for libraries matching the regular expression."),
15953                      catch_unload_command_1,
15954                      NULL,
15955                      CATCH_PERMANENT,
15956                      CATCH_TEMPORARY);
15957   add_catch_command ("syscall", _("\
15958 Catch system calls by their names and/or numbers.\n\
15959 Arguments say which system calls to catch.  If no arguments\n\
15960 are given, every system call will be caught.\n\
15961 Arguments, if given, should be one or more system call names\n\
15962 (if your system supports that), or system call numbers."),
15963                      catch_syscall_command_1,
15964                      catch_syscall_completer,
15965                      CATCH_PERMANENT,
15966                      CATCH_TEMPORARY);
15967
15968   c = add_com ("watch", class_breakpoint, watch_command, _("\
15969 Set a watchpoint for an expression.\n\
15970 Usage: watch [-l|-location] EXPRESSION\n\
15971 A watchpoint stops execution of your program whenever the value of\n\
15972 an expression changes.\n\
15973 If -l or -location is given, this evaluates EXPRESSION and watches\n\
15974 the memory to which it refers."));
15975   set_cmd_completer (c, expression_completer);
15976
15977   c = add_com ("rwatch", class_breakpoint, rwatch_command, _("\
15978 Set a read watchpoint for an expression.\n\
15979 Usage: rwatch [-l|-location] EXPRESSION\n\
15980 A watchpoint stops execution of your program whenever the value of\n\
15981 an expression is read.\n\
15982 If -l or -location is given, this evaluates EXPRESSION and watches\n\
15983 the memory to which it refers."));
15984   set_cmd_completer (c, expression_completer);
15985
15986   c = add_com ("awatch", class_breakpoint, awatch_command, _("\
15987 Set a watchpoint for an expression.\n\
15988 Usage: awatch [-l|-location] EXPRESSION\n\
15989 A watchpoint stops execution of your program whenever the value of\n\
15990 an expression is either read or written.\n\
15991 If -l or -location is given, this evaluates EXPRESSION and watches\n\
15992 the memory to which it refers."));
15993   set_cmd_completer (c, expression_completer);
15994
15995   add_info ("watchpoints", watchpoints_info, _("\
15996 Status of specified watchpoints (all watchpoints if no argument)."));
15997
15998   /* XXX: cagney/2005-02-23: This should be a boolean, and should
15999      respond to changes - contrary to the description.  */
16000   add_setshow_zinteger_cmd ("can-use-hw-watchpoints", class_support,
16001                             &can_use_hw_watchpoints, _("\
16002 Set debugger's willingness to use watchpoint hardware."), _("\
16003 Show debugger's willingness to use watchpoint hardware."), _("\
16004 If zero, gdb will not use hardware for new watchpoints, even if\n\
16005 such is available.  (However, any hardware watchpoints that were\n\
16006 created before setting this to nonzero, will continue to use watchpoint\n\
16007 hardware.)"),
16008                             NULL,
16009                             show_can_use_hw_watchpoints,
16010                             &setlist, &showlist);
16011
16012   can_use_hw_watchpoints = 1;
16013
16014   /* Tracepoint manipulation commands.  */
16015
16016   c = add_com ("trace", class_breakpoint, trace_command, _("\
16017 Set a tracepoint at specified line or function.\n\
16018 \n"
16019 BREAK_ARGS_HELP ("trace") "\n\
16020 Do \"help tracepoints\" for info on other tracepoint commands."));
16021   set_cmd_completer (c, location_completer);
16022
16023   add_com_alias ("tp", "trace", class_alias, 0);
16024   add_com_alias ("tr", "trace", class_alias, 1);
16025   add_com_alias ("tra", "trace", class_alias, 1);
16026   add_com_alias ("trac", "trace", class_alias, 1);
16027
16028   c = add_com ("ftrace", class_breakpoint, ftrace_command, _("\
16029 Set a fast tracepoint at specified line or function.\n\
16030 \n"
16031 BREAK_ARGS_HELP ("ftrace") "\n\
16032 Do \"help tracepoints\" for info on other tracepoint commands."));
16033   set_cmd_completer (c, location_completer);
16034
16035   c = add_com ("strace", class_breakpoint, strace_command, _("\
16036 Set a static tracepoint at specified line, function or marker.\n\
16037 \n\
16038 strace [LOCATION] [if CONDITION]\n\
16039 LOCATION may be a line number, function name, \"*\" and an address,\n\
16040 or -m MARKER_ID.\n\
16041 If a line number is specified, probe the marker at start of code\n\
16042 for that line.  If a function is specified, probe the marker at start\n\
16043 of code for that function.  If an address is specified, probe the marker\n\
16044 at that exact address.  If a marker id is specified, probe the marker\n\
16045 with that name.  With no LOCATION, uses current execution address of\n\
16046 the selected stack frame.\n\
16047 Static tracepoints accept an extra collect action -- ``collect $_sdata''.\n\
16048 This collects arbitrary user data passed in the probe point call to the\n\
16049 tracing library.  You can inspect it when analyzing the trace buffer,\n\
16050 by printing the $_sdata variable like any other convenience variable.\n\
16051 \n\
16052 CONDITION is a boolean expression.\n\
16053 \n\
16054 Multiple tracepoints at one place are permitted, and useful if their\n\
16055 conditions are different.\n\
16056 \n\
16057 Do \"help breakpoints\" for info on other commands dealing with breakpoints.\n\
16058 Do \"help tracepoints\" for info on other tracepoint commands."));
16059   set_cmd_completer (c, location_completer);
16060
16061   add_info ("tracepoints", tracepoints_info, _("\
16062 Status of specified tracepoints (all tracepoints if no argument).\n\
16063 Convenience variable \"$tpnum\" contains the number of the\n\
16064 last tracepoint set."));
16065
16066   add_info_alias ("tp", "tracepoints", 1);
16067
16068   add_cmd ("tracepoints", class_trace, delete_trace_command, _("\
16069 Delete specified tracepoints.\n\
16070 Arguments are tracepoint numbers, separated by spaces.\n\
16071 No argument means delete all tracepoints."),
16072            &deletelist);
16073
16074   c = add_cmd ("tracepoints", class_trace, disable_trace_command, _("\
16075 Disable specified tracepoints.\n\
16076 Arguments are tracepoint numbers, separated by spaces.\n\
16077 No argument means disable all tracepoints."),
16078            &disablelist);
16079   deprecate_cmd (c, "disable");
16080
16081   c = add_cmd ("tracepoints", class_trace, enable_trace_command, _("\
16082 Enable specified tracepoints.\n\
16083 Arguments are tracepoint numbers, separated by spaces.\n\
16084 No argument means enable all tracepoints."),
16085            &enablelist);
16086   deprecate_cmd (c, "enable");
16087
16088   add_com ("passcount", class_trace, trace_pass_command, _("\
16089 Set the passcount for a tracepoint.\n\
16090 The trace will end when the tracepoint has been passed 'count' times.\n\
16091 Usage: passcount COUNT TPNUM, where TPNUM may also be \"all\";\n\
16092 if TPNUM is omitted, passcount refers to the last tracepoint defined."));
16093
16094   add_prefix_cmd ("save", class_breakpoint, save_command,
16095                   _("Save breakpoint definitions as a script."),
16096                   &save_cmdlist, "save ",
16097                   0/*allow-unknown*/, &cmdlist);
16098
16099   c = add_cmd ("breakpoints", class_breakpoint, save_breakpoints_command, _("\
16100 Save current breakpoint definitions as a script.\n\
16101 This includes all types of breakpoints (breakpoints, watchpoints,\n\
16102 catchpoints, tracepoints).  Use the 'source' command in another debug\n\
16103 session to restore them."),
16104                &save_cmdlist);
16105   set_cmd_completer (c, filename_completer);
16106
16107   c = add_cmd ("tracepoints", class_trace, save_tracepoints_command, _("\
16108 Save current tracepoint definitions as a script.\n\
16109 Use the 'source' command in another debug session to restore them."),
16110                &save_cmdlist);
16111   set_cmd_completer (c, filename_completer);
16112
16113   c = add_com_alias ("save-tracepoints", "save tracepoints", class_trace, 0);
16114   deprecate_cmd (c, "save tracepoints");
16115
16116   add_prefix_cmd ("breakpoint", class_maintenance, set_breakpoint_cmd, _("\
16117 Breakpoint specific settings\n\
16118 Configure various breakpoint-specific variables such as\n\
16119 pending breakpoint behavior"),
16120                   &breakpoint_set_cmdlist, "set breakpoint ",
16121                   0/*allow-unknown*/, &setlist);
16122   add_prefix_cmd ("breakpoint", class_maintenance, show_breakpoint_cmd, _("\
16123 Breakpoint specific settings\n\
16124 Configure various breakpoint-specific variables such as\n\
16125 pending breakpoint behavior"),
16126                   &breakpoint_show_cmdlist, "show breakpoint ",
16127                   0/*allow-unknown*/, &showlist);
16128
16129   add_setshow_auto_boolean_cmd ("pending", no_class,
16130                                 &pending_break_support, _("\
16131 Set debugger's behavior regarding pending breakpoints."), _("\
16132 Show debugger's behavior regarding pending breakpoints."), _("\
16133 If on, an unrecognized breakpoint location will cause gdb to create a\n\
16134 pending breakpoint.  If off, an unrecognized breakpoint location results in\n\
16135 an error.  If auto, an unrecognized breakpoint location results in a\n\
16136 user-query to see if a pending breakpoint should be created."),
16137                                 NULL,
16138                                 show_pending_break_support,
16139                                 &breakpoint_set_cmdlist,
16140                                 &breakpoint_show_cmdlist);
16141
16142   pending_break_support = AUTO_BOOLEAN_AUTO;
16143
16144   add_setshow_boolean_cmd ("auto-hw", no_class,
16145                            &automatic_hardware_breakpoints, _("\
16146 Set automatic usage of hardware breakpoints."), _("\
16147 Show automatic usage of hardware breakpoints."), _("\
16148 If set, the debugger will automatically use hardware breakpoints for\n\
16149 breakpoints set with \"break\" but falling in read-only memory.  If not set,\n\
16150 a warning will be emitted for such breakpoints."),
16151                            NULL,
16152                            show_automatic_hardware_breakpoints,
16153                            &breakpoint_set_cmdlist,
16154                            &breakpoint_show_cmdlist);
16155
16156   add_setshow_auto_boolean_cmd ("always-inserted", class_support,
16157                                 &always_inserted_mode, _("\
16158 Set mode for inserting breakpoints."), _("\
16159 Show mode for inserting breakpoints."), _("\
16160 When this mode is off, breakpoints are inserted in inferior when it is\n\
16161 resumed, and removed when execution stops.  When this mode is on,\n\
16162 breakpoints are inserted immediately and removed only when the user\n\
16163 deletes the breakpoint.  When this mode is auto (which is the default),\n\
16164 the behaviour depends on the non-stop setting (see help set non-stop).\n\
16165 In this case, if gdb is controlling the inferior in non-stop mode, gdb\n\
16166 behaves as if always-inserted mode is on; if gdb is controlling the\n\
16167 inferior in all-stop mode, gdb behaves as if always-inserted mode is off."),
16168                                 NULL,
16169                                 &show_always_inserted_mode,
16170                                 &breakpoint_set_cmdlist,
16171                                 &breakpoint_show_cmdlist);
16172
16173   add_setshow_enum_cmd ("condition-evaluation", class_breakpoint,
16174                         condition_evaluation_enums,
16175                         &condition_evaluation_mode_1, _("\
16176 Set mode of breakpoint condition evaluation."), _("\
16177 Show mode of breakpoint condition evaluation."), _("\
16178 When this is set to \"host\", breakpoint conditions will be\n\
16179 evaluated on the host's side by GDB.  When it is set to \"target\",\n\
16180 breakpoint conditions will be downloaded to the target (if the target\n\
16181 supports such feature) and conditions will be evaluated on the target's side.\n\
16182 If this is set to \"auto\" (default), this will be automatically set to\n\
16183 \"target\" if it supports condition evaluation, otherwise it will\n\
16184 be set to \"gdb\""),
16185                            &set_condition_evaluation_mode,
16186                            &show_condition_evaluation_mode,
16187                            &breakpoint_set_cmdlist,
16188                            &breakpoint_show_cmdlist);
16189
16190   add_com ("break-range", class_breakpoint, break_range_command, _("\
16191 Set a breakpoint for an address range.\n\
16192 break-range START-LOCATION, END-LOCATION\n\
16193 where START-LOCATION and END-LOCATION can be one of the following:\n\
16194   LINENUM, for that line in the current file,\n\
16195   FILE:LINENUM, for that line in that file,\n\
16196   +OFFSET, for that number of lines after the current line\n\
16197            or the start of the range\n\
16198   FUNCTION, for the first line in that function,\n\
16199   FILE:FUNCTION, to distinguish among like-named static functions.\n\
16200   *ADDRESS, for the instruction at that address.\n\
16201 \n\
16202 The breakpoint will stop execution of the inferior whenever it executes\n\
16203 an instruction at any address within the [START-LOCATION, END-LOCATION]\n\
16204 range (including START-LOCATION and END-LOCATION)."));
16205
16206   c = add_com ("dprintf", class_breakpoint, dprintf_command, _("\
16207 Set a dynamic printf at specified line or function.\n\
16208 dprintf location,format string,arg1,arg2,...\n\
16209 location may be a line number, function name, or \"*\" and an address.\n\
16210 If a line number is specified, break at start of code for that line.\n\
16211 If a function is specified, break at start of code for that function.\n\
16212 "));
16213   set_cmd_completer (c, location_completer);
16214
16215   add_setshow_enum_cmd ("dprintf-style", class_support,
16216                         dprintf_style_enums, &dprintf_style, _("\
16217 Set the style of usage for dynamic printf."), _("\
16218 Show the style of usage for dynamic printf."), _("\
16219 This setting chooses how GDB will do a dynamic printf.\n\
16220 If the value is \"gdb\", then the printing is done by GDB to its own\n\
16221 console, as with the \"printf\" command.\n\
16222 If the value is \"call\", the print is done by calling a function in your\n\
16223 program; by default printf(), but you can choose a different function or\n\
16224 output stream by setting dprintf-function and dprintf-channel."),
16225                         update_dprintf_commands, NULL,
16226                         &setlist, &showlist);
16227
16228   dprintf_function = xstrdup ("printf");
16229   add_setshow_string_cmd ("dprintf-function", class_support,
16230                           &dprintf_function, _("\
16231 Set the function to use for dynamic printf"), _("\
16232 Show the function to use for dynamic printf"), NULL,
16233                           update_dprintf_commands, NULL,
16234                           &setlist, &showlist);
16235
16236   dprintf_channel = xstrdup ("");
16237   add_setshow_string_cmd ("dprintf-channel", class_support,
16238                           &dprintf_channel, _("\
16239 Set the channel to use for dynamic printf"), _("\
16240 Show the channel to use for dynamic printf"), NULL,
16241                           update_dprintf_commands, NULL,
16242                           &setlist, &showlist);
16243
16244   automatic_hardware_breakpoints = 1;
16245
16246   observer_attach_about_to_proceed (breakpoint_about_to_proceed);
16247 }