tracepoint->step_count fixes
[platform/upstream/binutils.git] / gdb / breakpoint.c
1 /* Everything about breakpoints, for GDB.
2
3    Copyright (C) 1986-2013 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 #include "format.h"
74
75 /* readline include files */
76 #include "readline/readline.h"
77 #include "readline/history.h"
78
79 /* readline defines this.  */
80 #undef savestring
81
82 #include "mi/mi-common.h"
83 #include "python/python.h"
84
85 /* Enums for exception-handling support.  */
86 enum exception_event_kind
87 {
88   EX_EVENT_THROW,
89   EX_EVENT_CATCH
90 };
91
92 /* Prototypes for local functions.  */
93
94 static void enable_delete_command (char *, int);
95
96 static void enable_once_command (char *, int);
97
98 static void enable_count_command (char *, int);
99
100 static void disable_command (char *, int);
101
102 static void enable_command (char *, int);
103
104 static void map_breakpoint_numbers (char *, void (*) (struct breakpoint *,
105                                                       void *),
106                                     void *);
107
108 static void ignore_command (char *, int);
109
110 static int breakpoint_re_set_one (void *);
111
112 static void breakpoint_re_set_default (struct breakpoint *);
113
114 static void create_sals_from_address_default (char **,
115                                               struct linespec_result *,
116                                               enum bptype, char *,
117                                               char **);
118
119 static void create_breakpoints_sal_default (struct gdbarch *,
120                                             struct linespec_result *,
121                                             struct linespec_sals *,
122                                             char *, char *, enum bptype,
123                                             enum bpdisp, int, int,
124                                             int,
125                                             const struct breakpoint_ops *,
126                                             int, int, int, unsigned);
127
128 static void decode_linespec_default (struct breakpoint *, char **,
129                                      struct symtabs_and_lines *);
130
131 static void clear_command (char *, int);
132
133 static void catch_command (char *, int);
134
135 static int can_use_hardware_watchpoint (struct value *);
136
137 static void break_command_1 (char *, int, int);
138
139 static void mention (struct breakpoint *);
140
141 static struct breakpoint *set_raw_breakpoint_without_location (struct gdbarch *,
142                                                                enum bptype,
143                                                                const struct breakpoint_ops *);
144 static struct bp_location *add_location_to_breakpoint (struct breakpoint *,
145                                                        const struct symtab_and_line *);
146
147 /* This function is used in gdbtk sources and thus can not be made
148    static.  */
149 struct breakpoint *set_raw_breakpoint (struct gdbarch *gdbarch,
150                                        struct symtab_and_line,
151                                        enum bptype,
152                                        const struct breakpoint_ops *);
153
154 static struct breakpoint *
155   momentary_breakpoint_from_master (struct breakpoint *orig,
156                                     enum bptype type,
157                                     const struct breakpoint_ops *ops);
158
159 static void breakpoint_adjustment_warning (CORE_ADDR, CORE_ADDR, int, int);
160
161 static CORE_ADDR adjust_breakpoint_address (struct gdbarch *gdbarch,
162                                             CORE_ADDR bpaddr,
163                                             enum bptype bptype);
164
165 static void describe_other_breakpoints (struct gdbarch *,
166                                         struct program_space *, CORE_ADDR,
167                                         struct obj_section *, int);
168
169 static int breakpoint_address_match (struct address_space *aspace1,
170                                      CORE_ADDR addr1,
171                                      struct address_space *aspace2,
172                                      CORE_ADDR addr2);
173
174 static int watchpoint_locations_match (struct bp_location *loc1,
175                                        struct bp_location *loc2);
176
177 static int breakpoint_location_address_match (struct bp_location *bl,
178                                               struct address_space *aspace,
179                                               CORE_ADDR addr);
180
181 static void breakpoints_info (char *, int);
182
183 static void watchpoints_info (char *, int);
184
185 static int breakpoint_1 (char *, int, 
186                          int (*) (const struct breakpoint *));
187
188 static int breakpoint_cond_eval (void *);
189
190 static void cleanup_executing_breakpoints (void *);
191
192 static void commands_command (char *, int);
193
194 static void condition_command (char *, int);
195
196 typedef enum
197   {
198     mark_inserted,
199     mark_uninserted
200   }
201 insertion_state_t;
202
203 static int remove_breakpoint (struct bp_location *, insertion_state_t);
204 static int remove_breakpoint_1 (struct bp_location *, insertion_state_t);
205
206 static enum print_stop_action print_bp_stop_message (bpstat bs);
207
208 static int watchpoint_check (void *);
209
210 static void maintenance_info_breakpoints (char *, int);
211
212 static int hw_breakpoint_used_count (void);
213
214 static int hw_watchpoint_use_count (struct breakpoint *);
215
216 static int hw_watchpoint_used_count_others (struct breakpoint *except,
217                                             enum bptype type,
218                                             int *other_type_used);
219
220 static void hbreak_command (char *, int);
221
222 static void thbreak_command (char *, int);
223
224 static void enable_breakpoint_disp (struct breakpoint *, enum bpdisp,
225                                     int count);
226
227 static void stop_command (char *arg, int from_tty);
228
229 static void stopin_command (char *arg, int from_tty);
230
231 static void stopat_command (char *arg, int from_tty);
232
233 static char *ep_parse_optional_if_clause (char **arg);
234
235 static void catch_exception_command_1 (enum exception_event_kind ex_event, 
236                                        char *arg, int tempflag, int from_tty);
237
238 static void tcatch_command (char *arg, int from_tty);
239
240 static void detach_single_step_breakpoints (void);
241
242 static int single_step_breakpoint_inserted_here_p (struct address_space *,
243                                                    CORE_ADDR pc);
244
245 static void free_bp_location (struct bp_location *loc);
246 static void incref_bp_location (struct bp_location *loc);
247 static void decref_bp_location (struct bp_location **loc);
248
249 static struct bp_location *allocate_bp_location (struct breakpoint *bpt);
250
251 static void update_global_location_list (int);
252
253 static void update_global_location_list_nothrow (int);
254
255 static int is_hardware_watchpoint (const struct breakpoint *bpt);
256
257 static void insert_breakpoint_locations (void);
258
259 static int syscall_catchpoint_p (struct breakpoint *b);
260
261 static void tracepoints_info (char *, int);
262
263 static void delete_trace_command (char *, int);
264
265 static void enable_trace_command (char *, int);
266
267 static void disable_trace_command (char *, int);
268
269 static void trace_pass_command (char *, int);
270
271 static void set_tracepoint_count (int num);
272
273 static int is_masked_watchpoint (const struct breakpoint *b);
274
275 static struct bp_location **get_first_locp_gte_addr (CORE_ADDR address);
276
277 /* Return 1 if B refers to a static tracepoint set by marker ("-m"), zero
278    otherwise.  */
279
280 static int strace_marker_p (struct breakpoint *b);
281
282 /* The abstract base class all breakpoint_ops structures inherit
283    from.  */
284 struct breakpoint_ops base_breakpoint_ops;
285
286 /* The breakpoint_ops structure to be inherited by all breakpoint_ops
287    that are implemented on top of software or hardware breakpoints
288    (user breakpoints, internal and momentary breakpoints, etc.).  */
289 static struct breakpoint_ops bkpt_base_breakpoint_ops;
290
291 /* Internal breakpoints class type.  */
292 static struct breakpoint_ops internal_breakpoint_ops;
293
294 /* Momentary breakpoints class type.  */
295 static struct breakpoint_ops momentary_breakpoint_ops;
296
297 /* Momentary breakpoints for bp_longjmp and bp_exception class type.  */
298 static struct breakpoint_ops longjmp_breakpoint_ops;
299
300 /* The breakpoint_ops structure to be used in regular user created
301    breakpoints.  */
302 struct breakpoint_ops bkpt_breakpoint_ops;
303
304 /* Breakpoints set on probes.  */
305 static struct breakpoint_ops bkpt_probe_breakpoint_ops;
306
307 /* Dynamic printf class type.  */
308 static struct breakpoint_ops dprintf_breakpoint_ops;
309
310 /* The style in which to perform a dynamic printf.  This is a user
311    option because different output options have different tradeoffs;
312    if GDB does the printing, there is better error handling if there
313    is a problem with any of the arguments, but using an inferior
314    function lets you have special-purpose printers and sending of
315    output to the same place as compiled-in print functions.  */
316
317 static const char dprintf_style_gdb[] = "gdb";
318 static const char dprintf_style_call[] = "call";
319 static const char dprintf_style_agent[] = "agent";
320 static const char *const dprintf_style_enums[] = {
321   dprintf_style_gdb,
322   dprintf_style_call,
323   dprintf_style_agent,
324   NULL
325 };
326 static const char *dprintf_style = dprintf_style_gdb;
327
328 /* The function to use for dynamic printf if the preferred style is to
329    call into the inferior.  The value is simply a string that is
330    copied into the command, so it can be anything that GDB can
331    evaluate to a callable address, not necessarily a function name.  */
332
333 static char *dprintf_function = "";
334
335 /* The channel to use for dynamic printf if the preferred style is to
336    call into the inferior; if a nonempty string, it will be passed to
337    the call as the first argument, with the format string as the
338    second.  As with the dprintf function, this can be anything that
339    GDB knows how to evaluate, so in addition to common choices like
340    "stderr", this could be an app-specific expression like
341    "mystreams[curlogger]".  */
342
343 static char *dprintf_channel = "";
344
345 /* True if dprintf commands should continue to operate even if GDB
346    has disconnected.  */
347 static int disconnected_dprintf = 1;
348
349 /* A reference-counted struct command_line.  This lets multiple
350    breakpoints share a single command list.  */
351 struct counted_command_line
352 {
353   /* The reference count.  */
354   int refc;
355
356   /* The command list.  */
357   struct command_line *commands;
358 };
359
360 struct command_line *
361 breakpoint_commands (struct breakpoint *b)
362 {
363   return b->commands ? b->commands->commands : NULL;
364 }
365
366 /* Flag indicating that a command has proceeded the inferior past the
367    current breakpoint.  */
368
369 static int breakpoint_proceeded;
370
371 const char *
372 bpdisp_text (enum bpdisp disp)
373 {
374   /* NOTE: the following values are a part of MI protocol and
375      represent values of 'disp' field returned when inferior stops at
376      a breakpoint.  */
377   static const char * const bpdisps[] = {"del", "dstp", "dis", "keep"};
378
379   return bpdisps[(int) disp];
380 }
381
382 /* Prototypes for exported functions.  */
383 /* If FALSE, gdb will not use hardware support for watchpoints, even
384    if such is available.  */
385 static int can_use_hw_watchpoints;
386
387 static void
388 show_can_use_hw_watchpoints (struct ui_file *file, int from_tty,
389                              struct cmd_list_element *c,
390                              const char *value)
391 {
392   fprintf_filtered (file,
393                     _("Debugger's willingness to use "
394                       "watchpoint hardware is %s.\n"),
395                     value);
396 }
397
398 /* If AUTO_BOOLEAN_FALSE, gdb will not attempt to create pending breakpoints.
399    If AUTO_BOOLEAN_TRUE, gdb will automatically create pending breakpoints
400    for unrecognized breakpoint locations.
401    If AUTO_BOOLEAN_AUTO, gdb will query when breakpoints are unrecognized.  */
402 static enum auto_boolean pending_break_support;
403 static void
404 show_pending_break_support (struct ui_file *file, int from_tty,
405                             struct cmd_list_element *c,
406                             const char *value)
407 {
408   fprintf_filtered (file,
409                     _("Debugger's behavior regarding "
410                       "pending breakpoints is %s.\n"),
411                     value);
412 }
413
414 /* If 1, gdb will automatically use hardware breakpoints for breakpoints
415    set with "break" but falling in read-only memory.
416    If 0, gdb will warn about such breakpoints, but won't automatically
417    use hardware breakpoints.  */
418 static int automatic_hardware_breakpoints;
419 static void
420 show_automatic_hardware_breakpoints (struct ui_file *file, int from_tty,
421                                      struct cmd_list_element *c,
422                                      const char *value)
423 {
424   fprintf_filtered (file,
425                     _("Automatic usage of hardware breakpoints is %s.\n"),
426                     value);
427 }
428
429 /* If on, gdb will keep breakpoints inserted even as inferior is
430    stopped, and immediately insert any new breakpoints.  If off, gdb
431    will insert breakpoints into inferior only when resuming it, and
432    will remove breakpoints upon stop.  If auto, GDB will behave as ON
433    if in non-stop mode, and as OFF if all-stop mode.*/
434
435 static enum auto_boolean always_inserted_mode = AUTO_BOOLEAN_AUTO;
436
437 static void
438 show_always_inserted_mode (struct ui_file *file, int from_tty,
439                      struct cmd_list_element *c, const char *value)
440 {
441   if (always_inserted_mode == AUTO_BOOLEAN_AUTO)
442     fprintf_filtered (file,
443                       _("Always inserted breakpoint "
444                         "mode is %s (currently %s).\n"),
445                       value,
446                       breakpoints_always_inserted_mode () ? "on" : "off");
447   else
448     fprintf_filtered (file, _("Always inserted breakpoint mode is %s.\n"),
449                       value);
450 }
451
452 int
453 breakpoints_always_inserted_mode (void)
454 {
455   return (always_inserted_mode == AUTO_BOOLEAN_TRUE
456           || (always_inserted_mode == AUTO_BOOLEAN_AUTO && non_stop));
457 }
458
459 static const char condition_evaluation_both[] = "host or target";
460
461 /* Modes for breakpoint condition evaluation.  */
462 static const char condition_evaluation_auto[] = "auto";
463 static const char condition_evaluation_host[] = "host";
464 static const char condition_evaluation_target[] = "target";
465 static const char *const condition_evaluation_enums[] = {
466   condition_evaluation_auto,
467   condition_evaluation_host,
468   condition_evaluation_target,
469   NULL
470 };
471
472 /* Global that holds the current mode for breakpoint condition evaluation.  */
473 static const char *condition_evaluation_mode_1 = condition_evaluation_auto;
474
475 /* Global that we use to display information to the user (gets its value from
476    condition_evaluation_mode_1.  */
477 static const char *condition_evaluation_mode = condition_evaluation_auto;
478
479 /* Translate a condition evaluation mode MODE into either "host"
480    or "target".  This is used mostly to translate from "auto" to the
481    real setting that is being used.  It returns the translated
482    evaluation mode.  */
483
484 static const char *
485 translate_condition_evaluation_mode (const char *mode)
486 {
487   if (mode == condition_evaluation_auto)
488     {
489       if (target_supports_evaluation_of_breakpoint_conditions ())
490         return condition_evaluation_target;
491       else
492         return condition_evaluation_host;
493     }
494   else
495     return mode;
496 }
497
498 /* Discovers what condition_evaluation_auto translates to.  */
499
500 static const char *
501 breakpoint_condition_evaluation_mode (void)
502 {
503   return translate_condition_evaluation_mode (condition_evaluation_mode);
504 }
505
506 /* Return true if GDB should evaluate breakpoint conditions or false
507    otherwise.  */
508
509 static int
510 gdb_evaluates_breakpoint_condition_p (void)
511 {
512   const char *mode = breakpoint_condition_evaluation_mode ();
513
514   return (mode == condition_evaluation_host);
515 }
516
517 void _initialize_breakpoint (void);
518
519 /* Are we executing breakpoint commands?  */
520 static int executing_breakpoint_commands;
521
522 /* Are overlay event breakpoints enabled? */
523 static int overlay_events_enabled;
524
525 /* See description in breakpoint.h. */
526 int target_exact_watchpoints = 0;
527
528 /* Walk the following statement or block through all breakpoints.
529    ALL_BREAKPOINTS_SAFE does so even if the statement deletes the
530    current breakpoint.  */
531
532 #define ALL_BREAKPOINTS(B)  for (B = breakpoint_chain; B; B = B->next)
533
534 #define ALL_BREAKPOINTS_SAFE(B,TMP)     \
535         for (B = breakpoint_chain;      \
536              B ? (TMP=B->next, 1): 0;   \
537              B = TMP)
538
539 /* Similar iterator for the low-level breakpoints.  SAFE variant is
540    not provided so update_global_location_list must not be called
541    while executing the block of ALL_BP_LOCATIONS.  */
542
543 #define ALL_BP_LOCATIONS(B,BP_TMP)                                      \
544         for (BP_TMP = bp_location;                                      \
545              BP_TMP < bp_location + bp_location_count && (B = *BP_TMP); \
546              BP_TMP++)
547
548 /* Iterates through locations with address ADDRESS for the currently selected
549    program space.  BP_LOCP_TMP points to each object.  BP_LOCP_START points
550    to where the loop should start from.
551    If BP_LOCP_START is a NULL pointer, the macro automatically seeks the
552    appropriate location to start with.  */
553
554 #define ALL_BP_LOCATIONS_AT_ADDR(BP_LOCP_TMP, BP_LOCP_START, ADDRESS)   \
555         for (BP_LOCP_START = BP_LOCP_START == NULL ? get_first_locp_gte_addr (ADDRESS) : BP_LOCP_START, \
556              BP_LOCP_TMP = BP_LOCP_START;                               \
557              BP_LOCP_START                                              \
558              && (BP_LOCP_TMP < bp_location + bp_location_count          \
559              && (*BP_LOCP_TMP)->address == ADDRESS);                    \
560              BP_LOCP_TMP++)
561
562 /* Iterator for tracepoints only.  */
563
564 #define ALL_TRACEPOINTS(B)  \
565   for (B = breakpoint_chain; B; B = B->next)  \
566     if (is_tracepoint (B))
567
568 /* Chains of all breakpoints defined.  */
569
570 struct breakpoint *breakpoint_chain;
571
572 /* Array is sorted by bp_location_compare - primarily by the ADDRESS.  */
573
574 static struct bp_location **bp_location;
575
576 /* Number of elements of BP_LOCATION.  */
577
578 static unsigned bp_location_count;
579
580 /* Maximum alignment offset between bp_target_info.PLACED_ADDRESS and
581    ADDRESS for the current elements of BP_LOCATION which get a valid
582    result from bp_location_has_shadow.  You can use it for roughly
583    limiting the subrange of BP_LOCATION to scan for shadow bytes for
584    an address you need to read.  */
585
586 static CORE_ADDR bp_location_placed_address_before_address_max;
587
588 /* Maximum offset plus alignment between bp_target_info.PLACED_ADDRESS
589    + bp_target_info.SHADOW_LEN and ADDRESS for the current elements of
590    BP_LOCATION which get a valid result from bp_location_has_shadow.
591    You can use it for roughly limiting the subrange of BP_LOCATION to
592    scan for shadow bytes for an address you need to read.  */
593
594 static CORE_ADDR bp_location_shadow_len_after_address_max;
595
596 /* The locations that no longer correspond to any breakpoint, unlinked
597    from bp_location array, but for which a hit may still be reported
598    by a target.  */
599 VEC(bp_location_p) *moribund_locations = NULL;
600
601 /* Number of last breakpoint made.  */
602
603 static int breakpoint_count;
604
605 /* The value of `breakpoint_count' before the last command that
606    created breakpoints.  If the last (break-like) command created more
607    than one breakpoint, then the difference between BREAKPOINT_COUNT
608    and PREV_BREAKPOINT_COUNT is more than one.  */
609 static int prev_breakpoint_count;
610
611 /* Number of last tracepoint made.  */
612
613 static int tracepoint_count;
614
615 static struct cmd_list_element *breakpoint_set_cmdlist;
616 static struct cmd_list_element *breakpoint_show_cmdlist;
617 struct cmd_list_element *save_cmdlist;
618
619 /* Return whether a breakpoint is an active enabled breakpoint.  */
620 static int
621 breakpoint_enabled (struct breakpoint *b)
622 {
623   return (b->enable_state == bp_enabled);
624 }
625
626 /* Set breakpoint count to NUM.  */
627
628 static void
629 set_breakpoint_count (int num)
630 {
631   prev_breakpoint_count = breakpoint_count;
632   breakpoint_count = num;
633   set_internalvar_integer (lookup_internalvar ("bpnum"), num);
634 }
635
636 /* Used by `start_rbreak_breakpoints' below, to record the current
637    breakpoint count before "rbreak" creates any breakpoint.  */
638 static int rbreak_start_breakpoint_count;
639
640 /* Called at the start an "rbreak" command to record the first
641    breakpoint made.  */
642
643 void
644 start_rbreak_breakpoints (void)
645 {
646   rbreak_start_breakpoint_count = breakpoint_count;
647 }
648
649 /* Called at the end of an "rbreak" command to record the last
650    breakpoint made.  */
651
652 void
653 end_rbreak_breakpoints (void)
654 {
655   prev_breakpoint_count = rbreak_start_breakpoint_count;
656 }
657
658 /* Used in run_command to zero the hit count when a new run starts.  */
659
660 void
661 clear_breakpoint_hit_counts (void)
662 {
663   struct breakpoint *b;
664
665   ALL_BREAKPOINTS (b)
666     b->hit_count = 0;
667 }
668
669 /* Allocate a new counted_command_line with reference count of 1.
670    The new structure owns COMMANDS.  */
671
672 static struct counted_command_line *
673 alloc_counted_command_line (struct command_line *commands)
674 {
675   struct counted_command_line *result
676     = xmalloc (sizeof (struct counted_command_line));
677
678   result->refc = 1;
679   result->commands = commands;
680   return result;
681 }
682
683 /* Increment reference count.  This does nothing if CMD is NULL.  */
684
685 static void
686 incref_counted_command_line (struct counted_command_line *cmd)
687 {
688   if (cmd)
689     ++cmd->refc;
690 }
691
692 /* Decrement reference count.  If the reference count reaches 0,
693    destroy the counted_command_line.  Sets *CMDP to NULL.  This does
694    nothing if *CMDP is NULL.  */
695
696 static void
697 decref_counted_command_line (struct counted_command_line **cmdp)
698 {
699   if (*cmdp)
700     {
701       if (--(*cmdp)->refc == 0)
702         {
703           free_command_lines (&(*cmdp)->commands);
704           xfree (*cmdp);
705         }
706       *cmdp = NULL;
707     }
708 }
709
710 /* A cleanup function that calls decref_counted_command_line.  */
711
712 static void
713 do_cleanup_counted_command_line (void *arg)
714 {
715   decref_counted_command_line (arg);
716 }
717
718 /* Create a cleanup that calls decref_counted_command_line on the
719    argument.  */
720
721 static struct cleanup *
722 make_cleanup_decref_counted_command_line (struct counted_command_line **cmdp)
723 {
724   return make_cleanup (do_cleanup_counted_command_line, cmdp);
725 }
726
727 \f
728 /* Return the breakpoint with the specified number, or NULL
729    if the number does not refer to an existing breakpoint.  */
730
731 struct breakpoint *
732 get_breakpoint (int num)
733 {
734   struct breakpoint *b;
735
736   ALL_BREAKPOINTS (b)
737     if (b->number == num)
738       return b;
739   
740   return NULL;
741 }
742
743 \f
744
745 /* Mark locations as "conditions have changed" in case the target supports
746    evaluating conditions on its side.  */
747
748 static void
749 mark_breakpoint_modified (struct breakpoint *b)
750 {
751   struct bp_location *loc;
752
753   /* This is only meaningful if the target is
754      evaluating conditions and if the user has
755      opted for condition evaluation on the target's
756      side.  */
757   if (gdb_evaluates_breakpoint_condition_p ()
758       || !target_supports_evaluation_of_breakpoint_conditions ())
759     return;
760
761   if (!is_breakpoint (b))
762     return;
763
764   for (loc = b->loc; loc; loc = loc->next)
765     loc->condition_changed = condition_modified;
766 }
767
768 /* Mark location as "conditions have changed" in case the target supports
769    evaluating conditions on its side.  */
770
771 static void
772 mark_breakpoint_location_modified (struct bp_location *loc)
773 {
774   /* This is only meaningful if the target is
775      evaluating conditions and if the user has
776      opted for condition evaluation on the target's
777      side.  */
778   if (gdb_evaluates_breakpoint_condition_p ()
779       || !target_supports_evaluation_of_breakpoint_conditions ())
780
781     return;
782
783   if (!is_breakpoint (loc->owner))
784     return;
785
786   loc->condition_changed = condition_modified;
787 }
788
789 /* Sets the condition-evaluation mode using the static global
790    condition_evaluation_mode.  */
791
792 static void
793 set_condition_evaluation_mode (char *args, int from_tty,
794                                struct cmd_list_element *c)
795 {
796   const char *old_mode, *new_mode;
797
798   if ((condition_evaluation_mode_1 == condition_evaluation_target)
799       && !target_supports_evaluation_of_breakpoint_conditions ())
800     {
801       condition_evaluation_mode_1 = condition_evaluation_mode;
802       warning (_("Target does not support breakpoint condition evaluation.\n"
803                  "Using host evaluation mode instead."));
804       return;
805     }
806
807   new_mode = translate_condition_evaluation_mode (condition_evaluation_mode_1);
808   old_mode = translate_condition_evaluation_mode (condition_evaluation_mode);
809
810   /* Flip the switch.  Flip it even if OLD_MODE == NEW_MODE as one of the
811      settings was "auto".  */
812   condition_evaluation_mode = condition_evaluation_mode_1;
813
814   /* Only update the mode if the user picked a different one.  */
815   if (new_mode != old_mode)
816     {
817       struct bp_location *loc, **loc_tmp;
818       /* If the user switched to a different evaluation mode, we
819          need to synch the changes with the target as follows:
820
821          "host" -> "target": Send all (valid) conditions to the target.
822          "target" -> "host": Remove all the conditions from the target.
823       */
824
825       if (new_mode == condition_evaluation_target)
826         {
827           /* Mark everything modified and synch conditions with the
828              target.  */
829           ALL_BP_LOCATIONS (loc, loc_tmp)
830             mark_breakpoint_location_modified (loc);
831         }
832       else
833         {
834           /* Manually mark non-duplicate locations to synch conditions
835              with the target.  We do this to remove all the conditions the
836              target knows about.  */
837           ALL_BP_LOCATIONS (loc, loc_tmp)
838             if (is_breakpoint (loc->owner) && loc->inserted)
839               loc->needs_update = 1;
840         }
841
842       /* Do the update.  */
843       update_global_location_list (1);
844     }
845
846   return;
847 }
848
849 /* Shows the current mode of breakpoint condition evaluation.  Explicitly shows
850    what "auto" is translating to.  */
851
852 static void
853 show_condition_evaluation_mode (struct ui_file *file, int from_tty,
854                                 struct cmd_list_element *c, const char *value)
855 {
856   if (condition_evaluation_mode == condition_evaluation_auto)
857     fprintf_filtered (file,
858                       _("Breakpoint condition evaluation "
859                         "mode is %s (currently %s).\n"),
860                       value,
861                       breakpoint_condition_evaluation_mode ());
862   else
863     fprintf_filtered (file, _("Breakpoint condition evaluation mode is %s.\n"),
864                       value);
865 }
866
867 /* A comparison function for bp_location AP and BP that is used by
868    bsearch.  This comparison function only cares about addresses, unlike
869    the more general bp_location_compare function.  */
870
871 static int
872 bp_location_compare_addrs (const void *ap, const void *bp)
873 {
874   struct bp_location *a = *(void **) ap;
875   struct bp_location *b = *(void **) bp;
876
877   if (a->address == b->address)
878     return 0;
879   else
880     return ((a->address > b->address) - (a->address < b->address));
881 }
882
883 /* Helper function to skip all bp_locations with addresses
884    less than ADDRESS.  It returns the first bp_location that
885    is greater than or equal to ADDRESS.  If none is found, just
886    return NULL.  */
887
888 static struct bp_location **
889 get_first_locp_gte_addr (CORE_ADDR address)
890 {
891   struct bp_location dummy_loc;
892   struct bp_location *dummy_locp = &dummy_loc;
893   struct bp_location **locp_found = NULL;
894
895   /* Initialize the dummy location's address field.  */
896   memset (&dummy_loc, 0, sizeof (struct bp_location));
897   dummy_loc.address = address;
898
899   /* Find a close match to the first location at ADDRESS.  */
900   locp_found = bsearch (&dummy_locp, bp_location, bp_location_count,
901                         sizeof (struct bp_location **),
902                         bp_location_compare_addrs);
903
904   /* Nothing was found, nothing left to do.  */
905   if (locp_found == NULL)
906     return NULL;
907
908   /* We may have found a location that is at ADDRESS but is not the first in the
909      location's list.  Go backwards (if possible) and locate the first one.  */
910   while ((locp_found - 1) >= bp_location
911          && (*(locp_found - 1))->address == address)
912     locp_found--;
913
914   return locp_found;
915 }
916
917 void
918 set_breakpoint_condition (struct breakpoint *b, char *exp,
919                           int from_tty)
920 {
921   xfree (b->cond_string);
922   b->cond_string = NULL;
923
924   if (is_watchpoint (b))
925     {
926       struct watchpoint *w = (struct watchpoint *) b;
927
928       xfree (w->cond_exp);
929       w->cond_exp = NULL;
930     }
931   else
932     {
933       struct bp_location *loc;
934
935       for (loc = b->loc; loc; loc = loc->next)
936         {
937           xfree (loc->cond);
938           loc->cond = NULL;
939
940           /* No need to free the condition agent expression
941              bytecode (if we have one).  We will handle this
942              when we go through update_global_location_list.  */
943         }
944     }
945
946   if (*exp == 0)
947     {
948       if (from_tty)
949         printf_filtered (_("Breakpoint %d now unconditional.\n"), b->number);
950     }
951   else
952     {
953       const char *arg = exp;
954
955       /* I don't know if it matters whether this is the string the user
956          typed in or the decompiled expression.  */
957       b->cond_string = xstrdup (arg);
958       b->condition_not_parsed = 0;
959
960       if (is_watchpoint (b))
961         {
962           struct watchpoint *w = (struct watchpoint *) b;
963
964           innermost_block = NULL;
965           arg = exp;
966           w->cond_exp = parse_exp_1 (&arg, 0, 0, 0);
967           if (*arg)
968             error (_("Junk at end of expression"));
969           w->cond_exp_valid_block = innermost_block;
970         }
971       else
972         {
973           struct bp_location *loc;
974
975           for (loc = b->loc; loc; loc = loc->next)
976             {
977               arg = exp;
978               loc->cond =
979                 parse_exp_1 (&arg, loc->address,
980                              block_for_pc (loc->address), 0);
981               if (*arg)
982                 error (_("Junk at end of expression"));
983             }
984         }
985     }
986   mark_breakpoint_modified (b);
987
988   observer_notify_breakpoint_modified (b);
989 }
990
991 /* Completion for the "condition" command.  */
992
993 static VEC (char_ptr) *
994 condition_completer (struct cmd_list_element *cmd,
995                      const char *text, const char *word)
996 {
997   const char *space;
998
999   text = skip_spaces_const (text);
1000   space = skip_to_space_const (text);
1001   if (*space == '\0')
1002     {
1003       int len;
1004       struct breakpoint *b;
1005       VEC (char_ptr) *result = NULL;
1006
1007       if (text[0] == '$')
1008         {
1009           /* We don't support completion of history indices.  */
1010           if (isdigit (text[1]))
1011             return NULL;
1012           return complete_internalvar (&text[1]);
1013         }
1014
1015       /* We're completing the breakpoint number.  */
1016       len = strlen (text);
1017
1018       ALL_BREAKPOINTS (b)
1019       {
1020         int single = b->loc->next == NULL;
1021         struct bp_location *loc;
1022         int count = 1;
1023
1024         for (loc = b->loc; loc; loc = loc->next)
1025           {
1026             char location[50];
1027
1028             if (single)
1029               xsnprintf (location, sizeof (location), "%d", b->number);
1030             else
1031               xsnprintf (location, sizeof (location),  "%d.%d", b->number,
1032                          count);
1033
1034             if (strncmp (location, text, len) == 0)
1035               VEC_safe_push (char_ptr, result, xstrdup (location));
1036
1037             ++count;
1038           }
1039       }
1040
1041       return result;
1042     }
1043
1044   /* We're completing the expression part.  */
1045   text = skip_spaces_const (space);
1046   return expression_completer (cmd, text, word);
1047 }
1048
1049 /* condition N EXP -- set break condition of breakpoint N to EXP.  */
1050
1051 static void
1052 condition_command (char *arg, int from_tty)
1053 {
1054   struct breakpoint *b;
1055   char *p;
1056   int bnum;
1057
1058   if (arg == 0)
1059     error_no_arg (_("breakpoint number"));
1060
1061   p = arg;
1062   bnum = get_number (&p);
1063   if (bnum == 0)
1064     error (_("Bad breakpoint argument: '%s'"), arg);
1065
1066   ALL_BREAKPOINTS (b)
1067     if (b->number == bnum)
1068       {
1069         /* Check if this breakpoint has a Python object assigned to
1070            it, and if it has a definition of the "stop"
1071            method.  This method and conditions entered into GDB from
1072            the CLI are mutually exclusive.  */
1073         if (b->py_bp_object
1074             && gdbpy_breakpoint_has_py_cond (b->py_bp_object))
1075           error (_("Cannot set a condition where a Python 'stop' "
1076                    "method has been defined in the breakpoint."));
1077         set_breakpoint_condition (b, p, from_tty);
1078
1079         if (is_breakpoint (b))
1080           update_global_location_list (1);
1081
1082         return;
1083       }
1084
1085   error (_("No breakpoint number %d."), bnum);
1086 }
1087
1088 /* Check that COMMAND do not contain commands that are suitable
1089    only for tracepoints and not suitable for ordinary breakpoints.
1090    Throw if any such commands is found.  */
1091
1092 static void
1093 check_no_tracepoint_commands (struct command_line *commands)
1094 {
1095   struct command_line *c;
1096
1097   for (c = commands; c; c = c->next)
1098     {
1099       int i;
1100
1101       if (c->control_type == while_stepping_control)
1102         error (_("The 'while-stepping' command can "
1103                  "only be used for tracepoints"));
1104
1105       for (i = 0; i < c->body_count; ++i)
1106         check_no_tracepoint_commands ((c->body_list)[i]);
1107
1108       /* Not that command parsing removes leading whitespace and comment
1109          lines and also empty lines.  So, we only need to check for
1110          command directly.  */
1111       if (strstr (c->line, "collect ") == c->line)
1112         error (_("The 'collect' command can only be used for tracepoints"));
1113
1114       if (strstr (c->line, "teval ") == c->line)
1115         error (_("The 'teval' command can only be used for tracepoints"));
1116     }
1117 }
1118
1119 /* Encapsulate tests for different types of tracepoints.  */
1120
1121 static int
1122 is_tracepoint_type (enum bptype type)
1123 {
1124   return (type == bp_tracepoint
1125           || type == bp_fast_tracepoint
1126           || type == bp_static_tracepoint);
1127 }
1128
1129 int
1130 is_tracepoint (const struct breakpoint *b)
1131 {
1132   return is_tracepoint_type (b->type);
1133 }
1134
1135 /* A helper function that validates that COMMANDS are valid for a
1136    breakpoint.  This function will throw an exception if a problem is
1137    found.  */
1138
1139 static void
1140 validate_commands_for_breakpoint (struct breakpoint *b,
1141                                   struct command_line *commands)
1142 {
1143   if (is_tracepoint (b))
1144     {
1145       struct tracepoint *t = (struct tracepoint *) b;
1146       struct command_line *c;
1147       struct command_line *while_stepping = 0;
1148
1149       /* Reset the while-stepping step count.  The previous commands
1150          might have included a while-stepping action, while the new
1151          ones might not.  */
1152       t->step_count = 0;
1153
1154       /* We need to verify that each top-level element of commands is
1155          valid for tracepoints, that there's at most one
1156          while-stepping element, and that the while-stepping's body
1157          has valid tracing commands excluding nested while-stepping.
1158          We also need to validate the tracepoint action line in the
1159          context of the tracepoint --- validate_actionline actually
1160          has side effects, like setting the tracepoint's
1161          while-stepping STEP_COUNT, in addition to checking if the
1162          collect/teval actions parse and make sense in the
1163          tracepoint's context.  */
1164       for (c = commands; c; c = c->next)
1165         {
1166           if (c->control_type == while_stepping_control)
1167             {
1168               if (b->type == bp_fast_tracepoint)
1169                 error (_("The 'while-stepping' command "
1170                          "cannot be used for fast tracepoint"));
1171               else if (b->type == bp_static_tracepoint)
1172                 error (_("The 'while-stepping' command "
1173                          "cannot be used for static tracepoint"));
1174
1175               if (while_stepping)
1176                 error (_("The 'while-stepping' command "
1177                          "can be used only once"));
1178               else
1179                 while_stepping = c;
1180             }
1181
1182           validate_actionline (c->line, b);
1183         }
1184       if (while_stepping)
1185         {
1186           struct command_line *c2;
1187
1188           gdb_assert (while_stepping->body_count == 1);
1189           c2 = while_stepping->body_list[0];
1190           for (; c2; c2 = c2->next)
1191             {
1192               if (c2->control_type == while_stepping_control)
1193                 error (_("The 'while-stepping' command cannot be nested"));
1194             }
1195         }
1196     }
1197   else
1198     {
1199       check_no_tracepoint_commands (commands);
1200     }
1201 }
1202
1203 /* Return a vector of all the static tracepoints set at ADDR.  The
1204    caller is responsible for releasing the vector.  */
1205
1206 VEC(breakpoint_p) *
1207 static_tracepoints_here (CORE_ADDR addr)
1208 {
1209   struct breakpoint *b;
1210   VEC(breakpoint_p) *found = 0;
1211   struct bp_location *loc;
1212
1213   ALL_BREAKPOINTS (b)
1214     if (b->type == bp_static_tracepoint)
1215       {
1216         for (loc = b->loc; loc; loc = loc->next)
1217           if (loc->address == addr)
1218             VEC_safe_push(breakpoint_p, found, b);
1219       }
1220
1221   return found;
1222 }
1223
1224 /* Set the command list of B to COMMANDS.  If breakpoint is tracepoint,
1225    validate that only allowed commands are included.  */
1226
1227 void
1228 breakpoint_set_commands (struct breakpoint *b, 
1229                          struct command_line *commands)
1230 {
1231   validate_commands_for_breakpoint (b, commands);
1232
1233   decref_counted_command_line (&b->commands);
1234   b->commands = alloc_counted_command_line (commands);
1235   observer_notify_breakpoint_modified (b);
1236 }
1237
1238 /* Set the internal `silent' flag on the breakpoint.  Note that this
1239    is not the same as the "silent" that may appear in the breakpoint's
1240    commands.  */
1241
1242 void
1243 breakpoint_set_silent (struct breakpoint *b, int silent)
1244 {
1245   int old_silent = b->silent;
1246
1247   b->silent = silent;
1248   if (old_silent != silent)
1249     observer_notify_breakpoint_modified (b);
1250 }
1251
1252 /* Set the thread for this breakpoint.  If THREAD is -1, make the
1253    breakpoint work for any thread.  */
1254
1255 void
1256 breakpoint_set_thread (struct breakpoint *b, int thread)
1257 {
1258   int old_thread = b->thread;
1259
1260   b->thread = thread;
1261   if (old_thread != thread)
1262     observer_notify_breakpoint_modified (b);
1263 }
1264
1265 /* Set the task for this breakpoint.  If TASK is 0, make the
1266    breakpoint work for any task.  */
1267
1268 void
1269 breakpoint_set_task (struct breakpoint *b, int task)
1270 {
1271   int old_task = b->task;
1272
1273   b->task = task;
1274   if (old_task != task)
1275     observer_notify_breakpoint_modified (b);
1276 }
1277
1278 void
1279 check_tracepoint_command (char *line, void *closure)
1280 {
1281   struct breakpoint *b = closure;
1282
1283   validate_actionline (line, b);
1284 }
1285
1286 /* A structure used to pass information through
1287    map_breakpoint_numbers.  */
1288
1289 struct commands_info
1290 {
1291   /* True if the command was typed at a tty.  */
1292   int from_tty;
1293
1294   /* The breakpoint range spec.  */
1295   char *arg;
1296
1297   /* Non-NULL if the body of the commands are being read from this
1298      already-parsed command.  */
1299   struct command_line *control;
1300
1301   /* The command lines read from the user, or NULL if they have not
1302      yet been read.  */
1303   struct counted_command_line *cmd;
1304 };
1305
1306 /* A callback for map_breakpoint_numbers that sets the commands for
1307    commands_command.  */
1308
1309 static void
1310 do_map_commands_command (struct breakpoint *b, void *data)
1311 {
1312   struct commands_info *info = data;
1313
1314   if (info->cmd == NULL)
1315     {
1316       struct command_line *l;
1317
1318       if (info->control != NULL)
1319         l = copy_command_lines (info->control->body_list[0]);
1320       else
1321         {
1322           struct cleanup *old_chain;
1323           char *str;
1324
1325           str = xstrprintf (_("Type commands for breakpoint(s) "
1326                               "%s, one per line."),
1327                             info->arg);
1328
1329           old_chain = make_cleanup (xfree, str);
1330
1331           l = read_command_lines (str,
1332                                   info->from_tty, 1,
1333                                   (is_tracepoint (b)
1334                                    ? check_tracepoint_command : 0),
1335                                   b);
1336
1337           do_cleanups (old_chain);
1338         }
1339
1340       info->cmd = alloc_counted_command_line (l);
1341     }
1342
1343   /* If a breakpoint was on the list more than once, we don't need to
1344      do anything.  */
1345   if (b->commands != info->cmd)
1346     {
1347       validate_commands_for_breakpoint (b, info->cmd->commands);
1348       incref_counted_command_line (info->cmd);
1349       decref_counted_command_line (&b->commands);
1350       b->commands = info->cmd;
1351       observer_notify_breakpoint_modified (b);
1352     }
1353 }
1354
1355 static void
1356 commands_command_1 (char *arg, int from_tty, 
1357                     struct command_line *control)
1358 {
1359   struct cleanup *cleanups;
1360   struct commands_info info;
1361
1362   info.from_tty = from_tty;
1363   info.control = control;
1364   info.cmd = NULL;
1365   /* If we read command lines from the user, then `info' will hold an
1366      extra reference to the commands that we must clean up.  */
1367   cleanups = make_cleanup_decref_counted_command_line (&info.cmd);
1368
1369   if (arg == NULL || !*arg)
1370     {
1371       if (breakpoint_count - prev_breakpoint_count > 1)
1372         arg = xstrprintf ("%d-%d", prev_breakpoint_count + 1, 
1373                           breakpoint_count);
1374       else if (breakpoint_count > 0)
1375         arg = xstrprintf ("%d", breakpoint_count);
1376       else
1377         {
1378           /* So that we don't try to free the incoming non-NULL
1379              argument in the cleanup below.  Mapping breakpoint
1380              numbers will fail in this case.  */
1381           arg = NULL;
1382         }
1383     }
1384   else
1385     /* The command loop has some static state, so we need to preserve
1386        our argument.  */
1387     arg = xstrdup (arg);
1388
1389   if (arg != NULL)
1390     make_cleanup (xfree, arg);
1391
1392   info.arg = arg;
1393
1394   map_breakpoint_numbers (arg, do_map_commands_command, &info);
1395
1396   if (info.cmd == NULL)
1397     error (_("No breakpoints specified."));
1398
1399   do_cleanups (cleanups);
1400 }
1401
1402 static void
1403 commands_command (char *arg, int from_tty)
1404 {
1405   commands_command_1 (arg, from_tty, NULL);
1406 }
1407
1408 /* Like commands_command, but instead of reading the commands from
1409    input stream, takes them from an already parsed command structure.
1410
1411    This is used by cli-script.c to DTRT with breakpoint commands
1412    that are part of if and while bodies.  */
1413 enum command_control_type
1414 commands_from_control_command (char *arg, struct command_line *cmd)
1415 {
1416   commands_command_1 (arg, 0, cmd);
1417   return simple_control;
1418 }
1419
1420 /* Return non-zero if BL->TARGET_INFO contains valid information.  */
1421
1422 static int
1423 bp_location_has_shadow (struct bp_location *bl)
1424 {
1425   if (bl->loc_type != bp_loc_software_breakpoint)
1426     return 0;
1427   if (!bl->inserted)
1428     return 0;
1429   if (bl->target_info.shadow_len == 0)
1430     /* BL isn't valid, or doesn't shadow memory.  */
1431     return 0;
1432   return 1;
1433 }
1434
1435 /* Update BUF, which is LEN bytes read from the target address MEMADDR,
1436    by replacing any memory breakpoints with their shadowed contents.
1437
1438    If READBUF is not NULL, this buffer must not overlap with any of
1439    the breakpoint location's shadow_contents buffers.  Otherwise,
1440    a failed assertion internal error will be raised.
1441
1442    The range of shadowed area by each bp_location is:
1443      bl->address - bp_location_placed_address_before_address_max
1444      up to bl->address + bp_location_shadow_len_after_address_max
1445    The range we were requested to resolve shadows for is:
1446      memaddr ... memaddr + len
1447    Thus the safe cutoff boundaries for performance optimization are
1448      memaddr + len <= (bl->address
1449                        - bp_location_placed_address_before_address_max)
1450    and:
1451      bl->address + bp_location_shadow_len_after_address_max <= memaddr  */
1452
1453 void
1454 breakpoint_xfer_memory (gdb_byte *readbuf, gdb_byte *writebuf,
1455                         const gdb_byte *writebuf_org,
1456                         ULONGEST memaddr, LONGEST len)
1457 {
1458   /* Left boundary, right boundary and median element of our binary
1459      search.  */
1460   unsigned bc_l, bc_r, bc;
1461
1462   /* Find BC_L which is a leftmost element which may affect BUF
1463      content.  It is safe to report lower value but a failure to
1464      report higher one.  */
1465
1466   bc_l = 0;
1467   bc_r = bp_location_count;
1468   while (bc_l + 1 < bc_r)
1469     {
1470       struct bp_location *bl;
1471
1472       bc = (bc_l + bc_r) / 2;
1473       bl = bp_location[bc];
1474
1475       /* Check first BL->ADDRESS will not overflow due to the added
1476          constant.  Then advance the left boundary only if we are sure
1477          the BC element can in no way affect the BUF content (MEMADDR
1478          to MEMADDR + LEN range).
1479
1480          Use the BP_LOCATION_SHADOW_LEN_AFTER_ADDRESS_MAX safety
1481          offset so that we cannot miss a breakpoint with its shadow
1482          range tail still reaching MEMADDR.  */
1483
1484       if ((bl->address + bp_location_shadow_len_after_address_max
1485            >= bl->address)
1486           && (bl->address + bp_location_shadow_len_after_address_max
1487               <= memaddr))
1488         bc_l = bc;
1489       else
1490         bc_r = bc;
1491     }
1492
1493   /* Due to the binary search above, we need to make sure we pick the
1494      first location that's at BC_L's address.  E.g., if there are
1495      multiple locations at the same address, BC_L may end up pointing
1496      at a duplicate location, and miss the "master"/"inserted"
1497      location.  Say, given locations L1, L2 and L3 at addresses A and
1498      B:
1499
1500       L1@A, L2@A, L3@B, ...
1501
1502      BC_L could end up pointing at location L2, while the "master"
1503      location could be L1.  Since the `loc->inserted' flag is only set
1504      on "master" locations, we'd forget to restore the shadow of L1
1505      and L2.  */
1506   while (bc_l > 0
1507          && bp_location[bc_l]->address == bp_location[bc_l - 1]->address)
1508     bc_l--;
1509
1510   /* Now do full processing of the found relevant range of elements.  */
1511
1512   for (bc = bc_l; bc < bp_location_count; bc++)
1513   {
1514     struct bp_location *bl = bp_location[bc];
1515     CORE_ADDR bp_addr = 0;
1516     int bp_size = 0;
1517     int bptoffset = 0;
1518
1519     /* bp_location array has BL->OWNER always non-NULL.  */
1520     if (bl->owner->type == bp_none)
1521       warning (_("reading through apparently deleted breakpoint #%d?"),
1522                bl->owner->number);
1523
1524     /* Performance optimization: any further element can no longer affect BUF
1525        content.  */
1526
1527     if (bl->address >= bp_location_placed_address_before_address_max
1528         && memaddr + len <= (bl->address
1529                              - bp_location_placed_address_before_address_max))
1530       break;
1531
1532     if (!bp_location_has_shadow (bl))
1533       continue;
1534     if (!breakpoint_address_match (bl->target_info.placed_address_space, 0,
1535                                    current_program_space->aspace, 0))
1536       continue;
1537
1538     /* Addresses and length of the part of the breakpoint that
1539        we need to copy.  */
1540     bp_addr = bl->target_info.placed_address;
1541     bp_size = bl->target_info.shadow_len;
1542
1543     if (bp_addr + bp_size <= memaddr)
1544       /* The breakpoint is entirely before the chunk of memory we
1545          are reading.  */
1546       continue;
1547
1548     if (bp_addr >= memaddr + len)
1549       /* The breakpoint is entirely after the chunk of memory we are
1550          reading.  */
1551       continue;
1552
1553     /* Offset within shadow_contents.  */
1554     if (bp_addr < memaddr)
1555       {
1556         /* Only copy the second part of the breakpoint.  */
1557         bp_size -= memaddr - bp_addr;
1558         bptoffset = memaddr - bp_addr;
1559         bp_addr = memaddr;
1560       }
1561
1562     if (bp_addr + bp_size > memaddr + len)
1563       {
1564         /* Only copy the first part of the breakpoint.  */
1565         bp_size -= (bp_addr + bp_size) - (memaddr + len);
1566       }
1567
1568     if (readbuf != NULL)
1569       {
1570         /* Verify that the readbuf buffer does not overlap with
1571            the shadow_contents buffer.  */
1572         gdb_assert (bl->target_info.shadow_contents >= readbuf + len
1573                     || readbuf >= (bl->target_info.shadow_contents
1574                                    + bl->target_info.shadow_len));
1575
1576         /* Update the read buffer with this inserted breakpoint's
1577            shadow.  */
1578         memcpy (readbuf + bp_addr - memaddr,
1579                 bl->target_info.shadow_contents + bptoffset, bp_size);
1580       }
1581     else
1582       {
1583         struct gdbarch *gdbarch = bl->gdbarch;
1584         const unsigned char *bp;
1585         CORE_ADDR placed_address = bl->target_info.placed_address;
1586         int placed_size = bl->target_info.placed_size;
1587
1588         /* Update the shadow with what we want to write to memory.  */
1589         memcpy (bl->target_info.shadow_contents + bptoffset,
1590                 writebuf_org + bp_addr - memaddr, bp_size);
1591
1592         /* Determine appropriate breakpoint contents and size for this
1593            address.  */
1594         bp = gdbarch_breakpoint_from_pc (gdbarch, &placed_address, &placed_size);
1595
1596         /* Update the final write buffer with this inserted
1597            breakpoint's INSN.  */
1598         memcpy (writebuf + bp_addr - memaddr, bp + bptoffset, bp_size);
1599       }
1600   }
1601 }
1602 \f
1603
1604 /* Return true if BPT is either a software breakpoint or a hardware
1605    breakpoint.  */
1606
1607 int
1608 is_breakpoint (const struct breakpoint *bpt)
1609 {
1610   return (bpt->type == bp_breakpoint
1611           || bpt->type == bp_hardware_breakpoint
1612           || bpt->type == bp_dprintf);
1613 }
1614
1615 /* Return true if BPT is of any hardware watchpoint kind.  */
1616
1617 static int
1618 is_hardware_watchpoint (const struct breakpoint *bpt)
1619 {
1620   return (bpt->type == bp_hardware_watchpoint
1621           || bpt->type == bp_read_watchpoint
1622           || bpt->type == bp_access_watchpoint);
1623 }
1624
1625 /* Return true if BPT is of any watchpoint kind, hardware or
1626    software.  */
1627
1628 int
1629 is_watchpoint (const struct breakpoint *bpt)
1630 {
1631   return (is_hardware_watchpoint (bpt)
1632           || bpt->type == bp_watchpoint);
1633 }
1634
1635 /* Returns true if the current thread and its running state are safe
1636    to evaluate or update watchpoint B.  Watchpoints on local
1637    expressions need to be evaluated in the context of the thread that
1638    was current when the watchpoint was created, and, that thread needs
1639    to be stopped to be able to select the correct frame context.
1640    Watchpoints on global expressions can be evaluated on any thread,
1641    and in any state.  It is presently left to the target allowing
1642    memory accesses when threads are running.  */
1643
1644 static int
1645 watchpoint_in_thread_scope (struct watchpoint *b)
1646 {
1647   return (b->base.pspace == current_program_space
1648           && (ptid_equal (b->watchpoint_thread, null_ptid)
1649               || (ptid_equal (inferior_ptid, b->watchpoint_thread)
1650                   && !is_executing (inferior_ptid))));
1651 }
1652
1653 /* Set watchpoint B to disp_del_at_next_stop, even including its possible
1654    associated bp_watchpoint_scope breakpoint.  */
1655
1656 static void
1657 watchpoint_del_at_next_stop (struct watchpoint *w)
1658 {
1659   struct breakpoint *b = &w->base;
1660
1661   if (b->related_breakpoint != b)
1662     {
1663       gdb_assert (b->related_breakpoint->type == bp_watchpoint_scope);
1664       gdb_assert (b->related_breakpoint->related_breakpoint == b);
1665       b->related_breakpoint->disposition = disp_del_at_next_stop;
1666       b->related_breakpoint->related_breakpoint = b->related_breakpoint;
1667       b->related_breakpoint = b;
1668     }
1669   b->disposition = disp_del_at_next_stop;
1670 }
1671
1672 /* Assuming that B is a watchpoint:
1673    - Reparse watchpoint expression, if REPARSE is non-zero
1674    - Evaluate expression and store the result in B->val
1675    - Evaluate the condition if there is one, and store the result
1676      in b->loc->cond.
1677    - Update the list of values that must be watched in B->loc.
1678
1679    If the watchpoint disposition is disp_del_at_next_stop, then do
1680    nothing.  If this is local watchpoint that is out of scope, delete
1681    it.
1682
1683    Even with `set breakpoint always-inserted on' the watchpoints are
1684    removed + inserted on each stop here.  Normal breakpoints must
1685    never be removed because they might be missed by a running thread
1686    when debugging in non-stop mode.  On the other hand, hardware
1687    watchpoints (is_hardware_watchpoint; processed here) are specific
1688    to each LWP since they are stored in each LWP's hardware debug
1689    registers.  Therefore, such LWP must be stopped first in order to
1690    be able to modify its hardware watchpoints.
1691
1692    Hardware watchpoints must be reset exactly once after being
1693    presented to the user.  It cannot be done sooner, because it would
1694    reset the data used to present the watchpoint hit to the user.  And
1695    it must not be done later because it could display the same single
1696    watchpoint hit during multiple GDB stops.  Note that the latter is
1697    relevant only to the hardware watchpoint types bp_read_watchpoint
1698    and bp_access_watchpoint.  False hit by bp_hardware_watchpoint is
1699    not user-visible - its hit is suppressed if the memory content has
1700    not changed.
1701
1702    The following constraints influence the location where we can reset
1703    hardware watchpoints:
1704
1705    * target_stopped_by_watchpoint and target_stopped_data_address are
1706      called several times when GDB stops.
1707
1708    [linux] 
1709    * Multiple hardware watchpoints can be hit at the same time,
1710      causing GDB to stop.  GDB only presents one hardware watchpoint
1711      hit at a time as the reason for stopping, and all the other hits
1712      are presented later, one after the other, each time the user
1713      requests the execution to be resumed.  Execution is not resumed
1714      for the threads still having pending hit event stored in
1715      LWP_INFO->STATUS.  While the watchpoint is already removed from
1716      the inferior on the first stop the thread hit event is kept being
1717      reported from its cached value by linux_nat_stopped_data_address
1718      until the real thread resume happens after the watchpoint gets
1719      presented and thus its LWP_INFO->STATUS gets reset.
1720
1721    Therefore the hardware watchpoint hit can get safely reset on the
1722    watchpoint removal from inferior.  */
1723
1724 static void
1725 update_watchpoint (struct watchpoint *b, int reparse)
1726 {
1727   int within_current_scope;
1728   struct frame_id saved_frame_id;
1729   int frame_saved;
1730
1731   /* If this is a local watchpoint, we only want to check if the
1732      watchpoint frame is in scope if the current thread is the thread
1733      that was used to create the watchpoint.  */
1734   if (!watchpoint_in_thread_scope (b))
1735     return;
1736
1737   if (b->base.disposition == disp_del_at_next_stop)
1738     return;
1739  
1740   frame_saved = 0;
1741
1742   /* Determine if the watchpoint is within scope.  */
1743   if (b->exp_valid_block == NULL)
1744     within_current_scope = 1;
1745   else
1746     {
1747       struct frame_info *fi = get_current_frame ();
1748       struct gdbarch *frame_arch = get_frame_arch (fi);
1749       CORE_ADDR frame_pc = get_frame_pc (fi);
1750
1751       /* If we're in a function epilogue, unwinding may not work
1752          properly, so do not attempt to recreate locations at this
1753          point.  See similar comments in watchpoint_check.  */
1754       if (gdbarch_in_function_epilogue_p (frame_arch, frame_pc))
1755         return;
1756
1757       /* Save the current frame's ID so we can restore it after
1758          evaluating the watchpoint expression on its own frame.  */
1759       /* FIXME drow/2003-09-09: It would be nice if evaluate_expression
1760          took a frame parameter, so that we didn't have to change the
1761          selected frame.  */
1762       frame_saved = 1;
1763       saved_frame_id = get_frame_id (get_selected_frame (NULL));
1764
1765       fi = frame_find_by_id (b->watchpoint_frame);
1766       within_current_scope = (fi != NULL);
1767       if (within_current_scope)
1768         select_frame (fi);
1769     }
1770
1771   /* We don't free locations.  They are stored in the bp_location array
1772      and update_global_location_list will eventually delete them and
1773      remove breakpoints if needed.  */
1774   b->base.loc = NULL;
1775
1776   if (within_current_scope && reparse)
1777     {
1778       const char *s;
1779
1780       if (b->exp)
1781         {
1782           xfree (b->exp);
1783           b->exp = NULL;
1784         }
1785       s = b->exp_string_reparse ? b->exp_string_reparse : b->exp_string;
1786       b->exp = parse_exp_1 (&s, 0, b->exp_valid_block, 0);
1787       /* If the meaning of expression itself changed, the old value is
1788          no longer relevant.  We don't want to report a watchpoint hit
1789          to the user when the old value and the new value may actually
1790          be completely different objects.  */
1791       value_free (b->val);
1792       b->val = NULL;
1793       b->val_valid = 0;
1794
1795       /* Note that unlike with breakpoints, the watchpoint's condition
1796          expression is stored in the breakpoint object, not in the
1797          locations (re)created below.  */
1798       if (b->base.cond_string != NULL)
1799         {
1800           if (b->cond_exp != NULL)
1801             {
1802               xfree (b->cond_exp);
1803               b->cond_exp = NULL;
1804             }
1805
1806           s = b->base.cond_string;
1807           b->cond_exp = parse_exp_1 (&s, 0, b->cond_exp_valid_block, 0);
1808         }
1809     }
1810
1811   /* If we failed to parse the expression, for example because
1812      it refers to a global variable in a not-yet-loaded shared library,
1813      don't try to insert watchpoint.  We don't automatically delete
1814      such watchpoint, though, since failure to parse expression
1815      is different from out-of-scope watchpoint.  */
1816   if ( !target_has_execution)
1817     {
1818       /* Without execution, memory can't change.  No use to try and
1819          set watchpoint locations.  The watchpoint will be reset when
1820          the target gains execution, through breakpoint_re_set.  */
1821     }
1822   else if (within_current_scope && b->exp)
1823     {
1824       int pc = 0;
1825       struct value *val_chain, *v, *result, *next;
1826       struct program_space *frame_pspace;
1827
1828       fetch_subexp_value (b->exp, &pc, &v, &result, &val_chain);
1829
1830       /* Avoid setting b->val if it's already set.  The meaning of
1831          b->val is 'the last value' user saw, and we should update
1832          it only if we reported that last value to user.  As it
1833          happens, the code that reports it updates b->val directly.
1834          We don't keep track of the memory value for masked
1835          watchpoints.  */
1836       if (!b->val_valid && !is_masked_watchpoint (&b->base))
1837         {
1838           b->val = v;
1839           b->val_valid = 1;
1840         }
1841
1842       frame_pspace = get_frame_program_space (get_selected_frame (NULL));
1843
1844       /* Look at each value on the value chain.  */
1845       for (v = val_chain; v; v = value_next (v))
1846         {
1847           /* If it's a memory location, and GDB actually needed
1848              its contents to evaluate the expression, then we
1849              must watch it.  If the first value returned is
1850              still lazy, that means an error occurred reading it;
1851              watch it anyway in case it becomes readable.  */
1852           if (VALUE_LVAL (v) == lval_memory
1853               && (v == val_chain || ! value_lazy (v)))
1854             {
1855               struct type *vtype = check_typedef (value_type (v));
1856
1857               /* We only watch structs and arrays if user asked
1858                  for it explicitly, never if they just happen to
1859                  appear in the middle of some value chain.  */
1860               if (v == result
1861                   || (TYPE_CODE (vtype) != TYPE_CODE_STRUCT
1862                       && TYPE_CODE (vtype) != TYPE_CODE_ARRAY))
1863                 {
1864                   CORE_ADDR addr;
1865                   int type;
1866                   struct bp_location *loc, **tmp;
1867
1868                   addr = value_address (v);
1869                   type = hw_write;
1870                   if (b->base.type == bp_read_watchpoint)
1871                     type = hw_read;
1872                   else if (b->base.type == bp_access_watchpoint)
1873                     type = hw_access;
1874
1875                   loc = allocate_bp_location (&b->base);
1876                   for (tmp = &(b->base.loc); *tmp != NULL; tmp = &((*tmp)->next))
1877                     ;
1878                   *tmp = loc;
1879                   loc->gdbarch = get_type_arch (value_type (v));
1880
1881                   loc->pspace = frame_pspace;
1882                   loc->address = addr;
1883                   loc->length = TYPE_LENGTH (value_type (v));
1884                   loc->watchpoint_type = type;
1885                 }
1886             }
1887         }
1888
1889       /* Change the type of breakpoint between hardware assisted or
1890          an ordinary watchpoint depending on the hardware support
1891          and free hardware slots.  REPARSE is set when the inferior
1892          is started.  */
1893       if (reparse)
1894         {
1895           int reg_cnt;
1896           enum bp_loc_type loc_type;
1897           struct bp_location *bl;
1898
1899           reg_cnt = can_use_hardware_watchpoint (val_chain);
1900
1901           if (reg_cnt)
1902             {
1903               int i, target_resources_ok, other_type_used;
1904               enum bptype type;
1905
1906               /* Use an exact watchpoint when there's only one memory region to be
1907                  watched, and only one debug register is needed to watch it.  */
1908               b->exact = target_exact_watchpoints && reg_cnt == 1;
1909
1910               /* We need to determine how many resources are already
1911                  used for all other hardware watchpoints plus this one
1912                  to see if we still have enough resources to also fit
1913                  this watchpoint in as well.  */
1914
1915               /* If this is a software watchpoint, we try to turn it
1916                  to a hardware one -- count resources as if B was of
1917                  hardware watchpoint type.  */
1918               type = b->base.type;
1919               if (type == bp_watchpoint)
1920                 type = bp_hardware_watchpoint;
1921
1922               /* This watchpoint may or may not have been placed on
1923                  the list yet at this point (it won't be in the list
1924                  if we're trying to create it for the first time,
1925                  through watch_command), so always account for it
1926                  manually.  */
1927
1928               /* Count resources used by all watchpoints except B.  */
1929               i = hw_watchpoint_used_count_others (&b->base, type, &other_type_used);
1930
1931               /* Add in the resources needed for B.  */
1932               i += hw_watchpoint_use_count (&b->base);
1933
1934               target_resources_ok
1935                 = target_can_use_hardware_watchpoint (type, i, other_type_used);
1936               if (target_resources_ok <= 0)
1937                 {
1938                   int sw_mode = b->base.ops->works_in_software_mode (&b->base);
1939
1940                   if (target_resources_ok == 0 && !sw_mode)
1941                     error (_("Target does not support this type of "
1942                              "hardware watchpoint."));
1943                   else if (target_resources_ok < 0 && !sw_mode)
1944                     error (_("There are not enough available hardware "
1945                              "resources for this watchpoint."));
1946
1947                   /* Downgrade to software watchpoint.  */
1948                   b->base.type = bp_watchpoint;
1949                 }
1950               else
1951                 {
1952                   /* If this was a software watchpoint, we've just
1953                      found we have enough resources to turn it to a
1954                      hardware watchpoint.  Otherwise, this is a
1955                      nop.  */
1956                   b->base.type = type;
1957                 }
1958             }
1959           else if (!b->base.ops->works_in_software_mode (&b->base))
1960             error (_("Expression cannot be implemented with "
1961                      "read/access watchpoint."));
1962           else
1963             b->base.type = bp_watchpoint;
1964
1965           loc_type = (b->base.type == bp_watchpoint? bp_loc_other
1966                       : bp_loc_hardware_watchpoint);
1967           for (bl = b->base.loc; bl; bl = bl->next)
1968             bl->loc_type = loc_type;
1969         }
1970
1971       for (v = val_chain; v; v = next)
1972         {
1973           next = value_next (v);
1974           if (v != b->val)
1975             value_free (v);
1976         }
1977
1978       /* If a software watchpoint is not watching any memory, then the
1979          above left it without any location set up.  But,
1980          bpstat_stop_status requires a location to be able to report
1981          stops, so make sure there's at least a dummy one.  */
1982       if (b->base.type == bp_watchpoint && b->base.loc == NULL)
1983         {
1984           struct breakpoint *base = &b->base;
1985           base->loc = allocate_bp_location (base);
1986           base->loc->pspace = frame_pspace;
1987           base->loc->address = -1;
1988           base->loc->length = -1;
1989           base->loc->watchpoint_type = -1;
1990         }
1991     }
1992   else if (!within_current_scope)
1993     {
1994       printf_filtered (_("\
1995 Watchpoint %d deleted because the program has left the block\n\
1996 in which its expression is valid.\n"),
1997                        b->base.number);
1998       watchpoint_del_at_next_stop (b);
1999     }
2000
2001   /* Restore the selected frame.  */
2002   if (frame_saved)
2003     select_frame (frame_find_by_id (saved_frame_id));
2004 }
2005
2006
2007 /* Returns 1 iff breakpoint location should be
2008    inserted in the inferior.  We don't differentiate the type of BL's owner
2009    (breakpoint vs. tracepoint), although insert_location in tracepoint's
2010    breakpoint_ops is not defined, because in insert_bp_location,
2011    tracepoint's insert_location will not be called.  */
2012 static int
2013 should_be_inserted (struct bp_location *bl)
2014 {
2015   if (bl->owner == NULL || !breakpoint_enabled (bl->owner))
2016     return 0;
2017
2018   if (bl->owner->disposition == disp_del_at_next_stop)
2019     return 0;
2020
2021   if (!bl->enabled || bl->shlib_disabled || bl->duplicate)
2022     return 0;
2023
2024   if (user_breakpoint_p (bl->owner) && bl->pspace->executing_startup)
2025     return 0;
2026
2027   /* This is set for example, when we're attached to the parent of a
2028      vfork, and have detached from the child.  The child is running
2029      free, and we expect it to do an exec or exit, at which point the
2030      OS makes the parent schedulable again (and the target reports
2031      that the vfork is done).  Until the child is done with the shared
2032      memory region, do not insert breakpoints in the parent, otherwise
2033      the child could still trip on the parent's breakpoints.  Since
2034      the parent is blocked anyway, it won't miss any breakpoint.  */
2035   if (bl->pspace->breakpoints_not_allowed)
2036     return 0;
2037
2038   return 1;
2039 }
2040
2041 /* Same as should_be_inserted but does the check assuming
2042    that the location is not duplicated.  */
2043
2044 static int
2045 unduplicated_should_be_inserted (struct bp_location *bl)
2046 {
2047   int result;
2048   const int save_duplicate = bl->duplicate;
2049
2050   bl->duplicate = 0;
2051   result = should_be_inserted (bl);
2052   bl->duplicate = save_duplicate;
2053   return result;
2054 }
2055
2056 /* Parses a conditional described by an expression COND into an
2057    agent expression bytecode suitable for evaluation
2058    by the bytecode interpreter.  Return NULL if there was
2059    any error during parsing.  */
2060
2061 static struct agent_expr *
2062 parse_cond_to_aexpr (CORE_ADDR scope, struct expression *cond)
2063 {
2064   struct agent_expr *aexpr = NULL;
2065   volatile struct gdb_exception ex;
2066
2067   if (!cond)
2068     return NULL;
2069
2070   /* We don't want to stop processing, so catch any errors
2071      that may show up.  */
2072   TRY_CATCH (ex, RETURN_MASK_ERROR)
2073     {
2074       aexpr = gen_eval_for_expr (scope, cond);
2075     }
2076
2077   if (ex.reason < 0)
2078     {
2079       /* If we got here, it means the condition could not be parsed to a valid
2080          bytecode expression and thus can't be evaluated on the target's side.
2081          It's no use iterating through the conditions.  */
2082       return NULL;
2083     }
2084
2085   /* We have a valid agent expression.  */
2086   return aexpr;
2087 }
2088
2089 /* Based on location BL, create a list of breakpoint conditions to be
2090    passed on to the target.  If we have duplicated locations with different
2091    conditions, we will add such conditions to the list.  The idea is that the
2092    target will evaluate the list of conditions and will only notify GDB when
2093    one of them is true.  */
2094
2095 static void
2096 build_target_condition_list (struct bp_location *bl)
2097 {
2098   struct bp_location **locp = NULL, **loc2p;
2099   int null_condition_or_parse_error = 0;
2100   int modified = bl->needs_update;
2101   struct bp_location *loc;
2102
2103   /* This is only meaningful if the target is
2104      evaluating conditions and if the user has
2105      opted for condition evaluation on the target's
2106      side.  */
2107   if (gdb_evaluates_breakpoint_condition_p ()
2108       || !target_supports_evaluation_of_breakpoint_conditions ())
2109     return;
2110
2111   /* Do a first pass to check for locations with no assigned
2112      conditions or conditions that fail to parse to a valid agent expression
2113      bytecode.  If any of these happen, then it's no use to send conditions
2114      to the target since this location will always trigger and generate a
2115      response back to GDB.  */
2116   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2117     {
2118       loc = (*loc2p);
2119       if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2120         {
2121           if (modified)
2122             {
2123               struct agent_expr *aexpr;
2124
2125               /* Re-parse the conditions since something changed.  In that
2126                  case we already freed the condition bytecodes (see
2127                  force_breakpoint_reinsertion).  We just
2128                  need to parse the condition to bytecodes again.  */
2129               aexpr = parse_cond_to_aexpr (bl->address, loc->cond);
2130               loc->cond_bytecode = aexpr;
2131
2132               /* Check if we managed to parse the conditional expression
2133                  correctly.  If not, we will not send this condition
2134                  to the target.  */
2135               if (aexpr)
2136                 continue;
2137             }
2138
2139           /* If we have a NULL bytecode expression, it means something
2140              went wrong or we have a null condition expression.  */
2141           if (!loc->cond_bytecode)
2142             {
2143               null_condition_or_parse_error = 1;
2144               break;
2145             }
2146         }
2147     }
2148
2149   /* If any of these happened, it means we will have to evaluate the conditions
2150      for the location's address on gdb's side.  It is no use keeping bytecodes
2151      for all the other duplicate locations, thus we free all of them here.
2152
2153      This is so we have a finer control over which locations' conditions are
2154      being evaluated by GDB or the remote stub.  */
2155   if (null_condition_or_parse_error)
2156     {
2157       ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2158         {
2159           loc = (*loc2p);
2160           if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2161             {
2162               /* Only go as far as the first NULL bytecode is
2163                  located.  */
2164               if (!loc->cond_bytecode)
2165                 return;
2166
2167               free_agent_expr (loc->cond_bytecode);
2168               loc->cond_bytecode = NULL;
2169             }
2170         }
2171     }
2172
2173   /* No NULL conditions or failed bytecode generation.  Build a condition list
2174      for this location's address.  */
2175   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2176     {
2177       loc = (*loc2p);
2178       if (loc->cond
2179           && is_breakpoint (loc->owner)
2180           && loc->pspace->num == bl->pspace->num
2181           && loc->owner->enable_state == bp_enabled
2182           && loc->enabled)
2183         /* Add the condition to the vector.  This will be used later to send the
2184            conditions to the target.  */
2185         VEC_safe_push (agent_expr_p, bl->target_info.conditions,
2186                        loc->cond_bytecode);
2187     }
2188
2189   return;
2190 }
2191
2192 /* Parses a command described by string CMD into an agent expression
2193    bytecode suitable for evaluation by the bytecode interpreter.
2194    Return NULL if there was any error during parsing.  */
2195
2196 static struct agent_expr *
2197 parse_cmd_to_aexpr (CORE_ADDR scope, char *cmd)
2198 {
2199   struct cleanup *old_cleanups = 0;
2200   struct expression *expr, **argvec;
2201   struct agent_expr *aexpr = NULL;
2202   volatile struct gdb_exception ex;
2203   const char *cmdrest;
2204   const char *format_start, *format_end;
2205   struct format_piece *fpieces;
2206   int nargs;
2207   struct gdbarch *gdbarch = get_current_arch ();
2208
2209   if (!cmd)
2210     return NULL;
2211
2212   cmdrest = cmd;
2213
2214   if (*cmdrest == ',')
2215     ++cmdrest;
2216   cmdrest = skip_spaces_const (cmdrest);
2217
2218   if (*cmdrest++ != '"')
2219     error (_("No format string following the location"));
2220
2221   format_start = cmdrest;
2222
2223   fpieces = parse_format_string (&cmdrest);
2224
2225   old_cleanups = make_cleanup (free_format_pieces_cleanup, &fpieces);
2226
2227   format_end = cmdrest;
2228
2229   if (*cmdrest++ != '"')
2230     error (_("Bad format string, non-terminated '\"'."));
2231   
2232   cmdrest = skip_spaces_const (cmdrest);
2233
2234   if (!(*cmdrest == ',' || *cmdrest == '\0'))
2235     error (_("Invalid argument syntax"));
2236
2237   if (*cmdrest == ',')
2238     cmdrest++;
2239   cmdrest = skip_spaces_const (cmdrest);
2240
2241   /* For each argument, make an expression.  */
2242
2243   argvec = (struct expression **) alloca (strlen (cmd)
2244                                          * sizeof (struct expression *));
2245
2246   nargs = 0;
2247   while (*cmdrest != '\0')
2248     {
2249       const char *cmd1;
2250
2251       cmd1 = cmdrest;
2252       expr = parse_exp_1 (&cmd1, scope, block_for_pc (scope), 1);
2253       argvec[nargs++] = expr;
2254       cmdrest = cmd1;
2255       if (*cmdrest == ',')
2256         ++cmdrest;
2257     }
2258
2259   /* We don't want to stop processing, so catch any errors
2260      that may show up.  */
2261   TRY_CATCH (ex, RETURN_MASK_ERROR)
2262     {
2263       aexpr = gen_printf (scope, gdbarch, 0, 0,
2264                           format_start, format_end - format_start,
2265                           fpieces, nargs, argvec);
2266     }
2267
2268   if (ex.reason < 0)
2269     {
2270       /* If we got here, it means the command could not be parsed to a valid
2271          bytecode expression and thus can't be evaluated on the target's side.
2272          It's no use iterating through the other commands.  */
2273       return NULL;
2274     }
2275
2276   do_cleanups (old_cleanups);
2277
2278   /* We have a valid agent expression, return it.  */
2279   return aexpr;
2280 }
2281
2282 /* Based on location BL, create a list of breakpoint commands to be
2283    passed on to the target.  If we have duplicated locations with
2284    different commands, we will add any such to the list.  */
2285
2286 static void
2287 build_target_command_list (struct bp_location *bl)
2288 {
2289   struct bp_location **locp = NULL, **loc2p;
2290   int null_command_or_parse_error = 0;
2291   int modified = bl->needs_update;
2292   struct bp_location *loc;
2293
2294   /* For now, limit to agent-style dprintf breakpoints.  */
2295   if (bl->owner->type != bp_dprintf
2296       || strcmp (dprintf_style, dprintf_style_agent) != 0)
2297     return;
2298
2299   if (!target_can_run_breakpoint_commands ())
2300     return;
2301
2302   /* Do a first pass to check for locations with no assigned
2303      conditions or conditions that fail to parse to a valid agent expression
2304      bytecode.  If any of these happen, then it's no use to send conditions
2305      to the target since this location will always trigger and generate a
2306      response back to GDB.  */
2307   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2308     {
2309       loc = (*loc2p);
2310       if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2311         {
2312           if (modified)
2313             {
2314               struct agent_expr *aexpr;
2315
2316               /* Re-parse the commands since something changed.  In that
2317                  case we already freed the command bytecodes (see
2318                  force_breakpoint_reinsertion).  We just
2319                  need to parse the command to bytecodes again.  */
2320               aexpr = parse_cmd_to_aexpr (bl->address,
2321                                           loc->owner->extra_string);
2322               loc->cmd_bytecode = aexpr;
2323
2324               if (!aexpr)
2325                 continue;
2326             }
2327
2328           /* If we have a NULL bytecode expression, it means something
2329              went wrong or we have a null command expression.  */
2330           if (!loc->cmd_bytecode)
2331             {
2332               null_command_or_parse_error = 1;
2333               break;
2334             }
2335         }
2336     }
2337
2338   /* If anything failed, then we're not doing target-side commands,
2339      and so clean up.  */
2340   if (null_command_or_parse_error)
2341     {
2342       ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2343         {
2344           loc = (*loc2p);
2345           if (is_breakpoint (loc->owner)
2346               && loc->pspace->num == bl->pspace->num)
2347             {
2348               /* Only go as far as the first NULL bytecode is
2349                  located.  */
2350               if (!loc->cond_bytecode)
2351                 return;
2352
2353               free_agent_expr (loc->cond_bytecode);
2354               loc->cond_bytecode = NULL;
2355             }
2356         }
2357     }
2358
2359   /* No NULL commands or failed bytecode generation.  Build a command list
2360      for this location's address.  */
2361   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2362     {
2363       loc = (*loc2p);
2364       if (loc->owner->extra_string
2365           && is_breakpoint (loc->owner)
2366           && loc->pspace->num == bl->pspace->num
2367           && loc->owner->enable_state == bp_enabled
2368           && loc->enabled)
2369         /* Add the command to the vector.  This will be used later
2370            to send the commands to the target.  */
2371         VEC_safe_push (agent_expr_p, bl->target_info.tcommands,
2372                        loc->cmd_bytecode);
2373     }
2374
2375   bl->target_info.persist = 0;
2376   /* Maybe flag this location as persistent.  */
2377   if (bl->owner->type == bp_dprintf && disconnected_dprintf)
2378     bl->target_info.persist = 1;
2379 }
2380
2381 /* Insert a low-level "breakpoint" of some type.  BL is the breakpoint
2382    location.  Any error messages are printed to TMP_ERROR_STREAM; and
2383    DISABLED_BREAKS, and HW_BREAKPOINT_ERROR are used to report problems.
2384    Returns 0 for success, 1 if the bp_location type is not supported or
2385    -1 for failure.
2386
2387    NOTE drow/2003-09-09: This routine could be broken down to an
2388    object-style method for each breakpoint or catchpoint type.  */
2389 static int
2390 insert_bp_location (struct bp_location *bl,
2391                     struct ui_file *tmp_error_stream,
2392                     int *disabled_breaks,
2393                     int *hw_breakpoint_error,
2394                     int *hw_bp_error_explained_already)
2395 {
2396   int val = 0;
2397   char *hw_bp_err_string = NULL;
2398   struct gdb_exception e;
2399
2400   if (!should_be_inserted (bl) || (bl->inserted && !bl->needs_update))
2401     return 0;
2402
2403   /* Note we don't initialize bl->target_info, as that wipes out
2404      the breakpoint location's shadow_contents if the breakpoint
2405      is still inserted at that location.  This in turn breaks
2406      target_read_memory which depends on these buffers when
2407      a memory read is requested at the breakpoint location:
2408      Once the target_info has been wiped, we fail to see that
2409      we have a breakpoint inserted at that address and thus
2410      read the breakpoint instead of returning the data saved in
2411      the breakpoint location's shadow contents.  */
2412   bl->target_info.placed_address = bl->address;
2413   bl->target_info.placed_address_space = bl->pspace->aspace;
2414   bl->target_info.length = bl->length;
2415
2416   /* When working with target-side conditions, we must pass all the conditions
2417      for the same breakpoint address down to the target since GDB will not
2418      insert those locations.  With a list of breakpoint conditions, the target
2419      can decide when to stop and notify GDB.  */
2420
2421   if (is_breakpoint (bl->owner))
2422     {
2423       build_target_condition_list (bl);
2424       build_target_command_list (bl);
2425       /* Reset the modification marker.  */
2426       bl->needs_update = 0;
2427     }
2428
2429   if (bl->loc_type == bp_loc_software_breakpoint
2430       || bl->loc_type == bp_loc_hardware_breakpoint)
2431     {
2432       if (bl->owner->type != bp_hardware_breakpoint)
2433         {
2434           /* If the explicitly specified breakpoint type
2435              is not hardware breakpoint, check the memory map to see
2436              if the breakpoint address is in read only memory or not.
2437
2438              Two important cases are:
2439              - location type is not hardware breakpoint, memory
2440              is readonly.  We change the type of the location to
2441              hardware breakpoint.
2442              - location type is hardware breakpoint, memory is
2443              read-write.  This means we've previously made the
2444              location hardware one, but then the memory map changed,
2445              so we undo.
2446              
2447              When breakpoints are removed, remove_breakpoints will use
2448              location types we've just set here, the only possible
2449              problem is that memory map has changed during running
2450              program, but it's not going to work anyway with current
2451              gdb.  */
2452           struct mem_region *mr 
2453             = lookup_mem_region (bl->target_info.placed_address);
2454           
2455           if (mr)
2456             {
2457               if (automatic_hardware_breakpoints)
2458                 {
2459                   enum bp_loc_type new_type;
2460                   
2461                   if (mr->attrib.mode != MEM_RW)
2462                     new_type = bp_loc_hardware_breakpoint;
2463                   else 
2464                     new_type = bp_loc_software_breakpoint;
2465                   
2466                   if (new_type != bl->loc_type)
2467                     {
2468                       static int said = 0;
2469
2470                       bl->loc_type = new_type;
2471                       if (!said)
2472                         {
2473                           fprintf_filtered (gdb_stdout,
2474                                             _("Note: automatically using "
2475                                               "hardware breakpoints for "
2476                                               "read-only addresses.\n"));
2477                           said = 1;
2478                         }
2479                     }
2480                 }
2481               else if (bl->loc_type == bp_loc_software_breakpoint
2482                        && mr->attrib.mode != MEM_RW)        
2483                 warning (_("cannot set software breakpoint "
2484                            "at readonly address %s"),
2485                          paddress (bl->gdbarch, bl->address));
2486             }
2487         }
2488         
2489       /* First check to see if we have to handle an overlay.  */
2490       if (overlay_debugging == ovly_off
2491           || bl->section == NULL
2492           || !(section_is_overlay (bl->section)))
2493         {
2494           /* No overlay handling: just set the breakpoint.  */
2495           TRY_CATCH (e, RETURN_MASK_ALL)
2496             {
2497               val = bl->owner->ops->insert_location (bl);
2498             }
2499           if (e.reason < 0)
2500             {
2501               val = 1;
2502               hw_bp_err_string = (char *) e.message;
2503             }
2504         }
2505       else
2506         {
2507           /* This breakpoint is in an overlay section.
2508              Shall we set a breakpoint at the LMA?  */
2509           if (!overlay_events_enabled)
2510             {
2511               /* Yes -- overlay event support is not active, 
2512                  so we must try to set a breakpoint at the LMA.
2513                  This will not work for a hardware breakpoint.  */
2514               if (bl->loc_type == bp_loc_hardware_breakpoint)
2515                 warning (_("hardware breakpoint %d not supported in overlay!"),
2516                          bl->owner->number);
2517               else
2518                 {
2519                   CORE_ADDR addr = overlay_unmapped_address (bl->address,
2520                                                              bl->section);
2521                   /* Set a software (trap) breakpoint at the LMA.  */
2522                   bl->overlay_target_info = bl->target_info;
2523                   bl->overlay_target_info.placed_address = addr;
2524                   val = target_insert_breakpoint (bl->gdbarch,
2525                                                   &bl->overlay_target_info);
2526                   if (val != 0)
2527                     fprintf_unfiltered (tmp_error_stream,
2528                                         "Overlay breakpoint %d "
2529                                         "failed: in ROM?\n",
2530                                         bl->owner->number);
2531                 }
2532             }
2533           /* Shall we set a breakpoint at the VMA? */
2534           if (section_is_mapped (bl->section))
2535             {
2536               /* Yes.  This overlay section is mapped into memory.  */
2537               TRY_CATCH (e, RETURN_MASK_ALL)
2538                 {
2539                   val = bl->owner->ops->insert_location (bl);
2540                 }
2541               if (e.reason < 0)
2542                 {
2543                   val = 1;
2544                   hw_bp_err_string = (char *) e.message;
2545                 }
2546             }
2547           else
2548             {
2549               /* No.  This breakpoint will not be inserted.  
2550                  No error, but do not mark the bp as 'inserted'.  */
2551               return 0;
2552             }
2553         }
2554
2555       if (val)
2556         {
2557           /* Can't set the breakpoint.  */
2558           if (solib_name_from_address (bl->pspace, bl->address))
2559             {
2560               /* See also: disable_breakpoints_in_shlibs.  */
2561               val = 0;
2562               bl->shlib_disabled = 1;
2563               observer_notify_breakpoint_modified (bl->owner);
2564               if (!*disabled_breaks)
2565                 {
2566                   fprintf_unfiltered (tmp_error_stream, 
2567                                       "Cannot insert breakpoint %d.\n", 
2568                                       bl->owner->number);
2569                   fprintf_unfiltered (tmp_error_stream, 
2570                                       "Temporarily disabling shared "
2571                                       "library breakpoints:\n");
2572                 }
2573               *disabled_breaks = 1;
2574               fprintf_unfiltered (tmp_error_stream,
2575                                   "breakpoint #%d\n", bl->owner->number);
2576             }
2577           else
2578             {
2579               if (bl->loc_type == bp_loc_hardware_breakpoint)
2580                 {
2581                   *hw_breakpoint_error = 1;
2582                   *hw_bp_error_explained_already = hw_bp_err_string != NULL;
2583                   fprintf_unfiltered (tmp_error_stream,
2584                                       "Cannot insert hardware breakpoint %d%s",
2585                                       bl->owner->number, hw_bp_err_string ? ":" : ".\n");
2586                   if (hw_bp_err_string)
2587                     fprintf_unfiltered (tmp_error_stream, "%s.\n", hw_bp_err_string);
2588                 }
2589               else
2590                 {
2591                   fprintf_unfiltered (tmp_error_stream, 
2592                                       "Cannot insert breakpoint %d.\n", 
2593                                       bl->owner->number);
2594                   fprintf_filtered (tmp_error_stream, 
2595                                     "Error accessing memory address ");
2596                   fputs_filtered (paddress (bl->gdbarch, bl->address),
2597                                   tmp_error_stream);
2598                   fprintf_filtered (tmp_error_stream, ": %s.\n",
2599                                     safe_strerror (val));
2600                 }
2601
2602             }
2603         }
2604       else
2605         bl->inserted = 1;
2606
2607       return val;
2608     }
2609
2610   else if (bl->loc_type == bp_loc_hardware_watchpoint
2611            /* NOTE drow/2003-09-08: This state only exists for removing
2612               watchpoints.  It's not clear that it's necessary...  */
2613            && bl->owner->disposition != disp_del_at_next_stop)
2614     {
2615       gdb_assert (bl->owner->ops != NULL
2616                   && bl->owner->ops->insert_location != NULL);
2617
2618       val = bl->owner->ops->insert_location (bl);
2619
2620       /* If trying to set a read-watchpoint, and it turns out it's not
2621          supported, try emulating one with an access watchpoint.  */
2622       if (val == 1 && bl->watchpoint_type == hw_read)
2623         {
2624           struct bp_location *loc, **loc_temp;
2625
2626           /* But don't try to insert it, if there's already another
2627              hw_access location that would be considered a duplicate
2628              of this one.  */
2629           ALL_BP_LOCATIONS (loc, loc_temp)
2630             if (loc != bl
2631                 && loc->watchpoint_type == hw_access
2632                 && watchpoint_locations_match (bl, loc))
2633               {
2634                 bl->duplicate = 1;
2635                 bl->inserted = 1;
2636                 bl->target_info = loc->target_info;
2637                 bl->watchpoint_type = hw_access;
2638                 val = 0;
2639                 break;
2640               }
2641
2642           if (val == 1)
2643             {
2644               bl->watchpoint_type = hw_access;
2645               val = bl->owner->ops->insert_location (bl);
2646
2647               if (val)
2648                 /* Back to the original value.  */
2649                 bl->watchpoint_type = hw_read;
2650             }
2651         }
2652
2653       bl->inserted = (val == 0);
2654     }
2655
2656   else if (bl->owner->type == bp_catchpoint)
2657     {
2658       gdb_assert (bl->owner->ops != NULL
2659                   && bl->owner->ops->insert_location != NULL);
2660
2661       val = bl->owner->ops->insert_location (bl);
2662       if (val)
2663         {
2664           bl->owner->enable_state = bp_disabled;
2665
2666           if (val == 1)
2667             warning (_("\
2668 Error inserting catchpoint %d: Your system does not support this type\n\
2669 of catchpoint."), bl->owner->number);
2670           else
2671             warning (_("Error inserting catchpoint %d."), bl->owner->number);
2672         }
2673
2674       bl->inserted = (val == 0);
2675
2676       /* We've already printed an error message if there was a problem
2677          inserting this catchpoint, and we've disabled the catchpoint,
2678          so just return success.  */
2679       return 0;
2680     }
2681
2682   return 0;
2683 }
2684
2685 /* This function is called when program space PSPACE is about to be
2686    deleted.  It takes care of updating breakpoints to not reference
2687    PSPACE anymore.  */
2688
2689 void
2690 breakpoint_program_space_exit (struct program_space *pspace)
2691 {
2692   struct breakpoint *b, *b_temp;
2693   struct bp_location *loc, **loc_temp;
2694
2695   /* Remove any breakpoint that was set through this program space.  */
2696   ALL_BREAKPOINTS_SAFE (b, b_temp)
2697     {
2698       if (b->pspace == pspace)
2699         delete_breakpoint (b);
2700     }
2701
2702   /* Breakpoints set through other program spaces could have locations
2703      bound to PSPACE as well.  Remove those.  */
2704   ALL_BP_LOCATIONS (loc, loc_temp)
2705     {
2706       struct bp_location *tmp;
2707
2708       if (loc->pspace == pspace)
2709         {
2710           /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
2711           if (loc->owner->loc == loc)
2712             loc->owner->loc = loc->next;
2713           else
2714             for (tmp = loc->owner->loc; tmp->next != NULL; tmp = tmp->next)
2715               if (tmp->next == loc)
2716                 {
2717                   tmp->next = loc->next;
2718                   break;
2719                 }
2720         }
2721     }
2722
2723   /* Now update the global location list to permanently delete the
2724      removed locations above.  */
2725   update_global_location_list (0);
2726 }
2727
2728 /* Make sure all breakpoints are inserted in inferior.
2729    Throws exception on any error.
2730    A breakpoint that is already inserted won't be inserted
2731    again, so calling this function twice is safe.  */
2732 void
2733 insert_breakpoints (void)
2734 {
2735   struct breakpoint *bpt;
2736
2737   ALL_BREAKPOINTS (bpt)
2738     if (is_hardware_watchpoint (bpt))
2739       {
2740         struct watchpoint *w = (struct watchpoint *) bpt;
2741
2742         update_watchpoint (w, 0 /* don't reparse.  */);
2743       }
2744
2745   update_global_location_list (1);
2746
2747   /* update_global_location_list does not insert breakpoints when
2748      always_inserted_mode is not enabled.  Explicitly insert them
2749      now.  */
2750   if (!breakpoints_always_inserted_mode ())
2751     insert_breakpoint_locations ();
2752 }
2753
2754 /* Invoke CALLBACK for each of bp_location.  */
2755
2756 void
2757 iterate_over_bp_locations (walk_bp_location_callback callback)
2758 {
2759   struct bp_location *loc, **loc_tmp;
2760
2761   ALL_BP_LOCATIONS (loc, loc_tmp)
2762     {
2763       callback (loc, NULL);
2764     }
2765 }
2766
2767 /* This is used when we need to synch breakpoint conditions between GDB and the
2768    target.  It is the case with deleting and disabling of breakpoints when using
2769    always-inserted mode.  */
2770
2771 static void
2772 update_inserted_breakpoint_locations (void)
2773 {
2774   struct bp_location *bl, **blp_tmp;
2775   int error_flag = 0;
2776   int val = 0;
2777   int disabled_breaks = 0;
2778   int hw_breakpoint_error = 0;
2779   int hw_bp_details_reported = 0;
2780
2781   struct ui_file *tmp_error_stream = mem_fileopen ();
2782   struct cleanup *cleanups = make_cleanup_ui_file_delete (tmp_error_stream);
2783
2784   /* Explicitly mark the warning -- this will only be printed if
2785      there was an error.  */
2786   fprintf_unfiltered (tmp_error_stream, "Warning:\n");
2787
2788   save_current_space_and_thread ();
2789
2790   ALL_BP_LOCATIONS (bl, blp_tmp)
2791     {
2792       /* We only want to update software breakpoints and hardware
2793          breakpoints.  */
2794       if (!is_breakpoint (bl->owner))
2795         continue;
2796
2797       /* We only want to update locations that are already inserted
2798          and need updating.  This is to avoid unwanted insertion during
2799          deletion of breakpoints.  */
2800       if (!bl->inserted || (bl->inserted && !bl->needs_update))
2801         continue;
2802
2803       switch_to_program_space_and_thread (bl->pspace);
2804
2805       /* For targets that support global breakpoints, there's no need
2806          to select an inferior to insert breakpoint to.  In fact, even
2807          if we aren't attached to any process yet, we should still
2808          insert breakpoints.  */
2809       if (!gdbarch_has_global_breakpoints (target_gdbarch ())
2810           && ptid_equal (inferior_ptid, null_ptid))
2811         continue;
2812
2813       val = insert_bp_location (bl, tmp_error_stream, &disabled_breaks,
2814                                     &hw_breakpoint_error, &hw_bp_details_reported);
2815       if (val)
2816         error_flag = val;
2817     }
2818
2819   if (error_flag)
2820     {
2821       target_terminal_ours_for_output ();
2822       error_stream (tmp_error_stream);
2823     }
2824
2825   do_cleanups (cleanups);
2826 }
2827
2828 /* Used when starting or continuing the program.  */
2829
2830 static void
2831 insert_breakpoint_locations (void)
2832 {
2833   struct breakpoint *bpt;
2834   struct bp_location *bl, **blp_tmp;
2835   int error_flag = 0;
2836   int val = 0;
2837   int disabled_breaks = 0;
2838   int hw_breakpoint_error = 0;
2839   int hw_bp_error_explained_already = 0;
2840
2841   struct ui_file *tmp_error_stream = mem_fileopen ();
2842   struct cleanup *cleanups = make_cleanup_ui_file_delete (tmp_error_stream);
2843   
2844   /* Explicitly mark the warning -- this will only be printed if
2845      there was an error.  */
2846   fprintf_unfiltered (tmp_error_stream, "Warning:\n");
2847
2848   save_current_space_and_thread ();
2849
2850   ALL_BP_LOCATIONS (bl, blp_tmp)
2851     {
2852       if (!should_be_inserted (bl) || (bl->inserted && !bl->needs_update))
2853         continue;
2854
2855       /* There is no point inserting thread-specific breakpoints if
2856          the thread no longer exists.  ALL_BP_LOCATIONS bp_location
2857          has BL->OWNER always non-NULL.  */
2858       if (bl->owner->thread != -1
2859           && !valid_thread_id (bl->owner->thread))
2860         continue;
2861
2862       switch_to_program_space_and_thread (bl->pspace);
2863
2864       /* For targets that support global breakpoints, there's no need
2865          to select an inferior to insert breakpoint to.  In fact, even
2866          if we aren't attached to any process yet, we should still
2867          insert breakpoints.  */
2868       if (!gdbarch_has_global_breakpoints (target_gdbarch ())
2869           && ptid_equal (inferior_ptid, null_ptid))
2870         continue;
2871
2872       val = insert_bp_location (bl, tmp_error_stream, &disabled_breaks,
2873                                     &hw_breakpoint_error, &hw_bp_error_explained_already);
2874       if (val)
2875         error_flag = val;
2876     }
2877
2878   /* If we failed to insert all locations of a watchpoint, remove
2879      them, as half-inserted watchpoint is of limited use.  */
2880   ALL_BREAKPOINTS (bpt)  
2881     {
2882       int some_failed = 0;
2883       struct bp_location *loc;
2884
2885       if (!is_hardware_watchpoint (bpt))
2886         continue;
2887
2888       if (!breakpoint_enabled (bpt))
2889         continue;
2890
2891       if (bpt->disposition == disp_del_at_next_stop)
2892         continue;
2893       
2894       for (loc = bpt->loc; loc; loc = loc->next)
2895         if (!loc->inserted && should_be_inserted (loc))
2896           {
2897             some_failed = 1;
2898             break;
2899           }
2900       if (some_failed)
2901         {
2902           for (loc = bpt->loc; loc; loc = loc->next)
2903             if (loc->inserted)
2904               remove_breakpoint (loc, mark_uninserted);
2905
2906           hw_breakpoint_error = 1;
2907           fprintf_unfiltered (tmp_error_stream,
2908                               "Could not insert hardware watchpoint %d.\n", 
2909                               bpt->number);
2910           error_flag = -1;
2911         }
2912     }
2913
2914   if (error_flag)
2915     {
2916       /* If a hardware breakpoint or watchpoint was inserted, add a
2917          message about possibly exhausted resources.  */
2918       if (hw_breakpoint_error && !hw_bp_error_explained_already)
2919         {
2920           fprintf_unfiltered (tmp_error_stream, 
2921                               "Could not insert hardware breakpoints:\n\
2922 You may have requested too many hardware breakpoints/watchpoints.\n");
2923         }
2924       target_terminal_ours_for_output ();
2925       error_stream (tmp_error_stream);
2926     }
2927
2928   do_cleanups (cleanups);
2929 }
2930
2931 /* Used when the program stops.
2932    Returns zero if successful, or non-zero if there was a problem
2933    removing a breakpoint location.  */
2934
2935 int
2936 remove_breakpoints (void)
2937 {
2938   struct bp_location *bl, **blp_tmp;
2939   int val = 0;
2940
2941   ALL_BP_LOCATIONS (bl, blp_tmp)
2942   {
2943     if (bl->inserted && !is_tracepoint (bl->owner))
2944       val |= remove_breakpoint (bl, mark_uninserted);
2945   }
2946   return val;
2947 }
2948
2949 /* Remove breakpoints of process PID.  */
2950
2951 int
2952 remove_breakpoints_pid (int pid)
2953 {
2954   struct bp_location *bl, **blp_tmp;
2955   int val;
2956   struct inferior *inf = find_inferior_pid (pid);
2957
2958   ALL_BP_LOCATIONS (bl, blp_tmp)
2959   {
2960     if (bl->pspace != inf->pspace)
2961       continue;
2962
2963     if (bl->owner->type == bp_dprintf)
2964       continue;
2965
2966     if (bl->inserted)
2967       {
2968         val = remove_breakpoint (bl, mark_uninserted);
2969         if (val != 0)
2970           return val;
2971       }
2972   }
2973   return 0;
2974 }
2975
2976 int
2977 reattach_breakpoints (int pid)
2978 {
2979   struct cleanup *old_chain;
2980   struct bp_location *bl, **blp_tmp;
2981   int val;
2982   struct ui_file *tmp_error_stream;
2983   int dummy1 = 0, dummy2 = 0, dummy3 = 0;
2984   struct inferior *inf;
2985   struct thread_info *tp;
2986
2987   tp = any_live_thread_of_process (pid);
2988   if (tp == NULL)
2989     return 1;
2990
2991   inf = find_inferior_pid (pid);
2992   old_chain = save_inferior_ptid ();
2993
2994   inferior_ptid = tp->ptid;
2995
2996   tmp_error_stream = mem_fileopen ();
2997   make_cleanup_ui_file_delete (tmp_error_stream);
2998
2999   ALL_BP_LOCATIONS (bl, blp_tmp)
3000   {
3001     if (bl->pspace != inf->pspace)
3002       continue;
3003
3004     if (bl->inserted)
3005       {
3006         bl->inserted = 0;
3007         val = insert_bp_location (bl, tmp_error_stream, &dummy1, &dummy2, &dummy3);
3008         if (val != 0)
3009           {
3010             do_cleanups (old_chain);
3011             return val;
3012           }
3013       }
3014   }
3015   do_cleanups (old_chain);
3016   return 0;
3017 }
3018
3019 static int internal_breakpoint_number = -1;
3020
3021 /* Set the breakpoint number of B, depending on the value of INTERNAL.
3022    If INTERNAL is non-zero, the breakpoint number will be populated
3023    from internal_breakpoint_number and that variable decremented.
3024    Otherwise the breakpoint number will be populated from
3025    breakpoint_count and that value incremented.  Internal breakpoints
3026    do not set the internal var bpnum.  */
3027 static void
3028 set_breakpoint_number (int internal, struct breakpoint *b)
3029 {
3030   if (internal)
3031     b->number = internal_breakpoint_number--;
3032   else
3033     {
3034       set_breakpoint_count (breakpoint_count + 1);
3035       b->number = breakpoint_count;
3036     }
3037 }
3038
3039 static struct breakpoint *
3040 create_internal_breakpoint (struct gdbarch *gdbarch,
3041                             CORE_ADDR address, enum bptype type,
3042                             const struct breakpoint_ops *ops)
3043 {
3044   struct symtab_and_line sal;
3045   struct breakpoint *b;
3046
3047   init_sal (&sal);              /* Initialize to zeroes.  */
3048
3049   sal.pc = address;
3050   sal.section = find_pc_overlay (sal.pc);
3051   sal.pspace = current_program_space;
3052
3053   b = set_raw_breakpoint (gdbarch, sal, type, ops);
3054   b->number = internal_breakpoint_number--;
3055   b->disposition = disp_donttouch;
3056
3057   return b;
3058 }
3059
3060 static const char *const longjmp_names[] =
3061   {
3062     "longjmp", "_longjmp", "siglongjmp", "_siglongjmp"
3063   };
3064 #define NUM_LONGJMP_NAMES ARRAY_SIZE(longjmp_names)
3065
3066 /* Per-objfile data private to breakpoint.c.  */
3067 struct breakpoint_objfile_data
3068 {
3069   /* Minimal symbol for "_ovly_debug_event" (if any).  */
3070   struct minimal_symbol *overlay_msym;
3071
3072   /* Minimal symbol(s) for "longjmp", "siglongjmp", etc. (if any).  */
3073   struct minimal_symbol *longjmp_msym[NUM_LONGJMP_NAMES];
3074
3075   /* True if we have looked for longjmp probes.  */
3076   int longjmp_searched;
3077
3078   /* SystemTap probe points for longjmp (if any).  */
3079   VEC (probe_p) *longjmp_probes;
3080
3081   /* Minimal symbol for "std::terminate()" (if any).  */
3082   struct minimal_symbol *terminate_msym;
3083
3084   /* Minimal symbol for "_Unwind_DebugHook" (if any).  */
3085   struct minimal_symbol *exception_msym;
3086
3087   /* True if we have looked for exception probes.  */
3088   int exception_searched;
3089
3090   /* SystemTap probe points for unwinding (if any).  */
3091   VEC (probe_p) *exception_probes;
3092 };
3093
3094 static const struct objfile_data *breakpoint_objfile_key;
3095
3096 /* Minimal symbol not found sentinel.  */
3097 static struct minimal_symbol msym_not_found;
3098
3099 /* Returns TRUE if MSYM point to the "not found" sentinel.  */
3100
3101 static int
3102 msym_not_found_p (const struct minimal_symbol *msym)
3103 {
3104   return msym == &msym_not_found;
3105 }
3106
3107 /* Return per-objfile data needed by breakpoint.c.
3108    Allocate the data if necessary.  */
3109
3110 static struct breakpoint_objfile_data *
3111 get_breakpoint_objfile_data (struct objfile *objfile)
3112 {
3113   struct breakpoint_objfile_data *bp_objfile_data;
3114
3115   bp_objfile_data = objfile_data (objfile, breakpoint_objfile_key);
3116   if (bp_objfile_data == NULL)
3117     {
3118       bp_objfile_data = obstack_alloc (&objfile->objfile_obstack,
3119                                        sizeof (*bp_objfile_data));
3120
3121       memset (bp_objfile_data, 0, sizeof (*bp_objfile_data));
3122       set_objfile_data (objfile, breakpoint_objfile_key, bp_objfile_data);
3123     }
3124   return bp_objfile_data;
3125 }
3126
3127 static void
3128 free_breakpoint_probes (struct objfile *obj, void *data)
3129 {
3130   struct breakpoint_objfile_data *bp_objfile_data = data;
3131
3132   VEC_free (probe_p, bp_objfile_data->longjmp_probes);
3133   VEC_free (probe_p, bp_objfile_data->exception_probes);
3134 }
3135
3136 static void
3137 create_overlay_event_breakpoint (void)
3138 {
3139   struct objfile *objfile;
3140   const char *const func_name = "_ovly_debug_event";
3141
3142   ALL_OBJFILES (objfile)
3143     {
3144       struct breakpoint *b;
3145       struct breakpoint_objfile_data *bp_objfile_data;
3146       CORE_ADDR addr;
3147
3148       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3149
3150       if (msym_not_found_p (bp_objfile_data->overlay_msym))
3151         continue;
3152
3153       if (bp_objfile_data->overlay_msym == NULL)
3154         {
3155           struct minimal_symbol *m;
3156
3157           m = lookup_minimal_symbol_text (func_name, objfile);
3158           if (m == NULL)
3159             {
3160               /* Avoid future lookups in this objfile.  */
3161               bp_objfile_data->overlay_msym = &msym_not_found;
3162               continue;
3163             }
3164           bp_objfile_data->overlay_msym = m;
3165         }
3166
3167       addr = SYMBOL_VALUE_ADDRESS (bp_objfile_data->overlay_msym);
3168       b = create_internal_breakpoint (get_objfile_arch (objfile), addr,
3169                                       bp_overlay_event,
3170                                       &internal_breakpoint_ops);
3171       b->addr_string = xstrdup (func_name);
3172
3173       if (overlay_debugging == ovly_auto)
3174         {
3175           b->enable_state = bp_enabled;
3176           overlay_events_enabled = 1;
3177         }
3178       else
3179        {
3180          b->enable_state = bp_disabled;
3181          overlay_events_enabled = 0;
3182        }
3183     }
3184   update_global_location_list (1);
3185 }
3186
3187 static void
3188 create_longjmp_master_breakpoint (void)
3189 {
3190   struct program_space *pspace;
3191   struct cleanup *old_chain;
3192
3193   old_chain = save_current_program_space ();
3194
3195   ALL_PSPACES (pspace)
3196   {
3197     struct objfile *objfile;
3198
3199     set_current_program_space (pspace);
3200
3201     ALL_OBJFILES (objfile)
3202     {
3203       int i;
3204       struct gdbarch *gdbarch;
3205       struct breakpoint_objfile_data *bp_objfile_data;
3206
3207       gdbarch = get_objfile_arch (objfile);
3208       if (!gdbarch_get_longjmp_target_p (gdbarch))
3209         continue;
3210
3211       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3212
3213       if (!bp_objfile_data->longjmp_searched)
3214         {
3215           bp_objfile_data->longjmp_probes
3216             = find_probes_in_objfile (objfile, "libc", "longjmp");
3217           bp_objfile_data->longjmp_searched = 1;
3218         }
3219
3220       if (bp_objfile_data->longjmp_probes != NULL)
3221         {
3222           int i;
3223           struct probe *probe;
3224           struct gdbarch *gdbarch = get_objfile_arch (objfile);
3225
3226           for (i = 0;
3227                VEC_iterate (probe_p,
3228                             bp_objfile_data->longjmp_probes,
3229                             i, probe);
3230                ++i)
3231             {
3232               struct breakpoint *b;
3233
3234               b = create_internal_breakpoint (gdbarch, probe->address,
3235                                               bp_longjmp_master,
3236                                               &internal_breakpoint_ops);
3237               b->addr_string = xstrdup ("-probe-stap libc:longjmp");
3238               b->enable_state = bp_disabled;
3239             }
3240
3241           continue;
3242         }
3243
3244       for (i = 0; i < NUM_LONGJMP_NAMES; i++)
3245         {
3246           struct breakpoint *b;
3247           const char *func_name;
3248           CORE_ADDR addr;
3249
3250           if (msym_not_found_p (bp_objfile_data->longjmp_msym[i]))
3251             continue;
3252
3253           func_name = longjmp_names[i];
3254           if (bp_objfile_data->longjmp_msym[i] == NULL)
3255             {
3256               struct minimal_symbol *m;
3257
3258               m = lookup_minimal_symbol_text (func_name, objfile);
3259               if (m == NULL)
3260                 {
3261                   /* Prevent future lookups in this objfile.  */
3262                   bp_objfile_data->longjmp_msym[i] = &msym_not_found;
3263                   continue;
3264                 }
3265               bp_objfile_data->longjmp_msym[i] = m;
3266             }
3267
3268           addr = SYMBOL_VALUE_ADDRESS (bp_objfile_data->longjmp_msym[i]);
3269           b = create_internal_breakpoint (gdbarch, addr, bp_longjmp_master,
3270                                           &internal_breakpoint_ops);
3271           b->addr_string = xstrdup (func_name);
3272           b->enable_state = bp_disabled;
3273         }
3274     }
3275   }
3276   update_global_location_list (1);
3277
3278   do_cleanups (old_chain);
3279 }
3280
3281 /* Create a master std::terminate breakpoint.  */
3282 static void
3283 create_std_terminate_master_breakpoint (void)
3284 {
3285   struct program_space *pspace;
3286   struct cleanup *old_chain;
3287   const char *const func_name = "std::terminate()";
3288
3289   old_chain = save_current_program_space ();
3290
3291   ALL_PSPACES (pspace)
3292   {
3293     struct objfile *objfile;
3294     CORE_ADDR addr;
3295
3296     set_current_program_space (pspace);
3297
3298     ALL_OBJFILES (objfile)
3299     {
3300       struct breakpoint *b;
3301       struct breakpoint_objfile_data *bp_objfile_data;
3302
3303       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3304
3305       if (msym_not_found_p (bp_objfile_data->terminate_msym))
3306         continue;
3307
3308       if (bp_objfile_data->terminate_msym == NULL)
3309         {
3310           struct minimal_symbol *m;
3311
3312           m = lookup_minimal_symbol (func_name, NULL, objfile);
3313           if (m == NULL || (MSYMBOL_TYPE (m) != mst_text
3314                             && MSYMBOL_TYPE (m) != mst_file_text))
3315             {
3316               /* Prevent future lookups in this objfile.  */
3317               bp_objfile_data->terminate_msym = &msym_not_found;
3318               continue;
3319             }
3320           bp_objfile_data->terminate_msym = m;
3321         }
3322
3323       addr = SYMBOL_VALUE_ADDRESS (bp_objfile_data->terminate_msym);
3324       b = create_internal_breakpoint (get_objfile_arch (objfile), addr,
3325                                       bp_std_terminate_master,
3326                                       &internal_breakpoint_ops);
3327       b->addr_string = xstrdup (func_name);
3328       b->enable_state = bp_disabled;
3329     }
3330   }
3331
3332   update_global_location_list (1);
3333
3334   do_cleanups (old_chain);
3335 }
3336
3337 /* Install a master breakpoint on the unwinder's debug hook.  */
3338
3339 static void
3340 create_exception_master_breakpoint (void)
3341 {
3342   struct objfile *objfile;
3343   const char *const func_name = "_Unwind_DebugHook";
3344
3345   ALL_OBJFILES (objfile)
3346     {
3347       struct breakpoint *b;
3348       struct gdbarch *gdbarch;
3349       struct breakpoint_objfile_data *bp_objfile_data;
3350       CORE_ADDR addr;
3351
3352       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3353
3354       /* We prefer the SystemTap probe point if it exists.  */
3355       if (!bp_objfile_data->exception_searched)
3356         {
3357           bp_objfile_data->exception_probes
3358             = find_probes_in_objfile (objfile, "libgcc", "unwind");
3359           bp_objfile_data->exception_searched = 1;
3360         }
3361
3362       if (bp_objfile_data->exception_probes != NULL)
3363         {
3364           struct gdbarch *gdbarch = get_objfile_arch (objfile);
3365           int i;
3366           struct probe *probe;
3367
3368           for (i = 0;
3369                VEC_iterate (probe_p,
3370                             bp_objfile_data->exception_probes,
3371                             i, probe);
3372                ++i)
3373             {
3374               struct breakpoint *b;
3375
3376               b = create_internal_breakpoint (gdbarch, probe->address,
3377                                               bp_exception_master,
3378                                               &internal_breakpoint_ops);
3379               b->addr_string = xstrdup ("-probe-stap libgcc:unwind");
3380               b->enable_state = bp_disabled;
3381             }
3382
3383           continue;
3384         }
3385
3386       /* Otherwise, try the hook function.  */
3387
3388       if (msym_not_found_p (bp_objfile_data->exception_msym))
3389         continue;
3390
3391       gdbarch = get_objfile_arch (objfile);
3392
3393       if (bp_objfile_data->exception_msym == NULL)
3394         {
3395           struct minimal_symbol *debug_hook;
3396
3397           debug_hook = lookup_minimal_symbol (func_name, NULL, objfile);
3398           if (debug_hook == NULL)
3399             {
3400               bp_objfile_data->exception_msym = &msym_not_found;
3401               continue;
3402             }
3403
3404           bp_objfile_data->exception_msym = debug_hook;
3405         }
3406
3407       addr = SYMBOL_VALUE_ADDRESS (bp_objfile_data->exception_msym);
3408       addr = gdbarch_convert_from_func_ptr_addr (gdbarch, addr,
3409                                                  &current_target);
3410       b = create_internal_breakpoint (gdbarch, addr, bp_exception_master,
3411                                       &internal_breakpoint_ops);
3412       b->addr_string = xstrdup (func_name);
3413       b->enable_state = bp_disabled;
3414     }
3415
3416   update_global_location_list (1);
3417 }
3418
3419 void
3420 update_breakpoints_after_exec (void)
3421 {
3422   struct breakpoint *b, *b_tmp;
3423   struct bp_location *bploc, **bplocp_tmp;
3424
3425   /* We're about to delete breakpoints from GDB's lists.  If the
3426      INSERTED flag is true, GDB will try to lift the breakpoints by
3427      writing the breakpoints' "shadow contents" back into memory.  The
3428      "shadow contents" are NOT valid after an exec, so GDB should not
3429      do that.  Instead, the target is responsible from marking
3430      breakpoints out as soon as it detects an exec.  We don't do that
3431      here instead, because there may be other attempts to delete
3432      breakpoints after detecting an exec and before reaching here.  */
3433   ALL_BP_LOCATIONS (bploc, bplocp_tmp)
3434     if (bploc->pspace == current_program_space)
3435       gdb_assert (!bploc->inserted);
3436
3437   ALL_BREAKPOINTS_SAFE (b, b_tmp)
3438   {
3439     if (b->pspace != current_program_space)
3440       continue;
3441
3442     /* Solib breakpoints must be explicitly reset after an exec().  */
3443     if (b->type == bp_shlib_event)
3444       {
3445         delete_breakpoint (b);
3446         continue;
3447       }
3448
3449     /* JIT breakpoints must be explicitly reset after an exec().  */
3450     if (b->type == bp_jit_event)
3451       {
3452         delete_breakpoint (b);
3453         continue;
3454       }
3455
3456     /* Thread event breakpoints must be set anew after an exec(),
3457        as must overlay event and longjmp master breakpoints.  */
3458     if (b->type == bp_thread_event || b->type == bp_overlay_event
3459         || b->type == bp_longjmp_master || b->type == bp_std_terminate_master
3460         || b->type == bp_exception_master)
3461       {
3462         delete_breakpoint (b);
3463         continue;
3464       }
3465
3466     /* Step-resume breakpoints are meaningless after an exec().  */
3467     if (b->type == bp_step_resume || b->type == bp_hp_step_resume)
3468       {
3469         delete_breakpoint (b);
3470         continue;
3471       }
3472
3473     /* Longjmp and longjmp-resume breakpoints are also meaningless
3474        after an exec.  */
3475     if (b->type == bp_longjmp || b->type == bp_longjmp_resume
3476         || b->type == bp_longjmp_call_dummy
3477         || b->type == bp_exception || b->type == bp_exception_resume)
3478       {
3479         delete_breakpoint (b);
3480         continue;
3481       }
3482
3483     if (b->type == bp_catchpoint)
3484       {
3485         /* For now, none of the bp_catchpoint breakpoints need to
3486            do anything at this point.  In the future, if some of
3487            the catchpoints need to something, we will need to add
3488            a new method, and call this method from here.  */
3489         continue;
3490       }
3491
3492     /* bp_finish is a special case.  The only way we ought to be able
3493        to see one of these when an exec() has happened, is if the user
3494        caught a vfork, and then said "finish".  Ordinarily a finish just
3495        carries them to the call-site of the current callee, by setting
3496        a temporary bp there and resuming.  But in this case, the finish
3497        will carry them entirely through the vfork & exec.
3498
3499        We don't want to allow a bp_finish to remain inserted now.  But
3500        we can't safely delete it, 'cause finish_command has a handle to
3501        the bp on a bpstat, and will later want to delete it.  There's a
3502        chance (and I've seen it happen) that if we delete the bp_finish
3503        here, that its storage will get reused by the time finish_command
3504        gets 'round to deleting the "use to be a bp_finish" breakpoint.
3505        We really must allow finish_command to delete a bp_finish.
3506
3507        In the absence of a general solution for the "how do we know
3508        it's safe to delete something others may have handles to?"
3509        problem, what we'll do here is just uninsert the bp_finish, and
3510        let finish_command delete it.
3511
3512        (We know the bp_finish is "doomed" in the sense that it's
3513        momentary, and will be deleted as soon as finish_command sees
3514        the inferior stopped.  So it doesn't matter that the bp's
3515        address is probably bogus in the new a.out, unlike e.g., the
3516        solib breakpoints.)  */
3517
3518     if (b->type == bp_finish)
3519       {
3520         continue;
3521       }
3522
3523     /* Without a symbolic address, we have little hope of the
3524        pre-exec() address meaning the same thing in the post-exec()
3525        a.out.  */
3526     if (b->addr_string == NULL)
3527       {
3528         delete_breakpoint (b);
3529         continue;
3530       }
3531   }
3532   /* FIXME what about longjmp breakpoints?  Re-create them here?  */
3533   create_overlay_event_breakpoint ();
3534   create_longjmp_master_breakpoint ();
3535   create_std_terminate_master_breakpoint ();
3536   create_exception_master_breakpoint ();
3537 }
3538
3539 int
3540 detach_breakpoints (ptid_t ptid)
3541 {
3542   struct bp_location *bl, **blp_tmp;
3543   int val = 0;
3544   struct cleanup *old_chain = save_inferior_ptid ();
3545   struct inferior *inf = current_inferior ();
3546
3547   if (PIDGET (ptid) == PIDGET (inferior_ptid))
3548     error (_("Cannot detach breakpoints of inferior_ptid"));
3549
3550   /* Set inferior_ptid; remove_breakpoint_1 uses this global.  */
3551   inferior_ptid = ptid;
3552   ALL_BP_LOCATIONS (bl, blp_tmp)
3553   {
3554     if (bl->pspace != inf->pspace)
3555       continue;
3556
3557     if (bl->inserted)
3558       val |= remove_breakpoint_1 (bl, mark_inserted);
3559   }
3560
3561   /* Detach single-step breakpoints as well.  */
3562   detach_single_step_breakpoints ();
3563
3564   do_cleanups (old_chain);
3565   return val;
3566 }
3567
3568 /* Remove the breakpoint location BL from the current address space.
3569    Note that this is used to detach breakpoints from a child fork.
3570    When we get here, the child isn't in the inferior list, and neither
3571    do we have objects to represent its address space --- we should
3572    *not* look at bl->pspace->aspace here.  */
3573
3574 static int
3575 remove_breakpoint_1 (struct bp_location *bl, insertion_state_t is)
3576 {
3577   int val;
3578
3579   /* BL is never in moribund_locations by our callers.  */
3580   gdb_assert (bl->owner != NULL);
3581
3582   if (bl->owner->enable_state == bp_permanent)
3583     /* Permanent breakpoints cannot be inserted or removed.  */
3584     return 0;
3585
3586   /* The type of none suggests that owner is actually deleted.
3587      This should not ever happen.  */
3588   gdb_assert (bl->owner->type != bp_none);
3589
3590   if (bl->loc_type == bp_loc_software_breakpoint
3591       || bl->loc_type == bp_loc_hardware_breakpoint)
3592     {
3593       /* "Normal" instruction breakpoint: either the standard
3594          trap-instruction bp (bp_breakpoint), or a
3595          bp_hardware_breakpoint.  */
3596
3597       /* First check to see if we have to handle an overlay.  */
3598       if (overlay_debugging == ovly_off
3599           || bl->section == NULL
3600           || !(section_is_overlay (bl->section)))
3601         {
3602           /* No overlay handling: just remove the breakpoint.  */
3603           val = bl->owner->ops->remove_location (bl);
3604         }
3605       else
3606         {
3607           /* This breakpoint is in an overlay section.
3608              Did we set a breakpoint at the LMA?  */
3609           if (!overlay_events_enabled)
3610               {
3611                 /* Yes -- overlay event support is not active, so we
3612                    should have set a breakpoint at the LMA.  Remove it.  
3613                 */
3614                 /* Ignore any failures: if the LMA is in ROM, we will
3615                    have already warned when we failed to insert it.  */
3616                 if (bl->loc_type == bp_loc_hardware_breakpoint)
3617                   target_remove_hw_breakpoint (bl->gdbarch,
3618                                                &bl->overlay_target_info);
3619                 else
3620                   target_remove_breakpoint (bl->gdbarch,
3621                                             &bl->overlay_target_info);
3622               }
3623           /* Did we set a breakpoint at the VMA? 
3624              If so, we will have marked the breakpoint 'inserted'.  */
3625           if (bl->inserted)
3626             {
3627               /* Yes -- remove it.  Previously we did not bother to
3628                  remove the breakpoint if the section had been
3629                  unmapped, but let's not rely on that being safe.  We
3630                  don't know what the overlay manager might do.  */
3631
3632               /* However, we should remove *software* breakpoints only
3633                  if the section is still mapped, or else we overwrite
3634                  wrong code with the saved shadow contents.  */
3635               if (bl->loc_type == bp_loc_hardware_breakpoint
3636                   || section_is_mapped (bl->section))
3637                 val = bl->owner->ops->remove_location (bl);
3638               else
3639                 val = 0;
3640             }
3641           else
3642             {
3643               /* No -- not inserted, so no need to remove.  No error.  */
3644               val = 0;
3645             }
3646         }
3647
3648       /* In some cases, we might not be able to remove a breakpoint
3649          in a shared library that has already been removed, but we
3650          have not yet processed the shlib unload event.  */
3651       if (val && solib_name_from_address (bl->pspace, bl->address))
3652         val = 0;
3653
3654       if (val)
3655         return val;
3656       bl->inserted = (is == mark_inserted);
3657     }
3658   else if (bl->loc_type == bp_loc_hardware_watchpoint)
3659     {
3660       gdb_assert (bl->owner->ops != NULL
3661                   && bl->owner->ops->remove_location != NULL);
3662
3663       bl->inserted = (is == mark_inserted);
3664       bl->owner->ops->remove_location (bl);
3665
3666       /* Failure to remove any of the hardware watchpoints comes here.  */
3667       if ((is == mark_uninserted) && (bl->inserted))
3668         warning (_("Could not remove hardware watchpoint %d."),
3669                  bl->owner->number);
3670     }
3671   else if (bl->owner->type == bp_catchpoint
3672            && breakpoint_enabled (bl->owner)
3673            && !bl->duplicate)
3674     {
3675       gdb_assert (bl->owner->ops != NULL
3676                   && bl->owner->ops->remove_location != NULL);
3677
3678       val = bl->owner->ops->remove_location (bl);
3679       if (val)
3680         return val;
3681
3682       bl->inserted = (is == mark_inserted);
3683     }
3684
3685   return 0;
3686 }
3687
3688 static int
3689 remove_breakpoint (struct bp_location *bl, insertion_state_t is)
3690 {
3691   int ret;
3692   struct cleanup *old_chain;
3693
3694   /* BL is never in moribund_locations by our callers.  */
3695   gdb_assert (bl->owner != NULL);
3696
3697   if (bl->owner->enable_state == bp_permanent)
3698     /* Permanent breakpoints cannot be inserted or removed.  */
3699     return 0;
3700
3701   /* The type of none suggests that owner is actually deleted.
3702      This should not ever happen.  */
3703   gdb_assert (bl->owner->type != bp_none);
3704
3705   old_chain = save_current_space_and_thread ();
3706
3707   switch_to_program_space_and_thread (bl->pspace);
3708
3709   ret = remove_breakpoint_1 (bl, is);
3710
3711   do_cleanups (old_chain);
3712   return ret;
3713 }
3714
3715 /* Clear the "inserted" flag in all breakpoints.  */
3716
3717 void
3718 mark_breakpoints_out (void)
3719 {
3720   struct bp_location *bl, **blp_tmp;
3721
3722   ALL_BP_LOCATIONS (bl, blp_tmp)
3723     if (bl->pspace == current_program_space)
3724       bl->inserted = 0;
3725 }
3726
3727 /* Clear the "inserted" flag in all breakpoints and delete any
3728    breakpoints which should go away between runs of the program.
3729
3730    Plus other such housekeeping that has to be done for breakpoints
3731    between runs.
3732
3733    Note: this function gets called at the end of a run (by
3734    generic_mourn_inferior) and when a run begins (by
3735    init_wait_for_inferior).  */
3736
3737
3738
3739 void
3740 breakpoint_init_inferior (enum inf_context context)
3741 {
3742   struct breakpoint *b, *b_tmp;
3743   struct bp_location *bl, **blp_tmp;
3744   int ix;
3745   struct program_space *pspace = current_program_space;
3746
3747   /* If breakpoint locations are shared across processes, then there's
3748      nothing to do.  */
3749   if (gdbarch_has_global_breakpoints (target_gdbarch ()))
3750     return;
3751
3752   ALL_BP_LOCATIONS (bl, blp_tmp)
3753   {
3754     /* ALL_BP_LOCATIONS bp_location has BL->OWNER always non-NULL.  */
3755     if (bl->pspace == pspace
3756         && bl->owner->enable_state != bp_permanent)
3757       bl->inserted = 0;
3758   }
3759
3760   ALL_BREAKPOINTS_SAFE (b, b_tmp)
3761   {
3762     if (b->loc && b->loc->pspace != pspace)
3763       continue;
3764
3765     switch (b->type)
3766       {
3767       case bp_call_dummy:
3768       case bp_longjmp_call_dummy:
3769
3770         /* If the call dummy breakpoint is at the entry point it will
3771            cause problems when the inferior is rerun, so we better get
3772            rid of it.  */
3773
3774       case bp_watchpoint_scope:
3775
3776         /* Also get rid of scope breakpoints.  */
3777
3778       case bp_shlib_event:
3779
3780         /* Also remove solib event breakpoints.  Their addresses may
3781            have changed since the last time we ran the program.
3782            Actually we may now be debugging against different target;
3783            and so the solib backend that installed this breakpoint may
3784            not be used in by the target.  E.g.,
3785
3786            (gdb) file prog-linux
3787            (gdb) run               # native linux target
3788            ...
3789            (gdb) kill
3790            (gdb) file prog-win.exe
3791            (gdb) tar rem :9999     # remote Windows gdbserver.
3792         */
3793
3794       case bp_step_resume:
3795
3796         /* Also remove step-resume breakpoints.  */
3797
3798         delete_breakpoint (b);
3799         break;
3800
3801       case bp_watchpoint:
3802       case bp_hardware_watchpoint:
3803       case bp_read_watchpoint:
3804       case bp_access_watchpoint:
3805         {
3806           struct watchpoint *w = (struct watchpoint *) b;
3807
3808           /* Likewise for watchpoints on local expressions.  */
3809           if (w->exp_valid_block != NULL)
3810             delete_breakpoint (b);
3811           else if (context == inf_starting)
3812             {
3813               /* Reset val field to force reread of starting value in
3814                  insert_breakpoints.  */
3815               if (w->val)
3816                 value_free (w->val);
3817               w->val = NULL;
3818               w->val_valid = 0;
3819           }
3820         }
3821         break;
3822       default:
3823         break;
3824       }
3825   }
3826
3827   /* Get rid of the moribund locations.  */
3828   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, bl); ++ix)
3829     decref_bp_location (&bl);
3830   VEC_free (bp_location_p, moribund_locations);
3831 }
3832
3833 /* These functions concern about actual breakpoints inserted in the
3834    target --- to e.g. check if we need to do decr_pc adjustment or if
3835    we need to hop over the bkpt --- so we check for address space
3836    match, not program space.  */
3837
3838 /* breakpoint_here_p (PC) returns non-zero if an enabled breakpoint
3839    exists at PC.  It returns ordinary_breakpoint_here if it's an
3840    ordinary breakpoint, or permanent_breakpoint_here if it's a
3841    permanent breakpoint.
3842    - When continuing from a location with an ordinary breakpoint, we
3843      actually single step once before calling insert_breakpoints.
3844    - When continuing from a location with a permanent breakpoint, we
3845      need to use the `SKIP_PERMANENT_BREAKPOINT' macro, provided by
3846      the target, to advance the PC past the breakpoint.  */
3847
3848 enum breakpoint_here
3849 breakpoint_here_p (struct address_space *aspace, CORE_ADDR pc)
3850 {
3851   struct bp_location *bl, **blp_tmp;
3852   int any_breakpoint_here = 0;
3853
3854   ALL_BP_LOCATIONS (bl, blp_tmp)
3855     {
3856       if (bl->loc_type != bp_loc_software_breakpoint
3857           && bl->loc_type != bp_loc_hardware_breakpoint)
3858         continue;
3859
3860       /* ALL_BP_LOCATIONS bp_location has BL->OWNER always non-NULL.  */
3861       if ((breakpoint_enabled (bl->owner)
3862            || bl->owner->enable_state == bp_permanent)
3863           && breakpoint_location_address_match (bl, aspace, pc))
3864         {
3865           if (overlay_debugging 
3866               && section_is_overlay (bl->section)
3867               && !section_is_mapped (bl->section))
3868             continue;           /* unmapped overlay -- can't be a match */
3869           else if (bl->owner->enable_state == bp_permanent)
3870             return permanent_breakpoint_here;
3871           else
3872             any_breakpoint_here = 1;
3873         }
3874     }
3875
3876   return any_breakpoint_here ? ordinary_breakpoint_here : 0;
3877 }
3878
3879 /* Return true if there's a moribund breakpoint at PC.  */
3880
3881 int
3882 moribund_breakpoint_here_p (struct address_space *aspace, CORE_ADDR pc)
3883 {
3884   struct bp_location *loc;
3885   int ix;
3886
3887   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
3888     if (breakpoint_location_address_match (loc, aspace, pc))
3889       return 1;
3890
3891   return 0;
3892 }
3893
3894 /* Returns non-zero if there's a breakpoint inserted at PC, which is
3895    inserted using regular breakpoint_chain / bp_location array
3896    mechanism.  This does not check for single-step breakpoints, which
3897    are inserted and removed using direct target manipulation.  */
3898
3899 int
3900 regular_breakpoint_inserted_here_p (struct address_space *aspace, 
3901                                     CORE_ADDR pc)
3902 {
3903   struct bp_location *bl, **blp_tmp;
3904
3905   ALL_BP_LOCATIONS (bl, blp_tmp)
3906     {
3907       if (bl->loc_type != bp_loc_software_breakpoint
3908           && bl->loc_type != bp_loc_hardware_breakpoint)
3909         continue;
3910
3911       if (bl->inserted
3912           && breakpoint_location_address_match (bl, aspace, pc))
3913         {
3914           if (overlay_debugging 
3915               && section_is_overlay (bl->section)
3916               && !section_is_mapped (bl->section))
3917             continue;           /* unmapped overlay -- can't be a match */
3918           else
3919             return 1;
3920         }
3921     }
3922   return 0;
3923 }
3924
3925 /* Returns non-zero iff there's either regular breakpoint
3926    or a single step breakpoint inserted at PC.  */
3927
3928 int
3929 breakpoint_inserted_here_p (struct address_space *aspace, CORE_ADDR pc)
3930 {
3931   if (regular_breakpoint_inserted_here_p (aspace, pc))
3932     return 1;
3933
3934   if (single_step_breakpoint_inserted_here_p (aspace, pc))
3935     return 1;
3936
3937   return 0;
3938 }
3939
3940 /* This function returns non-zero iff there is a software breakpoint
3941    inserted at PC.  */
3942
3943 int
3944 software_breakpoint_inserted_here_p (struct address_space *aspace,
3945                                      CORE_ADDR pc)
3946 {
3947   struct bp_location *bl, **blp_tmp;
3948
3949   ALL_BP_LOCATIONS (bl, blp_tmp)
3950     {
3951       if (bl->loc_type != bp_loc_software_breakpoint)
3952         continue;
3953
3954       if (bl->inserted
3955           && breakpoint_address_match (bl->pspace->aspace, bl->address,
3956                                        aspace, pc))
3957         {
3958           if (overlay_debugging 
3959               && section_is_overlay (bl->section)
3960               && !section_is_mapped (bl->section))
3961             continue;           /* unmapped overlay -- can't be a match */
3962           else
3963             return 1;
3964         }
3965     }
3966
3967   /* Also check for software single-step breakpoints.  */
3968   if (single_step_breakpoint_inserted_here_p (aspace, pc))
3969     return 1;
3970
3971   return 0;
3972 }
3973
3974 int
3975 hardware_watchpoint_inserted_in_range (struct address_space *aspace,
3976                                        CORE_ADDR addr, ULONGEST len)
3977 {
3978   struct breakpoint *bpt;
3979
3980   ALL_BREAKPOINTS (bpt)
3981     {
3982       struct bp_location *loc;
3983
3984       if (bpt->type != bp_hardware_watchpoint
3985           && bpt->type != bp_access_watchpoint)
3986         continue;
3987
3988       if (!breakpoint_enabled (bpt))
3989         continue;
3990
3991       for (loc = bpt->loc; loc; loc = loc->next)
3992         if (loc->pspace->aspace == aspace && loc->inserted)
3993           {
3994             CORE_ADDR l, h;
3995
3996             /* Check for intersection.  */
3997             l = max (loc->address, addr);
3998             h = min (loc->address + loc->length, addr + len);
3999             if (l < h)
4000               return 1;
4001           }
4002     }
4003   return 0;
4004 }
4005
4006 /* breakpoint_thread_match (PC, PTID) returns true if the breakpoint at
4007    PC is valid for process/thread PTID.  */
4008
4009 int
4010 breakpoint_thread_match (struct address_space *aspace, CORE_ADDR pc,
4011                          ptid_t ptid)
4012 {
4013   struct bp_location *bl, **blp_tmp;
4014   /* The thread and task IDs associated to PTID, computed lazily.  */
4015   int thread = -1;
4016   int task = 0;
4017   
4018   ALL_BP_LOCATIONS (bl, blp_tmp)
4019     {
4020       if (bl->loc_type != bp_loc_software_breakpoint
4021           && bl->loc_type != bp_loc_hardware_breakpoint)
4022         continue;
4023
4024       /* ALL_BP_LOCATIONS bp_location has bl->OWNER always non-NULL.  */
4025       if (!breakpoint_enabled (bl->owner)
4026           && bl->owner->enable_state != bp_permanent)
4027         continue;
4028
4029       if (!breakpoint_location_address_match (bl, aspace, pc))
4030         continue;
4031
4032       if (bl->owner->thread != -1)
4033         {
4034           /* This is a thread-specific breakpoint.  Check that ptid
4035              matches that thread.  If thread hasn't been computed yet,
4036              it is now time to do so.  */
4037           if (thread == -1)
4038             thread = pid_to_thread_id (ptid);
4039           if (bl->owner->thread != thread)
4040             continue;
4041         }
4042
4043       if (bl->owner->task != 0)
4044         {
4045           /* This is a task-specific breakpoint.  Check that ptid
4046              matches that task.  If task hasn't been computed yet,
4047              it is now time to do so.  */
4048           if (task == 0)
4049             task = ada_get_task_number (ptid);
4050           if (bl->owner->task != task)
4051             continue;
4052         }
4053
4054       if (overlay_debugging 
4055           && section_is_overlay (bl->section)
4056           && !section_is_mapped (bl->section))
4057         continue;           /* unmapped overlay -- can't be a match */
4058
4059       return 1;
4060     }
4061
4062   return 0;
4063 }
4064 \f
4065
4066 /* bpstat stuff.  External routines' interfaces are documented
4067    in breakpoint.h.  */
4068
4069 int
4070 is_catchpoint (struct breakpoint *ep)
4071 {
4072   return (ep->type == bp_catchpoint);
4073 }
4074
4075 /* Frees any storage that is part of a bpstat.  Does not walk the
4076    'next' chain.  */
4077
4078 static void
4079 bpstat_free (bpstat bs)
4080 {
4081   if (bs->old_val != NULL)
4082     value_free (bs->old_val);
4083   decref_counted_command_line (&bs->commands);
4084   decref_bp_location (&bs->bp_location_at);
4085   xfree (bs);
4086 }
4087
4088 /* Clear a bpstat so that it says we are not at any breakpoint.
4089    Also free any storage that is part of a bpstat.  */
4090
4091 void
4092 bpstat_clear (bpstat *bsp)
4093 {
4094   bpstat p;
4095   bpstat q;
4096
4097   if (bsp == 0)
4098     return;
4099   p = *bsp;
4100   while (p != NULL)
4101     {
4102       q = p->next;
4103       bpstat_free (p);
4104       p = q;
4105     }
4106   *bsp = NULL;
4107 }
4108
4109 /* Return a copy of a bpstat.  Like "bs1 = bs2" but all storage that
4110    is part of the bpstat is copied as well.  */
4111
4112 bpstat
4113 bpstat_copy (bpstat bs)
4114 {
4115   bpstat p = NULL;
4116   bpstat tmp;
4117   bpstat retval = NULL;
4118
4119   if (bs == NULL)
4120     return bs;
4121
4122   for (; bs != NULL; bs = bs->next)
4123     {
4124       tmp = (bpstat) xmalloc (sizeof (*tmp));
4125       memcpy (tmp, bs, sizeof (*tmp));
4126       incref_counted_command_line (tmp->commands);
4127       incref_bp_location (tmp->bp_location_at);
4128       if (bs->old_val != NULL)
4129         {
4130           tmp->old_val = value_copy (bs->old_val);
4131           release_value (tmp->old_val);
4132         }
4133
4134       if (p == NULL)
4135         /* This is the first thing in the chain.  */
4136         retval = tmp;
4137       else
4138         p->next = tmp;
4139       p = tmp;
4140     }
4141   p->next = NULL;
4142   return retval;
4143 }
4144
4145 /* Find the bpstat associated with this breakpoint.  */
4146
4147 bpstat
4148 bpstat_find_breakpoint (bpstat bsp, struct breakpoint *breakpoint)
4149 {
4150   if (bsp == NULL)
4151     return NULL;
4152
4153   for (; bsp != NULL; bsp = bsp->next)
4154     {
4155       if (bsp->breakpoint_at == breakpoint)
4156         return bsp;
4157     }
4158   return NULL;
4159 }
4160
4161 /* See breakpoint.h.  */
4162
4163 enum bpstat_signal_value
4164 bpstat_explains_signal (bpstat bsp)
4165 {
4166   enum bpstat_signal_value result = BPSTAT_SIGNAL_NO;
4167
4168   for (; bsp != NULL; bsp = bsp->next)
4169     {
4170       /* Ensure that, if we ever entered this loop, then we at least
4171          return BPSTAT_SIGNAL_HIDE.  */
4172       enum bpstat_signal_value newval = BPSTAT_SIGNAL_HIDE;
4173
4174       if (bsp->breakpoint_at != NULL)
4175         newval = bsp->breakpoint_at->ops->explains_signal (bsp->breakpoint_at);
4176
4177       if (newval > result)
4178         result = newval;
4179     }
4180
4181   return result;
4182 }
4183
4184 /* Put in *NUM the breakpoint number of the first breakpoint we are
4185    stopped at.  *BSP upon return is a bpstat which points to the
4186    remaining breakpoints stopped at (but which is not guaranteed to be
4187    good for anything but further calls to bpstat_num).
4188
4189    Return 0 if passed a bpstat which does not indicate any breakpoints.
4190    Return -1 if stopped at a breakpoint that has been deleted since
4191    we set it.
4192    Return 1 otherwise.  */
4193
4194 int
4195 bpstat_num (bpstat *bsp, int *num)
4196 {
4197   struct breakpoint *b;
4198
4199   if ((*bsp) == NULL)
4200     return 0;                   /* No more breakpoint values */
4201
4202   /* We assume we'll never have several bpstats that correspond to a
4203      single breakpoint -- otherwise, this function might return the
4204      same number more than once and this will look ugly.  */
4205   b = (*bsp)->breakpoint_at;
4206   *bsp = (*bsp)->next;
4207   if (b == NULL)
4208     return -1;                  /* breakpoint that's been deleted since */
4209
4210   *num = b->number;             /* We have its number */
4211   return 1;
4212 }
4213
4214 /* See breakpoint.h.  */
4215
4216 void
4217 bpstat_clear_actions (void)
4218 {
4219   struct thread_info *tp;
4220   bpstat bs;
4221
4222   if (ptid_equal (inferior_ptid, null_ptid))
4223     return;
4224
4225   tp = find_thread_ptid (inferior_ptid);
4226   if (tp == NULL)
4227     return;
4228
4229   for (bs = tp->control.stop_bpstat; bs != NULL; bs = bs->next)
4230     {
4231       decref_counted_command_line (&bs->commands);
4232
4233       if (bs->old_val != NULL)
4234         {
4235           value_free (bs->old_val);
4236           bs->old_val = NULL;
4237         }
4238     }
4239 }
4240
4241 /* Called when a command is about to proceed the inferior.  */
4242
4243 static void
4244 breakpoint_about_to_proceed (void)
4245 {
4246   if (!ptid_equal (inferior_ptid, null_ptid))
4247     {
4248       struct thread_info *tp = inferior_thread ();
4249
4250       /* Allow inferior function calls in breakpoint commands to not
4251          interrupt the command list.  When the call finishes
4252          successfully, the inferior will be standing at the same
4253          breakpoint as if nothing happened.  */
4254       if (tp->control.in_infcall)
4255         return;
4256     }
4257
4258   breakpoint_proceeded = 1;
4259 }
4260
4261 /* Stub for cleaning up our state if we error-out of a breakpoint
4262    command.  */
4263 static void
4264 cleanup_executing_breakpoints (void *ignore)
4265 {
4266   executing_breakpoint_commands = 0;
4267 }
4268
4269 /* Return non-zero iff CMD as the first line of a command sequence is `silent'
4270    or its equivalent.  */
4271
4272 static int
4273 command_line_is_silent (struct command_line *cmd)
4274 {
4275   return cmd && (strcmp ("silent", cmd->line) == 0
4276                  || (xdb_commands && strcmp ("Q", cmd->line) == 0));
4277 }
4278
4279 /* Execute all the commands associated with all the breakpoints at
4280    this location.  Any of these commands could cause the process to
4281    proceed beyond this point, etc.  We look out for such changes by
4282    checking the global "breakpoint_proceeded" after each command.
4283
4284    Returns true if a breakpoint command resumed the inferior.  In that
4285    case, it is the caller's responsibility to recall it again with the
4286    bpstat of the current thread.  */
4287
4288 static int
4289 bpstat_do_actions_1 (bpstat *bsp)
4290 {
4291   bpstat bs;
4292   struct cleanup *old_chain;
4293   int again = 0;
4294
4295   /* Avoid endless recursion if a `source' command is contained
4296      in bs->commands.  */
4297   if (executing_breakpoint_commands)
4298     return 0;
4299
4300   executing_breakpoint_commands = 1;
4301   old_chain = make_cleanup (cleanup_executing_breakpoints, 0);
4302
4303   prevent_dont_repeat ();
4304
4305   /* This pointer will iterate over the list of bpstat's.  */
4306   bs = *bsp;
4307
4308   breakpoint_proceeded = 0;
4309   for (; bs != NULL; bs = bs->next)
4310     {
4311       struct counted_command_line *ccmd;
4312       struct command_line *cmd;
4313       struct cleanup *this_cmd_tree_chain;
4314
4315       /* Take ownership of the BSP's command tree, if it has one.
4316
4317          The command tree could legitimately contain commands like
4318          'step' and 'next', which call clear_proceed_status, which
4319          frees stop_bpstat's command tree.  To make sure this doesn't
4320          free the tree we're executing out from under us, we need to
4321          take ownership of the tree ourselves.  Since a given bpstat's
4322          commands are only executed once, we don't need to copy it; we
4323          can clear the pointer in the bpstat, and make sure we free
4324          the tree when we're done.  */
4325       ccmd = bs->commands;
4326       bs->commands = NULL;
4327       this_cmd_tree_chain = make_cleanup_decref_counted_command_line (&ccmd);
4328       cmd = ccmd ? ccmd->commands : NULL;
4329       if (command_line_is_silent (cmd))
4330         {
4331           /* The action has been already done by bpstat_stop_status.  */
4332           cmd = cmd->next;
4333         }
4334
4335       while (cmd != NULL)
4336         {
4337           execute_control_command (cmd);
4338
4339           if (breakpoint_proceeded)
4340             break;
4341           else
4342             cmd = cmd->next;
4343         }
4344
4345       /* We can free this command tree now.  */
4346       do_cleanups (this_cmd_tree_chain);
4347
4348       if (breakpoint_proceeded)
4349         {
4350           if (target_can_async_p ())
4351             /* If we are in async mode, then the target might be still
4352                running, not stopped at any breakpoint, so nothing for
4353                us to do here -- just return to the event loop.  */
4354             ;
4355           else
4356             /* In sync mode, when execute_control_command returns
4357                we're already standing on the next breakpoint.
4358                Breakpoint commands for that stop were not run, since
4359                execute_command does not run breakpoint commands --
4360                only command_line_handler does, but that one is not
4361                involved in execution of breakpoint commands.  So, we
4362                can now execute breakpoint commands.  It should be
4363                noted that making execute_command do bpstat actions is
4364                not an option -- in this case we'll have recursive
4365                invocation of bpstat for each breakpoint with a
4366                command, and can easily blow up GDB stack.  Instead, we
4367                return true, which will trigger the caller to recall us
4368                with the new stop_bpstat.  */
4369             again = 1;
4370           break;
4371         }
4372     }
4373   do_cleanups (old_chain);
4374   return again;
4375 }
4376
4377 void
4378 bpstat_do_actions (void)
4379 {
4380   struct cleanup *cleanup_if_error = make_bpstat_clear_actions_cleanup ();
4381
4382   /* Do any commands attached to breakpoint we are stopped at.  */
4383   while (!ptid_equal (inferior_ptid, null_ptid)
4384          && target_has_execution
4385          && !is_exited (inferior_ptid)
4386          && !is_executing (inferior_ptid))
4387     /* Since in sync mode, bpstat_do_actions may resume the inferior,
4388        and only return when it is stopped at the next breakpoint, we
4389        keep doing breakpoint actions until it returns false to
4390        indicate the inferior was not resumed.  */
4391     if (!bpstat_do_actions_1 (&inferior_thread ()->control.stop_bpstat))
4392       break;
4393
4394   discard_cleanups (cleanup_if_error);
4395 }
4396
4397 /* Print out the (old or new) value associated with a watchpoint.  */
4398
4399 static void
4400 watchpoint_value_print (struct value *val, struct ui_file *stream)
4401 {
4402   if (val == NULL)
4403     fprintf_unfiltered (stream, _("<unreadable>"));
4404   else
4405     {
4406       struct value_print_options opts;
4407       get_user_print_options (&opts);
4408       value_print (val, stream, &opts);
4409     }
4410 }
4411
4412 /* Generic routine for printing messages indicating why we
4413    stopped.  The behavior of this function depends on the value
4414    'print_it' in the bpstat structure.  Under some circumstances we
4415    may decide not to print anything here and delegate the task to
4416    normal_stop().  */
4417
4418 static enum print_stop_action
4419 print_bp_stop_message (bpstat bs)
4420 {
4421   switch (bs->print_it)
4422     {
4423     case print_it_noop:
4424       /* Nothing should be printed for this bpstat entry.  */
4425       return PRINT_UNKNOWN;
4426       break;
4427
4428     case print_it_done:
4429       /* We still want to print the frame, but we already printed the
4430          relevant messages.  */
4431       return PRINT_SRC_AND_LOC;
4432       break;
4433
4434     case print_it_normal:
4435       {
4436         struct breakpoint *b = bs->breakpoint_at;
4437
4438         /* bs->breakpoint_at can be NULL if it was a momentary breakpoint
4439            which has since been deleted.  */
4440         if (b == NULL)
4441           return PRINT_UNKNOWN;
4442
4443         /* Normal case.  Call the breakpoint's print_it method.  */
4444         return b->ops->print_it (bs);
4445       }
4446       break;
4447
4448     default:
4449       internal_error (__FILE__, __LINE__,
4450                       _("print_bp_stop_message: unrecognized enum value"));
4451       break;
4452     }
4453 }
4454
4455 /* A helper function that prints a shared library stopped event.  */
4456
4457 static void
4458 print_solib_event (int is_catchpoint)
4459 {
4460   int any_deleted
4461     = !VEC_empty (char_ptr, current_program_space->deleted_solibs);
4462   int any_added
4463     = !VEC_empty (so_list_ptr, current_program_space->added_solibs);
4464
4465   if (!is_catchpoint)
4466     {
4467       if (any_added || any_deleted)
4468         ui_out_text (current_uiout,
4469                      _("Stopped due to shared library event:\n"));
4470       else
4471         ui_out_text (current_uiout,
4472                      _("Stopped due to shared library event (no "
4473                        "libraries added or removed)\n"));
4474     }
4475
4476   if (ui_out_is_mi_like_p (current_uiout))
4477     ui_out_field_string (current_uiout, "reason",
4478                          async_reason_lookup (EXEC_ASYNC_SOLIB_EVENT));
4479
4480   if (any_deleted)
4481     {
4482       struct cleanup *cleanup;
4483       char *name;
4484       int ix;
4485
4486       ui_out_text (current_uiout, _("  Inferior unloaded "));
4487       cleanup = make_cleanup_ui_out_list_begin_end (current_uiout,
4488                                                     "removed");
4489       for (ix = 0;
4490            VEC_iterate (char_ptr, current_program_space->deleted_solibs,
4491                         ix, name);
4492            ++ix)
4493         {
4494           if (ix > 0)
4495             ui_out_text (current_uiout, "    ");
4496           ui_out_field_string (current_uiout, "library", name);
4497           ui_out_text (current_uiout, "\n");
4498         }
4499
4500       do_cleanups (cleanup);
4501     }
4502
4503   if (any_added)
4504     {
4505       struct so_list *iter;
4506       int ix;
4507       struct cleanup *cleanup;
4508
4509       ui_out_text (current_uiout, _("  Inferior loaded "));
4510       cleanup = make_cleanup_ui_out_list_begin_end (current_uiout,
4511                                                     "added");
4512       for (ix = 0;
4513            VEC_iterate (so_list_ptr, current_program_space->added_solibs,
4514                         ix, iter);
4515            ++ix)
4516         {
4517           if (ix > 0)
4518             ui_out_text (current_uiout, "    ");
4519           ui_out_field_string (current_uiout, "library", iter->so_name);
4520           ui_out_text (current_uiout, "\n");
4521         }
4522
4523       do_cleanups (cleanup);
4524     }
4525 }
4526
4527 /* Print a message indicating what happened.  This is called from
4528    normal_stop().  The input to this routine is the head of the bpstat
4529    list - a list of the eventpoints that caused this stop.  KIND is
4530    the target_waitkind for the stopping event.  This
4531    routine calls the generic print routine for printing a message
4532    about reasons for stopping.  This will print (for example) the
4533    "Breakpoint n," part of the output.  The return value of this
4534    routine is one of:
4535
4536    PRINT_UNKNOWN: Means we printed nothing.
4537    PRINT_SRC_AND_LOC: Means we printed something, and expect subsequent
4538    code to print the location.  An example is 
4539    "Breakpoint 1, " which should be followed by
4540    the location.
4541    PRINT_SRC_ONLY: Means we printed something, but there is no need
4542    to also print the location part of the message.
4543    An example is the catch/throw messages, which
4544    don't require a location appended to the end.
4545    PRINT_NOTHING: We have done some printing and we don't need any 
4546    further info to be printed.  */
4547
4548 enum print_stop_action
4549 bpstat_print (bpstat bs, int kind)
4550 {
4551   int val;
4552
4553   /* Maybe another breakpoint in the chain caused us to stop.
4554      (Currently all watchpoints go on the bpstat whether hit or not.
4555      That probably could (should) be changed, provided care is taken
4556      with respect to bpstat_explains_signal).  */
4557   for (; bs; bs = bs->next)
4558     {
4559       val = print_bp_stop_message (bs);
4560       if (val == PRINT_SRC_ONLY 
4561           || val == PRINT_SRC_AND_LOC 
4562           || val == PRINT_NOTHING)
4563         return val;
4564     }
4565
4566   /* If we had hit a shared library event breakpoint,
4567      print_bp_stop_message would print out this message.  If we hit an
4568      OS-level shared library event, do the same thing.  */
4569   if (kind == TARGET_WAITKIND_LOADED)
4570     {
4571       print_solib_event (0);
4572       return PRINT_NOTHING;
4573     }
4574
4575   /* We reached the end of the chain, or we got a null BS to start
4576      with and nothing was printed.  */
4577   return PRINT_UNKNOWN;
4578 }
4579
4580 /* Evaluate the expression EXP and return 1 if value is zero.  This is
4581    used inside a catch_errors to evaluate the breakpoint condition.
4582    The argument is a "struct expression *" that has been cast to a
4583    "char *" to make it pass through catch_errors.  */
4584
4585 static int
4586 breakpoint_cond_eval (void *exp)
4587 {
4588   struct value *mark = value_mark ();
4589   int i = !value_true (evaluate_expression ((struct expression *) exp));
4590
4591   value_free_to_mark (mark);
4592   return i;
4593 }
4594
4595 /* Allocate a new bpstat.  Link it to the FIFO list by BS_LINK_POINTER.  */
4596
4597 static bpstat
4598 bpstat_alloc (struct bp_location *bl, bpstat **bs_link_pointer)
4599 {
4600   bpstat bs;
4601
4602   bs = (bpstat) xmalloc (sizeof (*bs));
4603   bs->next = NULL;
4604   **bs_link_pointer = bs;
4605   *bs_link_pointer = &bs->next;
4606   bs->breakpoint_at = bl->owner;
4607   bs->bp_location_at = bl;
4608   incref_bp_location (bl);
4609   /* If the condition is false, etc., don't do the commands.  */
4610   bs->commands = NULL;
4611   bs->old_val = NULL;
4612   bs->print_it = print_it_normal;
4613   return bs;
4614 }
4615 \f
4616 /* The target has stopped with waitstatus WS.  Check if any hardware
4617    watchpoints have triggered, according to the target.  */
4618
4619 int
4620 watchpoints_triggered (struct target_waitstatus *ws)
4621 {
4622   int stopped_by_watchpoint = target_stopped_by_watchpoint ();
4623   CORE_ADDR addr;
4624   struct breakpoint *b;
4625
4626   if (!stopped_by_watchpoint)
4627     {
4628       /* We were not stopped by a watchpoint.  Mark all watchpoints
4629          as not triggered.  */
4630       ALL_BREAKPOINTS (b)
4631         if (is_hardware_watchpoint (b))
4632           {
4633             struct watchpoint *w = (struct watchpoint *) b;
4634
4635             w->watchpoint_triggered = watch_triggered_no;
4636           }
4637
4638       return 0;
4639     }
4640
4641   if (!target_stopped_data_address (&current_target, &addr))
4642     {
4643       /* We were stopped by a watchpoint, but we don't know where.
4644          Mark all watchpoints as unknown.  */
4645       ALL_BREAKPOINTS (b)
4646         if (is_hardware_watchpoint (b))
4647           {
4648             struct watchpoint *w = (struct watchpoint *) b;
4649
4650             w->watchpoint_triggered = watch_triggered_unknown;
4651           }
4652
4653       return stopped_by_watchpoint;
4654     }
4655
4656   /* The target could report the data address.  Mark watchpoints
4657      affected by this data address as triggered, and all others as not
4658      triggered.  */
4659
4660   ALL_BREAKPOINTS (b)
4661     if (is_hardware_watchpoint (b))
4662       {
4663         struct watchpoint *w = (struct watchpoint *) b;
4664         struct bp_location *loc;
4665
4666         w->watchpoint_triggered = watch_triggered_no;
4667         for (loc = b->loc; loc; loc = loc->next)
4668           {
4669             if (is_masked_watchpoint (b))
4670               {
4671                 CORE_ADDR newaddr = addr & w->hw_wp_mask;
4672                 CORE_ADDR start = loc->address & w->hw_wp_mask;
4673
4674                 if (newaddr == start)
4675                   {
4676                     w->watchpoint_triggered = watch_triggered_yes;
4677                     break;
4678                   }
4679               }
4680             /* Exact match not required.  Within range is sufficient.  */
4681             else if (target_watchpoint_addr_within_range (&current_target,
4682                                                          addr, loc->address,
4683                                                          loc->length))
4684               {
4685                 w->watchpoint_triggered = watch_triggered_yes;
4686                 break;
4687               }
4688           }
4689       }
4690
4691   return 1;
4692 }
4693
4694 /* Possible return values for watchpoint_check (this can't be an enum
4695    because of check_errors).  */
4696 /* The watchpoint has been deleted.  */
4697 #define WP_DELETED 1
4698 /* The value has changed.  */
4699 #define WP_VALUE_CHANGED 2
4700 /* The value has not changed.  */
4701 #define WP_VALUE_NOT_CHANGED 3
4702 /* Ignore this watchpoint, no matter if the value changed or not.  */
4703 #define WP_IGNORE 4
4704
4705 #define BP_TEMPFLAG 1
4706 #define BP_HARDWAREFLAG 2
4707
4708 /* Evaluate watchpoint condition expression and check if its value
4709    changed.
4710
4711    P should be a pointer to struct bpstat, but is defined as a void *
4712    in order for this function to be usable with catch_errors.  */
4713
4714 static int
4715 watchpoint_check (void *p)
4716 {
4717   bpstat bs = (bpstat) p;
4718   struct watchpoint *b;
4719   struct frame_info *fr;
4720   int within_current_scope;
4721
4722   /* BS is built from an existing struct breakpoint.  */
4723   gdb_assert (bs->breakpoint_at != NULL);
4724   b = (struct watchpoint *) bs->breakpoint_at;
4725
4726   /* If this is a local watchpoint, we only want to check if the
4727      watchpoint frame is in scope if the current thread is the thread
4728      that was used to create the watchpoint.  */
4729   if (!watchpoint_in_thread_scope (b))
4730     return WP_IGNORE;
4731
4732   if (b->exp_valid_block == NULL)
4733     within_current_scope = 1;
4734   else
4735     {
4736       struct frame_info *frame = get_current_frame ();
4737       struct gdbarch *frame_arch = get_frame_arch (frame);
4738       CORE_ADDR frame_pc = get_frame_pc (frame);
4739
4740       /* in_function_epilogue_p() returns a non-zero value if we're
4741          still in the function but the stack frame has already been
4742          invalidated.  Since we can't rely on the values of local
4743          variables after the stack has been destroyed, we are treating
4744          the watchpoint in that state as `not changed' without further
4745          checking.  Don't mark watchpoints as changed if the current
4746          frame is in an epilogue - even if they are in some other
4747          frame, our view of the stack is likely to be wrong and
4748          frame_find_by_id could error out.  */
4749       if (gdbarch_in_function_epilogue_p (frame_arch, frame_pc))
4750         return WP_IGNORE;
4751
4752       fr = frame_find_by_id (b->watchpoint_frame);
4753       within_current_scope = (fr != NULL);
4754
4755       /* If we've gotten confused in the unwinder, we might have
4756          returned a frame that can't describe this variable.  */
4757       if (within_current_scope)
4758         {
4759           struct symbol *function;
4760
4761           function = get_frame_function (fr);
4762           if (function == NULL
4763               || !contained_in (b->exp_valid_block,
4764                                 SYMBOL_BLOCK_VALUE (function)))
4765             within_current_scope = 0;
4766         }
4767
4768       if (within_current_scope)
4769         /* If we end up stopping, the current frame will get selected
4770            in normal_stop.  So this call to select_frame won't affect
4771            the user.  */
4772         select_frame (fr);
4773     }
4774
4775   if (within_current_scope)
4776     {
4777       /* We use value_{,free_to_}mark because it could be a *long*
4778          time before we return to the command level and call
4779          free_all_values.  We can't call free_all_values because we
4780          might be in the middle of evaluating a function call.  */
4781
4782       int pc = 0;
4783       struct value *mark;
4784       struct value *new_val;
4785
4786       if (is_masked_watchpoint (&b->base))
4787         /* Since we don't know the exact trigger address (from
4788            stopped_data_address), just tell the user we've triggered
4789            a mask watchpoint.  */
4790         return WP_VALUE_CHANGED;
4791
4792       mark = value_mark ();
4793       fetch_subexp_value (b->exp, &pc, &new_val, NULL, NULL);
4794
4795       /* We use value_equal_contents instead of value_equal because
4796          the latter coerces an array to a pointer, thus comparing just
4797          the address of the array instead of its contents.  This is
4798          not what we want.  */
4799       if ((b->val != NULL) != (new_val != NULL)
4800           || (b->val != NULL && !value_equal_contents (b->val, new_val)))
4801         {
4802           if (new_val != NULL)
4803             {
4804               release_value (new_val);
4805               value_free_to_mark (mark);
4806             }
4807           bs->old_val = b->val;
4808           b->val = new_val;
4809           b->val_valid = 1;
4810           return WP_VALUE_CHANGED;
4811         }
4812       else
4813         {
4814           /* Nothing changed.  */
4815           value_free_to_mark (mark);
4816           return WP_VALUE_NOT_CHANGED;
4817         }
4818     }
4819   else
4820     {
4821       struct ui_out *uiout = current_uiout;
4822
4823       /* This seems like the only logical thing to do because
4824          if we temporarily ignored the watchpoint, then when
4825          we reenter the block in which it is valid it contains
4826          garbage (in the case of a function, it may have two
4827          garbage values, one before and one after the prologue).
4828          So we can't even detect the first assignment to it and
4829          watch after that (since the garbage may or may not equal
4830          the first value assigned).  */
4831       /* We print all the stop information in
4832          breakpoint_ops->print_it, but in this case, by the time we
4833          call breakpoint_ops->print_it this bp will be deleted
4834          already.  So we have no choice but print the information
4835          here.  */
4836       if (ui_out_is_mi_like_p (uiout))
4837         ui_out_field_string
4838           (uiout, "reason", async_reason_lookup (EXEC_ASYNC_WATCHPOINT_SCOPE));
4839       ui_out_text (uiout, "\nWatchpoint ");
4840       ui_out_field_int (uiout, "wpnum", b->base.number);
4841       ui_out_text (uiout,
4842                    " deleted because the program has left the block in\n\
4843 which its expression is valid.\n");     
4844
4845       /* Make sure the watchpoint's commands aren't executed.  */
4846       decref_counted_command_line (&b->base.commands);
4847       watchpoint_del_at_next_stop (b);
4848
4849       return WP_DELETED;
4850     }
4851 }
4852
4853 /* Return true if it looks like target has stopped due to hitting
4854    breakpoint location BL.  This function does not check if we should
4855    stop, only if BL explains the stop.  */
4856
4857 static int
4858 bpstat_check_location (const struct bp_location *bl,
4859                        struct address_space *aspace, CORE_ADDR bp_addr,
4860                        const struct target_waitstatus *ws)
4861 {
4862   struct breakpoint *b = bl->owner;
4863
4864   /* BL is from an existing breakpoint.  */
4865   gdb_assert (b != NULL);
4866
4867   return b->ops->breakpoint_hit (bl, aspace, bp_addr, ws);
4868 }
4869
4870 /* Determine if the watched values have actually changed, and we
4871    should stop.  If not, set BS->stop to 0.  */
4872
4873 static void
4874 bpstat_check_watchpoint (bpstat bs)
4875 {
4876   const struct bp_location *bl;
4877   struct watchpoint *b;
4878
4879   /* BS is built for existing struct breakpoint.  */
4880   bl = bs->bp_location_at;
4881   gdb_assert (bl != NULL);
4882   b = (struct watchpoint *) bs->breakpoint_at;
4883   gdb_assert (b != NULL);
4884
4885     {
4886       int must_check_value = 0;
4887       
4888       if (b->base.type == bp_watchpoint)
4889         /* For a software watchpoint, we must always check the
4890            watched value.  */
4891         must_check_value = 1;
4892       else if (b->watchpoint_triggered == watch_triggered_yes)
4893         /* We have a hardware watchpoint (read, write, or access)
4894            and the target earlier reported an address watched by
4895            this watchpoint.  */
4896         must_check_value = 1;
4897       else if (b->watchpoint_triggered == watch_triggered_unknown
4898                && b->base.type == bp_hardware_watchpoint)
4899         /* We were stopped by a hardware watchpoint, but the target could
4900            not report the data address.  We must check the watchpoint's
4901            value.  Access and read watchpoints are out of luck; without
4902            a data address, we can't figure it out.  */
4903         must_check_value = 1;
4904
4905       if (must_check_value)
4906         {
4907           char *message
4908             = xstrprintf ("Error evaluating expression for watchpoint %d\n",
4909                           b->base.number);
4910           struct cleanup *cleanups = make_cleanup (xfree, message);
4911           int e = catch_errors (watchpoint_check, bs, message,
4912                                 RETURN_MASK_ALL);
4913           do_cleanups (cleanups);
4914           switch (e)
4915             {
4916             case WP_DELETED:
4917               /* We've already printed what needs to be printed.  */
4918               bs->print_it = print_it_done;
4919               /* Stop.  */
4920               break;
4921             case WP_IGNORE:
4922               bs->print_it = print_it_noop;
4923               bs->stop = 0;
4924               break;
4925             case WP_VALUE_CHANGED:
4926               if (b->base.type == bp_read_watchpoint)
4927                 {
4928                   /* There are two cases to consider here:
4929
4930                      1. We're watching the triggered memory for reads.
4931                      In that case, trust the target, and always report
4932                      the watchpoint hit to the user.  Even though
4933                      reads don't cause value changes, the value may
4934                      have changed since the last time it was read, and
4935                      since we're not trapping writes, we will not see
4936                      those, and as such we should ignore our notion of
4937                      old value.
4938
4939                      2. We're watching the triggered memory for both
4940                      reads and writes.  There are two ways this may
4941                      happen:
4942
4943                      2.1. This is a target that can't break on data
4944                      reads only, but can break on accesses (reads or
4945                      writes), such as e.g., x86.  We detect this case
4946                      at the time we try to insert read watchpoints.
4947
4948                      2.2. Otherwise, the target supports read
4949                      watchpoints, but, the user set an access or write
4950                      watchpoint watching the same memory as this read
4951                      watchpoint.
4952
4953                      If we're watching memory writes as well as reads,
4954                      ignore watchpoint hits when we find that the
4955                      value hasn't changed, as reads don't cause
4956                      changes.  This still gives false positives when
4957                      the program writes the same value to memory as
4958                      what there was already in memory (we will confuse
4959                      it for a read), but it's much better than
4960                      nothing.  */
4961
4962                   int other_write_watchpoint = 0;
4963
4964                   if (bl->watchpoint_type == hw_read)
4965                     {
4966                       struct breakpoint *other_b;
4967
4968                       ALL_BREAKPOINTS (other_b)
4969                         if (other_b->type == bp_hardware_watchpoint
4970                             || other_b->type == bp_access_watchpoint)
4971                           {
4972                             struct watchpoint *other_w =
4973                               (struct watchpoint *) other_b;
4974
4975                             if (other_w->watchpoint_triggered
4976                                 == watch_triggered_yes)
4977                               {
4978                                 other_write_watchpoint = 1;
4979                                 break;
4980                               }
4981                           }
4982                     }
4983
4984                   if (other_write_watchpoint
4985                       || bl->watchpoint_type == hw_access)
4986                     {
4987                       /* We're watching the same memory for writes,
4988                          and the value changed since the last time we
4989                          updated it, so this trap must be for a write.
4990                          Ignore it.  */
4991                       bs->print_it = print_it_noop;
4992                       bs->stop = 0;
4993                     }
4994                 }
4995               break;
4996             case WP_VALUE_NOT_CHANGED:
4997               if (b->base.type == bp_hardware_watchpoint
4998                   || b->base.type == bp_watchpoint)
4999                 {
5000                   /* Don't stop: write watchpoints shouldn't fire if
5001                      the value hasn't changed.  */
5002                   bs->print_it = print_it_noop;
5003                   bs->stop = 0;
5004                 }
5005               /* Stop.  */
5006               break;
5007             default:
5008               /* Can't happen.  */
5009             case 0:
5010               /* Error from catch_errors.  */
5011               printf_filtered (_("Watchpoint %d deleted.\n"), b->base.number);
5012               watchpoint_del_at_next_stop (b);
5013               /* We've already printed what needs to be printed.  */
5014               bs->print_it = print_it_done;
5015               break;
5016             }
5017         }
5018       else      /* must_check_value == 0 */
5019         {
5020           /* This is a case where some watchpoint(s) triggered, but
5021              not at the address of this watchpoint, or else no
5022              watchpoint triggered after all.  So don't print
5023              anything for this watchpoint.  */
5024           bs->print_it = print_it_noop;
5025           bs->stop = 0;
5026         }
5027     }
5028 }
5029
5030
5031 /* Check conditions (condition proper, frame, thread and ignore count)
5032    of breakpoint referred to by BS.  If we should not stop for this
5033    breakpoint, set BS->stop to 0.  */
5034
5035 static void
5036 bpstat_check_breakpoint_conditions (bpstat bs, ptid_t ptid)
5037 {
5038   int thread_id = pid_to_thread_id (ptid);
5039   const struct bp_location *bl;
5040   struct breakpoint *b;
5041
5042   /* BS is built for existing struct breakpoint.  */
5043   bl = bs->bp_location_at;
5044   gdb_assert (bl != NULL);
5045   b = bs->breakpoint_at;
5046   gdb_assert (b != NULL);
5047
5048   /* Even if the target evaluated the condition on its end and notified GDB, we
5049      need to do so again since GDB does not know if we stopped due to a
5050      breakpoint or a single step breakpoint.  */
5051
5052   if (frame_id_p (b->frame_id)
5053       && !frame_id_eq (b->frame_id, get_stack_frame_id (get_current_frame ())))
5054     bs->stop = 0;
5055   else if (bs->stop)
5056     {
5057       int value_is_zero = 0;
5058       struct expression *cond;
5059
5060       /* Evaluate Python breakpoints that have a "stop"
5061          method implemented.  */
5062       if (b->py_bp_object)
5063         bs->stop = gdbpy_should_stop (b->py_bp_object);
5064
5065       if (is_watchpoint (b))
5066         {
5067           struct watchpoint *w = (struct watchpoint *) b;
5068
5069           cond = w->cond_exp;
5070         }
5071       else
5072         cond = bl->cond;
5073
5074       if (cond && b->disposition != disp_del_at_next_stop)
5075         {
5076           int within_current_scope = 1;
5077           struct watchpoint * w;
5078
5079           /* We use value_mark and value_free_to_mark because it could
5080              be a long time before we return to the command level and
5081              call free_all_values.  We can't call free_all_values
5082              because we might be in the middle of evaluating a
5083              function call.  */
5084           struct value *mark = value_mark ();
5085
5086           if (is_watchpoint (b))
5087             w = (struct watchpoint *) b;
5088           else
5089             w = NULL;
5090
5091           /* Need to select the frame, with all that implies so that
5092              the conditions will have the right context.  Because we
5093              use the frame, we will not see an inlined function's
5094              variables when we arrive at a breakpoint at the start
5095              of the inlined function; the current frame will be the
5096              call site.  */
5097           if (w == NULL || w->cond_exp_valid_block == NULL)
5098             select_frame (get_current_frame ());
5099           else
5100             {
5101               struct frame_info *frame;
5102
5103               /* For local watchpoint expressions, which particular
5104                  instance of a local is being watched matters, so we
5105                  keep track of the frame to evaluate the expression
5106                  in.  To evaluate the condition however, it doesn't
5107                  really matter which instantiation of the function
5108                  where the condition makes sense triggers the
5109                  watchpoint.  This allows an expression like "watch
5110                  global if q > 10" set in `func', catch writes to
5111                  global on all threads that call `func', or catch
5112                  writes on all recursive calls of `func' by a single
5113                  thread.  We simply always evaluate the condition in
5114                  the innermost frame that's executing where it makes
5115                  sense to evaluate the condition.  It seems
5116                  intuitive.  */
5117               frame = block_innermost_frame (w->cond_exp_valid_block);
5118               if (frame != NULL)
5119                 select_frame (frame);
5120               else
5121                 within_current_scope = 0;
5122             }
5123           if (within_current_scope)
5124             value_is_zero
5125               = catch_errors (breakpoint_cond_eval, cond,
5126                               "Error in testing breakpoint condition:\n",
5127                               RETURN_MASK_ALL);
5128           else
5129             {
5130               warning (_("Watchpoint condition cannot be tested "
5131                          "in the current scope"));
5132               /* If we failed to set the right context for this
5133                  watchpoint, unconditionally report it.  */
5134               value_is_zero = 0;
5135             }
5136           /* FIXME-someday, should give breakpoint #.  */
5137           value_free_to_mark (mark);
5138         }
5139
5140       if (cond && value_is_zero)
5141         {
5142           bs->stop = 0;
5143         }
5144       else if (b->thread != -1 && b->thread != thread_id)
5145         {
5146           bs->stop = 0;
5147         }
5148       else if (b->ignore_count > 0)
5149         {
5150           b->ignore_count--;
5151           bs->stop = 0;
5152           /* Increase the hit count even though we don't stop.  */
5153           ++(b->hit_count);
5154           observer_notify_breakpoint_modified (b);
5155         }       
5156     }
5157 }
5158
5159
5160 /* Get a bpstat associated with having just stopped at address
5161    BP_ADDR in thread PTID.
5162
5163    Determine whether we stopped at a breakpoint, etc, or whether we
5164    don't understand this stop.  Result is a chain of bpstat's such
5165    that:
5166
5167    if we don't understand the stop, the result is a null pointer.
5168
5169    if we understand why we stopped, the result is not null.
5170
5171    Each element of the chain refers to a particular breakpoint or
5172    watchpoint at which we have stopped.  (We may have stopped for
5173    several reasons concurrently.)
5174
5175    Each element of the chain has valid next, breakpoint_at,
5176    commands, FIXME??? fields.  */
5177
5178 bpstat
5179 bpstat_stop_status (struct address_space *aspace,
5180                     CORE_ADDR bp_addr, ptid_t ptid,
5181                     const struct target_waitstatus *ws)
5182 {
5183   struct breakpoint *b = NULL;
5184   struct bp_location *bl;
5185   struct bp_location *loc;
5186   /* First item of allocated bpstat's.  */
5187   bpstat bs_head = NULL, *bs_link = &bs_head;
5188   /* Pointer to the last thing in the chain currently.  */
5189   bpstat bs;
5190   int ix;
5191   int need_remove_insert;
5192   int removed_any;
5193
5194   /* First, build the bpstat chain with locations that explain a
5195      target stop, while being careful to not set the target running,
5196      as that may invalidate locations (in particular watchpoint
5197      locations are recreated).  Resuming will happen here with
5198      breakpoint conditions or watchpoint expressions that include
5199      inferior function calls.  */
5200
5201   ALL_BREAKPOINTS (b)
5202     {
5203       if (!breakpoint_enabled (b) && b->enable_state != bp_permanent)
5204         continue;
5205
5206       for (bl = b->loc; bl != NULL; bl = bl->next)
5207         {
5208           /* For hardware watchpoints, we look only at the first
5209              location.  The watchpoint_check function will work on the
5210              entire expression, not the individual locations.  For
5211              read watchpoints, the watchpoints_triggered function has
5212              checked all locations already.  */
5213           if (b->type == bp_hardware_watchpoint && bl != b->loc)
5214             break;
5215
5216           if (!bl->enabled || bl->shlib_disabled)
5217             continue;
5218
5219           if (!bpstat_check_location (bl, aspace, bp_addr, ws))
5220             continue;
5221
5222           /* Come here if it's a watchpoint, or if the break address
5223              matches.  */
5224
5225           bs = bpstat_alloc (bl, &bs_link);     /* Alloc a bpstat to
5226                                                    explain stop.  */
5227
5228           /* Assume we stop.  Should we find a watchpoint that is not
5229              actually triggered, or if the condition of the breakpoint
5230              evaluates as false, we'll reset 'stop' to 0.  */
5231           bs->stop = 1;
5232           bs->print = 1;
5233
5234           /* If this is a scope breakpoint, mark the associated
5235              watchpoint as triggered so that we will handle the
5236              out-of-scope event.  We'll get to the watchpoint next
5237              iteration.  */
5238           if (b->type == bp_watchpoint_scope && b->related_breakpoint != b)
5239             {
5240               struct watchpoint *w = (struct watchpoint *) b->related_breakpoint;
5241
5242               w->watchpoint_triggered = watch_triggered_yes;
5243             }
5244         }
5245     }
5246
5247   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
5248     {
5249       if (breakpoint_location_address_match (loc, aspace, bp_addr))
5250         {
5251           bs = bpstat_alloc (loc, &bs_link);
5252           /* For hits of moribund locations, we should just proceed.  */
5253           bs->stop = 0;
5254           bs->print = 0;
5255           bs->print_it = print_it_noop;
5256         }
5257     }
5258
5259   /* A bit of special processing for shlib breakpoints.  We need to
5260      process solib loading here, so that the lists of loaded and
5261      unloaded libraries are correct before we handle "catch load" and
5262      "catch unload".  */
5263   for (bs = bs_head; bs != NULL; bs = bs->next)
5264     {
5265       if (bs->breakpoint_at && bs->breakpoint_at->type == bp_shlib_event)
5266         {
5267           handle_solib_event ();
5268           break;
5269         }
5270     }
5271
5272   /* Now go through the locations that caused the target to stop, and
5273      check whether we're interested in reporting this stop to higher
5274      layers, or whether we should resume the target transparently.  */
5275
5276   removed_any = 0;
5277
5278   for (bs = bs_head; bs != NULL; bs = bs->next)
5279     {
5280       if (!bs->stop)
5281         continue;
5282
5283       b = bs->breakpoint_at;
5284       b->ops->check_status (bs);
5285       if (bs->stop)
5286         {
5287           bpstat_check_breakpoint_conditions (bs, ptid);
5288
5289           if (bs->stop)
5290             {
5291               ++(b->hit_count);
5292               observer_notify_breakpoint_modified (b);
5293
5294               /* We will stop here.  */
5295               if (b->disposition == disp_disable)
5296                 {
5297                   --(b->enable_count);
5298                   if (b->enable_count <= 0
5299                       && b->enable_state != bp_permanent)
5300                     b->enable_state = bp_disabled;
5301                   removed_any = 1;
5302                 }
5303               if (b->silent)
5304                 bs->print = 0;
5305               bs->commands = b->commands;
5306               incref_counted_command_line (bs->commands);
5307               if (command_line_is_silent (bs->commands
5308                                           ? bs->commands->commands : NULL))
5309                 bs->print = 0;
5310             }
5311
5312         }
5313
5314       /* Print nothing for this entry if we don't stop or don't
5315          print.  */
5316       if (!bs->stop || !bs->print)
5317         bs->print_it = print_it_noop;
5318     }
5319
5320   /* If we aren't stopping, the value of some hardware watchpoint may
5321      not have changed, but the intermediate memory locations we are
5322      watching may have.  Don't bother if we're stopping; this will get
5323      done later.  */
5324   need_remove_insert = 0;
5325   if (! bpstat_causes_stop (bs_head))
5326     for (bs = bs_head; bs != NULL; bs = bs->next)
5327       if (!bs->stop
5328           && bs->breakpoint_at
5329           && is_hardware_watchpoint (bs->breakpoint_at))
5330         {
5331           struct watchpoint *w = (struct watchpoint *) bs->breakpoint_at;
5332
5333           update_watchpoint (w, 0 /* don't reparse.  */);
5334           need_remove_insert = 1;
5335         }
5336
5337   if (need_remove_insert)
5338     update_global_location_list (1);
5339   else if (removed_any)
5340     update_global_location_list (0);
5341
5342   return bs_head;
5343 }
5344
5345 static void
5346 handle_jit_event (void)
5347 {
5348   struct frame_info *frame;
5349   struct gdbarch *gdbarch;
5350
5351   /* Switch terminal for any messages produced by
5352      breakpoint_re_set.  */
5353   target_terminal_ours_for_output ();
5354
5355   frame = get_current_frame ();
5356   gdbarch = get_frame_arch (frame);
5357
5358   jit_event_handler (gdbarch);
5359
5360   target_terminal_inferior ();
5361 }
5362
5363 /* Handle an solib event by calling solib_add.  */
5364
5365 void
5366 handle_solib_event (void)
5367 {
5368   clear_program_space_solib_cache (current_inferior ()->pspace);
5369
5370   /* Check for any newly added shared libraries if we're supposed to
5371      be adding them automatically.  Switch terminal for any messages
5372      produced by breakpoint_re_set.  */
5373   target_terminal_ours_for_output ();
5374 #ifdef SOLIB_ADD
5375   SOLIB_ADD (NULL, 0, &current_target, auto_solib_add);
5376 #else
5377   solib_add (NULL, 0, &current_target, auto_solib_add);
5378 #endif
5379   target_terminal_inferior ();
5380 }
5381
5382 /* Prepare WHAT final decision for infrun.  */
5383
5384 /* Decide what infrun needs to do with this bpstat.  */
5385
5386 struct bpstat_what
5387 bpstat_what (bpstat bs_head)
5388 {
5389   struct bpstat_what retval;
5390   int jit_event = 0;
5391   bpstat bs;
5392
5393   retval.main_action = BPSTAT_WHAT_KEEP_CHECKING;
5394   retval.call_dummy = STOP_NONE;
5395   retval.is_longjmp = 0;
5396
5397   for (bs = bs_head; bs != NULL; bs = bs->next)
5398     {
5399       /* Extract this BS's action.  After processing each BS, we check
5400          if its action overrides all we've seem so far.  */
5401       enum bpstat_what_main_action this_action = BPSTAT_WHAT_KEEP_CHECKING;
5402       enum bptype bptype;
5403
5404       if (bs->breakpoint_at == NULL)
5405         {
5406           /* I suspect this can happen if it was a momentary
5407              breakpoint which has since been deleted.  */
5408           bptype = bp_none;
5409         }
5410       else
5411         bptype = bs->breakpoint_at->type;
5412
5413       switch (bptype)
5414         {
5415         case bp_none:
5416           break;
5417         case bp_breakpoint:
5418         case bp_hardware_breakpoint:
5419         case bp_until:
5420         case bp_finish:
5421         case bp_shlib_event:
5422           if (bs->stop)
5423             {
5424               if (bs->print)
5425                 this_action = BPSTAT_WHAT_STOP_NOISY;
5426               else
5427                 this_action = BPSTAT_WHAT_STOP_SILENT;
5428             }
5429           else
5430             this_action = BPSTAT_WHAT_SINGLE;
5431           break;
5432         case bp_watchpoint:
5433         case bp_hardware_watchpoint:
5434         case bp_read_watchpoint:
5435         case bp_access_watchpoint:
5436           if (bs->stop)
5437             {
5438               if (bs->print)
5439                 this_action = BPSTAT_WHAT_STOP_NOISY;
5440               else
5441                 this_action = BPSTAT_WHAT_STOP_SILENT;
5442             }
5443           else
5444             {
5445               /* There was a watchpoint, but we're not stopping.
5446                  This requires no further action.  */
5447             }
5448           break;
5449         case bp_longjmp:
5450         case bp_longjmp_call_dummy:
5451         case bp_exception:
5452           this_action = BPSTAT_WHAT_SET_LONGJMP_RESUME;
5453           retval.is_longjmp = bptype != bp_exception;
5454           break;
5455         case bp_longjmp_resume:
5456         case bp_exception_resume:
5457           this_action = BPSTAT_WHAT_CLEAR_LONGJMP_RESUME;
5458           retval.is_longjmp = bptype == bp_longjmp_resume;
5459           break;
5460         case bp_step_resume:
5461           if (bs->stop)
5462             this_action = BPSTAT_WHAT_STEP_RESUME;
5463           else
5464             {
5465               /* It is for the wrong frame.  */
5466               this_action = BPSTAT_WHAT_SINGLE;
5467             }
5468           break;
5469         case bp_hp_step_resume:
5470           if (bs->stop)
5471             this_action = BPSTAT_WHAT_HP_STEP_RESUME;
5472           else
5473             {
5474               /* It is for the wrong frame.  */
5475               this_action = BPSTAT_WHAT_SINGLE;
5476             }
5477           break;
5478         case bp_watchpoint_scope:
5479         case bp_thread_event:
5480         case bp_overlay_event:
5481         case bp_longjmp_master:
5482         case bp_std_terminate_master:
5483         case bp_exception_master:
5484           this_action = BPSTAT_WHAT_SINGLE;
5485           break;
5486         case bp_catchpoint:
5487           if (bs->stop)
5488             {
5489               if (bs->print)
5490                 this_action = BPSTAT_WHAT_STOP_NOISY;
5491               else
5492                 this_action = BPSTAT_WHAT_STOP_SILENT;
5493             }
5494           else
5495             {
5496               /* There was a catchpoint, but we're not stopping.
5497                  This requires no further action.  */
5498             }
5499           break;
5500         case bp_jit_event:
5501           jit_event = 1;
5502           this_action = BPSTAT_WHAT_SINGLE;
5503           break;
5504         case bp_call_dummy:
5505           /* Make sure the action is stop (silent or noisy),
5506              so infrun.c pops the dummy frame.  */
5507           retval.call_dummy = STOP_STACK_DUMMY;
5508           this_action = BPSTAT_WHAT_STOP_SILENT;
5509           break;
5510         case bp_std_terminate:
5511           /* Make sure the action is stop (silent or noisy),
5512              so infrun.c pops the dummy frame.  */
5513           retval.call_dummy = STOP_STD_TERMINATE;
5514           this_action = BPSTAT_WHAT_STOP_SILENT;
5515           break;
5516         case bp_tracepoint:
5517         case bp_fast_tracepoint:
5518         case bp_static_tracepoint:
5519           /* Tracepoint hits should not be reported back to GDB, and
5520              if one got through somehow, it should have been filtered
5521              out already.  */
5522           internal_error (__FILE__, __LINE__,
5523                           _("bpstat_what: tracepoint encountered"));
5524           break;
5525         case bp_gnu_ifunc_resolver:
5526           /* Step over it (and insert bp_gnu_ifunc_resolver_return).  */
5527           this_action = BPSTAT_WHAT_SINGLE;
5528           break;
5529         case bp_gnu_ifunc_resolver_return:
5530           /* The breakpoint will be removed, execution will restart from the
5531              PC of the former breakpoint.  */
5532           this_action = BPSTAT_WHAT_KEEP_CHECKING;
5533           break;
5534
5535         case bp_dprintf:
5536           this_action = BPSTAT_WHAT_STOP_SILENT;
5537           break;
5538
5539         default:
5540           internal_error (__FILE__, __LINE__,
5541                           _("bpstat_what: unhandled bptype %d"), (int) bptype);
5542         }
5543
5544       retval.main_action = max (retval.main_action, this_action);
5545     }
5546
5547   /* These operations may affect the bs->breakpoint_at state so they are
5548      delayed after MAIN_ACTION is decided above.  */
5549
5550   if (jit_event)
5551     {
5552       if (debug_infrun)
5553         fprintf_unfiltered (gdb_stdlog, "bpstat_what: bp_jit_event\n");
5554
5555       handle_jit_event ();
5556     }
5557
5558   for (bs = bs_head; bs != NULL; bs = bs->next)
5559     {
5560       struct breakpoint *b = bs->breakpoint_at;
5561
5562       if (b == NULL)
5563         continue;
5564       switch (b->type)
5565         {
5566         case bp_gnu_ifunc_resolver:
5567           gnu_ifunc_resolver_stop (b);
5568           break;
5569         case bp_gnu_ifunc_resolver_return:
5570           gnu_ifunc_resolver_return_stop (b);
5571           break;
5572         }
5573     }
5574
5575   return retval;
5576 }
5577
5578 /* Nonzero if we should step constantly (e.g. watchpoints on machines
5579    without hardware support).  This isn't related to a specific bpstat,
5580    just to things like whether watchpoints are set.  */
5581
5582 int
5583 bpstat_should_step (void)
5584 {
5585   struct breakpoint *b;
5586
5587   ALL_BREAKPOINTS (b)
5588     if (breakpoint_enabled (b) && b->type == bp_watchpoint && b->loc != NULL)
5589       return 1;
5590   return 0;
5591 }
5592
5593 int
5594 bpstat_causes_stop (bpstat bs)
5595 {
5596   for (; bs != NULL; bs = bs->next)
5597     if (bs->stop)
5598       return 1;
5599
5600   return 0;
5601 }
5602
5603 \f
5604
5605 /* Compute a string of spaces suitable to indent the next line
5606    so it starts at the position corresponding to the table column
5607    named COL_NAME in the currently active table of UIOUT.  */
5608
5609 static char *
5610 wrap_indent_at_field (struct ui_out *uiout, const char *col_name)
5611 {
5612   static char wrap_indent[80];
5613   int i, total_width, width, align;
5614   char *text;
5615
5616   total_width = 0;
5617   for (i = 1; ui_out_query_field (uiout, i, &width, &align, &text); i++)
5618     {
5619       if (strcmp (text, col_name) == 0)
5620         {
5621           gdb_assert (total_width < sizeof wrap_indent);
5622           memset (wrap_indent, ' ', total_width);
5623           wrap_indent[total_width] = 0;
5624
5625           return wrap_indent;
5626         }
5627
5628       total_width += width + 1;
5629     }
5630
5631   return NULL;
5632 }
5633
5634 /* Determine if the locations of this breakpoint will have their conditions
5635    evaluated by the target, host or a mix of both.  Returns the following:
5636
5637     "host": Host evals condition.
5638     "host or target": Host or Target evals condition.
5639     "target": Target evals condition.
5640 */
5641
5642 static const char *
5643 bp_condition_evaluator (struct breakpoint *b)
5644 {
5645   struct bp_location *bl;
5646   char host_evals = 0;
5647   char target_evals = 0;
5648
5649   if (!b)
5650     return NULL;
5651
5652   if (!is_breakpoint (b))
5653     return NULL;
5654
5655   if (gdb_evaluates_breakpoint_condition_p ()
5656       || !target_supports_evaluation_of_breakpoint_conditions ())
5657     return condition_evaluation_host;
5658
5659   for (bl = b->loc; bl; bl = bl->next)
5660     {
5661       if (bl->cond_bytecode)
5662         target_evals++;
5663       else
5664         host_evals++;
5665     }
5666
5667   if (host_evals && target_evals)
5668     return condition_evaluation_both;
5669   else if (target_evals)
5670     return condition_evaluation_target;
5671   else
5672     return condition_evaluation_host;
5673 }
5674
5675 /* Determine the breakpoint location's condition evaluator.  This is
5676    similar to bp_condition_evaluator, but for locations.  */
5677
5678 static const char *
5679 bp_location_condition_evaluator (struct bp_location *bl)
5680 {
5681   if (bl && !is_breakpoint (bl->owner))
5682     return NULL;
5683
5684   if (gdb_evaluates_breakpoint_condition_p ()
5685       || !target_supports_evaluation_of_breakpoint_conditions ())
5686     return condition_evaluation_host;
5687
5688   if (bl && bl->cond_bytecode)
5689     return condition_evaluation_target;
5690   else
5691     return condition_evaluation_host;
5692 }
5693
5694 /* Print the LOC location out of the list of B->LOC locations.  */
5695
5696 static void
5697 print_breakpoint_location (struct breakpoint *b,
5698                            struct bp_location *loc)
5699 {
5700   struct ui_out *uiout = current_uiout;
5701   struct cleanup *old_chain = save_current_program_space ();
5702
5703   if (loc != NULL && loc->shlib_disabled)
5704     loc = NULL;
5705
5706   if (loc != NULL)
5707     set_current_program_space (loc->pspace);
5708
5709   if (b->display_canonical)
5710     ui_out_field_string (uiout, "what", b->addr_string);
5711   else if (loc && loc->symtab)
5712     {
5713       struct symbol *sym 
5714         = find_pc_sect_function (loc->address, loc->section);
5715       if (sym)
5716         {
5717           ui_out_text (uiout, "in ");
5718           ui_out_field_string (uiout, "func",
5719                                SYMBOL_PRINT_NAME (sym));
5720           ui_out_text (uiout, " ");
5721           ui_out_wrap_hint (uiout, wrap_indent_at_field (uiout, "what"));
5722           ui_out_text (uiout, "at ");
5723         }
5724       ui_out_field_string (uiout, "file",
5725                            symtab_to_filename_for_display (loc->symtab));
5726       ui_out_text (uiout, ":");
5727
5728       if (ui_out_is_mi_like_p (uiout))
5729         ui_out_field_string (uiout, "fullname",
5730                              symtab_to_fullname (loc->symtab));
5731       
5732       ui_out_field_int (uiout, "line", loc->line_number);
5733     }
5734   else if (loc)
5735     {
5736       struct ui_file *stb = mem_fileopen ();
5737       struct cleanup *stb_chain = make_cleanup_ui_file_delete (stb);
5738
5739       print_address_symbolic (loc->gdbarch, loc->address, stb,
5740                               demangle, "");
5741       ui_out_field_stream (uiout, "at", stb);
5742
5743       do_cleanups (stb_chain);
5744     }
5745   else
5746     ui_out_field_string (uiout, "pending", b->addr_string);
5747
5748   if (loc && is_breakpoint (b)
5749       && breakpoint_condition_evaluation_mode () == condition_evaluation_target
5750       && bp_condition_evaluator (b) == condition_evaluation_both)
5751     {
5752       ui_out_text (uiout, " (");
5753       ui_out_field_string (uiout, "evaluated-by",
5754                            bp_location_condition_evaluator (loc));
5755       ui_out_text (uiout, ")");
5756     }
5757
5758   do_cleanups (old_chain);
5759 }
5760
5761 static const char *
5762 bptype_string (enum bptype type)
5763 {
5764   struct ep_type_description
5765     {
5766       enum bptype type;
5767       char *description;
5768     };
5769   static struct ep_type_description bptypes[] =
5770   {
5771     {bp_none, "?deleted?"},
5772     {bp_breakpoint, "breakpoint"},
5773     {bp_hardware_breakpoint, "hw breakpoint"},
5774     {bp_until, "until"},
5775     {bp_finish, "finish"},
5776     {bp_watchpoint, "watchpoint"},
5777     {bp_hardware_watchpoint, "hw watchpoint"},
5778     {bp_read_watchpoint, "read watchpoint"},
5779     {bp_access_watchpoint, "acc watchpoint"},
5780     {bp_longjmp, "longjmp"},
5781     {bp_longjmp_resume, "longjmp resume"},
5782     {bp_longjmp_call_dummy, "longjmp for call dummy"},
5783     {bp_exception, "exception"},
5784     {bp_exception_resume, "exception resume"},
5785     {bp_step_resume, "step resume"},
5786     {bp_hp_step_resume, "high-priority step resume"},
5787     {bp_watchpoint_scope, "watchpoint scope"},
5788     {bp_call_dummy, "call dummy"},
5789     {bp_std_terminate, "std::terminate"},
5790     {bp_shlib_event, "shlib events"},
5791     {bp_thread_event, "thread events"},
5792     {bp_overlay_event, "overlay events"},
5793     {bp_longjmp_master, "longjmp master"},
5794     {bp_std_terminate_master, "std::terminate master"},
5795     {bp_exception_master, "exception master"},
5796     {bp_catchpoint, "catchpoint"},
5797     {bp_tracepoint, "tracepoint"},
5798     {bp_fast_tracepoint, "fast tracepoint"},
5799     {bp_static_tracepoint, "static tracepoint"},
5800     {bp_dprintf, "dprintf"},
5801     {bp_jit_event, "jit events"},
5802     {bp_gnu_ifunc_resolver, "STT_GNU_IFUNC resolver"},
5803     {bp_gnu_ifunc_resolver_return, "STT_GNU_IFUNC resolver return"},
5804   };
5805
5806   if (((int) type >= (sizeof (bptypes) / sizeof (bptypes[0])))
5807       || ((int) type != bptypes[(int) type].type))
5808     internal_error (__FILE__, __LINE__,
5809                     _("bptypes table does not describe type #%d."),
5810                     (int) type);
5811
5812   return bptypes[(int) type].description;
5813 }
5814
5815 DEF_VEC_I(int);
5816
5817 /* For MI, output a field named 'thread-groups' with a list as the value.
5818    For CLI, prefix the list with the string 'inf'. */
5819
5820 static void
5821 output_thread_groups (struct ui_out *uiout,
5822                       const char *field_name,
5823                       VEC(int) *inf_num,
5824                       int mi_only)
5825 {
5826   struct cleanup *back_to = make_cleanup_ui_out_list_begin_end (uiout,
5827                                                                 field_name);
5828   int is_mi = ui_out_is_mi_like_p (uiout);
5829   int inf;
5830   int i;
5831
5832   /* For backward compatibility, don't display inferiors in CLI unless
5833      there are several.  Always display them for MI. */
5834   if (!is_mi && mi_only)
5835     return;
5836
5837   for (i = 0; VEC_iterate (int, inf_num, i, inf); ++i)
5838     {
5839       if (is_mi)
5840         {
5841           char mi_group[10];
5842
5843           xsnprintf (mi_group, sizeof (mi_group), "i%d", inf);
5844           ui_out_field_string (uiout, NULL, mi_group);
5845         }
5846       else
5847         {
5848           if (i == 0)
5849             ui_out_text (uiout, " inf ");
5850           else
5851             ui_out_text (uiout, ", ");
5852         
5853           ui_out_text (uiout, plongest (inf));
5854         }
5855     }
5856
5857   do_cleanups (back_to);
5858 }
5859
5860 /* Print B to gdb_stdout.  */
5861
5862 static void
5863 print_one_breakpoint_location (struct breakpoint *b,
5864                                struct bp_location *loc,
5865                                int loc_number,
5866                                struct bp_location **last_loc,
5867                                int allflag)
5868 {
5869   struct command_line *l;
5870   static char bpenables[] = "nynny";
5871
5872   struct ui_out *uiout = current_uiout;
5873   int header_of_multiple = 0;
5874   int part_of_multiple = (loc != NULL);
5875   struct value_print_options opts;
5876
5877   get_user_print_options (&opts);
5878
5879   gdb_assert (!loc || loc_number != 0);
5880   /* See comment in print_one_breakpoint concerning treatment of
5881      breakpoints with single disabled location.  */
5882   if (loc == NULL 
5883       && (b->loc != NULL 
5884           && (b->loc->next != NULL || !b->loc->enabled)))
5885     header_of_multiple = 1;
5886   if (loc == NULL)
5887     loc = b->loc;
5888
5889   annotate_record ();
5890
5891   /* 1 */
5892   annotate_field (0);
5893   if (part_of_multiple)
5894     {
5895       char *formatted;
5896       formatted = xstrprintf ("%d.%d", b->number, loc_number);
5897       ui_out_field_string (uiout, "number", formatted);
5898       xfree (formatted);
5899     }
5900   else
5901     {
5902       ui_out_field_int (uiout, "number", b->number);
5903     }
5904
5905   /* 2 */
5906   annotate_field (1);
5907   if (part_of_multiple)
5908     ui_out_field_skip (uiout, "type");
5909   else
5910     ui_out_field_string (uiout, "type", bptype_string (b->type));
5911
5912   /* 3 */
5913   annotate_field (2);
5914   if (part_of_multiple)
5915     ui_out_field_skip (uiout, "disp");
5916   else
5917     ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
5918
5919
5920   /* 4 */
5921   annotate_field (3);
5922   if (part_of_multiple)
5923     ui_out_field_string (uiout, "enabled", loc->enabled ? "y" : "n");
5924   else
5925     ui_out_field_fmt (uiout, "enabled", "%c", 
5926                       bpenables[(int) b->enable_state]);
5927   ui_out_spaces (uiout, 2);
5928
5929   
5930   /* 5 and 6 */
5931   if (b->ops != NULL && b->ops->print_one != NULL)
5932     {
5933       /* Although the print_one can possibly print all locations,
5934          calling it here is not likely to get any nice result.  So,
5935          make sure there's just one location.  */
5936       gdb_assert (b->loc == NULL || b->loc->next == NULL);
5937       b->ops->print_one (b, last_loc);
5938     }
5939   else
5940     switch (b->type)
5941       {
5942       case bp_none:
5943         internal_error (__FILE__, __LINE__,
5944                         _("print_one_breakpoint: bp_none encountered\n"));
5945         break;
5946
5947       case bp_watchpoint:
5948       case bp_hardware_watchpoint:
5949       case bp_read_watchpoint:
5950       case bp_access_watchpoint:
5951         {
5952           struct watchpoint *w = (struct watchpoint *) b;
5953
5954           /* Field 4, the address, is omitted (which makes the columns
5955              not line up too nicely with the headers, but the effect
5956              is relatively readable).  */
5957           if (opts.addressprint)
5958             ui_out_field_skip (uiout, "addr");
5959           annotate_field (5);
5960           ui_out_field_string (uiout, "what", w->exp_string);
5961         }
5962         break;
5963
5964       case bp_breakpoint:
5965       case bp_hardware_breakpoint:
5966       case bp_until:
5967       case bp_finish:
5968       case bp_longjmp:
5969       case bp_longjmp_resume:
5970       case bp_longjmp_call_dummy:
5971       case bp_exception:
5972       case bp_exception_resume:
5973       case bp_step_resume:
5974       case bp_hp_step_resume:
5975       case bp_watchpoint_scope:
5976       case bp_call_dummy:
5977       case bp_std_terminate:
5978       case bp_shlib_event:
5979       case bp_thread_event:
5980       case bp_overlay_event:
5981       case bp_longjmp_master:
5982       case bp_std_terminate_master:
5983       case bp_exception_master:
5984       case bp_tracepoint:
5985       case bp_fast_tracepoint:
5986       case bp_static_tracepoint:
5987       case bp_dprintf:
5988       case bp_jit_event:
5989       case bp_gnu_ifunc_resolver:
5990       case bp_gnu_ifunc_resolver_return:
5991         if (opts.addressprint)
5992           {
5993             annotate_field (4);
5994             if (header_of_multiple)
5995               ui_out_field_string (uiout, "addr", "<MULTIPLE>");
5996             else if (b->loc == NULL || loc->shlib_disabled)
5997               ui_out_field_string (uiout, "addr", "<PENDING>");
5998             else
5999               ui_out_field_core_addr (uiout, "addr",
6000                                       loc->gdbarch, loc->address);
6001           }
6002         annotate_field (5);
6003         if (!header_of_multiple)
6004           print_breakpoint_location (b, loc);
6005         if (b->loc)
6006           *last_loc = b->loc;
6007         break;
6008       }
6009
6010
6011   if (loc != NULL && !header_of_multiple)
6012     {
6013       struct inferior *inf;
6014       VEC(int) *inf_num = NULL;
6015       int mi_only = 1;
6016
6017       ALL_INFERIORS (inf)
6018         {
6019           if (inf->pspace == loc->pspace)
6020             VEC_safe_push (int, inf_num, inf->num);
6021         }
6022
6023         /* For backward compatibility, don't display inferiors in CLI unless
6024            there are several.  Always display for MI. */
6025         if (allflag
6026             || (!gdbarch_has_global_breakpoints (target_gdbarch ())
6027                 && (number_of_program_spaces () > 1
6028                     || number_of_inferiors () > 1)
6029                 /* LOC is for existing B, it cannot be in
6030                    moribund_locations and thus having NULL OWNER.  */
6031                 && loc->owner->type != bp_catchpoint))
6032         mi_only = 0;
6033       output_thread_groups (uiout, "thread-groups", inf_num, mi_only);
6034       VEC_free (int, inf_num);
6035     }
6036
6037   if (!part_of_multiple)
6038     {
6039       if (b->thread != -1)
6040         {
6041           /* FIXME: This seems to be redundant and lost here; see the
6042              "stop only in" line a little further down.  */
6043           ui_out_text (uiout, " thread ");
6044           ui_out_field_int (uiout, "thread", b->thread);
6045         }
6046       else if (b->task != 0)
6047         {
6048           ui_out_text (uiout, " task ");
6049           ui_out_field_int (uiout, "task", b->task);
6050         }
6051     }
6052
6053   ui_out_text (uiout, "\n");
6054
6055   if (!part_of_multiple)
6056     b->ops->print_one_detail (b, uiout);
6057
6058   if (part_of_multiple && frame_id_p (b->frame_id))
6059     {
6060       annotate_field (6);
6061       ui_out_text (uiout, "\tstop only in stack frame at ");
6062       /* FIXME: cagney/2002-12-01: Shouldn't be poking around inside
6063          the frame ID.  */
6064       ui_out_field_core_addr (uiout, "frame",
6065                               b->gdbarch, b->frame_id.stack_addr);
6066       ui_out_text (uiout, "\n");
6067     }
6068   
6069   if (!part_of_multiple && b->cond_string)
6070     {
6071       annotate_field (7);
6072       if (is_tracepoint (b))
6073         ui_out_text (uiout, "\ttrace only if ");
6074       else
6075         ui_out_text (uiout, "\tstop only if ");
6076       ui_out_field_string (uiout, "cond", b->cond_string);
6077
6078       /* Print whether the target is doing the breakpoint's condition
6079          evaluation.  If GDB is doing the evaluation, don't print anything.  */
6080       if (is_breakpoint (b)
6081           && breakpoint_condition_evaluation_mode ()
6082           == condition_evaluation_target)
6083         {
6084           ui_out_text (uiout, " (");
6085           ui_out_field_string (uiout, "evaluated-by",
6086                                bp_condition_evaluator (b));
6087           ui_out_text (uiout, " evals)");
6088         }
6089       ui_out_text (uiout, "\n");
6090     }
6091
6092   if (!part_of_multiple && b->thread != -1)
6093     {
6094       /* FIXME should make an annotation for this.  */
6095       ui_out_text (uiout, "\tstop only in thread ");
6096       ui_out_field_int (uiout, "thread", b->thread);
6097       ui_out_text (uiout, "\n");
6098     }
6099   
6100   if (!part_of_multiple)
6101     {
6102       if (b->hit_count)
6103         {
6104           /* FIXME should make an annotation for this.  */
6105           if (is_catchpoint (b))
6106             ui_out_text (uiout, "\tcatchpoint");
6107           else if (is_tracepoint (b))
6108             ui_out_text (uiout, "\ttracepoint");
6109           else
6110             ui_out_text (uiout, "\tbreakpoint");
6111           ui_out_text (uiout, " already hit ");
6112           ui_out_field_int (uiout, "times", b->hit_count);
6113           if (b->hit_count == 1)
6114             ui_out_text (uiout, " time\n");
6115           else
6116             ui_out_text (uiout, " times\n");
6117         }
6118       else
6119         {
6120           /* Output the count also if it is zero, but only if this is mi.  */
6121           if (ui_out_is_mi_like_p (uiout))
6122             ui_out_field_int (uiout, "times", b->hit_count);
6123         }
6124     }
6125
6126   if (!part_of_multiple && b->ignore_count)
6127     {
6128       annotate_field (8);
6129       ui_out_text (uiout, "\tignore next ");
6130       ui_out_field_int (uiout, "ignore", b->ignore_count);
6131       ui_out_text (uiout, " hits\n");
6132     }
6133
6134   /* Note that an enable count of 1 corresponds to "enable once"
6135      behavior, which is reported by the combination of enablement and
6136      disposition, so we don't need to mention it here.  */
6137   if (!part_of_multiple && b->enable_count > 1)
6138     {
6139       annotate_field (8);
6140       ui_out_text (uiout, "\tdisable after ");
6141       /* Tweak the wording to clarify that ignore and enable counts
6142          are distinct, and have additive effect.  */
6143       if (b->ignore_count)
6144         ui_out_text (uiout, "additional ");
6145       else
6146         ui_out_text (uiout, "next ");
6147       ui_out_field_int (uiout, "enable", b->enable_count);
6148       ui_out_text (uiout, " hits\n");
6149     }
6150
6151   if (!part_of_multiple && is_tracepoint (b))
6152     {
6153       struct tracepoint *tp = (struct tracepoint *) b;
6154
6155       if (tp->traceframe_usage)
6156         {
6157           ui_out_text (uiout, "\ttrace buffer usage ");
6158           ui_out_field_int (uiout, "traceframe-usage", tp->traceframe_usage);
6159           ui_out_text (uiout, " bytes\n");
6160         }
6161     }
6162
6163   l = b->commands ? b->commands->commands : NULL;
6164   if (!part_of_multiple && l)
6165     {
6166       struct cleanup *script_chain;
6167
6168       annotate_field (9);
6169       script_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "script");
6170       print_command_lines (uiout, l, 4);
6171       do_cleanups (script_chain);
6172     }
6173
6174   if (is_tracepoint (b))
6175     {
6176       struct tracepoint *t = (struct tracepoint *) b;
6177
6178       if (!part_of_multiple && t->pass_count)
6179         {
6180           annotate_field (10);
6181           ui_out_text (uiout, "\tpass count ");
6182           ui_out_field_int (uiout, "pass", t->pass_count);
6183           ui_out_text (uiout, " \n");
6184         }
6185
6186       /* Don't display it when tracepoint or tracepoint location is
6187          pending.   */
6188       if (!header_of_multiple && loc != NULL && !loc->shlib_disabled)
6189         {
6190           annotate_field (11);
6191
6192           if (ui_out_is_mi_like_p (uiout))
6193             ui_out_field_string (uiout, "installed",
6194                                  loc->inserted ? "y" : "n");
6195           else
6196             {
6197               if (loc->inserted)
6198                 ui_out_text (uiout, "\t");
6199               else
6200                 ui_out_text (uiout, "\tnot ");
6201               ui_out_text (uiout, "installed on target\n");
6202             }
6203         }
6204     }
6205
6206   if (ui_out_is_mi_like_p (uiout) && !part_of_multiple)
6207     {
6208       if (is_watchpoint (b))
6209         {
6210           struct watchpoint *w = (struct watchpoint *) b;
6211
6212           ui_out_field_string (uiout, "original-location", w->exp_string);
6213         }
6214       else if (b->addr_string)
6215         ui_out_field_string (uiout, "original-location", b->addr_string);
6216     }
6217 }
6218
6219 static void
6220 print_one_breakpoint (struct breakpoint *b,
6221                       struct bp_location **last_loc, 
6222                       int allflag)
6223 {
6224   struct cleanup *bkpt_chain;
6225   struct ui_out *uiout = current_uiout;
6226
6227   bkpt_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "bkpt");
6228
6229   print_one_breakpoint_location (b, NULL, 0, last_loc, allflag);
6230   do_cleanups (bkpt_chain);
6231
6232   /* If this breakpoint has custom print function,
6233      it's already printed.  Otherwise, print individual
6234      locations, if any.  */
6235   if (b->ops == NULL || b->ops->print_one == NULL)
6236     {
6237       /* If breakpoint has a single location that is disabled, we
6238          print it as if it had several locations, since otherwise it's
6239          hard to represent "breakpoint enabled, location disabled"
6240          situation.
6241
6242          Note that while hardware watchpoints have several locations
6243          internally, that's not a property exposed to user.  */
6244       if (b->loc 
6245           && !is_hardware_watchpoint (b)
6246           && (b->loc->next || !b->loc->enabled))
6247         {
6248           struct bp_location *loc;
6249           int n = 1;
6250
6251           for (loc = b->loc; loc; loc = loc->next, ++n)
6252             {
6253               struct cleanup *inner2 =
6254                 make_cleanup_ui_out_tuple_begin_end (uiout, NULL);
6255               print_one_breakpoint_location (b, loc, n, last_loc, allflag);
6256               do_cleanups (inner2);
6257             }
6258         }
6259     }
6260 }
6261
6262 static int
6263 breakpoint_address_bits (struct breakpoint *b)
6264 {
6265   int print_address_bits = 0;
6266   struct bp_location *loc;
6267
6268   for (loc = b->loc; loc; loc = loc->next)
6269     {
6270       int addr_bit;
6271
6272       /* Software watchpoints that aren't watching memory don't have
6273          an address to print.  */
6274       if (b->type == bp_watchpoint && loc->watchpoint_type == -1)
6275         continue;
6276
6277       addr_bit = gdbarch_addr_bit (loc->gdbarch);
6278       if (addr_bit > print_address_bits)
6279         print_address_bits = addr_bit;
6280     }
6281
6282   return print_address_bits;
6283 }
6284
6285 struct captured_breakpoint_query_args
6286   {
6287     int bnum;
6288   };
6289
6290 static int
6291 do_captured_breakpoint_query (struct ui_out *uiout, void *data)
6292 {
6293   struct captured_breakpoint_query_args *args = data;
6294   struct breakpoint *b;
6295   struct bp_location *dummy_loc = NULL;
6296
6297   ALL_BREAKPOINTS (b)
6298     {
6299       if (args->bnum == b->number)
6300         {
6301           print_one_breakpoint (b, &dummy_loc, 0);
6302           return GDB_RC_OK;
6303         }
6304     }
6305   return GDB_RC_NONE;
6306 }
6307
6308 enum gdb_rc
6309 gdb_breakpoint_query (struct ui_out *uiout, int bnum, 
6310                       char **error_message)
6311 {
6312   struct captured_breakpoint_query_args args;
6313
6314   args.bnum = bnum;
6315   /* For the moment we don't trust print_one_breakpoint() to not throw
6316      an error.  */
6317   if (catch_exceptions_with_msg (uiout, do_captured_breakpoint_query, &args,
6318                                  error_message, RETURN_MASK_ALL) < 0)
6319     return GDB_RC_FAIL;
6320   else
6321     return GDB_RC_OK;
6322 }
6323
6324 /* Return true if this breakpoint was set by the user, false if it is
6325    internal or momentary.  */
6326
6327 int
6328 user_breakpoint_p (struct breakpoint *b)
6329 {
6330   return b->number > 0;
6331 }
6332
6333 /* Print information on user settable breakpoint (watchpoint, etc)
6334    number BNUM.  If BNUM is -1 print all user-settable breakpoints.
6335    If ALLFLAG is non-zero, include non-user-settable breakpoints.  If
6336    FILTER is non-NULL, call it on each breakpoint and only include the
6337    ones for which it returns non-zero.  Return the total number of
6338    breakpoints listed.  */
6339
6340 static int
6341 breakpoint_1 (char *args, int allflag, 
6342               int (*filter) (const struct breakpoint *))
6343 {
6344   struct breakpoint *b;
6345   struct bp_location *last_loc = NULL;
6346   int nr_printable_breakpoints;
6347   struct cleanup *bkpttbl_chain;
6348   struct value_print_options opts;
6349   int print_address_bits = 0;
6350   int print_type_col_width = 14;
6351   struct ui_out *uiout = current_uiout;
6352
6353   get_user_print_options (&opts);
6354
6355   /* Compute the number of rows in the table, as well as the size
6356      required for address fields.  */
6357   nr_printable_breakpoints = 0;
6358   ALL_BREAKPOINTS (b)
6359     {
6360       /* If we have a filter, only list the breakpoints it accepts.  */
6361       if (filter && !filter (b))
6362         continue;
6363
6364       /* If we have an "args" string, it is a list of breakpoints to 
6365          accept.  Skip the others.  */
6366       if (args != NULL && *args != '\0')
6367         {
6368           if (allflag && parse_and_eval_long (args) != b->number)
6369             continue;
6370           if (!allflag && !number_is_in_list (args, b->number))
6371             continue;
6372         }
6373
6374       if (allflag || user_breakpoint_p (b))
6375         {
6376           int addr_bit, type_len;
6377
6378           addr_bit = breakpoint_address_bits (b);
6379           if (addr_bit > print_address_bits)
6380             print_address_bits = addr_bit;
6381
6382           type_len = strlen (bptype_string (b->type));
6383           if (type_len > print_type_col_width)
6384             print_type_col_width = type_len;
6385
6386           nr_printable_breakpoints++;
6387         }
6388     }
6389
6390   if (opts.addressprint)
6391     bkpttbl_chain 
6392       = make_cleanup_ui_out_table_begin_end (uiout, 6,
6393                                              nr_printable_breakpoints,
6394                                              "BreakpointTable");
6395   else
6396     bkpttbl_chain 
6397       = make_cleanup_ui_out_table_begin_end (uiout, 5,
6398                                              nr_printable_breakpoints,
6399                                              "BreakpointTable");
6400
6401   if (nr_printable_breakpoints > 0)
6402     annotate_breakpoints_headers ();
6403   if (nr_printable_breakpoints > 0)
6404     annotate_field (0);
6405   ui_out_table_header (uiout, 7, ui_left, "number", "Num");     /* 1 */
6406   if (nr_printable_breakpoints > 0)
6407     annotate_field (1);
6408   ui_out_table_header (uiout, print_type_col_width, ui_left,
6409                        "type", "Type");                         /* 2 */
6410   if (nr_printable_breakpoints > 0)
6411     annotate_field (2);
6412   ui_out_table_header (uiout, 4, ui_left, "disp", "Disp");      /* 3 */
6413   if (nr_printable_breakpoints > 0)
6414     annotate_field (3);
6415   ui_out_table_header (uiout, 3, ui_left, "enabled", "Enb");    /* 4 */
6416   if (opts.addressprint)
6417     {
6418       if (nr_printable_breakpoints > 0)
6419         annotate_field (4);
6420       if (print_address_bits <= 32)
6421         ui_out_table_header (uiout, 10, ui_left, 
6422                              "addr", "Address");                /* 5 */
6423       else
6424         ui_out_table_header (uiout, 18, ui_left, 
6425                              "addr", "Address");                /* 5 */
6426     }
6427   if (nr_printable_breakpoints > 0)
6428     annotate_field (5);
6429   ui_out_table_header (uiout, 40, ui_noalign, "what", "What");  /* 6 */
6430   ui_out_table_body (uiout);
6431   if (nr_printable_breakpoints > 0)
6432     annotate_breakpoints_table ();
6433
6434   ALL_BREAKPOINTS (b)
6435     {
6436       QUIT;
6437       /* If we have a filter, only list the breakpoints it accepts.  */
6438       if (filter && !filter (b))
6439         continue;
6440
6441       /* If we have an "args" string, it is a list of breakpoints to 
6442          accept.  Skip the others.  */
6443
6444       if (args != NULL && *args != '\0')
6445         {
6446           if (allflag)  /* maintenance info breakpoint */
6447             {
6448               if (parse_and_eval_long (args) != b->number)
6449                 continue;
6450             }
6451           else          /* all others */
6452             {
6453               if (!number_is_in_list (args, b->number))
6454                 continue;
6455             }
6456         }
6457       /* We only print out user settable breakpoints unless the
6458          allflag is set.  */
6459       if (allflag || user_breakpoint_p (b))
6460         print_one_breakpoint (b, &last_loc, allflag);
6461     }
6462
6463   do_cleanups (bkpttbl_chain);
6464
6465   if (nr_printable_breakpoints == 0)
6466     {
6467       /* If there's a filter, let the caller decide how to report
6468          empty list.  */
6469       if (!filter)
6470         {
6471           if (args == NULL || *args == '\0')
6472             ui_out_message (uiout, 0, "No breakpoints or watchpoints.\n");
6473           else
6474             ui_out_message (uiout, 0, 
6475                             "No breakpoint or watchpoint matching '%s'.\n",
6476                             args);
6477         }
6478     }
6479   else
6480     {
6481       if (last_loc && !server_command)
6482         set_next_address (last_loc->gdbarch, last_loc->address);
6483     }
6484
6485   /* FIXME?  Should this be moved up so that it is only called when
6486      there have been breakpoints? */
6487   annotate_breakpoints_table_end ();
6488
6489   return nr_printable_breakpoints;
6490 }
6491
6492 /* Display the value of default-collect in a way that is generally
6493    compatible with the breakpoint list.  */
6494
6495 static void
6496 default_collect_info (void)
6497 {
6498   struct ui_out *uiout = current_uiout;
6499
6500   /* If it has no value (which is frequently the case), say nothing; a
6501      message like "No default-collect." gets in user's face when it's
6502      not wanted.  */
6503   if (!*default_collect)
6504     return;
6505
6506   /* The following phrase lines up nicely with per-tracepoint collect
6507      actions.  */
6508   ui_out_text (uiout, "default collect ");
6509   ui_out_field_string (uiout, "default-collect", default_collect);
6510   ui_out_text (uiout, " \n");
6511 }
6512   
6513 static void
6514 breakpoints_info (char *args, int from_tty)
6515 {
6516   breakpoint_1 (args, 0, NULL);
6517
6518   default_collect_info ();
6519 }
6520
6521 static void
6522 watchpoints_info (char *args, int from_tty)
6523 {
6524   int num_printed = breakpoint_1 (args, 0, is_watchpoint);
6525   struct ui_out *uiout = current_uiout;
6526
6527   if (num_printed == 0)
6528     {
6529       if (args == NULL || *args == '\0')
6530         ui_out_message (uiout, 0, "No watchpoints.\n");
6531       else
6532         ui_out_message (uiout, 0, "No watchpoint matching '%s'.\n", args);
6533     }
6534 }
6535
6536 static void
6537 maintenance_info_breakpoints (char *args, int from_tty)
6538 {
6539   breakpoint_1 (args, 1, NULL);
6540
6541   default_collect_info ();
6542 }
6543
6544 static int
6545 breakpoint_has_pc (struct breakpoint *b,
6546                    struct program_space *pspace,
6547                    CORE_ADDR pc, struct obj_section *section)
6548 {
6549   struct bp_location *bl = b->loc;
6550
6551   for (; bl; bl = bl->next)
6552     {
6553       if (bl->pspace == pspace
6554           && bl->address == pc
6555           && (!overlay_debugging || bl->section == section))
6556         return 1;         
6557     }
6558   return 0;
6559 }
6560
6561 /* Print a message describing any user-breakpoints set at PC.  This
6562    concerns with logical breakpoints, so we match program spaces, not
6563    address spaces.  */
6564
6565 static void
6566 describe_other_breakpoints (struct gdbarch *gdbarch,
6567                             struct program_space *pspace, CORE_ADDR pc,
6568                             struct obj_section *section, int thread)
6569 {
6570   int others = 0;
6571   struct breakpoint *b;
6572
6573   ALL_BREAKPOINTS (b)
6574     others += (user_breakpoint_p (b)
6575                && breakpoint_has_pc (b, pspace, pc, section));
6576   if (others > 0)
6577     {
6578       if (others == 1)
6579         printf_filtered (_("Note: breakpoint "));
6580       else /* if (others == ???) */
6581         printf_filtered (_("Note: breakpoints "));
6582       ALL_BREAKPOINTS (b)
6583         if (user_breakpoint_p (b) && breakpoint_has_pc (b, pspace, pc, section))
6584           {
6585             others--;
6586             printf_filtered ("%d", b->number);
6587             if (b->thread == -1 && thread != -1)
6588               printf_filtered (" (all threads)");
6589             else if (b->thread != -1)
6590               printf_filtered (" (thread %d)", b->thread);
6591             printf_filtered ("%s%s ",
6592                              ((b->enable_state == bp_disabled
6593                                || b->enable_state == bp_call_disabled)
6594                               ? " (disabled)"
6595                               : b->enable_state == bp_permanent 
6596                               ? " (permanent)"
6597                               : ""),
6598                              (others > 1) ? "," 
6599                              : ((others == 1) ? " and" : ""));
6600           }
6601       printf_filtered (_("also set at pc "));
6602       fputs_filtered (paddress (gdbarch, pc), gdb_stdout);
6603       printf_filtered (".\n");
6604     }
6605 }
6606 \f
6607
6608 /* Return true iff it is meaningful to use the address member of
6609    BPT.  For some breakpoint types, the address member is irrelevant
6610    and it makes no sense to attempt to compare it to other addresses
6611    (or use it for any other purpose either).
6612
6613    More specifically, each of the following breakpoint types will
6614    always have a zero valued address and we don't want to mark
6615    breakpoints of any of these types to be a duplicate of an actual
6616    breakpoint at address zero:
6617
6618       bp_watchpoint
6619       bp_catchpoint
6620
6621 */
6622
6623 static int
6624 breakpoint_address_is_meaningful (struct breakpoint *bpt)
6625 {
6626   enum bptype type = bpt->type;
6627
6628   return (type != bp_watchpoint && type != bp_catchpoint);
6629 }
6630
6631 /* Assuming LOC1 and LOC2's owners are hardware watchpoints, returns
6632    true if LOC1 and LOC2 represent the same watchpoint location.  */
6633
6634 static int
6635 watchpoint_locations_match (struct bp_location *loc1, 
6636                             struct bp_location *loc2)
6637 {
6638   struct watchpoint *w1 = (struct watchpoint *) loc1->owner;
6639   struct watchpoint *w2 = (struct watchpoint *) loc2->owner;
6640
6641   /* Both of them must exist.  */
6642   gdb_assert (w1 != NULL);
6643   gdb_assert (w2 != NULL);
6644
6645   /* If the target can evaluate the condition expression in hardware,
6646      then we we need to insert both watchpoints even if they are at
6647      the same place.  Otherwise the watchpoint will only trigger when
6648      the condition of whichever watchpoint was inserted evaluates to
6649      true, not giving a chance for GDB to check the condition of the
6650      other watchpoint.  */
6651   if ((w1->cond_exp
6652        && target_can_accel_watchpoint_condition (loc1->address, 
6653                                                  loc1->length,
6654                                                  loc1->watchpoint_type,
6655                                                  w1->cond_exp))
6656       || (w2->cond_exp
6657           && target_can_accel_watchpoint_condition (loc2->address, 
6658                                                     loc2->length,
6659                                                     loc2->watchpoint_type,
6660                                                     w2->cond_exp)))
6661     return 0;
6662
6663   /* Note that this checks the owner's type, not the location's.  In
6664      case the target does not support read watchpoints, but does
6665      support access watchpoints, we'll have bp_read_watchpoint
6666      watchpoints with hw_access locations.  Those should be considered
6667      duplicates of hw_read locations.  The hw_read locations will
6668      become hw_access locations later.  */
6669   return (loc1->owner->type == loc2->owner->type
6670           && loc1->pspace->aspace == loc2->pspace->aspace
6671           && loc1->address == loc2->address
6672           && loc1->length == loc2->length);
6673 }
6674
6675 /* Returns true if {ASPACE1,ADDR1} and {ASPACE2,ADDR2} represent the
6676    same breakpoint location.  In most targets, this can only be true
6677    if ASPACE1 matches ASPACE2.  On targets that have global
6678    breakpoints, the address space doesn't really matter.  */
6679
6680 static int
6681 breakpoint_address_match (struct address_space *aspace1, CORE_ADDR addr1,
6682                           struct address_space *aspace2, CORE_ADDR addr2)
6683 {
6684   return ((gdbarch_has_global_breakpoints (target_gdbarch ())
6685            || aspace1 == aspace2)
6686           && addr1 == addr2);
6687 }
6688
6689 /* Returns true if {ASPACE2,ADDR2} falls within the range determined by
6690    {ASPACE1,ADDR1,LEN1}.  In most targets, this can only be true if ASPACE1
6691    matches ASPACE2.  On targets that have global breakpoints, the address
6692    space doesn't really matter.  */
6693
6694 static int
6695 breakpoint_address_match_range (struct address_space *aspace1, CORE_ADDR addr1,
6696                                 int len1, struct address_space *aspace2,
6697                                 CORE_ADDR addr2)
6698 {
6699   return ((gdbarch_has_global_breakpoints (target_gdbarch ())
6700            || aspace1 == aspace2)
6701           && addr2 >= addr1 && addr2 < addr1 + len1);
6702 }
6703
6704 /* Returns true if {ASPACE,ADDR} matches the breakpoint BL.  BL may be
6705    a ranged breakpoint.  In most targets, a match happens only if ASPACE
6706    matches the breakpoint's address space.  On targets that have global
6707    breakpoints, the address space doesn't really matter.  */
6708
6709 static int
6710 breakpoint_location_address_match (struct bp_location *bl,
6711                                    struct address_space *aspace,
6712                                    CORE_ADDR addr)
6713 {
6714   return (breakpoint_address_match (bl->pspace->aspace, bl->address,
6715                                     aspace, addr)
6716           || (bl->length
6717               && breakpoint_address_match_range (bl->pspace->aspace,
6718                                                  bl->address, bl->length,
6719                                                  aspace, addr)));
6720 }
6721
6722 /* If LOC1 and LOC2's owners are not tracepoints, returns false directly.
6723    Then, if LOC1 and LOC2 represent the same tracepoint location, returns
6724    true, otherwise returns false.  */
6725
6726 static int
6727 tracepoint_locations_match (struct bp_location *loc1,
6728                             struct bp_location *loc2)
6729 {
6730   if (is_tracepoint (loc1->owner) && is_tracepoint (loc2->owner))
6731     /* Since tracepoint locations are never duplicated with others', tracepoint
6732        locations at the same address of different tracepoints are regarded as
6733        different locations.  */
6734     return (loc1->address == loc2->address && loc1->owner == loc2->owner);
6735   else
6736     return 0;
6737 }
6738
6739 /* Assuming LOC1 and LOC2's types' have meaningful target addresses
6740    (breakpoint_address_is_meaningful), returns true if LOC1 and LOC2
6741    represent the same location.  */
6742
6743 static int
6744 breakpoint_locations_match (struct bp_location *loc1, 
6745                             struct bp_location *loc2)
6746 {
6747   int hw_point1, hw_point2;
6748
6749   /* Both of them must not be in moribund_locations.  */
6750   gdb_assert (loc1->owner != NULL);
6751   gdb_assert (loc2->owner != NULL);
6752
6753   hw_point1 = is_hardware_watchpoint (loc1->owner);
6754   hw_point2 = is_hardware_watchpoint (loc2->owner);
6755
6756   if (hw_point1 != hw_point2)
6757     return 0;
6758   else if (hw_point1)
6759     return watchpoint_locations_match (loc1, loc2);
6760   else if (is_tracepoint (loc1->owner) || is_tracepoint (loc2->owner))
6761     return tracepoint_locations_match (loc1, loc2);
6762   else
6763     /* We compare bp_location.length in order to cover ranged breakpoints.  */
6764     return (breakpoint_address_match (loc1->pspace->aspace, loc1->address,
6765                                      loc2->pspace->aspace, loc2->address)
6766             && loc1->length == loc2->length);
6767 }
6768
6769 static void
6770 breakpoint_adjustment_warning (CORE_ADDR from_addr, CORE_ADDR to_addr,
6771                                int bnum, int have_bnum)
6772 {
6773   /* The longest string possibly returned by hex_string_custom
6774      is 50 chars.  These must be at least that big for safety.  */
6775   char astr1[64];
6776   char astr2[64];
6777
6778   strcpy (astr1, hex_string_custom ((unsigned long) from_addr, 8));
6779   strcpy (astr2, hex_string_custom ((unsigned long) to_addr, 8));
6780   if (have_bnum)
6781     warning (_("Breakpoint %d address previously adjusted from %s to %s."),
6782              bnum, astr1, astr2);
6783   else
6784     warning (_("Breakpoint address adjusted from %s to %s."), astr1, astr2);
6785 }
6786
6787 /* Adjust a breakpoint's address to account for architectural
6788    constraints on breakpoint placement.  Return the adjusted address.
6789    Note: Very few targets require this kind of adjustment.  For most
6790    targets, this function is simply the identity function.  */
6791
6792 static CORE_ADDR
6793 adjust_breakpoint_address (struct gdbarch *gdbarch,
6794                            CORE_ADDR bpaddr, enum bptype bptype)
6795 {
6796   if (!gdbarch_adjust_breakpoint_address_p (gdbarch))
6797     {
6798       /* Very few targets need any kind of breakpoint adjustment.  */
6799       return bpaddr;
6800     }
6801   else if (bptype == bp_watchpoint
6802            || bptype == bp_hardware_watchpoint
6803            || bptype == bp_read_watchpoint
6804            || bptype == bp_access_watchpoint
6805            || bptype == bp_catchpoint)
6806     {
6807       /* Watchpoints and the various bp_catch_* eventpoints should not
6808          have their addresses modified.  */
6809       return bpaddr;
6810     }
6811   else
6812     {
6813       CORE_ADDR adjusted_bpaddr;
6814
6815       /* Some targets have architectural constraints on the placement
6816          of breakpoint instructions.  Obtain the adjusted address.  */
6817       adjusted_bpaddr = gdbarch_adjust_breakpoint_address (gdbarch, bpaddr);
6818
6819       /* An adjusted breakpoint address can significantly alter
6820          a user's expectations.  Print a warning if an adjustment
6821          is required.  */
6822       if (adjusted_bpaddr != bpaddr)
6823         breakpoint_adjustment_warning (bpaddr, adjusted_bpaddr, 0, 0);
6824
6825       return adjusted_bpaddr;
6826     }
6827 }
6828
6829 void
6830 init_bp_location (struct bp_location *loc, const struct bp_location_ops *ops,
6831                   struct breakpoint *owner)
6832 {
6833   memset (loc, 0, sizeof (*loc));
6834
6835   gdb_assert (ops != NULL);
6836
6837   loc->ops = ops;
6838   loc->owner = owner;
6839   loc->cond = NULL;
6840   loc->cond_bytecode = NULL;
6841   loc->shlib_disabled = 0;
6842   loc->enabled = 1;
6843
6844   switch (owner->type)
6845     {
6846     case bp_breakpoint:
6847     case bp_until:
6848     case bp_finish:
6849     case bp_longjmp:
6850     case bp_longjmp_resume:
6851     case bp_longjmp_call_dummy:
6852     case bp_exception:
6853     case bp_exception_resume:
6854     case bp_step_resume:
6855     case bp_hp_step_resume:
6856     case bp_watchpoint_scope:
6857     case bp_call_dummy:
6858     case bp_std_terminate:
6859     case bp_shlib_event:
6860     case bp_thread_event:
6861     case bp_overlay_event:
6862     case bp_jit_event:
6863     case bp_longjmp_master:
6864     case bp_std_terminate_master:
6865     case bp_exception_master:
6866     case bp_gnu_ifunc_resolver:
6867     case bp_gnu_ifunc_resolver_return:
6868     case bp_dprintf:
6869       loc->loc_type = bp_loc_software_breakpoint;
6870       mark_breakpoint_location_modified (loc);
6871       break;
6872     case bp_hardware_breakpoint:
6873       loc->loc_type = bp_loc_hardware_breakpoint;
6874       mark_breakpoint_location_modified (loc);
6875       break;
6876     case bp_hardware_watchpoint:
6877     case bp_read_watchpoint:
6878     case bp_access_watchpoint:
6879       loc->loc_type = bp_loc_hardware_watchpoint;
6880       break;
6881     case bp_watchpoint:
6882     case bp_catchpoint:
6883     case bp_tracepoint:
6884     case bp_fast_tracepoint:
6885     case bp_static_tracepoint:
6886       loc->loc_type = bp_loc_other;
6887       break;
6888     default:
6889       internal_error (__FILE__, __LINE__, _("unknown breakpoint type"));
6890     }
6891
6892   loc->refc = 1;
6893 }
6894
6895 /* Allocate a struct bp_location.  */
6896
6897 static struct bp_location *
6898 allocate_bp_location (struct breakpoint *bpt)
6899 {
6900   return bpt->ops->allocate_location (bpt);
6901 }
6902
6903 static void
6904 free_bp_location (struct bp_location *loc)
6905 {
6906   loc->ops->dtor (loc);
6907   xfree (loc);
6908 }
6909
6910 /* Increment reference count.  */
6911
6912 static void
6913 incref_bp_location (struct bp_location *bl)
6914 {
6915   ++bl->refc;
6916 }
6917
6918 /* Decrement reference count.  If the reference count reaches 0,
6919    destroy the bp_location.  Sets *BLP to NULL.  */
6920
6921 static void
6922 decref_bp_location (struct bp_location **blp)
6923 {
6924   gdb_assert ((*blp)->refc > 0);
6925
6926   if (--(*blp)->refc == 0)
6927     free_bp_location (*blp);
6928   *blp = NULL;
6929 }
6930
6931 /* Add breakpoint B at the end of the global breakpoint chain.  */
6932
6933 static void
6934 add_to_breakpoint_chain (struct breakpoint *b)
6935 {
6936   struct breakpoint *b1;
6937
6938   /* Add this breakpoint to the end of the chain so that a list of
6939      breakpoints will come out in order of increasing numbers.  */
6940
6941   b1 = breakpoint_chain;
6942   if (b1 == 0)
6943     breakpoint_chain = b;
6944   else
6945     {
6946       while (b1->next)
6947         b1 = b1->next;
6948       b1->next = b;
6949     }
6950 }
6951
6952 /* Initializes breakpoint B with type BPTYPE and no locations yet.  */
6953
6954 static void
6955 init_raw_breakpoint_without_location (struct breakpoint *b,
6956                                       struct gdbarch *gdbarch,
6957                                       enum bptype bptype,
6958                                       const struct breakpoint_ops *ops)
6959 {
6960   memset (b, 0, sizeof (*b));
6961
6962   gdb_assert (ops != NULL);
6963
6964   b->ops = ops;
6965   b->type = bptype;
6966   b->gdbarch = gdbarch;
6967   b->language = current_language->la_language;
6968   b->input_radix = input_radix;
6969   b->thread = -1;
6970   b->enable_state = bp_enabled;
6971   b->next = 0;
6972   b->silent = 0;
6973   b->ignore_count = 0;
6974   b->commands = NULL;
6975   b->frame_id = null_frame_id;
6976   b->condition_not_parsed = 0;
6977   b->py_bp_object = NULL;
6978   b->related_breakpoint = b;
6979 }
6980
6981 /* Helper to set_raw_breakpoint below.  Creates a breakpoint
6982    that has type BPTYPE and has no locations as yet.  */
6983
6984 static struct breakpoint *
6985 set_raw_breakpoint_without_location (struct gdbarch *gdbarch,
6986                                      enum bptype bptype,
6987                                      const struct breakpoint_ops *ops)
6988 {
6989   struct breakpoint *b = XNEW (struct breakpoint);
6990
6991   init_raw_breakpoint_without_location (b, gdbarch, bptype, ops);
6992   add_to_breakpoint_chain (b);
6993   return b;
6994 }
6995
6996 /* Initialize loc->function_name.  EXPLICIT_LOC says no indirect function
6997    resolutions should be made as the user specified the location explicitly
6998    enough.  */
6999
7000 static void
7001 set_breakpoint_location_function (struct bp_location *loc, int explicit_loc)
7002 {
7003   gdb_assert (loc->owner != NULL);
7004
7005   if (loc->owner->type == bp_breakpoint
7006       || loc->owner->type == bp_hardware_breakpoint
7007       || is_tracepoint (loc->owner))
7008     {
7009       int is_gnu_ifunc;
7010       const char *function_name;
7011       CORE_ADDR func_addr;
7012
7013       find_pc_partial_function_gnu_ifunc (loc->address, &function_name,
7014                                           &func_addr, NULL, &is_gnu_ifunc);
7015
7016       if (is_gnu_ifunc && !explicit_loc)
7017         {
7018           struct breakpoint *b = loc->owner;
7019
7020           gdb_assert (loc->pspace == current_program_space);
7021           if (gnu_ifunc_resolve_name (function_name,
7022                                       &loc->requested_address))
7023             {
7024               /* Recalculate ADDRESS based on new REQUESTED_ADDRESS.  */
7025               loc->address = adjust_breakpoint_address (loc->gdbarch,
7026                                                         loc->requested_address,
7027                                                         b->type);
7028             }
7029           else if (b->type == bp_breakpoint && b->loc == loc
7030                    && loc->next == NULL && b->related_breakpoint == b)
7031             {
7032               /* Create only the whole new breakpoint of this type but do not
7033                  mess more complicated breakpoints with multiple locations.  */
7034               b->type = bp_gnu_ifunc_resolver;
7035               /* Remember the resolver's address for use by the return
7036                  breakpoint.  */
7037               loc->related_address = func_addr;
7038             }
7039         }
7040
7041       if (function_name)
7042         loc->function_name = xstrdup (function_name);
7043     }
7044 }
7045
7046 /* Attempt to determine architecture of location identified by SAL.  */
7047 struct gdbarch *
7048 get_sal_arch (struct symtab_and_line sal)
7049 {
7050   if (sal.section)
7051     return get_objfile_arch (sal.section->objfile);
7052   if (sal.symtab)
7053     return get_objfile_arch (sal.symtab->objfile);
7054
7055   return NULL;
7056 }
7057
7058 /* Low level routine for partially initializing a breakpoint of type
7059    BPTYPE.  The newly created breakpoint's address, section, source
7060    file name, and line number are provided by SAL.
7061
7062    It is expected that the caller will complete the initialization of
7063    the newly created breakpoint struct as well as output any status
7064    information regarding the creation of a new breakpoint.  */
7065
7066 static void
7067 init_raw_breakpoint (struct breakpoint *b, struct gdbarch *gdbarch,
7068                      struct symtab_and_line sal, enum bptype bptype,
7069                      const struct breakpoint_ops *ops)
7070 {
7071   init_raw_breakpoint_without_location (b, gdbarch, bptype, ops);
7072
7073   add_location_to_breakpoint (b, &sal);
7074
7075   if (bptype != bp_catchpoint)
7076     gdb_assert (sal.pspace != NULL);
7077
7078   /* Store the program space that was used to set the breakpoint,
7079      except for ordinary breakpoints, which are independent of the
7080      program space.  */
7081   if (bptype != bp_breakpoint && bptype != bp_hardware_breakpoint)
7082     b->pspace = sal.pspace;
7083 }
7084
7085 /* set_raw_breakpoint is a low level routine for allocating and
7086    partially initializing a breakpoint of type BPTYPE.  The newly
7087    created breakpoint's address, section, source file name, and line
7088    number are provided by SAL.  The newly created and partially
7089    initialized breakpoint is added to the breakpoint chain and
7090    is also returned as the value of this function.
7091
7092    It is expected that the caller will complete the initialization of
7093    the newly created breakpoint struct as well as output any status
7094    information regarding the creation of a new breakpoint.  In
7095    particular, set_raw_breakpoint does NOT set the breakpoint
7096    number!  Care should be taken to not allow an error to occur
7097    prior to completing the initialization of the breakpoint.  If this
7098    should happen, a bogus breakpoint will be left on the chain.  */
7099
7100 struct breakpoint *
7101 set_raw_breakpoint (struct gdbarch *gdbarch,
7102                     struct symtab_and_line sal, enum bptype bptype,
7103                     const struct breakpoint_ops *ops)
7104 {
7105   struct breakpoint *b = XNEW (struct breakpoint);
7106
7107   init_raw_breakpoint (b, gdbarch, sal, bptype, ops);
7108   add_to_breakpoint_chain (b);
7109   return b;
7110 }
7111
7112
7113 /* Note that the breakpoint object B describes a permanent breakpoint
7114    instruction, hard-wired into the inferior's code.  */
7115 void
7116 make_breakpoint_permanent (struct breakpoint *b)
7117 {
7118   struct bp_location *bl;
7119
7120   b->enable_state = bp_permanent;
7121
7122   /* By definition, permanent breakpoints are already present in the
7123      code.  Mark all locations as inserted.  For now,
7124      make_breakpoint_permanent is called in just one place, so it's
7125      hard to say if it's reasonable to have permanent breakpoint with
7126      multiple locations or not, but it's easy to implement.  */
7127   for (bl = b->loc; bl; bl = bl->next)
7128     bl->inserted = 1;
7129 }
7130
7131 /* Call this routine when stepping and nexting to enable a breakpoint
7132    if we do a longjmp() or 'throw' in TP.  FRAME is the frame which
7133    initiated the operation.  */
7134
7135 void
7136 set_longjmp_breakpoint (struct thread_info *tp, struct frame_id frame)
7137 {
7138   struct breakpoint *b, *b_tmp;
7139   int thread = tp->num;
7140
7141   /* To avoid having to rescan all objfile symbols at every step,
7142      we maintain a list of continually-inserted but always disabled
7143      longjmp "master" breakpoints.  Here, we simply create momentary
7144      clones of those and enable them for the requested thread.  */
7145   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7146     if (b->pspace == current_program_space
7147         && (b->type == bp_longjmp_master
7148             || b->type == bp_exception_master))
7149       {
7150         enum bptype type = b->type == bp_longjmp_master ? bp_longjmp : bp_exception;
7151         struct breakpoint *clone;
7152
7153         /* longjmp_breakpoint_ops ensures INITIATING_FRAME is cleared again
7154            after their removal.  */
7155         clone = momentary_breakpoint_from_master (b, type,
7156                                                   &longjmp_breakpoint_ops);
7157         clone->thread = thread;
7158       }
7159
7160   tp->initiating_frame = frame;
7161 }
7162
7163 /* Delete all longjmp breakpoints from THREAD.  */
7164 void
7165 delete_longjmp_breakpoint (int thread)
7166 {
7167   struct breakpoint *b, *b_tmp;
7168
7169   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7170     if (b->type == bp_longjmp || b->type == bp_exception)
7171       {
7172         if (b->thread == thread)
7173           delete_breakpoint (b);
7174       }
7175 }
7176
7177 void
7178 delete_longjmp_breakpoint_at_next_stop (int thread)
7179 {
7180   struct breakpoint *b, *b_tmp;
7181
7182   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7183     if (b->type == bp_longjmp || b->type == bp_exception)
7184       {
7185         if (b->thread == thread)
7186           b->disposition = disp_del_at_next_stop;
7187       }
7188 }
7189
7190 /* Place breakpoints of type bp_longjmp_call_dummy to catch longjmp for
7191    INFERIOR_PTID thread.  Chain them all by RELATED_BREAKPOINT and return
7192    pointer to any of them.  Return NULL if this system cannot place longjmp
7193    breakpoints.  */
7194
7195 struct breakpoint *
7196 set_longjmp_breakpoint_for_call_dummy (void)
7197 {
7198   struct breakpoint *b, *retval = NULL;
7199
7200   ALL_BREAKPOINTS (b)
7201     if (b->pspace == current_program_space && b->type == bp_longjmp_master)
7202       {
7203         struct breakpoint *new_b;
7204
7205         new_b = momentary_breakpoint_from_master (b, bp_longjmp_call_dummy,
7206                                                   &momentary_breakpoint_ops);
7207         new_b->thread = pid_to_thread_id (inferior_ptid);
7208
7209         /* Link NEW_B into the chain of RETVAL breakpoints.  */
7210
7211         gdb_assert (new_b->related_breakpoint == new_b);
7212         if (retval == NULL)
7213           retval = new_b;
7214         new_b->related_breakpoint = retval;
7215         while (retval->related_breakpoint != new_b->related_breakpoint)
7216           retval = retval->related_breakpoint;
7217         retval->related_breakpoint = new_b;
7218       }
7219
7220   return retval;
7221 }
7222
7223 /* Verify all existing dummy frames and their associated breakpoints for
7224    THREAD.  Remove those which can no longer be found in the current frame
7225    stack.
7226
7227    You should call this function only at places where it is safe to currently
7228    unwind the whole stack.  Failed stack unwind would discard live dummy
7229    frames.  */
7230
7231 void
7232 check_longjmp_breakpoint_for_call_dummy (int thread)
7233 {
7234   struct breakpoint *b, *b_tmp;
7235
7236   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7237     if (b->type == bp_longjmp_call_dummy && b->thread == thread)
7238       {
7239         struct breakpoint *dummy_b = b->related_breakpoint;
7240
7241         while (dummy_b != b && dummy_b->type != bp_call_dummy)
7242           dummy_b = dummy_b->related_breakpoint;
7243         if (dummy_b->type != bp_call_dummy
7244             || frame_find_by_id (dummy_b->frame_id) != NULL)
7245           continue;
7246         
7247         dummy_frame_discard (dummy_b->frame_id);
7248
7249         while (b->related_breakpoint != b)
7250           {
7251             if (b_tmp == b->related_breakpoint)
7252               b_tmp = b->related_breakpoint->next;
7253             delete_breakpoint (b->related_breakpoint);
7254           }
7255         delete_breakpoint (b);
7256       }
7257 }
7258
7259 void
7260 enable_overlay_breakpoints (void)
7261 {
7262   struct breakpoint *b;
7263
7264   ALL_BREAKPOINTS (b)
7265     if (b->type == bp_overlay_event)
7266     {
7267       b->enable_state = bp_enabled;
7268       update_global_location_list (1);
7269       overlay_events_enabled = 1;
7270     }
7271 }
7272
7273 void
7274 disable_overlay_breakpoints (void)
7275 {
7276   struct breakpoint *b;
7277
7278   ALL_BREAKPOINTS (b)
7279     if (b->type == bp_overlay_event)
7280     {
7281       b->enable_state = bp_disabled;
7282       update_global_location_list (0);
7283       overlay_events_enabled = 0;
7284     }
7285 }
7286
7287 /* Set an active std::terminate breakpoint for each std::terminate
7288    master breakpoint.  */
7289 void
7290 set_std_terminate_breakpoint (void)
7291 {
7292   struct breakpoint *b, *b_tmp;
7293
7294   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7295     if (b->pspace == current_program_space
7296         && b->type == bp_std_terminate_master)
7297       {
7298         momentary_breakpoint_from_master (b, bp_std_terminate,
7299                                           &momentary_breakpoint_ops);
7300       }
7301 }
7302
7303 /* Delete all the std::terminate breakpoints.  */
7304 void
7305 delete_std_terminate_breakpoint (void)
7306 {
7307   struct breakpoint *b, *b_tmp;
7308
7309   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7310     if (b->type == bp_std_terminate)
7311       delete_breakpoint (b);
7312 }
7313
7314 struct breakpoint *
7315 create_thread_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7316 {
7317   struct breakpoint *b;
7318
7319   b = create_internal_breakpoint (gdbarch, address, bp_thread_event,
7320                                   &internal_breakpoint_ops);
7321
7322   b->enable_state = bp_enabled;
7323   /* addr_string has to be used or breakpoint_re_set will delete me.  */
7324   b->addr_string
7325     = xstrprintf ("*%s", paddress (b->loc->gdbarch, b->loc->address));
7326
7327   update_global_location_list_nothrow (1);
7328
7329   return b;
7330 }
7331
7332 void
7333 remove_thread_event_breakpoints (void)
7334 {
7335   struct breakpoint *b, *b_tmp;
7336
7337   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7338     if (b->type == bp_thread_event
7339         && b->loc->pspace == current_program_space)
7340       delete_breakpoint (b);
7341 }
7342
7343 struct lang_and_radix
7344   {
7345     enum language lang;
7346     int radix;
7347   };
7348
7349 /* Create a breakpoint for JIT code registration and unregistration.  */
7350
7351 struct breakpoint *
7352 create_jit_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7353 {
7354   struct breakpoint *b;
7355
7356   b = create_internal_breakpoint (gdbarch, address, bp_jit_event,
7357                                   &internal_breakpoint_ops);
7358   update_global_location_list_nothrow (1);
7359   return b;
7360 }
7361
7362 /* Remove JIT code registration and unregistration breakpoint(s).  */
7363
7364 void
7365 remove_jit_event_breakpoints (void)
7366 {
7367   struct breakpoint *b, *b_tmp;
7368
7369   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7370     if (b->type == bp_jit_event
7371         && b->loc->pspace == current_program_space)
7372       delete_breakpoint (b);
7373 }
7374
7375 void
7376 remove_solib_event_breakpoints (void)
7377 {
7378   struct breakpoint *b, *b_tmp;
7379
7380   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7381     if (b->type == bp_shlib_event
7382         && b->loc->pspace == current_program_space)
7383       delete_breakpoint (b);
7384 }
7385
7386 struct breakpoint *
7387 create_solib_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7388 {
7389   struct breakpoint *b;
7390
7391   b = create_internal_breakpoint (gdbarch, address, bp_shlib_event,
7392                                   &internal_breakpoint_ops);
7393   update_global_location_list_nothrow (1);
7394   return b;
7395 }
7396
7397 /* Disable any breakpoints that are on code in shared libraries.  Only
7398    apply to enabled breakpoints, disabled ones can just stay disabled.  */
7399
7400 void
7401 disable_breakpoints_in_shlibs (void)
7402 {
7403   struct bp_location *loc, **locp_tmp;
7404
7405   ALL_BP_LOCATIONS (loc, locp_tmp)
7406   {
7407     /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
7408     struct breakpoint *b = loc->owner;
7409
7410     /* We apply the check to all breakpoints, including disabled for
7411        those with loc->duplicate set.  This is so that when breakpoint
7412        becomes enabled, or the duplicate is removed, gdb will try to
7413        insert all breakpoints.  If we don't set shlib_disabled here,
7414        we'll try to insert those breakpoints and fail.  */
7415     if (((b->type == bp_breakpoint)
7416          || (b->type == bp_jit_event)
7417          || (b->type == bp_hardware_breakpoint)
7418          || (is_tracepoint (b)))
7419         && loc->pspace == current_program_space
7420         && !loc->shlib_disabled
7421 #ifdef PC_SOLIB
7422         && PC_SOLIB (loc->address)
7423 #else
7424         && solib_name_from_address (loc->pspace, loc->address)
7425 #endif
7426         )
7427       {
7428         loc->shlib_disabled = 1;
7429       }
7430   }
7431 }
7432
7433 /* Disable any breakpoints and tracepoints that are in an unloaded shared
7434    library.  Only apply to enabled breakpoints, disabled ones can just stay
7435    disabled.  */
7436
7437 static void
7438 disable_breakpoints_in_unloaded_shlib (struct so_list *solib)
7439 {
7440   struct bp_location *loc, **locp_tmp;
7441   int disabled_shlib_breaks = 0;
7442
7443   /* SunOS a.out shared libraries are always mapped, so do not
7444      disable breakpoints; they will only be reported as unloaded
7445      through clear_solib when GDB discards its shared library
7446      list.  See clear_solib for more information.  */
7447   if (exec_bfd != NULL
7448       && bfd_get_flavour (exec_bfd) == bfd_target_aout_flavour)
7449     return;
7450
7451   ALL_BP_LOCATIONS (loc, locp_tmp)
7452   {
7453     /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
7454     struct breakpoint *b = loc->owner;
7455
7456     if (solib->pspace == loc->pspace
7457         && !loc->shlib_disabled
7458         && (((b->type == bp_breakpoint
7459               || b->type == bp_jit_event
7460               || b->type == bp_hardware_breakpoint)
7461              && (loc->loc_type == bp_loc_hardware_breakpoint
7462                  || loc->loc_type == bp_loc_software_breakpoint))
7463             || is_tracepoint (b))
7464         && solib_contains_address_p (solib, loc->address))
7465       {
7466         loc->shlib_disabled = 1;
7467         /* At this point, we cannot rely on remove_breakpoint
7468            succeeding so we must mark the breakpoint as not inserted
7469            to prevent future errors occurring in remove_breakpoints.  */
7470         loc->inserted = 0;
7471
7472         /* This may cause duplicate notifications for the same breakpoint.  */
7473         observer_notify_breakpoint_modified (b);
7474
7475         if (!disabled_shlib_breaks)
7476           {
7477             target_terminal_ours_for_output ();
7478             warning (_("Temporarily disabling breakpoints "
7479                        "for unloaded shared library \"%s\""),
7480                      solib->so_name);
7481           }
7482         disabled_shlib_breaks = 1;
7483       }
7484   }
7485 }
7486
7487 /* FORK & VFORK catchpoints.  */
7488
7489 /* An instance of this type is used to represent a fork or vfork
7490    catchpoint.  It includes a "struct breakpoint" as a kind of base
7491    class; users downcast to "struct breakpoint *" when needed.  A
7492    breakpoint is really of this type iff its ops pointer points to
7493    CATCH_FORK_BREAKPOINT_OPS.  */
7494
7495 struct fork_catchpoint
7496 {
7497   /* The base class.  */
7498   struct breakpoint base;
7499
7500   /* Process id of a child process whose forking triggered this
7501      catchpoint.  This field is only valid immediately after this
7502      catchpoint has triggered.  */
7503   ptid_t forked_inferior_pid;
7504 };
7505
7506 /* Implement the "insert" breakpoint_ops method for fork
7507    catchpoints.  */
7508
7509 static int
7510 insert_catch_fork (struct bp_location *bl)
7511 {
7512   return target_insert_fork_catchpoint (PIDGET (inferior_ptid));
7513 }
7514
7515 /* Implement the "remove" breakpoint_ops method for fork
7516    catchpoints.  */
7517
7518 static int
7519 remove_catch_fork (struct bp_location *bl)
7520 {
7521   return target_remove_fork_catchpoint (PIDGET (inferior_ptid));
7522 }
7523
7524 /* Implement the "breakpoint_hit" breakpoint_ops method for fork
7525    catchpoints.  */
7526
7527 static int
7528 breakpoint_hit_catch_fork (const struct bp_location *bl,
7529                            struct address_space *aspace, CORE_ADDR bp_addr,
7530                            const struct target_waitstatus *ws)
7531 {
7532   struct fork_catchpoint *c = (struct fork_catchpoint *) bl->owner;
7533
7534   if (ws->kind != TARGET_WAITKIND_FORKED)
7535     return 0;
7536
7537   c->forked_inferior_pid = ws->value.related_pid;
7538   return 1;
7539 }
7540
7541 /* Implement the "print_it" breakpoint_ops method for fork
7542    catchpoints.  */
7543
7544 static enum print_stop_action
7545 print_it_catch_fork (bpstat bs)
7546 {
7547   struct ui_out *uiout = current_uiout;
7548   struct breakpoint *b = bs->breakpoint_at;
7549   struct fork_catchpoint *c = (struct fork_catchpoint *) bs->breakpoint_at;
7550
7551   annotate_catchpoint (b->number);
7552   if (b->disposition == disp_del)
7553     ui_out_text (uiout, "\nTemporary catchpoint ");
7554   else
7555     ui_out_text (uiout, "\nCatchpoint ");
7556   if (ui_out_is_mi_like_p (uiout))
7557     {
7558       ui_out_field_string (uiout, "reason",
7559                            async_reason_lookup (EXEC_ASYNC_FORK));
7560       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
7561     }
7562   ui_out_field_int (uiout, "bkptno", b->number);
7563   ui_out_text (uiout, " (forked process ");
7564   ui_out_field_int (uiout, "newpid", ptid_get_pid (c->forked_inferior_pid));
7565   ui_out_text (uiout, "), ");
7566   return PRINT_SRC_AND_LOC;
7567 }
7568
7569 /* Implement the "print_one" breakpoint_ops method for fork
7570    catchpoints.  */
7571
7572 static void
7573 print_one_catch_fork (struct breakpoint *b, struct bp_location **last_loc)
7574 {
7575   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
7576   struct value_print_options opts;
7577   struct ui_out *uiout = current_uiout;
7578
7579   get_user_print_options (&opts);
7580
7581   /* Field 4, the address, is omitted (which makes the columns not
7582      line up too nicely with the headers, but the effect is relatively
7583      readable).  */
7584   if (opts.addressprint)
7585     ui_out_field_skip (uiout, "addr");
7586   annotate_field (5);
7587   ui_out_text (uiout, "fork");
7588   if (!ptid_equal (c->forked_inferior_pid, null_ptid))
7589     {
7590       ui_out_text (uiout, ", process ");
7591       ui_out_field_int (uiout, "what",
7592                         ptid_get_pid (c->forked_inferior_pid));
7593       ui_out_spaces (uiout, 1);
7594     }
7595
7596   if (ui_out_is_mi_like_p (uiout))
7597     ui_out_field_string (uiout, "catch-type", "fork");
7598 }
7599
7600 /* Implement the "print_mention" breakpoint_ops method for fork
7601    catchpoints.  */
7602
7603 static void
7604 print_mention_catch_fork (struct breakpoint *b)
7605 {
7606   printf_filtered (_("Catchpoint %d (fork)"), b->number);
7607 }
7608
7609 /* Implement the "print_recreate" breakpoint_ops method for fork
7610    catchpoints.  */
7611
7612 static void
7613 print_recreate_catch_fork (struct breakpoint *b, struct ui_file *fp)
7614 {
7615   fprintf_unfiltered (fp, "catch fork");
7616   print_recreate_thread (b, fp);
7617 }
7618
7619 /* The breakpoint_ops structure to be used in fork catchpoints.  */
7620
7621 static struct breakpoint_ops catch_fork_breakpoint_ops;
7622
7623 /* Implement the "insert" breakpoint_ops method for vfork
7624    catchpoints.  */
7625
7626 static int
7627 insert_catch_vfork (struct bp_location *bl)
7628 {
7629   return target_insert_vfork_catchpoint (PIDGET (inferior_ptid));
7630 }
7631
7632 /* Implement the "remove" breakpoint_ops method for vfork
7633    catchpoints.  */
7634
7635 static int
7636 remove_catch_vfork (struct bp_location *bl)
7637 {
7638   return target_remove_vfork_catchpoint (PIDGET (inferior_ptid));
7639 }
7640
7641 /* Implement the "breakpoint_hit" breakpoint_ops method for vfork
7642    catchpoints.  */
7643
7644 static int
7645 breakpoint_hit_catch_vfork (const struct bp_location *bl,
7646                             struct address_space *aspace, CORE_ADDR bp_addr,
7647                             const struct target_waitstatus *ws)
7648 {
7649   struct fork_catchpoint *c = (struct fork_catchpoint *) bl->owner;
7650
7651   if (ws->kind != TARGET_WAITKIND_VFORKED)
7652     return 0;
7653
7654   c->forked_inferior_pid = ws->value.related_pid;
7655   return 1;
7656 }
7657
7658 /* Implement the "print_it" breakpoint_ops method for vfork
7659    catchpoints.  */
7660
7661 static enum print_stop_action
7662 print_it_catch_vfork (bpstat bs)
7663 {
7664   struct ui_out *uiout = current_uiout;
7665   struct breakpoint *b = bs->breakpoint_at;
7666   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
7667
7668   annotate_catchpoint (b->number);
7669   if (b->disposition == disp_del)
7670     ui_out_text (uiout, "\nTemporary catchpoint ");
7671   else
7672     ui_out_text (uiout, "\nCatchpoint ");
7673   if (ui_out_is_mi_like_p (uiout))
7674     {
7675       ui_out_field_string (uiout, "reason",
7676                            async_reason_lookup (EXEC_ASYNC_VFORK));
7677       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
7678     }
7679   ui_out_field_int (uiout, "bkptno", b->number);
7680   ui_out_text (uiout, " (vforked process ");
7681   ui_out_field_int (uiout, "newpid", ptid_get_pid (c->forked_inferior_pid));
7682   ui_out_text (uiout, "), ");
7683   return PRINT_SRC_AND_LOC;
7684 }
7685
7686 /* Implement the "print_one" breakpoint_ops method for vfork
7687    catchpoints.  */
7688
7689 static void
7690 print_one_catch_vfork (struct breakpoint *b, struct bp_location **last_loc)
7691 {
7692   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
7693   struct value_print_options opts;
7694   struct ui_out *uiout = current_uiout;
7695
7696   get_user_print_options (&opts);
7697   /* Field 4, the address, is omitted (which makes the columns not
7698      line up too nicely with the headers, but the effect is relatively
7699      readable).  */
7700   if (opts.addressprint)
7701     ui_out_field_skip (uiout, "addr");
7702   annotate_field (5);
7703   ui_out_text (uiout, "vfork");
7704   if (!ptid_equal (c->forked_inferior_pid, null_ptid))
7705     {
7706       ui_out_text (uiout, ", process ");
7707       ui_out_field_int (uiout, "what",
7708                         ptid_get_pid (c->forked_inferior_pid));
7709       ui_out_spaces (uiout, 1);
7710     }
7711
7712   if (ui_out_is_mi_like_p (uiout))
7713     ui_out_field_string (uiout, "catch-type", "vfork");
7714 }
7715
7716 /* Implement the "print_mention" breakpoint_ops method for vfork
7717    catchpoints.  */
7718
7719 static void
7720 print_mention_catch_vfork (struct breakpoint *b)
7721 {
7722   printf_filtered (_("Catchpoint %d (vfork)"), b->number);
7723 }
7724
7725 /* Implement the "print_recreate" breakpoint_ops method for vfork
7726    catchpoints.  */
7727
7728 static void
7729 print_recreate_catch_vfork (struct breakpoint *b, struct ui_file *fp)
7730 {
7731   fprintf_unfiltered (fp, "catch vfork");
7732   print_recreate_thread (b, fp);
7733 }
7734
7735 /* The breakpoint_ops structure to be used in vfork catchpoints.  */
7736
7737 static struct breakpoint_ops catch_vfork_breakpoint_ops;
7738
7739 /* An instance of this type is used to represent an solib catchpoint.
7740    It includes a "struct breakpoint" as a kind of base class; users
7741    downcast to "struct breakpoint *" when needed.  A breakpoint is
7742    really of this type iff its ops pointer points to
7743    CATCH_SOLIB_BREAKPOINT_OPS.  */
7744
7745 struct solib_catchpoint
7746 {
7747   /* The base class.  */
7748   struct breakpoint base;
7749
7750   /* True for "catch load", false for "catch unload".  */
7751   unsigned char is_load;
7752
7753   /* Regular expression to match, if any.  COMPILED is only valid when
7754      REGEX is non-NULL.  */
7755   char *regex;
7756   regex_t compiled;
7757 };
7758
7759 static void
7760 dtor_catch_solib (struct breakpoint *b)
7761 {
7762   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
7763
7764   if (self->regex)
7765     regfree (&self->compiled);
7766   xfree (self->regex);
7767
7768   base_breakpoint_ops.dtor (b);
7769 }
7770
7771 static int
7772 insert_catch_solib (struct bp_location *ignore)
7773 {
7774   return 0;
7775 }
7776
7777 static int
7778 remove_catch_solib (struct bp_location *ignore)
7779 {
7780   return 0;
7781 }
7782
7783 static int
7784 breakpoint_hit_catch_solib (const struct bp_location *bl,
7785                             struct address_space *aspace,
7786                             CORE_ADDR bp_addr,
7787                             const struct target_waitstatus *ws)
7788 {
7789   struct solib_catchpoint *self = (struct solib_catchpoint *) bl->owner;
7790   struct breakpoint *other;
7791
7792   if (ws->kind == TARGET_WAITKIND_LOADED)
7793     return 1;
7794
7795   ALL_BREAKPOINTS (other)
7796   {
7797     struct bp_location *other_bl;
7798
7799     if (other == bl->owner)
7800       continue;
7801
7802     if (other->type != bp_shlib_event)
7803       continue;
7804
7805     if (self->base.pspace != NULL && other->pspace != self->base.pspace)
7806       continue;
7807
7808     for (other_bl = other->loc; other_bl != NULL; other_bl = other_bl->next)
7809       {
7810         if (other->ops->breakpoint_hit (other_bl, aspace, bp_addr, ws))
7811           return 1;
7812       }
7813   }
7814
7815   return 0;
7816 }
7817
7818 static void
7819 check_status_catch_solib (struct bpstats *bs)
7820 {
7821   struct solib_catchpoint *self
7822     = (struct solib_catchpoint *) bs->breakpoint_at;
7823   int ix;
7824
7825   if (self->is_load)
7826     {
7827       struct so_list *iter;
7828
7829       for (ix = 0;
7830            VEC_iterate (so_list_ptr, current_program_space->added_solibs,
7831                         ix, iter);
7832            ++ix)
7833         {
7834           if (!self->regex
7835               || regexec (&self->compiled, iter->so_name, 0, NULL, 0) == 0)
7836             return;
7837         }
7838     }
7839   else
7840     {
7841       char *iter;
7842
7843       for (ix = 0;
7844            VEC_iterate (char_ptr, current_program_space->deleted_solibs,
7845                         ix, iter);
7846            ++ix)
7847         {
7848           if (!self->regex
7849               || regexec (&self->compiled, iter, 0, NULL, 0) == 0)
7850             return;
7851         }
7852     }
7853
7854   bs->stop = 0;
7855   bs->print_it = print_it_noop;
7856 }
7857
7858 static enum print_stop_action
7859 print_it_catch_solib (bpstat bs)
7860 {
7861   struct breakpoint *b = bs->breakpoint_at;
7862   struct ui_out *uiout = current_uiout;
7863
7864   annotate_catchpoint (b->number);
7865   if (b->disposition == disp_del)
7866     ui_out_text (uiout, "\nTemporary catchpoint ");
7867   else
7868     ui_out_text (uiout, "\nCatchpoint ");
7869   ui_out_field_int (uiout, "bkptno", b->number);
7870   ui_out_text (uiout, "\n");
7871   if (ui_out_is_mi_like_p (uiout))
7872     ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
7873   print_solib_event (1);
7874   return PRINT_SRC_AND_LOC;
7875 }
7876
7877 static void
7878 print_one_catch_solib (struct breakpoint *b, struct bp_location **locs)
7879 {
7880   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
7881   struct value_print_options opts;
7882   struct ui_out *uiout = current_uiout;
7883   char *msg;
7884
7885   get_user_print_options (&opts);
7886   /* Field 4, the address, is omitted (which makes the columns not
7887      line up too nicely with the headers, but the effect is relatively
7888      readable).  */
7889   if (opts.addressprint)
7890     {
7891       annotate_field (4);
7892       ui_out_field_skip (uiout, "addr");
7893     }
7894
7895   annotate_field (5);
7896   if (self->is_load)
7897     {
7898       if (self->regex)
7899         msg = xstrprintf (_("load of library matching %s"), self->regex);
7900       else
7901         msg = xstrdup (_("load of library"));
7902     }
7903   else
7904     {
7905       if (self->regex)
7906         msg = xstrprintf (_("unload of library matching %s"), self->regex);
7907       else
7908         msg = xstrdup (_("unload of library"));
7909     }
7910   ui_out_field_string (uiout, "what", msg);
7911   xfree (msg);
7912
7913   if (ui_out_is_mi_like_p (uiout))
7914     ui_out_field_string (uiout, "catch-type",
7915                          self->is_load ? "load" : "unload");
7916 }
7917
7918 static void
7919 print_mention_catch_solib (struct breakpoint *b)
7920 {
7921   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
7922
7923   printf_filtered (_("Catchpoint %d (%s)"), b->number,
7924                    self->is_load ? "load" : "unload");
7925 }
7926
7927 static void
7928 print_recreate_catch_solib (struct breakpoint *b, struct ui_file *fp)
7929 {
7930   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
7931
7932   fprintf_unfiltered (fp, "%s %s",
7933                       b->disposition == disp_del ? "tcatch" : "catch",
7934                       self->is_load ? "load" : "unload");
7935   if (self->regex)
7936     fprintf_unfiltered (fp, " %s", self->regex);
7937   fprintf_unfiltered (fp, "\n");
7938 }
7939
7940 static struct breakpoint_ops catch_solib_breakpoint_ops;
7941
7942 /* Shared helper function (MI and CLI) for creating and installing
7943    a shared object event catchpoint.  If IS_LOAD is non-zero then
7944    the events to be caught are load events, otherwise they are
7945    unload events.  If IS_TEMP is non-zero the catchpoint is a
7946    temporary one.  If ENABLED is non-zero the catchpoint is
7947    created in an enabled state.  */
7948
7949 void
7950 add_solib_catchpoint (char *arg, int is_load, int is_temp, int enabled)
7951 {
7952   struct solib_catchpoint *c;
7953   struct gdbarch *gdbarch = get_current_arch ();
7954   struct cleanup *cleanup;
7955
7956   if (!arg)
7957     arg = "";
7958   arg = skip_spaces (arg);
7959
7960   c = XCNEW (struct solib_catchpoint);
7961   cleanup = make_cleanup (xfree, c);
7962
7963   if (*arg != '\0')
7964     {
7965       int errcode;
7966
7967       errcode = regcomp (&c->compiled, arg, REG_NOSUB);
7968       if (errcode != 0)
7969         {
7970           char *err = get_regcomp_error (errcode, &c->compiled);
7971
7972           make_cleanup (xfree, err);
7973           error (_("Invalid regexp (%s): %s"), err, arg);
7974         }
7975       c->regex = xstrdup (arg);
7976     }
7977
7978   c->is_load = is_load;
7979   init_catchpoint (&c->base, gdbarch, is_temp, NULL,
7980                    &catch_solib_breakpoint_ops);
7981
7982   c->base.enable_state = enabled ? bp_enabled : bp_disabled;
7983
7984   discard_cleanups (cleanup);
7985   install_breakpoint (0, &c->base, 1);
7986 }
7987
7988 /* A helper function that does all the work for "catch load" and
7989    "catch unload".  */
7990
7991 static void
7992 catch_load_or_unload (char *arg, int from_tty, int is_load,
7993                       struct cmd_list_element *command)
7994 {
7995   int tempflag;
7996   const int enabled = 1;
7997
7998   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
7999
8000   add_solib_catchpoint (arg, is_load, tempflag, enabled);
8001 }
8002
8003 static void
8004 catch_load_command_1 (char *arg, int from_tty,
8005                       struct cmd_list_element *command)
8006 {
8007   catch_load_or_unload (arg, from_tty, 1, command);
8008 }
8009
8010 static void
8011 catch_unload_command_1 (char *arg, int from_tty,
8012                         struct cmd_list_element *command)
8013 {
8014   catch_load_or_unload (arg, from_tty, 0, command);
8015 }
8016
8017 /* An instance of this type is used to represent a syscall catchpoint.
8018    It includes a "struct breakpoint" as a kind of base class; users
8019    downcast to "struct breakpoint *" when needed.  A breakpoint is
8020    really of this type iff its ops pointer points to
8021    CATCH_SYSCALL_BREAKPOINT_OPS.  */
8022
8023 struct syscall_catchpoint
8024 {
8025   /* The base class.  */
8026   struct breakpoint base;
8027
8028   /* Syscall numbers used for the 'catch syscall' feature.  If no
8029      syscall has been specified for filtering, its value is NULL.
8030      Otherwise, it holds a list of all syscalls to be caught.  The
8031      list elements are allocated with xmalloc.  */
8032   VEC(int) *syscalls_to_be_caught;
8033 };
8034
8035 /* Implement the "dtor" breakpoint_ops method for syscall
8036    catchpoints.  */
8037
8038 static void
8039 dtor_catch_syscall (struct breakpoint *b)
8040 {
8041   struct syscall_catchpoint *c = (struct syscall_catchpoint *) b;
8042
8043   VEC_free (int, c->syscalls_to_be_caught);
8044
8045   base_breakpoint_ops.dtor (b);
8046 }
8047
8048 static const struct inferior_data *catch_syscall_inferior_data = NULL;
8049
8050 struct catch_syscall_inferior_data
8051 {
8052   /* We keep a count of the number of times the user has requested a
8053      particular syscall to be tracked, and pass this information to the
8054      target.  This lets capable targets implement filtering directly.  */
8055
8056   /* Number of times that "any" syscall is requested.  */
8057   int any_syscall_count;
8058
8059   /* Count of each system call.  */
8060   VEC(int) *syscalls_counts;
8061
8062   /* This counts all syscall catch requests, so we can readily determine
8063      if any catching is necessary.  */
8064   int total_syscalls_count;
8065 };
8066
8067 static struct catch_syscall_inferior_data*
8068 get_catch_syscall_inferior_data (struct inferior *inf)
8069 {
8070   struct catch_syscall_inferior_data *inf_data;
8071
8072   inf_data = inferior_data (inf, catch_syscall_inferior_data);
8073   if (inf_data == NULL)
8074     {
8075       inf_data = XZALLOC (struct catch_syscall_inferior_data);
8076       set_inferior_data (inf, catch_syscall_inferior_data, inf_data);
8077     }
8078
8079   return inf_data;
8080 }
8081
8082 static void
8083 catch_syscall_inferior_data_cleanup (struct inferior *inf, void *arg)
8084 {
8085   xfree (arg);
8086 }
8087
8088
8089 /* Implement the "insert" breakpoint_ops method for syscall
8090    catchpoints.  */
8091
8092 static int
8093 insert_catch_syscall (struct bp_location *bl)
8094 {
8095   struct syscall_catchpoint *c = (struct syscall_catchpoint *) bl->owner;
8096   struct inferior *inf = current_inferior ();
8097   struct catch_syscall_inferior_data *inf_data
8098     = get_catch_syscall_inferior_data (inf);
8099
8100   ++inf_data->total_syscalls_count;
8101   if (!c->syscalls_to_be_caught)
8102     ++inf_data->any_syscall_count;
8103   else
8104     {
8105       int i, iter;
8106
8107       for (i = 0;
8108            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
8109            i++)
8110         {
8111           int elem;
8112
8113           if (iter >= VEC_length (int, inf_data->syscalls_counts))
8114             {
8115               int old_size = VEC_length (int, inf_data->syscalls_counts);
8116               uintptr_t vec_addr_offset
8117                 = old_size * ((uintptr_t) sizeof (int));
8118               uintptr_t vec_addr;
8119               VEC_safe_grow (int, inf_data->syscalls_counts, iter + 1);
8120               vec_addr = ((uintptr_t) VEC_address (int,
8121                                                   inf_data->syscalls_counts)
8122                           + vec_addr_offset);
8123               memset ((void *) vec_addr, 0,
8124                       (iter + 1 - old_size) * sizeof (int));
8125             }
8126           elem = VEC_index (int, inf_data->syscalls_counts, iter);
8127           VEC_replace (int, inf_data->syscalls_counts, iter, ++elem);
8128         }
8129     }
8130
8131   return target_set_syscall_catchpoint (PIDGET (inferior_ptid),
8132                                         inf_data->total_syscalls_count != 0,
8133                                         inf_data->any_syscall_count,
8134                                         VEC_length (int,
8135                                                     inf_data->syscalls_counts),
8136                                         VEC_address (int,
8137                                                      inf_data->syscalls_counts));
8138 }
8139
8140 /* Implement the "remove" breakpoint_ops method for syscall
8141    catchpoints.  */
8142
8143 static int
8144 remove_catch_syscall (struct bp_location *bl)
8145 {
8146   struct syscall_catchpoint *c = (struct syscall_catchpoint *) bl->owner;
8147   struct inferior *inf = current_inferior ();
8148   struct catch_syscall_inferior_data *inf_data
8149     = get_catch_syscall_inferior_data (inf);
8150
8151   --inf_data->total_syscalls_count;
8152   if (!c->syscalls_to_be_caught)
8153     --inf_data->any_syscall_count;
8154   else
8155     {
8156       int i, iter;
8157
8158       for (i = 0;
8159            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
8160            i++)
8161         {
8162           int elem;
8163           if (iter >= VEC_length (int, inf_data->syscalls_counts))
8164             /* Shouldn't happen.  */
8165             continue;
8166           elem = VEC_index (int, inf_data->syscalls_counts, iter);
8167           VEC_replace (int, inf_data->syscalls_counts, iter, --elem);
8168         }
8169     }
8170
8171   return target_set_syscall_catchpoint (PIDGET (inferior_ptid),
8172                                         inf_data->total_syscalls_count != 0,
8173                                         inf_data->any_syscall_count,
8174                                         VEC_length (int,
8175                                                     inf_data->syscalls_counts),
8176                                         VEC_address (int,
8177                                                      inf_data->syscalls_counts));
8178 }
8179
8180 /* Implement the "breakpoint_hit" breakpoint_ops method for syscall
8181    catchpoints.  */
8182
8183 static int
8184 breakpoint_hit_catch_syscall (const struct bp_location *bl,
8185                               struct address_space *aspace, CORE_ADDR bp_addr,
8186                               const struct target_waitstatus *ws)
8187 {
8188   /* We must check if we are catching specific syscalls in this
8189      breakpoint.  If we are, then we must guarantee that the called
8190      syscall is the same syscall we are catching.  */
8191   int syscall_number = 0;
8192   const struct syscall_catchpoint *c
8193     = (const struct syscall_catchpoint *) bl->owner;
8194
8195   if (ws->kind != TARGET_WAITKIND_SYSCALL_ENTRY
8196       && ws->kind != TARGET_WAITKIND_SYSCALL_RETURN)
8197     return 0;
8198
8199   syscall_number = ws->value.syscall_number;
8200
8201   /* Now, checking if the syscall is the same.  */
8202   if (c->syscalls_to_be_caught)
8203     {
8204       int i, iter;
8205
8206       for (i = 0;
8207            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
8208            i++)
8209         if (syscall_number == iter)
8210           break;
8211       /* Not the same.  */
8212       if (!iter)
8213         return 0;
8214     }
8215
8216   return 1;
8217 }
8218
8219 /* Implement the "print_it" breakpoint_ops method for syscall
8220    catchpoints.  */
8221
8222 static enum print_stop_action
8223 print_it_catch_syscall (bpstat bs)
8224 {
8225   struct ui_out *uiout = current_uiout;
8226   struct breakpoint *b = bs->breakpoint_at;
8227   /* These are needed because we want to know in which state a
8228      syscall is.  It can be in the TARGET_WAITKIND_SYSCALL_ENTRY
8229      or TARGET_WAITKIND_SYSCALL_RETURN, and depending on it we
8230      must print "called syscall" or "returned from syscall".  */
8231   ptid_t ptid;
8232   struct target_waitstatus last;
8233   struct syscall s;
8234
8235   get_last_target_status (&ptid, &last);
8236
8237   get_syscall_by_number (last.value.syscall_number, &s);
8238
8239   annotate_catchpoint (b->number);
8240
8241   if (b->disposition == disp_del)
8242     ui_out_text (uiout, "\nTemporary catchpoint ");
8243   else
8244     ui_out_text (uiout, "\nCatchpoint ");
8245   if (ui_out_is_mi_like_p (uiout))
8246     {
8247       ui_out_field_string (uiout, "reason",
8248                            async_reason_lookup (last.kind == TARGET_WAITKIND_SYSCALL_ENTRY
8249                                                 ? EXEC_ASYNC_SYSCALL_ENTRY
8250                                                 : EXEC_ASYNC_SYSCALL_RETURN));
8251       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
8252     }
8253   ui_out_field_int (uiout, "bkptno", b->number);
8254
8255   if (last.kind == TARGET_WAITKIND_SYSCALL_ENTRY)
8256     ui_out_text (uiout, " (call to syscall ");
8257   else
8258     ui_out_text (uiout, " (returned from syscall ");
8259
8260   if (s.name == NULL || ui_out_is_mi_like_p (uiout))
8261     ui_out_field_int (uiout, "syscall-number", last.value.syscall_number);
8262   if (s.name != NULL)
8263     ui_out_field_string (uiout, "syscall-name", s.name);
8264
8265   ui_out_text (uiout, "), ");
8266
8267   return PRINT_SRC_AND_LOC;
8268 }
8269
8270 /* Implement the "print_one" breakpoint_ops method for syscall
8271    catchpoints.  */
8272
8273 static void
8274 print_one_catch_syscall (struct breakpoint *b,
8275                          struct bp_location **last_loc)
8276 {
8277   struct syscall_catchpoint *c = (struct syscall_catchpoint *) b;
8278   struct value_print_options opts;
8279   struct ui_out *uiout = current_uiout;
8280
8281   get_user_print_options (&opts);
8282   /* Field 4, the address, is omitted (which makes the columns not
8283      line up too nicely with the headers, but the effect is relatively
8284      readable).  */
8285   if (opts.addressprint)
8286     ui_out_field_skip (uiout, "addr");
8287   annotate_field (5);
8288
8289   if (c->syscalls_to_be_caught
8290       && VEC_length (int, c->syscalls_to_be_caught) > 1)
8291     ui_out_text (uiout, "syscalls \"");
8292   else
8293     ui_out_text (uiout, "syscall \"");
8294
8295   if (c->syscalls_to_be_caught)
8296     {
8297       int i, iter;
8298       char *text = xstrprintf ("%s", "");
8299
8300       for (i = 0;
8301            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
8302            i++)
8303         {
8304           char *x = text;
8305           struct syscall s;
8306           get_syscall_by_number (iter, &s);
8307
8308           if (s.name != NULL)
8309             text = xstrprintf ("%s%s, ", text, s.name);
8310           else
8311             text = xstrprintf ("%s%d, ", text, iter);
8312
8313           /* We have to xfree the last 'text' (now stored at 'x')
8314              because xstrprintf dynamically allocates new space for it
8315              on every call.  */
8316           xfree (x);
8317         }
8318       /* Remove the last comma.  */
8319       text[strlen (text) - 2] = '\0';
8320       ui_out_field_string (uiout, "what", text);
8321     }
8322   else
8323     ui_out_field_string (uiout, "what", "<any syscall>");
8324   ui_out_text (uiout, "\" ");
8325
8326   if (ui_out_is_mi_like_p (uiout))
8327     ui_out_field_string (uiout, "catch-type", "syscall");
8328 }
8329
8330 /* Implement the "print_mention" breakpoint_ops method for syscall
8331    catchpoints.  */
8332
8333 static void
8334 print_mention_catch_syscall (struct breakpoint *b)
8335 {
8336   struct syscall_catchpoint *c = (struct syscall_catchpoint *) b;
8337
8338   if (c->syscalls_to_be_caught)
8339     {
8340       int i, iter;
8341
8342       if (VEC_length (int, c->syscalls_to_be_caught) > 1)
8343         printf_filtered (_("Catchpoint %d (syscalls"), b->number);
8344       else
8345         printf_filtered (_("Catchpoint %d (syscall"), b->number);
8346
8347       for (i = 0;
8348            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
8349            i++)
8350         {
8351           struct syscall s;
8352           get_syscall_by_number (iter, &s);
8353
8354           if (s.name)
8355             printf_filtered (" '%s' [%d]", s.name, s.number);
8356           else
8357             printf_filtered (" %d", s.number);
8358         }
8359       printf_filtered (")");
8360     }
8361   else
8362     printf_filtered (_("Catchpoint %d (any syscall)"),
8363                      b->number);
8364 }
8365
8366 /* Implement the "print_recreate" breakpoint_ops method for syscall
8367    catchpoints.  */
8368
8369 static void
8370 print_recreate_catch_syscall (struct breakpoint *b, struct ui_file *fp)
8371 {
8372   struct syscall_catchpoint *c = (struct syscall_catchpoint *) b;
8373
8374   fprintf_unfiltered (fp, "catch syscall");
8375
8376   if (c->syscalls_to_be_caught)
8377     {
8378       int i, iter;
8379
8380       for (i = 0;
8381            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
8382            i++)
8383         {
8384           struct syscall s;
8385
8386           get_syscall_by_number (iter, &s);
8387           if (s.name)
8388             fprintf_unfiltered (fp, " %s", s.name);
8389           else
8390             fprintf_unfiltered (fp, " %d", s.number);
8391         }
8392     }
8393   print_recreate_thread (b, fp);
8394 }
8395
8396 /* The breakpoint_ops structure to be used in syscall catchpoints.  */
8397
8398 static struct breakpoint_ops catch_syscall_breakpoint_ops;
8399
8400 /* Returns non-zero if 'b' is a syscall catchpoint.  */
8401
8402 static int
8403 syscall_catchpoint_p (struct breakpoint *b)
8404 {
8405   return (b->ops == &catch_syscall_breakpoint_ops);
8406 }
8407
8408 /* Initialize a new breakpoint of the bp_catchpoint kind.  If TEMPFLAG
8409    is non-zero, then make the breakpoint temporary.  If COND_STRING is
8410    not NULL, then store it in the breakpoint.  OPS, if not NULL, is
8411    the breakpoint_ops structure associated to the catchpoint.  */
8412
8413 void
8414 init_catchpoint (struct breakpoint *b,
8415                  struct gdbarch *gdbarch, int tempflag,
8416                  char *cond_string,
8417                  const struct breakpoint_ops *ops)
8418 {
8419   struct symtab_and_line sal;
8420
8421   init_sal (&sal);
8422   sal.pspace = current_program_space;
8423
8424   init_raw_breakpoint (b, gdbarch, sal, bp_catchpoint, ops);
8425
8426   b->cond_string = (cond_string == NULL) ? NULL : xstrdup (cond_string);
8427   b->disposition = tempflag ? disp_del : disp_donttouch;
8428 }
8429
8430 void
8431 install_breakpoint (int internal, struct breakpoint *b, int update_gll)
8432 {
8433   add_to_breakpoint_chain (b);
8434   set_breakpoint_number (internal, b);
8435   if (is_tracepoint (b))
8436     set_tracepoint_count (breakpoint_count);
8437   if (!internal)
8438     mention (b);
8439   observer_notify_breakpoint_created (b);
8440
8441   if (update_gll)
8442     update_global_location_list (1);
8443 }
8444
8445 static void
8446 create_fork_vfork_event_catchpoint (struct gdbarch *gdbarch,
8447                                     int tempflag, char *cond_string,
8448                                     const struct breakpoint_ops *ops)
8449 {
8450   struct fork_catchpoint *c = XNEW (struct fork_catchpoint);
8451
8452   init_catchpoint (&c->base, gdbarch, tempflag, cond_string, ops);
8453
8454   c->forked_inferior_pid = null_ptid;
8455
8456   install_breakpoint (0, &c->base, 1);
8457 }
8458
8459 /* Exec catchpoints.  */
8460
8461 /* An instance of this type is used to represent an exec catchpoint.
8462    It includes a "struct breakpoint" as a kind of base class; users
8463    downcast to "struct breakpoint *" when needed.  A breakpoint is
8464    really of this type iff its ops pointer points to
8465    CATCH_EXEC_BREAKPOINT_OPS.  */
8466
8467 struct exec_catchpoint
8468 {
8469   /* The base class.  */
8470   struct breakpoint base;
8471
8472   /* Filename of a program whose exec triggered this catchpoint.
8473      This field is only valid immediately after this catchpoint has
8474      triggered.  */
8475   char *exec_pathname;
8476 };
8477
8478 /* Implement the "dtor" breakpoint_ops method for exec
8479    catchpoints.  */
8480
8481 static void
8482 dtor_catch_exec (struct breakpoint *b)
8483 {
8484   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
8485
8486   xfree (c->exec_pathname);
8487
8488   base_breakpoint_ops.dtor (b);
8489 }
8490
8491 static int
8492 insert_catch_exec (struct bp_location *bl)
8493 {
8494   return target_insert_exec_catchpoint (PIDGET (inferior_ptid));
8495 }
8496
8497 static int
8498 remove_catch_exec (struct bp_location *bl)
8499 {
8500   return target_remove_exec_catchpoint (PIDGET (inferior_ptid));
8501 }
8502
8503 static int
8504 breakpoint_hit_catch_exec (const struct bp_location *bl,
8505                            struct address_space *aspace, CORE_ADDR bp_addr,
8506                            const struct target_waitstatus *ws)
8507 {
8508   struct exec_catchpoint *c = (struct exec_catchpoint *) bl->owner;
8509
8510   if (ws->kind != TARGET_WAITKIND_EXECD)
8511     return 0;
8512
8513   c->exec_pathname = xstrdup (ws->value.execd_pathname);
8514   return 1;
8515 }
8516
8517 static enum print_stop_action
8518 print_it_catch_exec (bpstat bs)
8519 {
8520   struct ui_out *uiout = current_uiout;
8521   struct breakpoint *b = bs->breakpoint_at;
8522   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
8523
8524   annotate_catchpoint (b->number);
8525   if (b->disposition == disp_del)
8526     ui_out_text (uiout, "\nTemporary catchpoint ");
8527   else
8528     ui_out_text (uiout, "\nCatchpoint ");
8529   if (ui_out_is_mi_like_p (uiout))
8530     {
8531       ui_out_field_string (uiout, "reason",
8532                            async_reason_lookup (EXEC_ASYNC_EXEC));
8533       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
8534     }
8535   ui_out_field_int (uiout, "bkptno", b->number);
8536   ui_out_text (uiout, " (exec'd ");
8537   ui_out_field_string (uiout, "new-exec", c->exec_pathname);
8538   ui_out_text (uiout, "), ");
8539
8540   return PRINT_SRC_AND_LOC;
8541 }
8542
8543 static void
8544 print_one_catch_exec (struct breakpoint *b, struct bp_location **last_loc)
8545 {
8546   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
8547   struct value_print_options opts;
8548   struct ui_out *uiout = current_uiout;
8549
8550   get_user_print_options (&opts);
8551
8552   /* Field 4, the address, is omitted (which makes the columns
8553      not line up too nicely with the headers, but the effect
8554      is relatively readable).  */
8555   if (opts.addressprint)
8556     ui_out_field_skip (uiout, "addr");
8557   annotate_field (5);
8558   ui_out_text (uiout, "exec");
8559   if (c->exec_pathname != NULL)
8560     {
8561       ui_out_text (uiout, ", program \"");
8562       ui_out_field_string (uiout, "what", c->exec_pathname);
8563       ui_out_text (uiout, "\" ");
8564     }
8565
8566   if (ui_out_is_mi_like_p (uiout))
8567     ui_out_field_string (uiout, "catch-type", "exec");
8568 }
8569
8570 static void
8571 print_mention_catch_exec (struct breakpoint *b)
8572 {
8573   printf_filtered (_("Catchpoint %d (exec)"), b->number);
8574 }
8575
8576 /* Implement the "print_recreate" breakpoint_ops method for exec
8577    catchpoints.  */
8578
8579 static void
8580 print_recreate_catch_exec (struct breakpoint *b, struct ui_file *fp)
8581 {
8582   fprintf_unfiltered (fp, "catch exec");
8583   print_recreate_thread (b, fp);
8584 }
8585
8586 static struct breakpoint_ops catch_exec_breakpoint_ops;
8587
8588 static void
8589 create_syscall_event_catchpoint (int tempflag, VEC(int) *filter,
8590                                  const struct breakpoint_ops *ops)
8591 {
8592   struct syscall_catchpoint *c;
8593   struct gdbarch *gdbarch = get_current_arch ();
8594
8595   c = XNEW (struct syscall_catchpoint);
8596   init_catchpoint (&c->base, gdbarch, tempflag, NULL, ops);
8597   c->syscalls_to_be_caught = filter;
8598
8599   install_breakpoint (0, &c->base, 1);
8600 }
8601
8602 static int
8603 hw_breakpoint_used_count (void)
8604 {
8605   int i = 0;
8606   struct breakpoint *b;
8607   struct bp_location *bl;
8608
8609   ALL_BREAKPOINTS (b)
8610   {
8611     if (b->type == bp_hardware_breakpoint && breakpoint_enabled (b))
8612       for (bl = b->loc; bl; bl = bl->next)
8613         {
8614           /* Special types of hardware breakpoints may use more than
8615              one register.  */
8616           i += b->ops->resources_needed (bl);
8617         }
8618   }
8619
8620   return i;
8621 }
8622
8623 /* Returns the resources B would use if it were a hardware
8624    watchpoint.  */
8625
8626 static int
8627 hw_watchpoint_use_count (struct breakpoint *b)
8628 {
8629   int i = 0;
8630   struct bp_location *bl;
8631
8632   if (!breakpoint_enabled (b))
8633     return 0;
8634
8635   for (bl = b->loc; bl; bl = bl->next)
8636     {
8637       /* Special types of hardware watchpoints may use more than
8638          one register.  */
8639       i += b->ops->resources_needed (bl);
8640     }
8641
8642   return i;
8643 }
8644
8645 /* Returns the sum the used resources of all hardware watchpoints of
8646    type TYPE in the breakpoints list.  Also returns in OTHER_TYPE_USED
8647    the sum of the used resources of all hardware watchpoints of other
8648    types _not_ TYPE.  */
8649
8650 static int
8651 hw_watchpoint_used_count_others (struct breakpoint *except,
8652                                  enum bptype type, int *other_type_used)
8653 {
8654   int i = 0;
8655   struct breakpoint *b;
8656
8657   *other_type_used = 0;
8658   ALL_BREAKPOINTS (b)
8659     {
8660       if (b == except)
8661         continue;
8662       if (!breakpoint_enabled (b))
8663         continue;
8664
8665       if (b->type == type)
8666         i += hw_watchpoint_use_count (b);
8667       else if (is_hardware_watchpoint (b))
8668         *other_type_used = 1;
8669     }
8670
8671   return i;
8672 }
8673
8674 void
8675 disable_watchpoints_before_interactive_call_start (void)
8676 {
8677   struct breakpoint *b;
8678
8679   ALL_BREAKPOINTS (b)
8680   {
8681     if (is_watchpoint (b) && breakpoint_enabled (b))
8682       {
8683         b->enable_state = bp_call_disabled;
8684         update_global_location_list (0);
8685       }
8686   }
8687 }
8688
8689 void
8690 enable_watchpoints_after_interactive_call_stop (void)
8691 {
8692   struct breakpoint *b;
8693
8694   ALL_BREAKPOINTS (b)
8695   {
8696     if (is_watchpoint (b) && b->enable_state == bp_call_disabled)
8697       {
8698         b->enable_state = bp_enabled;
8699         update_global_location_list (1);
8700       }
8701   }
8702 }
8703
8704 void
8705 disable_breakpoints_before_startup (void)
8706 {
8707   current_program_space->executing_startup = 1;
8708   update_global_location_list (0);
8709 }
8710
8711 void
8712 enable_breakpoints_after_startup (void)
8713 {
8714   current_program_space->executing_startup = 0;
8715   breakpoint_re_set ();
8716 }
8717
8718
8719 /* Set a breakpoint that will evaporate an end of command
8720    at address specified by SAL.
8721    Restrict it to frame FRAME if FRAME is nonzero.  */
8722
8723 struct breakpoint *
8724 set_momentary_breakpoint (struct gdbarch *gdbarch, struct symtab_and_line sal,
8725                           struct frame_id frame_id, enum bptype type)
8726 {
8727   struct breakpoint *b;
8728
8729   /* If FRAME_ID is valid, it should be a real frame, not an inlined or
8730      tail-called one.  */
8731   gdb_assert (!frame_id_artificial_p (frame_id));
8732
8733   b = set_raw_breakpoint (gdbarch, sal, type, &momentary_breakpoint_ops);
8734   b->enable_state = bp_enabled;
8735   b->disposition = disp_donttouch;
8736   b->frame_id = frame_id;
8737
8738   /* If we're debugging a multi-threaded program, then we want
8739      momentary breakpoints to be active in only a single thread of
8740      control.  */
8741   if (in_thread_list (inferior_ptid))
8742     b->thread = pid_to_thread_id (inferior_ptid);
8743
8744   update_global_location_list_nothrow (1);
8745
8746   return b;
8747 }
8748
8749 /* Make a momentary breakpoint based on the master breakpoint ORIG.
8750    The new breakpoint will have type TYPE, and use OPS as it
8751    breakpoint_ops.  */
8752
8753 static struct breakpoint *
8754 momentary_breakpoint_from_master (struct breakpoint *orig,
8755                                   enum bptype type,
8756                                   const struct breakpoint_ops *ops)
8757 {
8758   struct breakpoint *copy;
8759
8760   copy = set_raw_breakpoint_without_location (orig->gdbarch, type, ops);
8761   copy->loc = allocate_bp_location (copy);
8762   set_breakpoint_location_function (copy->loc, 1);
8763
8764   copy->loc->gdbarch = orig->loc->gdbarch;
8765   copy->loc->requested_address = orig->loc->requested_address;
8766   copy->loc->address = orig->loc->address;
8767   copy->loc->section = orig->loc->section;
8768   copy->loc->pspace = orig->loc->pspace;
8769   copy->loc->probe = orig->loc->probe;
8770   copy->loc->line_number = orig->loc->line_number;
8771   copy->loc->symtab = orig->loc->symtab;
8772   copy->frame_id = orig->frame_id;
8773   copy->thread = orig->thread;
8774   copy->pspace = orig->pspace;
8775
8776   copy->enable_state = bp_enabled;
8777   copy->disposition = disp_donttouch;
8778   copy->number = internal_breakpoint_number--;
8779
8780   update_global_location_list_nothrow (0);
8781   return copy;
8782 }
8783
8784 /* Make a deep copy of momentary breakpoint ORIG.  Returns NULL if
8785    ORIG is NULL.  */
8786
8787 struct breakpoint *
8788 clone_momentary_breakpoint (struct breakpoint *orig)
8789 {
8790   /* If there's nothing to clone, then return nothing.  */
8791   if (orig == NULL)
8792     return NULL;
8793
8794   return momentary_breakpoint_from_master (orig, orig->type, orig->ops);
8795 }
8796
8797 struct breakpoint *
8798 set_momentary_breakpoint_at_pc (struct gdbarch *gdbarch, CORE_ADDR pc,
8799                                 enum bptype type)
8800 {
8801   struct symtab_and_line sal;
8802
8803   sal = find_pc_line (pc, 0);
8804   sal.pc = pc;
8805   sal.section = find_pc_overlay (pc);
8806   sal.explicit_pc = 1;
8807
8808   return set_momentary_breakpoint (gdbarch, sal, null_frame_id, type);
8809 }
8810 \f
8811
8812 /* Tell the user we have just set a breakpoint B.  */
8813
8814 static void
8815 mention (struct breakpoint *b)
8816 {
8817   b->ops->print_mention (b);
8818   if (ui_out_is_mi_like_p (current_uiout))
8819     return;
8820   printf_filtered ("\n");
8821 }
8822 \f
8823
8824 static struct bp_location *
8825 add_location_to_breakpoint (struct breakpoint *b,
8826                             const struct symtab_and_line *sal)
8827 {
8828   struct bp_location *loc, **tmp;
8829   CORE_ADDR adjusted_address;
8830   struct gdbarch *loc_gdbarch = get_sal_arch (*sal);
8831
8832   if (loc_gdbarch == NULL)
8833     loc_gdbarch = b->gdbarch;
8834
8835   /* Adjust the breakpoint's address prior to allocating a location.
8836      Once we call allocate_bp_location(), that mostly uninitialized
8837      location will be placed on the location chain.  Adjustment of the
8838      breakpoint may cause target_read_memory() to be called and we do
8839      not want its scan of the location chain to find a breakpoint and
8840      location that's only been partially initialized.  */
8841   adjusted_address = adjust_breakpoint_address (loc_gdbarch,
8842                                                 sal->pc, b->type);
8843
8844   /* Sort the locations by their ADDRESS.  */
8845   loc = allocate_bp_location (b);
8846   for (tmp = &(b->loc); *tmp != NULL && (*tmp)->address <= adjusted_address;
8847        tmp = &((*tmp)->next))
8848     ;
8849   loc->next = *tmp;
8850   *tmp = loc;
8851
8852   loc->requested_address = sal->pc;
8853   loc->address = adjusted_address;
8854   loc->pspace = sal->pspace;
8855   loc->probe = sal->probe;
8856   gdb_assert (loc->pspace != NULL);
8857   loc->section = sal->section;
8858   loc->gdbarch = loc_gdbarch;
8859   loc->line_number = sal->line;
8860   loc->symtab = sal->symtab;
8861
8862   set_breakpoint_location_function (loc,
8863                                     sal->explicit_pc || sal->explicit_line);
8864   return loc;
8865 }
8866 \f
8867
8868 /* Return 1 if LOC is pointing to a permanent breakpoint, 
8869    return 0 otherwise.  */
8870
8871 static int
8872 bp_loc_is_permanent (struct bp_location *loc)
8873 {
8874   int len;
8875   CORE_ADDR addr;
8876   const gdb_byte *bpoint;
8877   gdb_byte *target_mem;
8878   struct cleanup *cleanup;
8879   int retval = 0;
8880
8881   gdb_assert (loc != NULL);
8882
8883   addr = loc->address;
8884   bpoint = gdbarch_breakpoint_from_pc (loc->gdbarch, &addr, &len);
8885
8886   /* Software breakpoints unsupported?  */
8887   if (bpoint == NULL)
8888     return 0;
8889
8890   target_mem = alloca (len);
8891
8892   /* Enable the automatic memory restoration from breakpoints while
8893      we read the memory.  Otherwise we could say about our temporary
8894      breakpoints they are permanent.  */
8895   cleanup = save_current_space_and_thread ();
8896
8897   switch_to_program_space_and_thread (loc->pspace);
8898   make_show_memory_breakpoints_cleanup (0);
8899
8900   if (target_read_memory (loc->address, target_mem, len) == 0
8901       && memcmp (target_mem, bpoint, len) == 0)
8902     retval = 1;
8903
8904   do_cleanups (cleanup);
8905
8906   return retval;
8907 }
8908
8909 /* Build a command list for the dprintf corresponding to the current
8910    settings of the dprintf style options.  */
8911
8912 static void
8913 update_dprintf_command_list (struct breakpoint *b)
8914 {
8915   char *dprintf_args = b->extra_string;
8916   char *printf_line = NULL;
8917
8918   if (!dprintf_args)
8919     return;
8920
8921   dprintf_args = skip_spaces (dprintf_args);
8922
8923   /* Allow a comma, as it may have terminated a location, but don't
8924      insist on it.  */
8925   if (*dprintf_args == ',')
8926     ++dprintf_args;
8927   dprintf_args = skip_spaces (dprintf_args);
8928
8929   if (*dprintf_args != '"')
8930     error (_("Bad format string, missing '\"'."));
8931
8932   if (strcmp (dprintf_style, dprintf_style_gdb) == 0)
8933     printf_line = xstrprintf ("printf %s", dprintf_args);
8934   else if (strcmp (dprintf_style, dprintf_style_call) == 0)
8935     {
8936       if (!dprintf_function)
8937         error (_("No function supplied for dprintf call"));
8938
8939       if (dprintf_channel && strlen (dprintf_channel) > 0)
8940         printf_line = xstrprintf ("call (void) %s (%s,%s)",
8941                                   dprintf_function,
8942                                   dprintf_channel,
8943                                   dprintf_args);
8944       else
8945         printf_line = xstrprintf ("call (void) %s (%s)",
8946                                   dprintf_function,
8947                                   dprintf_args);
8948     }
8949   else if (strcmp (dprintf_style, dprintf_style_agent) == 0)
8950     {
8951       if (target_can_run_breakpoint_commands ())
8952         printf_line = xstrprintf ("agent-printf %s", dprintf_args);
8953       else
8954         {
8955           warning (_("Target cannot run dprintf commands, falling back to GDB printf"));
8956           printf_line = xstrprintf ("printf %s", dprintf_args);
8957         }
8958     }
8959   else
8960     internal_error (__FILE__, __LINE__,
8961                     _("Invalid dprintf style."));
8962
8963   gdb_assert (printf_line != NULL);
8964   /* Manufacture a printf/continue sequence.  */
8965   {
8966     struct command_line *printf_cmd_line, *cont_cmd_line = NULL;
8967
8968     if (strcmp (dprintf_style, dprintf_style_agent) != 0)
8969       {
8970         cont_cmd_line = xmalloc (sizeof (struct command_line));
8971         cont_cmd_line->control_type = simple_control;
8972         cont_cmd_line->body_count = 0;
8973         cont_cmd_line->body_list = NULL;
8974         cont_cmd_line->next = NULL;
8975         cont_cmd_line->line = xstrdup ("continue");
8976       }
8977
8978     printf_cmd_line = xmalloc (sizeof (struct command_line));
8979     printf_cmd_line->control_type = simple_control;
8980     printf_cmd_line->body_count = 0;
8981     printf_cmd_line->body_list = NULL;
8982     printf_cmd_line->next = cont_cmd_line;
8983     printf_cmd_line->line = printf_line;
8984
8985     breakpoint_set_commands (b, printf_cmd_line);
8986   }
8987 }
8988
8989 /* Update all dprintf commands, making their command lists reflect
8990    current style settings.  */
8991
8992 static void
8993 update_dprintf_commands (char *args, int from_tty,
8994                          struct cmd_list_element *c)
8995 {
8996   struct breakpoint *b;
8997
8998   ALL_BREAKPOINTS (b)
8999     {
9000       if (b->type == bp_dprintf)
9001         update_dprintf_command_list (b);
9002     }
9003 }
9004
9005 /* Create a breakpoint with SAL as location.  Use ADDR_STRING
9006    as textual description of the location, and COND_STRING
9007    as condition expression.  */
9008
9009 static void
9010 init_breakpoint_sal (struct breakpoint *b, struct gdbarch *gdbarch,
9011                      struct symtabs_and_lines sals, char *addr_string,
9012                      char *filter, char *cond_string,
9013                      char *extra_string,
9014                      enum bptype type, enum bpdisp disposition,
9015                      int thread, int task, int ignore_count,
9016                      const struct breakpoint_ops *ops, int from_tty,
9017                      int enabled, int internal, unsigned flags,
9018                      int display_canonical)
9019 {
9020   int i;
9021
9022   if (type == bp_hardware_breakpoint)
9023     {
9024       int target_resources_ok;
9025
9026       i = hw_breakpoint_used_count ();
9027       target_resources_ok =
9028         target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
9029                                             i + 1, 0);
9030       if (target_resources_ok == 0)
9031         error (_("No hardware breakpoint support in the target."));
9032       else if (target_resources_ok < 0)
9033         error (_("Hardware breakpoints used exceeds limit."));
9034     }
9035
9036   gdb_assert (sals.nelts > 0);
9037
9038   for (i = 0; i < sals.nelts; ++i)
9039     {
9040       struct symtab_and_line sal = sals.sals[i];
9041       struct bp_location *loc;
9042
9043       if (from_tty)
9044         {
9045           struct gdbarch *loc_gdbarch = get_sal_arch (sal);
9046           if (!loc_gdbarch)
9047             loc_gdbarch = gdbarch;
9048
9049           describe_other_breakpoints (loc_gdbarch,
9050                                       sal.pspace, sal.pc, sal.section, thread);
9051         }
9052
9053       if (i == 0)
9054         {
9055           init_raw_breakpoint (b, gdbarch, sal, type, ops);
9056           b->thread = thread;
9057           b->task = task;
9058
9059           b->cond_string = cond_string;
9060           b->extra_string = extra_string;
9061           b->ignore_count = ignore_count;
9062           b->enable_state = enabled ? bp_enabled : bp_disabled;
9063           b->disposition = disposition;
9064
9065           if ((flags & CREATE_BREAKPOINT_FLAGS_INSERTED) != 0)
9066             b->loc->inserted = 1;
9067
9068           if (type == bp_static_tracepoint)
9069             {
9070               struct tracepoint *t = (struct tracepoint *) b;
9071               struct static_tracepoint_marker marker;
9072
9073               if (strace_marker_p (b))
9074                 {
9075                   /* We already know the marker exists, otherwise, we
9076                      wouldn't see a sal for it.  */
9077                   char *p = &addr_string[3];
9078                   char *endp;
9079                   char *marker_str;
9080
9081                   p = skip_spaces (p);
9082
9083                   endp = skip_to_space (p);
9084
9085                   marker_str = savestring (p, endp - p);
9086                   t->static_trace_marker_id = marker_str;
9087
9088                   printf_filtered (_("Probed static tracepoint "
9089                                      "marker \"%s\"\n"),
9090                                    t->static_trace_marker_id);
9091                 }
9092               else if (target_static_tracepoint_marker_at (sal.pc, &marker))
9093                 {
9094                   t->static_trace_marker_id = xstrdup (marker.str_id);
9095                   release_static_tracepoint_marker (&marker);
9096
9097                   printf_filtered (_("Probed static tracepoint "
9098                                      "marker \"%s\"\n"),
9099                                    t->static_trace_marker_id);
9100                 }
9101               else
9102                 warning (_("Couldn't determine the static "
9103                            "tracepoint marker to probe"));
9104             }
9105
9106           loc = b->loc;
9107         }
9108       else
9109         {
9110           loc = add_location_to_breakpoint (b, &sal);
9111           if ((flags & CREATE_BREAKPOINT_FLAGS_INSERTED) != 0)
9112             loc->inserted = 1;
9113         }
9114
9115       if (bp_loc_is_permanent (loc))
9116         make_breakpoint_permanent (b);
9117
9118       if (b->cond_string)
9119         {
9120           const char *arg = b->cond_string;
9121
9122           loc->cond = parse_exp_1 (&arg, loc->address,
9123                                    block_for_pc (loc->address), 0);
9124           if (*arg)
9125               error (_("Garbage '%s' follows condition"), arg);
9126         }
9127
9128       /* Dynamic printf requires and uses additional arguments on the
9129          command line, otherwise it's an error.  */
9130       if (type == bp_dprintf)
9131         {
9132           if (b->extra_string)
9133             update_dprintf_command_list (b);
9134           else
9135             error (_("Format string required"));
9136         }
9137       else if (b->extra_string)
9138         error (_("Garbage '%s' at end of command"), b->extra_string);
9139     }
9140
9141   b->display_canonical = display_canonical;
9142   if (addr_string)
9143     b->addr_string = addr_string;
9144   else
9145     /* addr_string has to be used or breakpoint_re_set will delete
9146        me.  */
9147     b->addr_string
9148       = xstrprintf ("*%s", paddress (b->loc->gdbarch, b->loc->address));
9149   b->filter = filter;
9150 }
9151
9152 static void
9153 create_breakpoint_sal (struct gdbarch *gdbarch,
9154                        struct symtabs_and_lines sals, char *addr_string,
9155                        char *filter, char *cond_string,
9156                        char *extra_string,
9157                        enum bptype type, enum bpdisp disposition,
9158                        int thread, int task, int ignore_count,
9159                        const struct breakpoint_ops *ops, int from_tty,
9160                        int enabled, int internal, unsigned flags,
9161                        int display_canonical)
9162 {
9163   struct breakpoint *b;
9164   struct cleanup *old_chain;
9165
9166   if (is_tracepoint_type (type))
9167     {
9168       struct tracepoint *t;
9169
9170       t = XCNEW (struct tracepoint);
9171       b = &t->base;
9172     }
9173   else
9174     b = XNEW (struct breakpoint);
9175
9176   old_chain = make_cleanup (xfree, b);
9177
9178   init_breakpoint_sal (b, gdbarch,
9179                        sals, addr_string,
9180                        filter, cond_string, extra_string,
9181                        type, disposition,
9182                        thread, task, ignore_count,
9183                        ops, from_tty,
9184                        enabled, internal, flags,
9185                        display_canonical);
9186   discard_cleanups (old_chain);
9187
9188   install_breakpoint (internal, b, 0);
9189 }
9190
9191 /* Add SALS.nelts breakpoints to the breakpoint table.  For each
9192    SALS.sal[i] breakpoint, include the corresponding ADDR_STRING[i]
9193    value.  COND_STRING, if not NULL, specified the condition to be
9194    used for all breakpoints.  Essentially the only case where
9195    SALS.nelts is not 1 is when we set a breakpoint on an overloaded
9196    function.  In that case, it's still not possible to specify
9197    separate conditions for different overloaded functions, so
9198    we take just a single condition string.
9199    
9200    NOTE: If the function succeeds, the caller is expected to cleanup
9201    the arrays ADDR_STRING, COND_STRING, and SALS (but not the
9202    array contents).  If the function fails (error() is called), the
9203    caller is expected to cleanups both the ADDR_STRING, COND_STRING,
9204    COND and SALS arrays and each of those arrays contents.  */
9205
9206 static void
9207 create_breakpoints_sal (struct gdbarch *gdbarch,
9208                         struct linespec_result *canonical,
9209                         char *cond_string, char *extra_string,
9210                         enum bptype type, enum bpdisp disposition,
9211                         int thread, int task, int ignore_count,
9212                         const struct breakpoint_ops *ops, int from_tty,
9213                         int enabled, int internal, unsigned flags)
9214 {
9215   int i;
9216   struct linespec_sals *lsal;
9217
9218   if (canonical->pre_expanded)
9219     gdb_assert (VEC_length (linespec_sals, canonical->sals) == 1);
9220
9221   for (i = 0; VEC_iterate (linespec_sals, canonical->sals, i, lsal); ++i)
9222     {
9223       /* Note that 'addr_string' can be NULL in the case of a plain
9224          'break', without arguments.  */
9225       char *addr_string = (canonical->addr_string
9226                            ? xstrdup (canonical->addr_string)
9227                            : NULL);
9228       char *filter_string = lsal->canonical ? xstrdup (lsal->canonical) : NULL;
9229       struct cleanup *inner = make_cleanup (xfree, addr_string);
9230
9231       make_cleanup (xfree, filter_string);
9232       create_breakpoint_sal (gdbarch, lsal->sals,
9233                              addr_string,
9234                              filter_string,
9235                              cond_string, extra_string,
9236                              type, disposition,
9237                              thread, task, ignore_count, ops,
9238                              from_tty, enabled, internal, flags,
9239                              canonical->special_display);
9240       discard_cleanups (inner);
9241     }
9242 }
9243
9244 /* Parse ADDRESS which is assumed to be a SAL specification possibly
9245    followed by conditionals.  On return, SALS contains an array of SAL
9246    addresses found.  ADDR_STRING contains a vector of (canonical)
9247    address strings.  ADDRESS points to the end of the SAL.
9248
9249    The array and the line spec strings are allocated on the heap, it is
9250    the caller's responsibility to free them.  */
9251
9252 static void
9253 parse_breakpoint_sals (char **address,
9254                        struct linespec_result *canonical)
9255 {
9256   /* If no arg given, or if first arg is 'if ', use the default
9257      breakpoint.  */
9258   if ((*address) == NULL
9259       || (strncmp ((*address), "if", 2) == 0 && isspace ((*address)[2])))
9260     {
9261       /* The last displayed codepoint, if it's valid, is our default breakpoint
9262          address.  */
9263       if (last_displayed_sal_is_valid ())
9264         {
9265           struct linespec_sals lsal;
9266           struct symtab_and_line sal;
9267           CORE_ADDR pc;
9268
9269           init_sal (&sal);              /* Initialize to zeroes.  */
9270           lsal.sals.sals = (struct symtab_and_line *)
9271             xmalloc (sizeof (struct symtab_and_line));
9272
9273           /* Set sal's pspace, pc, symtab, and line to the values
9274              corresponding to the last call to print_frame_info.
9275              Be sure to reinitialize LINE with NOTCURRENT == 0
9276              as the breakpoint line number is inappropriate otherwise.
9277              find_pc_line would adjust PC, re-set it back.  */
9278           get_last_displayed_sal (&sal);
9279           pc = sal.pc;
9280           sal = find_pc_line (pc, 0);
9281
9282           /* "break" without arguments is equivalent to "break *PC"
9283              where PC is the last displayed codepoint's address.  So
9284              make sure to set sal.explicit_pc to prevent GDB from
9285              trying to expand the list of sals to include all other
9286              instances with the same symtab and line.  */
9287           sal.pc = pc;
9288           sal.explicit_pc = 1;
9289
9290           lsal.sals.sals[0] = sal;
9291           lsal.sals.nelts = 1;
9292           lsal.canonical = NULL;
9293
9294           VEC_safe_push (linespec_sals, canonical->sals, &lsal);
9295         }
9296       else
9297         error (_("No default breakpoint address now."));
9298     }
9299   else
9300     {
9301       struct symtab_and_line cursal = get_current_source_symtab_and_line ();
9302
9303       /* Force almost all breakpoints to be in terms of the
9304          current_source_symtab (which is decode_line_1's default).
9305          This should produce the results we want almost all of the
9306          time while leaving default_breakpoint_* alone.
9307
9308          ObjC: However, don't match an Objective-C method name which
9309          may have a '+' or '-' succeeded by a '['.  */
9310       if (last_displayed_sal_is_valid ()
9311           && (!cursal.symtab
9312               || ((strchr ("+-", (*address)[0]) != NULL)
9313                   && ((*address)[1] != '['))))
9314         decode_line_full (address, DECODE_LINE_FUNFIRSTLINE,
9315                           get_last_displayed_symtab (),
9316                           get_last_displayed_line (),
9317                           canonical, NULL, NULL);
9318       else
9319         decode_line_full (address, DECODE_LINE_FUNFIRSTLINE,
9320                           cursal.symtab, cursal.line, canonical, NULL, NULL);
9321     }
9322 }
9323
9324
9325 /* Convert each SAL into a real PC.  Verify that the PC can be
9326    inserted as a breakpoint.  If it can't throw an error.  */
9327
9328 static void
9329 breakpoint_sals_to_pc (struct symtabs_and_lines *sals)
9330 {    
9331   int i;
9332
9333   for (i = 0; i < sals->nelts; i++)
9334     resolve_sal_pc (&sals->sals[i]);
9335 }
9336
9337 /* Fast tracepoints may have restrictions on valid locations.  For
9338    instance, a fast tracepoint using a jump instead of a trap will
9339    likely have to overwrite more bytes than a trap would, and so can
9340    only be placed where the instruction is longer than the jump, or a
9341    multi-instruction sequence does not have a jump into the middle of
9342    it, etc.  */
9343
9344 static void
9345 check_fast_tracepoint_sals (struct gdbarch *gdbarch,
9346                             struct symtabs_and_lines *sals)
9347 {
9348   int i, rslt;
9349   struct symtab_and_line *sal;
9350   char *msg;
9351   struct cleanup *old_chain;
9352
9353   for (i = 0; i < sals->nelts; i++)
9354     {
9355       struct gdbarch *sarch;
9356
9357       sal = &sals->sals[i];
9358
9359       sarch = get_sal_arch (*sal);
9360       /* We fall back to GDBARCH if there is no architecture
9361          associated with SAL.  */
9362       if (sarch == NULL)
9363         sarch = gdbarch;
9364       rslt = gdbarch_fast_tracepoint_valid_at (sarch, sal->pc,
9365                                                NULL, &msg);
9366       old_chain = make_cleanup (xfree, msg);
9367
9368       if (!rslt)
9369         error (_("May not have a fast tracepoint at 0x%s%s"),
9370                paddress (sarch, sal->pc), (msg ? msg : ""));
9371
9372       do_cleanups (old_chain);
9373     }
9374 }
9375
9376 /* Issue an invalid thread ID error.  */
9377
9378 static void ATTRIBUTE_NORETURN
9379 invalid_thread_id_error (int id)
9380 {
9381   error (_("Unknown thread %d."), id);
9382 }
9383
9384 /* Given TOK, a string specification of condition and thread, as
9385    accepted by the 'break' command, extract the condition
9386    string and thread number and set *COND_STRING and *THREAD.
9387    PC identifies the context at which the condition should be parsed.
9388    If no condition is found, *COND_STRING is set to NULL.
9389    If no thread is found, *THREAD is set to -1.  */
9390
9391 static void
9392 find_condition_and_thread (const char *tok, CORE_ADDR pc,
9393                            char **cond_string, int *thread, int *task,
9394                            char **rest)
9395 {
9396   *cond_string = NULL;
9397   *thread = -1;
9398   *task = 0;
9399   *rest = NULL;
9400
9401   while (tok && *tok)
9402     {
9403       const char *end_tok;
9404       int toklen;
9405       const char *cond_start = NULL;
9406       const char *cond_end = NULL;
9407
9408       tok = skip_spaces_const (tok);
9409
9410       if ((*tok == '"' || *tok == ',') && rest)
9411         {
9412           *rest = savestring (tok, strlen (tok));
9413           return;
9414         }
9415
9416       end_tok = skip_to_space_const (tok);
9417
9418       toklen = end_tok - tok;
9419
9420       if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
9421         {
9422           struct expression *expr;
9423
9424           tok = cond_start = end_tok + 1;
9425           expr = parse_exp_1 (&tok, pc, block_for_pc (pc), 0);
9426           xfree (expr);
9427           cond_end = tok;
9428           *cond_string = savestring (cond_start, cond_end - cond_start);
9429         }
9430       else if (toklen >= 1 && strncmp (tok, "thread", toklen) == 0)
9431         {
9432           char *tmptok;
9433
9434           tok = end_tok + 1;
9435           *thread = strtol (tok, &tmptok, 0);
9436           if (tok == tmptok)
9437             error (_("Junk after thread keyword."));
9438           if (!valid_thread_id (*thread))
9439             invalid_thread_id_error (*thread);
9440           tok = tmptok;
9441         }
9442       else if (toklen >= 1 && strncmp (tok, "task", toklen) == 0)
9443         {
9444           char *tmptok;
9445
9446           tok = end_tok + 1;
9447           *task = strtol (tok, &tmptok, 0);
9448           if (tok == tmptok)
9449             error (_("Junk after task keyword."));
9450           if (!valid_task_id (*task))
9451             error (_("Unknown task %d."), *task);
9452           tok = tmptok;
9453         }
9454       else if (rest)
9455         {
9456           *rest = savestring (tok, strlen (tok));
9457           return;
9458         }
9459       else
9460         error (_("Junk at end of arguments."));
9461     }
9462 }
9463
9464 /* Decode a static tracepoint marker spec.  */
9465
9466 static struct symtabs_and_lines
9467 decode_static_tracepoint_spec (char **arg_p)
9468 {
9469   VEC(static_tracepoint_marker_p) *markers = NULL;
9470   struct symtabs_and_lines sals;
9471   struct cleanup *old_chain;
9472   char *p = &(*arg_p)[3];
9473   char *endp;
9474   char *marker_str;
9475   int i;
9476
9477   p = skip_spaces (p);
9478
9479   endp = skip_to_space (p);
9480
9481   marker_str = savestring (p, endp - p);
9482   old_chain = make_cleanup (xfree, marker_str);
9483
9484   markers = target_static_tracepoint_markers_by_strid (marker_str);
9485   if (VEC_empty(static_tracepoint_marker_p, markers))
9486     error (_("No known static tracepoint marker named %s"), marker_str);
9487
9488   sals.nelts = VEC_length(static_tracepoint_marker_p, markers);
9489   sals.sals = xmalloc (sizeof *sals.sals * sals.nelts);
9490
9491   for (i = 0; i < sals.nelts; i++)
9492     {
9493       struct static_tracepoint_marker *marker;
9494
9495       marker = VEC_index (static_tracepoint_marker_p, markers, i);
9496
9497       init_sal (&sals.sals[i]);
9498
9499       sals.sals[i] = find_pc_line (marker->address, 0);
9500       sals.sals[i].pc = marker->address;
9501
9502       release_static_tracepoint_marker (marker);
9503     }
9504
9505   do_cleanups (old_chain);
9506
9507   *arg_p = endp;
9508   return sals;
9509 }
9510
9511 /* Set a breakpoint.  This function is shared between CLI and MI
9512    functions for setting a breakpoint.  This function has two major
9513    modes of operations, selected by the PARSE_CONDITION_AND_THREAD
9514    parameter.  If non-zero, the function will parse arg, extracting
9515    breakpoint location, address and thread.  Otherwise, ARG is just
9516    the location of breakpoint, with condition and thread specified by
9517    the COND_STRING and THREAD parameters.  If INTERNAL is non-zero,
9518    the breakpoint number will be allocated from the internal
9519    breakpoint count.  Returns true if any breakpoint was created;
9520    false otherwise.  */
9521
9522 int
9523 create_breakpoint (struct gdbarch *gdbarch,
9524                    char *arg, char *cond_string,
9525                    int thread, char *extra_string,
9526                    int parse_condition_and_thread,
9527                    int tempflag, enum bptype type_wanted,
9528                    int ignore_count,
9529                    enum auto_boolean pending_break_support,
9530                    const struct breakpoint_ops *ops,
9531                    int from_tty, int enabled, int internal,
9532                    unsigned flags)
9533 {
9534   volatile struct gdb_exception e;
9535   char *copy_arg = NULL;
9536   char *addr_start = arg;
9537   struct linespec_result canonical;
9538   struct cleanup *old_chain;
9539   struct cleanup *bkpt_chain = NULL;
9540   int pending = 0;
9541   int task = 0;
9542   int prev_bkpt_count = breakpoint_count;
9543
9544   gdb_assert (ops != NULL);
9545
9546   init_linespec_result (&canonical);
9547
9548   TRY_CATCH (e, RETURN_MASK_ALL)
9549     {
9550       ops->create_sals_from_address (&arg, &canonical, type_wanted,
9551                                      addr_start, &copy_arg);
9552     }
9553
9554   /* If caller is interested in rc value from parse, set value.  */
9555   switch (e.reason)
9556     {
9557     case GDB_NO_ERROR:
9558       if (VEC_empty (linespec_sals, canonical.sals))
9559         return 0;
9560       break;
9561     case RETURN_ERROR:
9562       switch (e.error)
9563         {
9564         case NOT_FOUND_ERROR:
9565
9566           /* If pending breakpoint support is turned off, throw
9567              error.  */
9568
9569           if (pending_break_support == AUTO_BOOLEAN_FALSE)
9570             throw_exception (e);
9571
9572           exception_print (gdb_stderr, e);
9573
9574           /* If pending breakpoint support is auto query and the user
9575              selects no, then simply return the error code.  */
9576           if (pending_break_support == AUTO_BOOLEAN_AUTO
9577               && !nquery (_("Make %s pending on future shared library load? "),
9578                           bptype_string (type_wanted)))
9579             return 0;
9580
9581           /* At this point, either the user was queried about setting
9582              a pending breakpoint and selected yes, or pending
9583              breakpoint behavior is on and thus a pending breakpoint
9584              is defaulted on behalf of the user.  */
9585           {
9586             struct linespec_sals lsal;
9587
9588             copy_arg = xstrdup (addr_start);
9589             lsal.canonical = xstrdup (copy_arg);
9590             lsal.sals.nelts = 1;
9591             lsal.sals.sals = XNEW (struct symtab_and_line);
9592             init_sal (&lsal.sals.sals[0]);
9593             pending = 1;
9594             VEC_safe_push (linespec_sals, canonical.sals, &lsal);
9595           }
9596           break;
9597         default:
9598           throw_exception (e);
9599         }
9600       break;
9601     default:
9602       throw_exception (e);
9603     }
9604
9605   /* Create a chain of things that always need to be cleaned up.  */
9606   old_chain = make_cleanup_destroy_linespec_result (&canonical);
9607
9608   /* ----------------------------- SNIP -----------------------------
9609      Anything added to the cleanup chain beyond this point is assumed
9610      to be part of a breakpoint.  If the breakpoint create succeeds
9611      then the memory is not reclaimed.  */
9612   bkpt_chain = make_cleanup (null_cleanup, 0);
9613
9614   /* Resolve all line numbers to PC's and verify that the addresses
9615      are ok for the target.  */
9616   if (!pending)
9617     {
9618       int ix;
9619       struct linespec_sals *iter;
9620
9621       for (ix = 0; VEC_iterate (linespec_sals, canonical.sals, ix, iter); ++ix)
9622         breakpoint_sals_to_pc (&iter->sals);
9623     }
9624
9625   /* Fast tracepoints may have additional restrictions on location.  */
9626   if (!pending && type_wanted == bp_fast_tracepoint)
9627     {
9628       int ix;
9629       struct linespec_sals *iter;
9630
9631       for (ix = 0; VEC_iterate (linespec_sals, canonical.sals, ix, iter); ++ix)
9632         check_fast_tracepoint_sals (gdbarch, &iter->sals);
9633     }
9634
9635   /* Verify that condition can be parsed, before setting any
9636      breakpoints.  Allocate a separate condition expression for each
9637      breakpoint.  */
9638   if (!pending)
9639     {
9640       struct linespec_sals *lsal;
9641
9642       lsal = VEC_index (linespec_sals, canonical.sals, 0);
9643
9644       if (parse_condition_and_thread)
9645         {
9646             char *rest;
9647             /* Here we only parse 'arg' to separate condition
9648                from thread number, so parsing in context of first
9649                sal is OK.  When setting the breakpoint we'll 
9650                re-parse it in context of each sal.  */
9651
9652             find_condition_and_thread (arg, lsal->sals.sals[0].pc, &cond_string,
9653                                        &thread, &task, &rest);
9654             if (cond_string)
9655                 make_cleanup (xfree, cond_string);
9656             if (rest)
9657               make_cleanup (xfree, rest);
9658             if (rest)
9659               extra_string = rest;
9660         }
9661       else
9662         {
9663             /* Create a private copy of condition string.  */
9664             if (cond_string)
9665             {
9666                 cond_string = xstrdup (cond_string);
9667                 make_cleanup (xfree, cond_string);
9668             }
9669             /* Create a private copy of any extra string.  */
9670             if (extra_string)
9671               {
9672                 extra_string = xstrdup (extra_string);
9673                 make_cleanup (xfree, extra_string);
9674               }
9675         }
9676
9677       ops->create_breakpoints_sal (gdbarch, &canonical, lsal,
9678                                    cond_string, extra_string, type_wanted,
9679                                    tempflag ? disp_del : disp_donttouch,
9680                                    thread, task, ignore_count, ops,
9681                                    from_tty, enabled, internal, flags);
9682     }
9683   else
9684     {
9685       struct breakpoint *b;
9686
9687       make_cleanup (xfree, copy_arg);
9688
9689       if (is_tracepoint_type (type_wanted))
9690         {
9691           struct tracepoint *t;
9692
9693           t = XCNEW (struct tracepoint);
9694           b = &t->base;
9695         }
9696       else
9697         b = XNEW (struct breakpoint);
9698
9699       init_raw_breakpoint_without_location (b, gdbarch, type_wanted, ops);
9700
9701       b->addr_string = copy_arg;
9702       if (parse_condition_and_thread)
9703         b->cond_string = NULL;
9704       else
9705         {
9706           /* Create a private copy of condition string.  */
9707           if (cond_string)
9708             {
9709               cond_string = xstrdup (cond_string);
9710               make_cleanup (xfree, cond_string);
9711             }
9712           b->cond_string = cond_string;
9713         }
9714       b->extra_string = NULL;
9715       b->ignore_count = ignore_count;
9716       b->disposition = tempflag ? disp_del : disp_donttouch;
9717       b->condition_not_parsed = 1;
9718       b->enable_state = enabled ? bp_enabled : bp_disabled;
9719       if ((type_wanted != bp_breakpoint
9720            && type_wanted != bp_hardware_breakpoint) || thread != -1)
9721         b->pspace = current_program_space;
9722
9723       install_breakpoint (internal, b, 0);
9724     }
9725   
9726   if (VEC_length (linespec_sals, canonical.sals) > 1)
9727     {
9728       warning (_("Multiple breakpoints were set.\nUse the "
9729                  "\"delete\" command to delete unwanted breakpoints."));
9730       prev_breakpoint_count = prev_bkpt_count;
9731     }
9732
9733   /* That's it.  Discard the cleanups for data inserted into the
9734      breakpoint.  */
9735   discard_cleanups (bkpt_chain);
9736   /* But cleanup everything else.  */
9737   do_cleanups (old_chain);
9738
9739   /* error call may happen here - have BKPT_CHAIN already discarded.  */
9740   update_global_location_list (1);
9741
9742   return 1;
9743 }
9744
9745 /* Set a breakpoint.
9746    ARG is a string describing breakpoint address,
9747    condition, and thread.
9748    FLAG specifies if a breakpoint is hardware on,
9749    and if breakpoint is temporary, using BP_HARDWARE_FLAG
9750    and BP_TEMPFLAG.  */
9751
9752 static void
9753 break_command_1 (char *arg, int flag, int from_tty)
9754 {
9755   int tempflag = flag & BP_TEMPFLAG;
9756   enum bptype type_wanted = (flag & BP_HARDWAREFLAG
9757                              ? bp_hardware_breakpoint
9758                              : bp_breakpoint);
9759   struct breakpoint_ops *ops;
9760   const char *arg_cp = arg;
9761
9762   /* Matching breakpoints on probes.  */
9763   if (arg && probe_linespec_to_ops (&arg_cp) != NULL)
9764     ops = &bkpt_probe_breakpoint_ops;
9765   else
9766     ops = &bkpt_breakpoint_ops;
9767
9768   create_breakpoint (get_current_arch (),
9769                      arg,
9770                      NULL, 0, NULL, 1 /* parse arg */,
9771                      tempflag, type_wanted,
9772                      0 /* Ignore count */,
9773                      pending_break_support,
9774                      ops,
9775                      from_tty,
9776                      1 /* enabled */,
9777                      0 /* internal */,
9778                      0);
9779 }
9780
9781 /* Helper function for break_command_1 and disassemble_command.  */
9782
9783 void
9784 resolve_sal_pc (struct symtab_and_line *sal)
9785 {
9786   CORE_ADDR pc;
9787
9788   if (sal->pc == 0 && sal->symtab != NULL)
9789     {
9790       if (!find_line_pc (sal->symtab, sal->line, &pc))
9791         error (_("No line %d in file \"%s\"."),
9792                sal->line, symtab_to_filename_for_display (sal->symtab));
9793       sal->pc = pc;
9794
9795       /* If this SAL corresponds to a breakpoint inserted using a line
9796          number, then skip the function prologue if necessary.  */
9797       if (sal->explicit_line)
9798         skip_prologue_sal (sal);
9799     }
9800
9801   if (sal->section == 0 && sal->symtab != NULL)
9802     {
9803       struct blockvector *bv;
9804       struct block *b;
9805       struct symbol *sym;
9806
9807       bv = blockvector_for_pc_sect (sal->pc, 0, &b, sal->symtab);
9808       if (bv != NULL)
9809         {
9810           sym = block_linkage_function (b);
9811           if (sym != NULL)
9812             {
9813               fixup_symbol_section (sym, sal->symtab->objfile);
9814               sal->section = SYMBOL_OBJ_SECTION (sym);
9815             }
9816           else
9817             {
9818               /* It really is worthwhile to have the section, so we'll
9819                  just have to look harder. This case can be executed
9820                  if we have line numbers but no functions (as can
9821                  happen in assembly source).  */
9822
9823               struct minimal_symbol *msym;
9824               struct cleanup *old_chain = save_current_space_and_thread ();
9825
9826               switch_to_program_space_and_thread (sal->pspace);
9827
9828               msym = lookup_minimal_symbol_by_pc (sal->pc);
9829               if (msym)
9830                 sal->section = SYMBOL_OBJ_SECTION (msym);
9831
9832               do_cleanups (old_chain);
9833             }
9834         }
9835     }
9836 }
9837
9838 void
9839 break_command (char *arg, int from_tty)
9840 {
9841   break_command_1 (arg, 0, from_tty);
9842 }
9843
9844 void
9845 tbreak_command (char *arg, int from_tty)
9846 {
9847   break_command_1 (arg, BP_TEMPFLAG, from_tty);
9848 }
9849
9850 static void
9851 hbreak_command (char *arg, int from_tty)
9852 {
9853   break_command_1 (arg, BP_HARDWAREFLAG, from_tty);
9854 }
9855
9856 static void
9857 thbreak_command (char *arg, int from_tty)
9858 {
9859   break_command_1 (arg, (BP_TEMPFLAG | BP_HARDWAREFLAG), from_tty);
9860 }
9861
9862 static void
9863 stop_command (char *arg, int from_tty)
9864 {
9865   printf_filtered (_("Specify the type of breakpoint to set.\n\
9866 Usage: stop in <function | address>\n\
9867        stop at <line>\n"));
9868 }
9869
9870 static void
9871 stopin_command (char *arg, int from_tty)
9872 {
9873   int badInput = 0;
9874
9875   if (arg == (char *) NULL)
9876     badInput = 1;
9877   else if (*arg != '*')
9878     {
9879       char *argptr = arg;
9880       int hasColon = 0;
9881
9882       /* Look for a ':'.  If this is a line number specification, then
9883          say it is bad, otherwise, it should be an address or
9884          function/method name.  */
9885       while (*argptr && !hasColon)
9886         {
9887           hasColon = (*argptr == ':');
9888           argptr++;
9889         }
9890
9891       if (hasColon)
9892         badInput = (*argptr != ':');    /* Not a class::method */
9893       else
9894         badInput = isdigit (*arg);      /* a simple line number */
9895     }
9896
9897   if (badInput)
9898     printf_filtered (_("Usage: stop in <function | address>\n"));
9899   else
9900     break_command_1 (arg, 0, from_tty);
9901 }
9902
9903 static void
9904 stopat_command (char *arg, int from_tty)
9905 {
9906   int badInput = 0;
9907
9908   if (arg == (char *) NULL || *arg == '*')      /* no line number */
9909     badInput = 1;
9910   else
9911     {
9912       char *argptr = arg;
9913       int hasColon = 0;
9914
9915       /* Look for a ':'.  If there is a '::' then get out, otherwise
9916          it is probably a line number.  */
9917       while (*argptr && !hasColon)
9918         {
9919           hasColon = (*argptr == ':');
9920           argptr++;
9921         }
9922
9923       if (hasColon)
9924         badInput = (*argptr == ':');    /* we have class::method */
9925       else
9926         badInput = !isdigit (*arg);     /* not a line number */
9927     }
9928
9929   if (badInput)
9930     printf_filtered (_("Usage: stop at <line>\n"));
9931   else
9932     break_command_1 (arg, 0, from_tty);
9933 }
9934
9935 /* The dynamic printf command is mostly like a regular breakpoint, but
9936    with a prewired command list consisting of a single output command,
9937    built from extra arguments supplied on the dprintf command
9938    line.  */
9939
9940 static void
9941 dprintf_command (char *arg, int from_tty)
9942 {
9943   create_breakpoint (get_current_arch (),
9944                      arg,
9945                      NULL, 0, NULL, 1 /* parse arg */,
9946                      0, bp_dprintf,
9947                      0 /* Ignore count */,
9948                      pending_break_support,
9949                      &dprintf_breakpoint_ops,
9950                      from_tty,
9951                      1 /* enabled */,
9952                      0 /* internal */,
9953                      0);
9954 }
9955
9956 static void
9957 agent_printf_command (char *arg, int from_tty)
9958 {
9959   error (_("May only run agent-printf on the target"));
9960 }
9961
9962 /* Implement the "breakpoint_hit" breakpoint_ops method for
9963    ranged breakpoints.  */
9964
9965 static int
9966 breakpoint_hit_ranged_breakpoint (const struct bp_location *bl,
9967                                   struct address_space *aspace,
9968                                   CORE_ADDR bp_addr,
9969                                   const struct target_waitstatus *ws)
9970 {
9971   if (ws->kind != TARGET_WAITKIND_STOPPED
9972       || ws->value.sig != GDB_SIGNAL_TRAP)
9973     return 0;
9974
9975   return breakpoint_address_match_range (bl->pspace->aspace, bl->address,
9976                                          bl->length, aspace, bp_addr);
9977 }
9978
9979 /* Implement the "resources_needed" breakpoint_ops method for
9980    ranged breakpoints.  */
9981
9982 static int
9983 resources_needed_ranged_breakpoint (const struct bp_location *bl)
9984 {
9985   return target_ranged_break_num_registers ();
9986 }
9987
9988 /* Implement the "print_it" breakpoint_ops method for
9989    ranged breakpoints.  */
9990
9991 static enum print_stop_action
9992 print_it_ranged_breakpoint (bpstat bs)
9993 {
9994   struct breakpoint *b = bs->breakpoint_at;
9995   struct bp_location *bl = b->loc;
9996   struct ui_out *uiout = current_uiout;
9997
9998   gdb_assert (b->type == bp_hardware_breakpoint);
9999
10000   /* Ranged breakpoints have only one location.  */
10001   gdb_assert (bl && bl->next == NULL);
10002
10003   annotate_breakpoint (b->number);
10004   if (b->disposition == disp_del)
10005     ui_out_text (uiout, "\nTemporary ranged breakpoint ");
10006   else
10007     ui_out_text (uiout, "\nRanged breakpoint ");
10008   if (ui_out_is_mi_like_p (uiout))
10009     {
10010       ui_out_field_string (uiout, "reason",
10011                       async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
10012       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
10013     }
10014   ui_out_field_int (uiout, "bkptno", b->number);
10015   ui_out_text (uiout, ", ");
10016
10017   return PRINT_SRC_AND_LOC;
10018 }
10019
10020 /* Implement the "print_one" breakpoint_ops method for
10021    ranged breakpoints.  */
10022
10023 static void
10024 print_one_ranged_breakpoint (struct breakpoint *b,
10025                              struct bp_location **last_loc)
10026 {
10027   struct bp_location *bl = b->loc;
10028   struct value_print_options opts;
10029   struct ui_out *uiout = current_uiout;
10030
10031   /* Ranged breakpoints have only one location.  */
10032   gdb_assert (bl && bl->next == NULL);
10033
10034   get_user_print_options (&opts);
10035
10036   if (opts.addressprint)
10037     /* We don't print the address range here, it will be printed later
10038        by print_one_detail_ranged_breakpoint.  */
10039     ui_out_field_skip (uiout, "addr");
10040   annotate_field (5);
10041   print_breakpoint_location (b, bl);
10042   *last_loc = bl;
10043 }
10044
10045 /* Implement the "print_one_detail" breakpoint_ops method for
10046    ranged breakpoints.  */
10047
10048 static void
10049 print_one_detail_ranged_breakpoint (const struct breakpoint *b,
10050                                     struct ui_out *uiout)
10051 {
10052   CORE_ADDR address_start, address_end;
10053   struct bp_location *bl = b->loc;
10054   struct ui_file *stb = mem_fileopen ();
10055   struct cleanup *cleanup = make_cleanup_ui_file_delete (stb);
10056
10057   gdb_assert (bl);
10058
10059   address_start = bl->address;
10060   address_end = address_start + bl->length - 1;
10061
10062   ui_out_text (uiout, "\taddress range: ");
10063   fprintf_unfiltered (stb, "[%s, %s]",
10064                       print_core_address (bl->gdbarch, address_start),
10065                       print_core_address (bl->gdbarch, address_end));
10066   ui_out_field_stream (uiout, "addr", stb);
10067   ui_out_text (uiout, "\n");
10068
10069   do_cleanups (cleanup);
10070 }
10071
10072 /* Implement the "print_mention" breakpoint_ops method for
10073    ranged breakpoints.  */
10074
10075 static void
10076 print_mention_ranged_breakpoint (struct breakpoint *b)
10077 {
10078   struct bp_location *bl = b->loc;
10079   struct ui_out *uiout = current_uiout;
10080
10081   gdb_assert (bl);
10082   gdb_assert (b->type == bp_hardware_breakpoint);
10083
10084   if (ui_out_is_mi_like_p (uiout))
10085     return;
10086
10087   printf_filtered (_("Hardware assisted ranged breakpoint %d from %s to %s."),
10088                    b->number, paddress (bl->gdbarch, bl->address),
10089                    paddress (bl->gdbarch, bl->address + bl->length - 1));
10090 }
10091
10092 /* Implement the "print_recreate" breakpoint_ops method for
10093    ranged breakpoints.  */
10094
10095 static void
10096 print_recreate_ranged_breakpoint (struct breakpoint *b, struct ui_file *fp)
10097 {
10098   fprintf_unfiltered (fp, "break-range %s, %s", b->addr_string,
10099                       b->addr_string_range_end);
10100   print_recreate_thread (b, fp);
10101 }
10102
10103 /* The breakpoint_ops structure to be used in ranged breakpoints.  */
10104
10105 static struct breakpoint_ops ranged_breakpoint_ops;
10106
10107 /* Find the address where the end of the breakpoint range should be
10108    placed, given the SAL of the end of the range.  This is so that if
10109    the user provides a line number, the end of the range is set to the
10110    last instruction of the given line.  */
10111
10112 static CORE_ADDR
10113 find_breakpoint_range_end (struct symtab_and_line sal)
10114 {
10115   CORE_ADDR end;
10116
10117   /* If the user provided a PC value, use it.  Otherwise,
10118      find the address of the end of the given location.  */
10119   if (sal.explicit_pc)
10120     end = sal.pc;
10121   else
10122     {
10123       int ret;
10124       CORE_ADDR start;
10125
10126       ret = find_line_pc_range (sal, &start, &end);
10127       if (!ret)
10128         error (_("Could not find location of the end of the range."));
10129
10130       /* find_line_pc_range returns the start of the next line.  */
10131       end--;
10132     }
10133
10134   return end;
10135 }
10136
10137 /* Implement the "break-range" CLI command.  */
10138
10139 static void
10140 break_range_command (char *arg, int from_tty)
10141 {
10142   char *arg_start, *addr_string_start, *addr_string_end;
10143   struct linespec_result canonical_start, canonical_end;
10144   int bp_count, can_use_bp, length;
10145   CORE_ADDR end;
10146   struct breakpoint *b;
10147   struct symtab_and_line sal_start, sal_end;
10148   struct cleanup *cleanup_bkpt;
10149   struct linespec_sals *lsal_start, *lsal_end;
10150
10151   /* We don't support software ranged breakpoints.  */
10152   if (target_ranged_break_num_registers () < 0)
10153     error (_("This target does not support hardware ranged breakpoints."));
10154
10155   bp_count = hw_breakpoint_used_count ();
10156   bp_count += target_ranged_break_num_registers ();
10157   can_use_bp = target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
10158                                                    bp_count, 0);
10159   if (can_use_bp < 0)
10160     error (_("Hardware breakpoints used exceeds limit."));
10161
10162   arg = skip_spaces (arg);
10163   if (arg == NULL || arg[0] == '\0')
10164     error(_("No address range specified."));
10165
10166   init_linespec_result (&canonical_start);
10167
10168   arg_start = arg;
10169   parse_breakpoint_sals (&arg, &canonical_start);
10170
10171   cleanup_bkpt = make_cleanup_destroy_linespec_result (&canonical_start);
10172
10173   if (arg[0] != ',')
10174     error (_("Too few arguments."));
10175   else if (VEC_empty (linespec_sals, canonical_start.sals))
10176     error (_("Could not find location of the beginning of the range."));
10177
10178   lsal_start = VEC_index (linespec_sals, canonical_start.sals, 0);
10179
10180   if (VEC_length (linespec_sals, canonical_start.sals) > 1
10181       || lsal_start->sals.nelts != 1)
10182     error (_("Cannot create a ranged breakpoint with multiple locations."));
10183
10184   sal_start = lsal_start->sals.sals[0];
10185   addr_string_start = savestring (arg_start, arg - arg_start);
10186   make_cleanup (xfree, addr_string_start);
10187
10188   arg++;        /* Skip the comma.  */
10189   arg = skip_spaces (arg);
10190
10191   /* Parse the end location.  */
10192
10193   init_linespec_result (&canonical_end);
10194   arg_start = arg;
10195
10196   /* We call decode_line_full directly here instead of using
10197      parse_breakpoint_sals because we need to specify the start location's
10198      symtab and line as the default symtab and line for the end of the
10199      range.  This makes it possible to have ranges like "foo.c:27, +14",
10200      where +14 means 14 lines from the start location.  */
10201   decode_line_full (&arg, DECODE_LINE_FUNFIRSTLINE,
10202                     sal_start.symtab, sal_start.line,
10203                     &canonical_end, NULL, NULL);
10204
10205   make_cleanup_destroy_linespec_result (&canonical_end);
10206
10207   if (VEC_empty (linespec_sals, canonical_end.sals))
10208     error (_("Could not find location of the end of the range."));
10209
10210   lsal_end = VEC_index (linespec_sals, canonical_end.sals, 0);
10211   if (VEC_length (linespec_sals, canonical_end.sals) > 1
10212       || lsal_end->sals.nelts != 1)
10213     error (_("Cannot create a ranged breakpoint with multiple locations."));
10214
10215   sal_end = lsal_end->sals.sals[0];
10216   addr_string_end = savestring (arg_start, arg - arg_start);
10217   make_cleanup (xfree, addr_string_end);
10218
10219   end = find_breakpoint_range_end (sal_end);
10220   if (sal_start.pc > end)
10221     error (_("Invalid address range, end precedes start."));
10222
10223   length = end - sal_start.pc + 1;
10224   if (length < 0)
10225     /* Length overflowed.  */
10226     error (_("Address range too large."));
10227   else if (length == 1)
10228     {
10229       /* This range is simple enough to be handled by
10230          the `hbreak' command.  */
10231       hbreak_command (addr_string_start, 1);
10232
10233       do_cleanups (cleanup_bkpt);
10234
10235       return;
10236     }
10237
10238   /* Now set up the breakpoint.  */
10239   b = set_raw_breakpoint (get_current_arch (), sal_start,
10240                           bp_hardware_breakpoint, &ranged_breakpoint_ops);
10241   set_breakpoint_count (breakpoint_count + 1);
10242   b->number = breakpoint_count;
10243   b->disposition = disp_donttouch;
10244   b->addr_string = xstrdup (addr_string_start);
10245   b->addr_string_range_end = xstrdup (addr_string_end);
10246   b->loc->length = length;
10247
10248   do_cleanups (cleanup_bkpt);
10249
10250   mention (b);
10251   observer_notify_breakpoint_created (b);
10252   update_global_location_list (1);
10253 }
10254
10255 /*  Return non-zero if EXP is verified as constant.  Returned zero
10256     means EXP is variable.  Also the constant detection may fail for
10257     some constant expressions and in such case still falsely return
10258     zero.  */
10259
10260 static int
10261 watchpoint_exp_is_const (const struct expression *exp)
10262 {
10263   int i = exp->nelts;
10264
10265   while (i > 0)
10266     {
10267       int oplenp, argsp;
10268
10269       /* We are only interested in the descriptor of each element.  */
10270       operator_length (exp, i, &oplenp, &argsp);
10271       i -= oplenp;
10272
10273       switch (exp->elts[i].opcode)
10274         {
10275         case BINOP_ADD:
10276         case BINOP_SUB:
10277         case BINOP_MUL:
10278         case BINOP_DIV:
10279         case BINOP_REM:
10280         case BINOP_MOD:
10281         case BINOP_LSH:
10282         case BINOP_RSH:
10283         case BINOP_LOGICAL_AND:
10284         case BINOP_LOGICAL_OR:
10285         case BINOP_BITWISE_AND:
10286         case BINOP_BITWISE_IOR:
10287         case BINOP_BITWISE_XOR:
10288         case BINOP_EQUAL:
10289         case BINOP_NOTEQUAL:
10290         case BINOP_LESS:
10291         case BINOP_GTR:
10292         case BINOP_LEQ:
10293         case BINOP_GEQ:
10294         case BINOP_REPEAT:
10295         case BINOP_COMMA:
10296         case BINOP_EXP:
10297         case BINOP_MIN:
10298         case BINOP_MAX:
10299         case BINOP_INTDIV:
10300         case BINOP_CONCAT:
10301         case BINOP_IN:
10302         case BINOP_RANGE:
10303         case TERNOP_COND:
10304         case TERNOP_SLICE:
10305
10306         case OP_LONG:
10307         case OP_DOUBLE:
10308         case OP_DECFLOAT:
10309         case OP_LAST:
10310         case OP_COMPLEX:
10311         case OP_STRING:
10312         case OP_ARRAY:
10313         case OP_TYPE:
10314         case OP_TYPEOF:
10315         case OP_DECLTYPE:
10316         case OP_NAME:
10317         case OP_OBJC_NSSTRING:
10318
10319         case UNOP_NEG:
10320         case UNOP_LOGICAL_NOT:
10321         case UNOP_COMPLEMENT:
10322         case UNOP_ADDR:
10323         case UNOP_HIGH:
10324         case UNOP_CAST:
10325
10326         case UNOP_CAST_TYPE:
10327         case UNOP_REINTERPRET_CAST:
10328         case UNOP_DYNAMIC_CAST:
10329           /* Unary, binary and ternary operators: We have to check
10330              their operands.  If they are constant, then so is the
10331              result of that operation.  For instance, if A and B are
10332              determined to be constants, then so is "A + B".
10333
10334              UNOP_IND is one exception to the rule above, because the
10335              value of *ADDR is not necessarily a constant, even when
10336              ADDR is.  */
10337           break;
10338
10339         case OP_VAR_VALUE:
10340           /* Check whether the associated symbol is a constant.
10341
10342              We use SYMBOL_CLASS rather than TYPE_CONST because it's
10343              possible that a buggy compiler could mark a variable as
10344              constant even when it is not, and TYPE_CONST would return
10345              true in this case, while SYMBOL_CLASS wouldn't.
10346
10347              We also have to check for function symbols because they
10348              are always constant.  */
10349           {
10350             struct symbol *s = exp->elts[i + 2].symbol;
10351
10352             if (SYMBOL_CLASS (s) != LOC_BLOCK
10353                 && SYMBOL_CLASS (s) != LOC_CONST
10354                 && SYMBOL_CLASS (s) != LOC_CONST_BYTES)
10355               return 0;
10356             break;
10357           }
10358
10359         /* The default action is to return 0 because we are using
10360            the optimistic approach here: If we don't know something,
10361            then it is not a constant.  */
10362         default:
10363           return 0;
10364         }
10365     }
10366
10367   return 1;
10368 }
10369
10370 /* Implement the "dtor" breakpoint_ops method for watchpoints.  */
10371
10372 static void
10373 dtor_watchpoint (struct breakpoint *self)
10374 {
10375   struct watchpoint *w = (struct watchpoint *) self;
10376
10377   xfree (w->cond_exp);
10378   xfree (w->exp);
10379   xfree (w->exp_string);
10380   xfree (w->exp_string_reparse);
10381   value_free (w->val);
10382
10383   base_breakpoint_ops.dtor (self);
10384 }
10385
10386 /* Implement the "re_set" breakpoint_ops method for watchpoints.  */
10387
10388 static void
10389 re_set_watchpoint (struct breakpoint *b)
10390 {
10391   struct watchpoint *w = (struct watchpoint *) b;
10392
10393   /* Watchpoint can be either on expression using entirely global
10394      variables, or it can be on local variables.
10395
10396      Watchpoints of the first kind are never auto-deleted, and even
10397      persist across program restarts.  Since they can use variables
10398      from shared libraries, we need to reparse expression as libraries
10399      are loaded and unloaded.
10400
10401      Watchpoints on local variables can also change meaning as result
10402      of solib event.  For example, if a watchpoint uses both a local
10403      and a global variables in expression, it's a local watchpoint,
10404      but unloading of a shared library will make the expression
10405      invalid.  This is not a very common use case, but we still
10406      re-evaluate expression, to avoid surprises to the user.
10407
10408      Note that for local watchpoints, we re-evaluate it only if
10409      watchpoints frame id is still valid.  If it's not, it means the
10410      watchpoint is out of scope and will be deleted soon.  In fact,
10411      I'm not sure we'll ever be called in this case.
10412
10413      If a local watchpoint's frame id is still valid, then
10414      w->exp_valid_block is likewise valid, and we can safely use it.
10415
10416      Don't do anything about disabled watchpoints, since they will be
10417      reevaluated again when enabled.  */
10418   update_watchpoint (w, 1 /* reparse */);
10419 }
10420
10421 /* Implement the "insert" breakpoint_ops method for hardware watchpoints.  */
10422
10423 static int
10424 insert_watchpoint (struct bp_location *bl)
10425 {
10426   struct watchpoint *w = (struct watchpoint *) bl->owner;
10427   int length = w->exact ? 1 : bl->length;
10428
10429   return target_insert_watchpoint (bl->address, length, bl->watchpoint_type,
10430                                    w->cond_exp);
10431 }
10432
10433 /* Implement the "remove" breakpoint_ops method for hardware watchpoints.  */
10434
10435 static int
10436 remove_watchpoint (struct bp_location *bl)
10437 {
10438   struct watchpoint *w = (struct watchpoint *) bl->owner;
10439   int length = w->exact ? 1 : bl->length;
10440
10441   return target_remove_watchpoint (bl->address, length, bl->watchpoint_type,
10442                                    w->cond_exp);
10443 }
10444
10445 static int
10446 breakpoint_hit_watchpoint (const struct bp_location *bl,
10447                            struct address_space *aspace, CORE_ADDR bp_addr,
10448                            const struct target_waitstatus *ws)
10449 {
10450   struct breakpoint *b = bl->owner;
10451   struct watchpoint *w = (struct watchpoint *) b;
10452
10453   /* Continuable hardware watchpoints are treated as non-existent if the
10454      reason we stopped wasn't a hardware watchpoint (we didn't stop on
10455      some data address).  Otherwise gdb won't stop on a break instruction
10456      in the code (not from a breakpoint) when a hardware watchpoint has
10457      been defined.  Also skip watchpoints which we know did not trigger
10458      (did not match the data address).  */
10459   if (is_hardware_watchpoint (b)
10460       && w->watchpoint_triggered == watch_triggered_no)
10461     return 0;
10462
10463   return 1;
10464 }
10465
10466 static void
10467 check_status_watchpoint (bpstat bs)
10468 {
10469   gdb_assert (is_watchpoint (bs->breakpoint_at));
10470
10471   bpstat_check_watchpoint (bs);
10472 }
10473
10474 /* Implement the "resources_needed" breakpoint_ops method for
10475    hardware watchpoints.  */
10476
10477 static int
10478 resources_needed_watchpoint (const struct bp_location *bl)
10479 {
10480   struct watchpoint *w = (struct watchpoint *) bl->owner;
10481   int length = w->exact? 1 : bl->length;
10482
10483   return target_region_ok_for_hw_watchpoint (bl->address, length);
10484 }
10485
10486 /* Implement the "works_in_software_mode" breakpoint_ops method for
10487    hardware watchpoints.  */
10488
10489 static int
10490 works_in_software_mode_watchpoint (const struct breakpoint *b)
10491 {
10492   /* Read and access watchpoints only work with hardware support.  */
10493   return b->type == bp_watchpoint || b->type == bp_hardware_watchpoint;
10494 }
10495
10496 static enum print_stop_action
10497 print_it_watchpoint (bpstat bs)
10498 {
10499   struct cleanup *old_chain;
10500   struct breakpoint *b;
10501   struct ui_file *stb;
10502   enum print_stop_action result;
10503   struct watchpoint *w;
10504   struct ui_out *uiout = current_uiout;
10505
10506   gdb_assert (bs->bp_location_at != NULL);
10507
10508   b = bs->breakpoint_at;
10509   w = (struct watchpoint *) b;
10510
10511   stb = mem_fileopen ();
10512   old_chain = make_cleanup_ui_file_delete (stb);
10513
10514   switch (b->type)
10515     {
10516     case bp_watchpoint:
10517     case bp_hardware_watchpoint:
10518       annotate_watchpoint (b->number);
10519       if (ui_out_is_mi_like_p (uiout))
10520         ui_out_field_string
10521           (uiout, "reason",
10522            async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
10523       mention (b);
10524       make_cleanup_ui_out_tuple_begin_end (uiout, "value");
10525       ui_out_text (uiout, "\nOld value = ");
10526       watchpoint_value_print (bs->old_val, stb);
10527       ui_out_field_stream (uiout, "old", stb);
10528       ui_out_text (uiout, "\nNew value = ");
10529       watchpoint_value_print (w->val, stb);
10530       ui_out_field_stream (uiout, "new", stb);
10531       ui_out_text (uiout, "\n");
10532       /* More than one watchpoint may have been triggered.  */
10533       result = PRINT_UNKNOWN;
10534       break;
10535
10536     case bp_read_watchpoint:
10537       if (ui_out_is_mi_like_p (uiout))
10538         ui_out_field_string
10539           (uiout, "reason",
10540            async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
10541       mention (b);
10542       make_cleanup_ui_out_tuple_begin_end (uiout, "value");
10543       ui_out_text (uiout, "\nValue = ");
10544       watchpoint_value_print (w->val, stb);
10545       ui_out_field_stream (uiout, "value", stb);
10546       ui_out_text (uiout, "\n");
10547       result = PRINT_UNKNOWN;
10548       break;
10549
10550     case bp_access_watchpoint:
10551       if (bs->old_val != NULL)
10552         {
10553           annotate_watchpoint (b->number);
10554           if (ui_out_is_mi_like_p (uiout))
10555             ui_out_field_string
10556               (uiout, "reason",
10557                async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10558           mention (b);
10559           make_cleanup_ui_out_tuple_begin_end (uiout, "value");
10560           ui_out_text (uiout, "\nOld value = ");
10561           watchpoint_value_print (bs->old_val, stb);
10562           ui_out_field_stream (uiout, "old", stb);
10563           ui_out_text (uiout, "\nNew value = ");
10564         }
10565       else
10566         {
10567           mention (b);
10568           if (ui_out_is_mi_like_p (uiout))
10569             ui_out_field_string
10570               (uiout, "reason",
10571                async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10572           make_cleanup_ui_out_tuple_begin_end (uiout, "value");
10573           ui_out_text (uiout, "\nValue = ");
10574         }
10575       watchpoint_value_print (w->val, stb);
10576       ui_out_field_stream (uiout, "new", stb);
10577       ui_out_text (uiout, "\n");
10578       result = PRINT_UNKNOWN;
10579       break;
10580     default:
10581       result = PRINT_UNKNOWN;
10582     }
10583
10584   do_cleanups (old_chain);
10585   return result;
10586 }
10587
10588 /* Implement the "print_mention" breakpoint_ops method for hardware
10589    watchpoints.  */
10590
10591 static void
10592 print_mention_watchpoint (struct breakpoint *b)
10593 {
10594   struct cleanup *ui_out_chain;
10595   struct watchpoint *w = (struct watchpoint *) b;
10596   struct ui_out *uiout = current_uiout;
10597
10598   switch (b->type)
10599     {
10600     case bp_watchpoint:
10601       ui_out_text (uiout, "Watchpoint ");
10602       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "wpt");
10603       break;
10604     case bp_hardware_watchpoint:
10605       ui_out_text (uiout, "Hardware watchpoint ");
10606       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "wpt");
10607       break;
10608     case bp_read_watchpoint:
10609       ui_out_text (uiout, "Hardware read watchpoint ");
10610       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-rwpt");
10611       break;
10612     case bp_access_watchpoint:
10613       ui_out_text (uiout, "Hardware access (read/write) watchpoint ");
10614       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-awpt");
10615       break;
10616     default:
10617       internal_error (__FILE__, __LINE__,
10618                       _("Invalid hardware watchpoint type."));
10619     }
10620
10621   ui_out_field_int (uiout, "number", b->number);
10622   ui_out_text (uiout, ": ");
10623   ui_out_field_string (uiout, "exp", w->exp_string);
10624   do_cleanups (ui_out_chain);
10625 }
10626
10627 /* Implement the "print_recreate" breakpoint_ops method for
10628    watchpoints.  */
10629
10630 static void
10631 print_recreate_watchpoint (struct breakpoint *b, struct ui_file *fp)
10632 {
10633   struct watchpoint *w = (struct watchpoint *) b;
10634
10635   switch (b->type)
10636     {
10637     case bp_watchpoint:
10638     case bp_hardware_watchpoint:
10639       fprintf_unfiltered (fp, "watch");
10640       break;
10641     case bp_read_watchpoint:
10642       fprintf_unfiltered (fp, "rwatch");
10643       break;
10644     case bp_access_watchpoint:
10645       fprintf_unfiltered (fp, "awatch");
10646       break;
10647     default:
10648       internal_error (__FILE__, __LINE__,
10649                       _("Invalid watchpoint type."));
10650     }
10651
10652   fprintf_unfiltered (fp, " %s", w->exp_string);
10653   print_recreate_thread (b, fp);
10654 }
10655
10656 /* The breakpoint_ops structure to be used in hardware watchpoints.  */
10657
10658 static struct breakpoint_ops watchpoint_breakpoint_ops;
10659
10660 /* Implement the "insert" breakpoint_ops method for
10661    masked hardware watchpoints.  */
10662
10663 static int
10664 insert_masked_watchpoint (struct bp_location *bl)
10665 {
10666   struct watchpoint *w = (struct watchpoint *) bl->owner;
10667
10668   return target_insert_mask_watchpoint (bl->address, w->hw_wp_mask,
10669                                         bl->watchpoint_type);
10670 }
10671
10672 /* Implement the "remove" breakpoint_ops method for
10673    masked hardware watchpoints.  */
10674
10675 static int
10676 remove_masked_watchpoint (struct bp_location *bl)
10677 {
10678   struct watchpoint *w = (struct watchpoint *) bl->owner;
10679
10680   return target_remove_mask_watchpoint (bl->address, w->hw_wp_mask,
10681                                         bl->watchpoint_type);
10682 }
10683
10684 /* Implement the "resources_needed" breakpoint_ops method for
10685    masked hardware watchpoints.  */
10686
10687 static int
10688 resources_needed_masked_watchpoint (const struct bp_location *bl)
10689 {
10690   struct watchpoint *w = (struct watchpoint *) bl->owner;
10691
10692   return target_masked_watch_num_registers (bl->address, w->hw_wp_mask);
10693 }
10694
10695 /* Implement the "works_in_software_mode" breakpoint_ops method for
10696    masked hardware watchpoints.  */
10697
10698 static int
10699 works_in_software_mode_masked_watchpoint (const struct breakpoint *b)
10700 {
10701   return 0;
10702 }
10703
10704 /* Implement the "print_it" breakpoint_ops method for
10705    masked hardware watchpoints.  */
10706
10707 static enum print_stop_action
10708 print_it_masked_watchpoint (bpstat bs)
10709 {
10710   struct breakpoint *b = bs->breakpoint_at;
10711   struct ui_out *uiout = current_uiout;
10712
10713   /* Masked watchpoints have only one location.  */
10714   gdb_assert (b->loc && b->loc->next == NULL);
10715
10716   switch (b->type)
10717     {
10718     case bp_hardware_watchpoint:
10719       annotate_watchpoint (b->number);
10720       if (ui_out_is_mi_like_p (uiout))
10721         ui_out_field_string
10722           (uiout, "reason",
10723            async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
10724       break;
10725
10726     case bp_read_watchpoint:
10727       if (ui_out_is_mi_like_p (uiout))
10728         ui_out_field_string
10729           (uiout, "reason",
10730            async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
10731       break;
10732
10733     case bp_access_watchpoint:
10734       if (ui_out_is_mi_like_p (uiout))
10735         ui_out_field_string
10736           (uiout, "reason",
10737            async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10738       break;
10739     default:
10740       internal_error (__FILE__, __LINE__,
10741                       _("Invalid hardware watchpoint type."));
10742     }
10743
10744   mention (b);
10745   ui_out_text (uiout, _("\n\
10746 Check the underlying instruction at PC for the memory\n\
10747 address and value which triggered this watchpoint.\n"));
10748   ui_out_text (uiout, "\n");
10749
10750   /* More than one watchpoint may have been triggered.  */
10751   return PRINT_UNKNOWN;
10752 }
10753
10754 /* Implement the "print_one_detail" breakpoint_ops method for
10755    masked hardware watchpoints.  */
10756
10757 static void
10758 print_one_detail_masked_watchpoint (const struct breakpoint *b,
10759                                     struct ui_out *uiout)
10760 {
10761   struct watchpoint *w = (struct watchpoint *) b;
10762
10763   /* Masked watchpoints have only one location.  */
10764   gdb_assert (b->loc && b->loc->next == NULL);
10765
10766   ui_out_text (uiout, "\tmask ");
10767   ui_out_field_core_addr (uiout, "mask", b->loc->gdbarch, w->hw_wp_mask);
10768   ui_out_text (uiout, "\n");
10769 }
10770
10771 /* Implement the "print_mention" breakpoint_ops method for
10772    masked hardware watchpoints.  */
10773
10774 static void
10775 print_mention_masked_watchpoint (struct breakpoint *b)
10776 {
10777   struct watchpoint *w = (struct watchpoint *) b;
10778   struct ui_out *uiout = current_uiout;
10779   struct cleanup *ui_out_chain;
10780
10781   switch (b->type)
10782     {
10783     case bp_hardware_watchpoint:
10784       ui_out_text (uiout, "Masked hardware watchpoint ");
10785       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "wpt");
10786       break;
10787     case bp_read_watchpoint:
10788       ui_out_text (uiout, "Masked hardware read watchpoint ");
10789       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-rwpt");
10790       break;
10791     case bp_access_watchpoint:
10792       ui_out_text (uiout, "Masked hardware access (read/write) watchpoint ");
10793       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-awpt");
10794       break;
10795     default:
10796       internal_error (__FILE__, __LINE__,
10797                       _("Invalid hardware watchpoint type."));
10798     }
10799
10800   ui_out_field_int (uiout, "number", b->number);
10801   ui_out_text (uiout, ": ");
10802   ui_out_field_string (uiout, "exp", w->exp_string);
10803   do_cleanups (ui_out_chain);
10804 }
10805
10806 /* Implement the "print_recreate" breakpoint_ops method for
10807    masked hardware watchpoints.  */
10808
10809 static void
10810 print_recreate_masked_watchpoint (struct breakpoint *b, struct ui_file *fp)
10811 {
10812   struct watchpoint *w = (struct watchpoint *) b;
10813   char tmp[40];
10814
10815   switch (b->type)
10816     {
10817     case bp_hardware_watchpoint:
10818       fprintf_unfiltered (fp, "watch");
10819       break;
10820     case bp_read_watchpoint:
10821       fprintf_unfiltered (fp, "rwatch");
10822       break;
10823     case bp_access_watchpoint:
10824       fprintf_unfiltered (fp, "awatch");
10825       break;
10826     default:
10827       internal_error (__FILE__, __LINE__,
10828                       _("Invalid hardware watchpoint type."));
10829     }
10830
10831   sprintf_vma (tmp, w->hw_wp_mask);
10832   fprintf_unfiltered (fp, " %s mask 0x%s", w->exp_string, tmp);
10833   print_recreate_thread (b, fp);
10834 }
10835
10836 /* The breakpoint_ops structure to be used in masked hardware watchpoints.  */
10837
10838 static struct breakpoint_ops masked_watchpoint_breakpoint_ops;
10839
10840 /* Tell whether the given watchpoint is a masked hardware watchpoint.  */
10841
10842 static int
10843 is_masked_watchpoint (const struct breakpoint *b)
10844 {
10845   return b->ops == &masked_watchpoint_breakpoint_ops;
10846 }
10847
10848 /* accessflag:  hw_write:  watch write, 
10849                 hw_read:   watch read, 
10850                 hw_access: watch access (read or write) */
10851 static void
10852 watch_command_1 (const char *arg, int accessflag, int from_tty,
10853                  int just_location, int internal)
10854 {
10855   volatile struct gdb_exception e;
10856   struct breakpoint *b, *scope_breakpoint = NULL;
10857   struct expression *exp;
10858   const struct block *exp_valid_block = NULL, *cond_exp_valid_block = NULL;
10859   struct value *val, *mark, *result;
10860   struct frame_info *frame;
10861   const char *exp_start = NULL;
10862   const char *exp_end = NULL;
10863   const char *tok, *end_tok;
10864   int toklen = -1;
10865   const char *cond_start = NULL;
10866   const char *cond_end = NULL;
10867   enum bptype bp_type;
10868   int thread = -1;
10869   int pc = 0;
10870   /* Flag to indicate whether we are going to use masks for
10871      the hardware watchpoint.  */
10872   int use_mask = 0;
10873   CORE_ADDR mask = 0;
10874   struct watchpoint *w;
10875   char *expression;
10876   struct cleanup *back_to;
10877
10878   /* Make sure that we actually have parameters to parse.  */
10879   if (arg != NULL && arg[0] != '\0')
10880     {
10881       const char *value_start;
10882
10883       exp_end = arg + strlen (arg);
10884
10885       /* Look for "parameter value" pairs at the end
10886          of the arguments string.  */
10887       for (tok = exp_end - 1; tok > arg; tok--)
10888         {
10889           /* Skip whitespace at the end of the argument list.  */
10890           while (tok > arg && (*tok == ' ' || *tok == '\t'))
10891             tok--;
10892
10893           /* Find the beginning of the last token.
10894              This is the value of the parameter.  */
10895           while (tok > arg && (*tok != ' ' && *tok != '\t'))
10896             tok--;
10897           value_start = tok + 1;
10898
10899           /* Skip whitespace.  */
10900           while (tok > arg && (*tok == ' ' || *tok == '\t'))
10901             tok--;
10902
10903           end_tok = tok;
10904
10905           /* Find the beginning of the second to last token.
10906              This is the parameter itself.  */
10907           while (tok > arg && (*tok != ' ' && *tok != '\t'))
10908             tok--;
10909           tok++;
10910           toklen = end_tok - tok + 1;
10911
10912           if (toklen == 6 && !strncmp (tok, "thread", 6))
10913             {
10914               /* At this point we've found a "thread" token, which means
10915                  the user is trying to set a watchpoint that triggers
10916                  only in a specific thread.  */
10917               char *endp;
10918
10919               if (thread != -1)
10920                 error(_("You can specify only one thread."));
10921
10922               /* Extract the thread ID from the next token.  */
10923               thread = strtol (value_start, &endp, 0);
10924
10925               /* Check if the user provided a valid numeric value for the
10926                  thread ID.  */
10927               if (*endp != ' ' && *endp != '\t' && *endp != '\0')
10928                 error (_("Invalid thread ID specification %s."), value_start);
10929
10930               /* Check if the thread actually exists.  */
10931               if (!valid_thread_id (thread))
10932                 invalid_thread_id_error (thread);
10933             }
10934           else if (toklen == 4 && !strncmp (tok, "mask", 4))
10935             {
10936               /* We've found a "mask" token, which means the user wants to
10937                  create a hardware watchpoint that is going to have the mask
10938                  facility.  */
10939               struct value *mask_value, *mark;
10940
10941               if (use_mask)
10942                 error(_("You can specify only one mask."));
10943
10944               use_mask = just_location = 1;
10945
10946               mark = value_mark ();
10947               mask_value = parse_to_comma_and_eval (&value_start);
10948               mask = value_as_address (mask_value);
10949               value_free_to_mark (mark);
10950             }
10951           else
10952             /* We didn't recognize what we found.  We should stop here.  */
10953             break;
10954
10955           /* Truncate the string and get rid of the "parameter value" pair before
10956              the arguments string is parsed by the parse_exp_1 function.  */
10957           exp_end = tok;
10958         }
10959     }
10960   else
10961     exp_end = arg;
10962
10963   /* Parse the rest of the arguments.  From here on out, everything
10964      is in terms of a newly allocated string instead of the original
10965      ARG.  */
10966   innermost_block = NULL;
10967   expression = savestring (arg, exp_end - arg);
10968   back_to = make_cleanup (xfree, expression);
10969   exp_start = arg = expression;
10970   exp = parse_exp_1 (&arg, 0, 0, 0);
10971   exp_end = arg;
10972   /* Remove trailing whitespace from the expression before saving it.
10973      This makes the eventual display of the expression string a bit
10974      prettier.  */
10975   while (exp_end > exp_start && (exp_end[-1] == ' ' || exp_end[-1] == '\t'))
10976     --exp_end;
10977
10978   /* Checking if the expression is not constant.  */
10979   if (watchpoint_exp_is_const (exp))
10980     {
10981       int len;
10982
10983       len = exp_end - exp_start;
10984       while (len > 0 && isspace (exp_start[len - 1]))
10985         len--;
10986       error (_("Cannot watch constant value `%.*s'."), len, exp_start);
10987     }
10988
10989   exp_valid_block = innermost_block;
10990   mark = value_mark ();
10991   fetch_subexp_value (exp, &pc, &val, &result, NULL);
10992
10993   if (just_location)
10994     {
10995       int ret;
10996
10997       exp_valid_block = NULL;
10998       val = value_addr (result);
10999       release_value (val);
11000       value_free_to_mark (mark);
11001
11002       if (use_mask)
11003         {
11004           ret = target_masked_watch_num_registers (value_as_address (val),
11005                                                    mask);
11006           if (ret == -1)
11007             error (_("This target does not support masked watchpoints."));
11008           else if (ret == -2)
11009             error (_("Invalid mask or memory region."));
11010         }
11011     }
11012   else if (val != NULL)
11013     release_value (val);
11014
11015   tok = skip_spaces_const (arg);
11016   end_tok = skip_to_space_const (tok);
11017
11018   toklen = end_tok - tok;
11019   if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
11020     {
11021       struct expression *cond;
11022
11023       innermost_block = NULL;
11024       tok = cond_start = end_tok + 1;
11025       cond = parse_exp_1 (&tok, 0, 0, 0);
11026
11027       /* The watchpoint expression may not be local, but the condition
11028          may still be.  E.g.: `watch global if local > 0'.  */
11029       cond_exp_valid_block = innermost_block;
11030
11031       xfree (cond);
11032       cond_end = tok;
11033     }
11034   if (*tok)
11035     error (_("Junk at end of command."));
11036
11037   if (accessflag == hw_read)
11038     bp_type = bp_read_watchpoint;
11039   else if (accessflag == hw_access)
11040     bp_type = bp_access_watchpoint;
11041   else
11042     bp_type = bp_hardware_watchpoint;
11043
11044   frame = block_innermost_frame (exp_valid_block);
11045
11046   /* If the expression is "local", then set up a "watchpoint scope"
11047      breakpoint at the point where we've left the scope of the watchpoint
11048      expression.  Create the scope breakpoint before the watchpoint, so
11049      that we will encounter it first in bpstat_stop_status.  */
11050   if (exp_valid_block && frame)
11051     {
11052       if (frame_id_p (frame_unwind_caller_id (frame)))
11053         {
11054           scope_breakpoint
11055             = create_internal_breakpoint (frame_unwind_caller_arch (frame),
11056                                           frame_unwind_caller_pc (frame),
11057                                           bp_watchpoint_scope,
11058                                           &momentary_breakpoint_ops);
11059
11060           scope_breakpoint->enable_state = bp_enabled;
11061
11062           /* Automatically delete the breakpoint when it hits.  */
11063           scope_breakpoint->disposition = disp_del;
11064
11065           /* Only break in the proper frame (help with recursion).  */
11066           scope_breakpoint->frame_id = frame_unwind_caller_id (frame);
11067
11068           /* Set the address at which we will stop.  */
11069           scope_breakpoint->loc->gdbarch
11070             = frame_unwind_caller_arch (frame);
11071           scope_breakpoint->loc->requested_address
11072             = frame_unwind_caller_pc (frame);
11073           scope_breakpoint->loc->address
11074             = adjust_breakpoint_address (scope_breakpoint->loc->gdbarch,
11075                                          scope_breakpoint->loc->requested_address,
11076                                          scope_breakpoint->type);
11077         }
11078     }
11079
11080   /* Now set up the breakpoint.  */
11081
11082   w = XCNEW (struct watchpoint);
11083   b = &w->base;
11084   if (use_mask)
11085     init_raw_breakpoint_without_location (b, NULL, bp_type,
11086                                           &masked_watchpoint_breakpoint_ops);
11087   else
11088     init_raw_breakpoint_without_location (b, NULL, bp_type,
11089                                           &watchpoint_breakpoint_ops);
11090   b->thread = thread;
11091   b->disposition = disp_donttouch;
11092   b->pspace = current_program_space;
11093   w->exp = exp;
11094   w->exp_valid_block = exp_valid_block;
11095   w->cond_exp_valid_block = cond_exp_valid_block;
11096   if (just_location)
11097     {
11098       struct type *t = value_type (val);
11099       CORE_ADDR addr = value_as_address (val);
11100       char *name;
11101
11102       t = check_typedef (TYPE_TARGET_TYPE (check_typedef (t)));
11103       name = type_to_string (t);
11104
11105       w->exp_string_reparse = xstrprintf ("* (%s *) %s", name,
11106                                           core_addr_to_string (addr));
11107       xfree (name);
11108
11109       w->exp_string = xstrprintf ("-location %.*s",
11110                                   (int) (exp_end - exp_start), exp_start);
11111
11112       /* The above expression is in C.  */
11113       b->language = language_c;
11114     }
11115   else
11116     w->exp_string = savestring (exp_start, exp_end - exp_start);
11117
11118   if (use_mask)
11119     {
11120       w->hw_wp_mask = mask;
11121     }
11122   else
11123     {
11124       w->val = val;
11125       w->val_valid = 1;
11126     }
11127
11128   if (cond_start)
11129     b->cond_string = savestring (cond_start, cond_end - cond_start);
11130   else
11131     b->cond_string = 0;
11132
11133   if (frame)
11134     {
11135       w->watchpoint_frame = get_frame_id (frame);
11136       w->watchpoint_thread = inferior_ptid;
11137     }
11138   else
11139     {
11140       w->watchpoint_frame = null_frame_id;
11141       w->watchpoint_thread = null_ptid;
11142     }
11143
11144   if (scope_breakpoint != NULL)
11145     {
11146       /* The scope breakpoint is related to the watchpoint.  We will
11147          need to act on them together.  */
11148       b->related_breakpoint = scope_breakpoint;
11149       scope_breakpoint->related_breakpoint = b;
11150     }
11151
11152   if (!just_location)
11153     value_free_to_mark (mark);
11154
11155   TRY_CATCH (e, RETURN_MASK_ALL)
11156     {
11157       /* Finally update the new watchpoint.  This creates the locations
11158          that should be inserted.  */
11159       update_watchpoint (w, 1);
11160     }
11161   if (e.reason < 0)
11162     {
11163       delete_breakpoint (b);
11164       throw_exception (e);
11165     }
11166
11167   install_breakpoint (internal, b, 1);
11168   do_cleanups (back_to);
11169 }
11170
11171 /* Return count of debug registers needed to watch the given expression.
11172    If the watchpoint cannot be handled in hardware return zero.  */
11173
11174 static int
11175 can_use_hardware_watchpoint (struct value *v)
11176 {
11177   int found_memory_cnt = 0;
11178   struct value *head = v;
11179
11180   /* Did the user specifically forbid us to use hardware watchpoints? */
11181   if (!can_use_hw_watchpoints)
11182     return 0;
11183
11184   /* Make sure that the value of the expression depends only upon
11185      memory contents, and values computed from them within GDB.  If we
11186      find any register references or function calls, we can't use a
11187      hardware watchpoint.
11188
11189      The idea here is that evaluating an expression generates a series
11190      of values, one holding the value of every subexpression.  (The
11191      expression a*b+c has five subexpressions: a, b, a*b, c, and
11192      a*b+c.)  GDB's values hold almost enough information to establish
11193      the criteria given above --- they identify memory lvalues,
11194      register lvalues, computed values, etcetera.  So we can evaluate
11195      the expression, and then scan the chain of values that leaves
11196      behind to decide whether we can detect any possible change to the
11197      expression's final value using only hardware watchpoints.
11198
11199      However, I don't think that the values returned by inferior
11200      function calls are special in any way.  So this function may not
11201      notice that an expression involving an inferior function call
11202      can't be watched with hardware watchpoints.  FIXME.  */
11203   for (; v; v = value_next (v))
11204     {
11205       if (VALUE_LVAL (v) == lval_memory)
11206         {
11207           if (v != head && value_lazy (v))
11208             /* A lazy memory lvalue in the chain is one that GDB never
11209                needed to fetch; we either just used its address (e.g.,
11210                `a' in `a.b') or we never needed it at all (e.g., `a'
11211                in `a,b').  This doesn't apply to HEAD; if that is
11212                lazy then it was not readable, but watch it anyway.  */
11213             ;
11214           else
11215             {
11216               /* Ahh, memory we actually used!  Check if we can cover
11217                  it with hardware watchpoints.  */
11218               struct type *vtype = check_typedef (value_type (v));
11219
11220               /* We only watch structs and arrays if user asked for it
11221                  explicitly, never if they just happen to appear in a
11222                  middle of some value chain.  */
11223               if (v == head
11224                   || (TYPE_CODE (vtype) != TYPE_CODE_STRUCT
11225                       && TYPE_CODE (vtype) != TYPE_CODE_ARRAY))
11226                 {
11227                   CORE_ADDR vaddr = value_address (v);
11228                   int len;
11229                   int num_regs;
11230
11231                   len = (target_exact_watchpoints
11232                          && is_scalar_type_recursive (vtype))?
11233                     1 : TYPE_LENGTH (value_type (v));
11234
11235                   num_regs = target_region_ok_for_hw_watchpoint (vaddr, len);
11236                   if (!num_regs)
11237                     return 0;
11238                   else
11239                     found_memory_cnt += num_regs;
11240                 }
11241             }
11242         }
11243       else if (VALUE_LVAL (v) != not_lval
11244                && deprecated_value_modifiable (v) == 0)
11245         return 0;       /* These are values from the history (e.g., $1).  */
11246       else if (VALUE_LVAL (v) == lval_register)
11247         return 0;       /* Cannot watch a register with a HW watchpoint.  */
11248     }
11249
11250   /* The expression itself looks suitable for using a hardware
11251      watchpoint, but give the target machine a chance to reject it.  */
11252   return found_memory_cnt;
11253 }
11254
11255 void
11256 watch_command_wrapper (char *arg, int from_tty, int internal)
11257 {
11258   watch_command_1 (arg, hw_write, from_tty, 0, internal);
11259 }
11260
11261 /* A helper function that looks for the "-location" argument and then
11262    calls watch_command_1.  */
11263
11264 static void
11265 watch_maybe_just_location (char *arg, int accessflag, int from_tty)
11266 {
11267   int just_location = 0;
11268
11269   if (arg
11270       && (check_for_argument (&arg, "-location", sizeof ("-location") - 1)
11271           || check_for_argument (&arg, "-l", sizeof ("-l") - 1)))
11272     {
11273       arg = skip_spaces (arg);
11274       just_location = 1;
11275     }
11276
11277   watch_command_1 (arg, accessflag, from_tty, just_location, 0);
11278 }
11279
11280 static void
11281 watch_command (char *arg, int from_tty)
11282 {
11283   watch_maybe_just_location (arg, hw_write, from_tty);
11284 }
11285
11286 void
11287 rwatch_command_wrapper (char *arg, int from_tty, int internal)
11288 {
11289   watch_command_1 (arg, hw_read, from_tty, 0, internal);
11290 }
11291
11292 static void
11293 rwatch_command (char *arg, int from_tty)
11294 {
11295   watch_maybe_just_location (arg, hw_read, from_tty);
11296 }
11297
11298 void
11299 awatch_command_wrapper (char *arg, int from_tty, int internal)
11300 {
11301   watch_command_1 (arg, hw_access, from_tty, 0, internal);
11302 }
11303
11304 static void
11305 awatch_command (char *arg, int from_tty)
11306 {
11307   watch_maybe_just_location (arg, hw_access, from_tty);
11308 }
11309 \f
11310
11311 /* Helper routines for the until_command routine in infcmd.c.  Here
11312    because it uses the mechanisms of breakpoints.  */
11313
11314 struct until_break_command_continuation_args
11315 {
11316   struct breakpoint *breakpoint;
11317   struct breakpoint *breakpoint2;
11318   int thread_num;
11319 };
11320
11321 /* This function is called by fetch_inferior_event via the
11322    cmd_continuation pointer, to complete the until command.  It takes
11323    care of cleaning up the temporary breakpoints set up by the until
11324    command.  */
11325 static void
11326 until_break_command_continuation (void *arg, int err)
11327 {
11328   struct until_break_command_continuation_args *a = arg;
11329
11330   delete_breakpoint (a->breakpoint);
11331   if (a->breakpoint2)
11332     delete_breakpoint (a->breakpoint2);
11333   delete_longjmp_breakpoint (a->thread_num);
11334 }
11335
11336 void
11337 until_break_command (char *arg, int from_tty, int anywhere)
11338 {
11339   struct symtabs_and_lines sals;
11340   struct symtab_and_line sal;
11341   struct frame_info *frame;
11342   struct gdbarch *frame_gdbarch;
11343   struct frame_id stack_frame_id;
11344   struct frame_id caller_frame_id;
11345   struct breakpoint *breakpoint;
11346   struct breakpoint *breakpoint2 = NULL;
11347   struct cleanup *old_chain;
11348   int thread;
11349   struct thread_info *tp;
11350
11351   clear_proceed_status ();
11352
11353   /* Set a breakpoint where the user wants it and at return from
11354      this function.  */
11355
11356   if (last_displayed_sal_is_valid ())
11357     sals = decode_line_1 (&arg, DECODE_LINE_FUNFIRSTLINE,
11358                           get_last_displayed_symtab (),
11359                           get_last_displayed_line ());
11360   else
11361     sals = decode_line_1 (&arg, DECODE_LINE_FUNFIRSTLINE,
11362                           (struct symtab *) NULL, 0);
11363
11364   if (sals.nelts != 1)
11365     error (_("Couldn't get information on specified line."));
11366
11367   sal = sals.sals[0];
11368   xfree (sals.sals);    /* malloc'd, so freed.  */
11369
11370   if (*arg)
11371     error (_("Junk at end of arguments."));
11372
11373   resolve_sal_pc (&sal);
11374
11375   tp = inferior_thread ();
11376   thread = tp->num;
11377
11378   old_chain = make_cleanup (null_cleanup, NULL);
11379
11380   /* Note linespec handling above invalidates the frame chain.
11381      Installing a breakpoint also invalidates the frame chain (as it
11382      may need to switch threads), so do any frame handling before
11383      that.  */
11384
11385   frame = get_selected_frame (NULL);
11386   frame_gdbarch = get_frame_arch (frame);
11387   stack_frame_id = get_stack_frame_id (frame);
11388   caller_frame_id = frame_unwind_caller_id (frame);
11389
11390   /* Keep within the current frame, or in frames called by the current
11391      one.  */
11392
11393   if (frame_id_p (caller_frame_id))
11394     {
11395       struct symtab_and_line sal2;
11396
11397       sal2 = find_pc_line (frame_unwind_caller_pc (frame), 0);
11398       sal2.pc = frame_unwind_caller_pc (frame);
11399       breakpoint2 = set_momentary_breakpoint (frame_unwind_caller_arch (frame),
11400                                               sal2,
11401                                               caller_frame_id,
11402                                               bp_until);
11403       make_cleanup_delete_breakpoint (breakpoint2);
11404
11405       set_longjmp_breakpoint (tp, caller_frame_id);
11406       make_cleanup (delete_longjmp_breakpoint_cleanup, &thread);
11407     }
11408
11409   /* set_momentary_breakpoint could invalidate FRAME.  */
11410   frame = NULL;
11411
11412   if (anywhere)
11413     /* If the user told us to continue until a specified location,
11414        we don't specify a frame at which we need to stop.  */
11415     breakpoint = set_momentary_breakpoint (frame_gdbarch, sal,
11416                                            null_frame_id, bp_until);
11417   else
11418     /* Otherwise, specify the selected frame, because we want to stop
11419        only at the very same frame.  */
11420     breakpoint = set_momentary_breakpoint (frame_gdbarch, sal,
11421                                            stack_frame_id, bp_until);
11422   make_cleanup_delete_breakpoint (breakpoint);
11423
11424   proceed (-1, GDB_SIGNAL_DEFAULT, 0);
11425
11426   /* If we are running asynchronously, and proceed call above has
11427      actually managed to start the target, arrange for breakpoints to
11428      be deleted when the target stops.  Otherwise, we're already
11429      stopped and delete breakpoints via cleanup chain.  */
11430
11431   if (target_can_async_p () && is_running (inferior_ptid))
11432     {
11433       struct until_break_command_continuation_args *args;
11434       args = xmalloc (sizeof (*args));
11435
11436       args->breakpoint = breakpoint;
11437       args->breakpoint2 = breakpoint2;
11438       args->thread_num = thread;
11439
11440       discard_cleanups (old_chain);
11441       add_continuation (inferior_thread (),
11442                         until_break_command_continuation, args,
11443                         xfree);
11444     }
11445   else
11446     do_cleanups (old_chain);
11447 }
11448
11449 /* This function attempts to parse an optional "if <cond>" clause
11450    from the arg string.  If one is not found, it returns NULL.
11451
11452    Else, it returns a pointer to the condition string.  (It does not
11453    attempt to evaluate the string against a particular block.)  And,
11454    it updates arg to point to the first character following the parsed
11455    if clause in the arg string.  */
11456
11457 static char *
11458 ep_parse_optional_if_clause (char **arg)
11459 {
11460   char *cond_string;
11461
11462   if (((*arg)[0] != 'i') || ((*arg)[1] != 'f') || !isspace ((*arg)[2]))
11463     return NULL;
11464
11465   /* Skip the "if" keyword.  */
11466   (*arg) += 2;
11467
11468   /* Skip any extra leading whitespace, and record the start of the
11469      condition string.  */
11470   *arg = skip_spaces (*arg);
11471   cond_string = *arg;
11472
11473   /* Assume that the condition occupies the remainder of the arg
11474      string.  */
11475   (*arg) += strlen (cond_string);
11476
11477   return cond_string;
11478 }
11479
11480 /* Commands to deal with catching events, such as signals, exceptions,
11481    process start/exit, etc.  */
11482
11483 typedef enum
11484 {
11485   catch_fork_temporary, catch_vfork_temporary,
11486   catch_fork_permanent, catch_vfork_permanent
11487 }
11488 catch_fork_kind;
11489
11490 static void
11491 catch_fork_command_1 (char *arg, int from_tty, 
11492                       struct cmd_list_element *command)
11493 {
11494   struct gdbarch *gdbarch = get_current_arch ();
11495   char *cond_string = NULL;
11496   catch_fork_kind fork_kind;
11497   int tempflag;
11498
11499   fork_kind = (catch_fork_kind) (uintptr_t) get_cmd_context (command);
11500   tempflag = (fork_kind == catch_fork_temporary
11501               || fork_kind == catch_vfork_temporary);
11502
11503   if (!arg)
11504     arg = "";
11505   arg = skip_spaces (arg);
11506
11507   /* The allowed syntax is:
11508      catch [v]fork
11509      catch [v]fork if <cond>
11510
11511      First, check if there's an if clause.  */
11512   cond_string = ep_parse_optional_if_clause (&arg);
11513
11514   if ((*arg != '\0') && !isspace (*arg))
11515     error (_("Junk at end of arguments."));
11516
11517   /* If this target supports it, create a fork or vfork catchpoint
11518      and enable reporting of such events.  */
11519   switch (fork_kind)
11520     {
11521     case catch_fork_temporary:
11522     case catch_fork_permanent:
11523       create_fork_vfork_event_catchpoint (gdbarch, tempflag, cond_string,
11524                                           &catch_fork_breakpoint_ops);
11525       break;
11526     case catch_vfork_temporary:
11527     case catch_vfork_permanent:
11528       create_fork_vfork_event_catchpoint (gdbarch, tempflag, cond_string,
11529                                           &catch_vfork_breakpoint_ops);
11530       break;
11531     default:
11532       error (_("unsupported or unknown fork kind; cannot catch it"));
11533       break;
11534     }
11535 }
11536
11537 static void
11538 catch_exec_command_1 (char *arg, int from_tty, 
11539                       struct cmd_list_element *command)
11540 {
11541   struct exec_catchpoint *c;
11542   struct gdbarch *gdbarch = get_current_arch ();
11543   int tempflag;
11544   char *cond_string = NULL;
11545
11546   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
11547
11548   if (!arg)
11549     arg = "";
11550   arg = skip_spaces (arg);
11551
11552   /* The allowed syntax is:
11553      catch exec
11554      catch exec if <cond>
11555
11556      First, check if there's an if clause.  */
11557   cond_string = ep_parse_optional_if_clause (&arg);
11558
11559   if ((*arg != '\0') && !isspace (*arg))
11560     error (_("Junk at end of arguments."));
11561
11562   c = XNEW (struct exec_catchpoint);
11563   init_catchpoint (&c->base, gdbarch, tempflag, cond_string,
11564                    &catch_exec_breakpoint_ops);
11565   c->exec_pathname = NULL;
11566
11567   install_breakpoint (0, &c->base, 1);
11568 }
11569
11570 static enum print_stop_action
11571 print_it_exception_catchpoint (bpstat bs)
11572 {
11573   struct ui_out *uiout = current_uiout;
11574   struct breakpoint *b = bs->breakpoint_at;
11575   int bp_temp, bp_throw;
11576
11577   annotate_catchpoint (b->number);
11578
11579   bp_throw = strstr (b->addr_string, "throw") != NULL;
11580   if (b->loc->address != b->loc->requested_address)
11581     breakpoint_adjustment_warning (b->loc->requested_address,
11582                                    b->loc->address,
11583                                    b->number, 1);
11584   bp_temp = b->disposition == disp_del;
11585   ui_out_text (uiout, 
11586                bp_temp ? "Temporary catchpoint "
11587                        : "Catchpoint ");
11588   if (!ui_out_is_mi_like_p (uiout))
11589     ui_out_field_int (uiout, "bkptno", b->number);
11590   ui_out_text (uiout,
11591                bp_throw ? " (exception thrown), "
11592                         : " (exception caught), ");
11593   if (ui_out_is_mi_like_p (uiout))
11594     {
11595       ui_out_field_string (uiout, "reason", 
11596                            async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
11597       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
11598       ui_out_field_int (uiout, "bkptno", b->number);
11599     }
11600   return PRINT_SRC_AND_LOC;
11601 }
11602
11603 static void
11604 print_one_exception_catchpoint (struct breakpoint *b, 
11605                                 struct bp_location **last_loc)
11606 {
11607   struct value_print_options opts;
11608   struct ui_out *uiout = current_uiout;
11609
11610   get_user_print_options (&opts);
11611   if (opts.addressprint)
11612     {
11613       annotate_field (4);
11614       if (b->loc == NULL || b->loc->shlib_disabled)
11615         ui_out_field_string (uiout, "addr", "<PENDING>");
11616       else
11617         ui_out_field_core_addr (uiout, "addr",
11618                                 b->loc->gdbarch, b->loc->address);
11619     }
11620   annotate_field (5);
11621   if (b->loc)
11622     *last_loc = b->loc;
11623   if (strstr (b->addr_string, "throw") != NULL)
11624     {
11625       ui_out_field_string (uiout, "what", "exception throw");
11626       if (ui_out_is_mi_like_p (uiout))
11627         ui_out_field_string (uiout, "catch-type", "throw");
11628     }
11629   else
11630     {
11631       ui_out_field_string (uiout, "what", "exception catch");
11632       if (ui_out_is_mi_like_p (uiout))
11633         ui_out_field_string (uiout, "catch-type", "catch");
11634     }
11635 }
11636
11637 static void
11638 print_mention_exception_catchpoint (struct breakpoint *b)
11639 {
11640   struct ui_out *uiout = current_uiout;
11641   int bp_temp;
11642   int bp_throw;
11643
11644   bp_temp = b->disposition == disp_del;
11645   bp_throw = strstr (b->addr_string, "throw") != NULL;
11646   ui_out_text (uiout, bp_temp ? _("Temporary catchpoint ")
11647                               : _("Catchpoint "));
11648   ui_out_field_int (uiout, "bkptno", b->number);
11649   ui_out_text (uiout, bp_throw ? _(" (throw)")
11650                                : _(" (catch)"));
11651 }
11652
11653 /* Implement the "print_recreate" breakpoint_ops method for throw and
11654    catch catchpoints.  */
11655
11656 static void
11657 print_recreate_exception_catchpoint (struct breakpoint *b, 
11658                                      struct ui_file *fp)
11659 {
11660   int bp_temp;
11661   int bp_throw;
11662
11663   bp_temp = b->disposition == disp_del;
11664   bp_throw = strstr (b->addr_string, "throw") != NULL;
11665   fprintf_unfiltered (fp, bp_temp ? "tcatch " : "catch ");
11666   fprintf_unfiltered (fp, bp_throw ? "throw" : "catch");
11667   print_recreate_thread (b, fp);
11668 }
11669
11670 static struct breakpoint_ops gnu_v3_exception_catchpoint_ops;
11671
11672 static int
11673 handle_gnu_v3_exceptions (int tempflag, char *cond_string,
11674                           enum exception_event_kind ex_event, int from_tty)
11675 {
11676   char *trigger_func_name;
11677  
11678   if (ex_event == EX_EVENT_CATCH)
11679     trigger_func_name = "__cxa_begin_catch";
11680   else
11681     trigger_func_name = "__cxa_throw";
11682
11683   create_breakpoint (get_current_arch (),
11684                      trigger_func_name, cond_string, -1, NULL,
11685                      0 /* condition and thread are valid.  */,
11686                      tempflag, bp_breakpoint,
11687                      0,
11688                      AUTO_BOOLEAN_TRUE /* pending */,
11689                      &gnu_v3_exception_catchpoint_ops, from_tty,
11690                      1 /* enabled */,
11691                      0 /* internal */,
11692                      0);
11693
11694   return 1;
11695 }
11696
11697 /* Deal with "catch catch" and "catch throw" commands.  */
11698
11699 static void
11700 catch_exception_command_1 (enum exception_event_kind ex_event, char *arg,
11701                            int tempflag, int from_tty)
11702 {
11703   char *cond_string = NULL;
11704
11705   if (!arg)
11706     arg = "";
11707   arg = skip_spaces (arg);
11708
11709   cond_string = ep_parse_optional_if_clause (&arg);
11710
11711   if ((*arg != '\0') && !isspace (*arg))
11712     error (_("Junk at end of arguments."));
11713
11714   if (ex_event != EX_EVENT_THROW
11715       && ex_event != EX_EVENT_CATCH)
11716     error (_("Unsupported or unknown exception event; cannot catch it"));
11717
11718   if (handle_gnu_v3_exceptions (tempflag, cond_string, ex_event, from_tty))
11719     return;
11720
11721   warning (_("Unsupported with this platform/compiler combination."));
11722 }
11723
11724 /* Implementation of "catch catch" command.  */
11725
11726 static void
11727 catch_catch_command (char *arg, int from_tty, struct cmd_list_element *command)
11728 {
11729   int tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
11730
11731   catch_exception_command_1 (EX_EVENT_CATCH, arg, tempflag, from_tty);
11732 }
11733
11734 /* Implementation of "catch throw" command.  */
11735
11736 static void
11737 catch_throw_command (char *arg, int from_tty, struct cmd_list_element *command)
11738 {
11739   int tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
11740
11741   catch_exception_command_1 (EX_EVENT_THROW, arg, tempflag, from_tty);
11742 }
11743
11744 void
11745 init_ada_exception_breakpoint (struct breakpoint *b,
11746                                struct gdbarch *gdbarch,
11747                                struct symtab_and_line sal,
11748                                char *addr_string,
11749                                const struct breakpoint_ops *ops,
11750                                int tempflag,
11751                                int from_tty)
11752 {
11753   if (from_tty)
11754     {
11755       struct gdbarch *loc_gdbarch = get_sal_arch (sal);
11756       if (!loc_gdbarch)
11757         loc_gdbarch = gdbarch;
11758
11759       describe_other_breakpoints (loc_gdbarch,
11760                                   sal.pspace, sal.pc, sal.section, -1);
11761       /* FIXME: brobecker/2006-12-28: Actually, re-implement a special
11762          version for exception catchpoints, because two catchpoints
11763          used for different exception names will use the same address.
11764          In this case, a "breakpoint ... also set at..." warning is
11765          unproductive.  Besides, the warning phrasing is also a bit
11766          inappropriate, we should use the word catchpoint, and tell
11767          the user what type of catchpoint it is.  The above is good
11768          enough for now, though.  */
11769     }
11770
11771   init_raw_breakpoint (b, gdbarch, sal, bp_breakpoint, ops);
11772
11773   b->enable_state = bp_enabled;
11774   b->disposition = tempflag ? disp_del : disp_donttouch;
11775   b->addr_string = addr_string;
11776   b->language = language_ada;
11777 }
11778
11779 /* Splits the argument using space as delimiter.  Returns an xmalloc'd
11780    filter list, or NULL if no filtering is required.  */
11781 static VEC(int) *
11782 catch_syscall_split_args (char *arg)
11783 {
11784   VEC(int) *result = NULL;
11785   struct cleanup *cleanup = make_cleanup (VEC_cleanup (int), &result);
11786
11787   while (*arg != '\0')
11788     {
11789       int i, syscall_number;
11790       char *endptr;
11791       char cur_name[128];
11792       struct syscall s;
11793
11794       /* Skip whitespace.  */
11795       arg = skip_spaces (arg);
11796
11797       for (i = 0; i < 127 && arg[i] && !isspace (arg[i]); ++i)
11798         cur_name[i] = arg[i];
11799       cur_name[i] = '\0';
11800       arg += i;
11801
11802       /* Check if the user provided a syscall name or a number.  */
11803       syscall_number = (int) strtol (cur_name, &endptr, 0);
11804       if (*endptr == '\0')
11805         get_syscall_by_number (syscall_number, &s);
11806       else
11807         {
11808           /* We have a name.  Let's check if it's valid and convert it
11809              to a number.  */
11810           get_syscall_by_name (cur_name, &s);
11811
11812           if (s.number == UNKNOWN_SYSCALL)
11813             /* Here we have to issue an error instead of a warning,
11814                because GDB cannot do anything useful if there's no
11815                syscall number to be caught.  */
11816             error (_("Unknown syscall name '%s'."), cur_name);
11817         }
11818
11819       /* Ok, it's valid.  */
11820       VEC_safe_push (int, result, s.number);
11821     }
11822
11823   discard_cleanups (cleanup);
11824   return result;
11825 }
11826
11827 /* Implement the "catch syscall" command.  */
11828
11829 static void
11830 catch_syscall_command_1 (char *arg, int from_tty, 
11831                          struct cmd_list_element *command)
11832 {
11833   int tempflag;
11834   VEC(int) *filter;
11835   struct syscall s;
11836   struct gdbarch *gdbarch = get_current_arch ();
11837
11838   /* Checking if the feature if supported.  */
11839   if (gdbarch_get_syscall_number_p (gdbarch) == 0)
11840     error (_("The feature 'catch syscall' is not supported on \
11841 this architecture yet."));
11842
11843   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
11844
11845   arg = skip_spaces (arg);
11846
11847   /* We need to do this first "dummy" translation in order
11848      to get the syscall XML file loaded or, most important,
11849      to display a warning to the user if there's no XML file
11850      for his/her architecture.  */
11851   get_syscall_by_number (0, &s);
11852
11853   /* The allowed syntax is:
11854      catch syscall
11855      catch syscall <name | number> [<name | number> ... <name | number>]
11856
11857      Let's check if there's a syscall name.  */
11858
11859   if (arg != NULL)
11860     filter = catch_syscall_split_args (arg);
11861   else
11862     filter = NULL;
11863
11864   create_syscall_event_catchpoint (tempflag, filter,
11865                                    &catch_syscall_breakpoint_ops);
11866 }
11867
11868 static void
11869 catch_command (char *arg, int from_tty)
11870 {
11871   error (_("Catch requires an event name."));
11872 }
11873 \f
11874
11875 static void
11876 tcatch_command (char *arg, int from_tty)
11877 {
11878   error (_("Catch requires an event name."));
11879 }
11880
11881 /* A qsort comparison function that sorts breakpoints in order.  */
11882
11883 static int
11884 compare_breakpoints (const void *a, const void *b)
11885 {
11886   const breakpoint_p *ba = a;
11887   uintptr_t ua = (uintptr_t) *ba;
11888   const breakpoint_p *bb = b;
11889   uintptr_t ub = (uintptr_t) *bb;
11890
11891   if ((*ba)->number < (*bb)->number)
11892     return -1;
11893   else if ((*ba)->number > (*bb)->number)
11894     return 1;
11895
11896   /* Now sort by address, in case we see, e..g, two breakpoints with
11897      the number 0.  */
11898   if (ua < ub)
11899     return -1;
11900   return ua > ub ? 1 : 0;
11901 }
11902
11903 /* Delete breakpoints by address or line.  */
11904
11905 static void
11906 clear_command (char *arg, int from_tty)
11907 {
11908   struct breakpoint *b, *prev;
11909   VEC(breakpoint_p) *found = 0;
11910   int ix;
11911   int default_match;
11912   struct symtabs_and_lines sals;
11913   struct symtab_and_line sal;
11914   int i;
11915   struct cleanup *cleanups = make_cleanup (null_cleanup, NULL);
11916
11917   if (arg)
11918     {
11919       sals = decode_line_with_current_source (arg,
11920                                               (DECODE_LINE_FUNFIRSTLINE
11921                                                | DECODE_LINE_LIST_MODE));
11922       make_cleanup (xfree, sals.sals);
11923       default_match = 0;
11924     }
11925   else
11926     {
11927       sals.sals = (struct symtab_and_line *)
11928         xmalloc (sizeof (struct symtab_and_line));
11929       make_cleanup (xfree, sals.sals);
11930       init_sal (&sal);          /* Initialize to zeroes.  */
11931
11932       /* Set sal's line, symtab, pc, and pspace to the values
11933          corresponding to the last call to print_frame_info.  If the
11934          codepoint is not valid, this will set all the fields to 0.  */
11935       get_last_displayed_sal (&sal);
11936       if (sal.symtab == 0)
11937         error (_("No source file specified."));
11938
11939       sals.sals[0] = sal;
11940       sals.nelts = 1;
11941
11942       default_match = 1;
11943     }
11944
11945   /* We don't call resolve_sal_pc here.  That's not as bad as it
11946      seems, because all existing breakpoints typically have both
11947      file/line and pc set.  So, if clear is given file/line, we can
11948      match this to existing breakpoint without obtaining pc at all.
11949
11950      We only support clearing given the address explicitly 
11951      present in breakpoint table.  Say, we've set breakpoint 
11952      at file:line.  There were several PC values for that file:line,
11953      due to optimization, all in one block.
11954
11955      We've picked one PC value.  If "clear" is issued with another
11956      PC corresponding to the same file:line, the breakpoint won't
11957      be cleared.  We probably can still clear the breakpoint, but 
11958      since the other PC value is never presented to user, user
11959      can only find it by guessing, and it does not seem important
11960      to support that.  */
11961
11962   /* For each line spec given, delete bps which correspond to it.  Do
11963      it in two passes, solely to preserve the current behavior that
11964      from_tty is forced true if we delete more than one
11965      breakpoint.  */
11966
11967   found = NULL;
11968   make_cleanup (VEC_cleanup (breakpoint_p), &found);
11969   for (i = 0; i < sals.nelts; i++)
11970     {
11971       const char *sal_fullname;
11972
11973       /* If exact pc given, clear bpts at that pc.
11974          If line given (pc == 0), clear all bpts on specified line.
11975          If defaulting, clear all bpts on default line
11976          or at default pc.
11977
11978          defaulting    sal.pc != 0    tests to do
11979
11980          0              1             pc
11981          1              1             pc _and_ line
11982          0              0             line
11983          1              0             <can't happen> */
11984
11985       sal = sals.sals[i];
11986       sal_fullname = (sal.symtab == NULL
11987                       ? NULL : symtab_to_fullname (sal.symtab));
11988
11989       /* Find all matching breakpoints and add them to 'found'.  */
11990       ALL_BREAKPOINTS (b)
11991         {
11992           int match = 0;
11993           /* Are we going to delete b?  */
11994           if (b->type != bp_none && !is_watchpoint (b))
11995             {
11996               struct bp_location *loc = b->loc;
11997               for (; loc; loc = loc->next)
11998                 {
11999                   /* If the user specified file:line, don't allow a PC
12000                      match.  This matches historical gdb behavior.  */
12001                   int pc_match = (!sal.explicit_line
12002                                   && sal.pc
12003                                   && (loc->pspace == sal.pspace)
12004                                   && (loc->address == sal.pc)
12005                                   && (!section_is_overlay (loc->section)
12006                                       || loc->section == sal.section));
12007                   int line_match = 0;
12008
12009                   if ((default_match || sal.explicit_line)
12010                       && loc->symtab != NULL
12011                       && sal_fullname != NULL
12012                       && sal.pspace == loc->pspace
12013                       && loc->line_number == sal.line
12014                       && filename_cmp (symtab_to_fullname (loc->symtab),
12015                                        sal_fullname) == 0)
12016                     line_match = 1;
12017
12018                   if (pc_match || line_match)
12019                     {
12020                       match = 1;
12021                       break;
12022                     }
12023                 }
12024             }
12025
12026           if (match)
12027             VEC_safe_push(breakpoint_p, found, b);
12028         }
12029     }
12030
12031   /* Now go thru the 'found' chain and delete them.  */
12032   if (VEC_empty(breakpoint_p, found))
12033     {
12034       if (arg)
12035         error (_("No breakpoint at %s."), arg);
12036       else
12037         error (_("No breakpoint at this line."));
12038     }
12039
12040   /* Remove duplicates from the vec.  */
12041   qsort (VEC_address (breakpoint_p, found),
12042          VEC_length (breakpoint_p, found),
12043          sizeof (breakpoint_p),
12044          compare_breakpoints);
12045   prev = VEC_index (breakpoint_p, found, 0);
12046   for (ix = 1; VEC_iterate (breakpoint_p, found, ix, b); ++ix)
12047     {
12048       if (b == prev)
12049         {
12050           VEC_ordered_remove (breakpoint_p, found, ix);
12051           --ix;
12052         }
12053     }
12054
12055   if (VEC_length(breakpoint_p, found) > 1)
12056     from_tty = 1;       /* Always report if deleted more than one.  */
12057   if (from_tty)
12058     {
12059       if (VEC_length(breakpoint_p, found) == 1)
12060         printf_unfiltered (_("Deleted breakpoint "));
12061       else
12062         printf_unfiltered (_("Deleted breakpoints "));
12063     }
12064
12065   for (ix = 0; VEC_iterate(breakpoint_p, found, ix, b); ix++)
12066     {
12067       if (from_tty)
12068         printf_unfiltered ("%d ", b->number);
12069       delete_breakpoint (b);
12070     }
12071   if (from_tty)
12072     putchar_unfiltered ('\n');
12073
12074   do_cleanups (cleanups);
12075 }
12076 \f
12077 /* Delete breakpoint in BS if they are `delete' breakpoints and
12078    all breakpoints that are marked for deletion, whether hit or not.
12079    This is called after any breakpoint is hit, or after errors.  */
12080
12081 void
12082 breakpoint_auto_delete (bpstat bs)
12083 {
12084   struct breakpoint *b, *b_tmp;
12085
12086   for (; bs; bs = bs->next)
12087     if (bs->breakpoint_at
12088         && bs->breakpoint_at->disposition == disp_del
12089         && bs->stop)
12090       delete_breakpoint (bs->breakpoint_at);
12091
12092   ALL_BREAKPOINTS_SAFE (b, b_tmp)
12093   {
12094     if (b->disposition == disp_del_at_next_stop)
12095       delete_breakpoint (b);
12096   }
12097 }
12098
12099 /* A comparison function for bp_location AP and BP being interfaced to
12100    qsort.  Sort elements primarily by their ADDRESS (no matter what
12101    does breakpoint_address_is_meaningful say for its OWNER),
12102    secondarily by ordering first bp_permanent OWNERed elements and
12103    terciarily just ensuring the array is sorted stable way despite
12104    qsort being an unstable algorithm.  */
12105
12106 static int
12107 bp_location_compare (const void *ap, const void *bp)
12108 {
12109   struct bp_location *a = *(void **) ap;
12110   struct bp_location *b = *(void **) bp;
12111   /* A and B come from existing breakpoints having non-NULL OWNER.  */
12112   int a_perm = a->owner->enable_state == bp_permanent;
12113   int b_perm = b->owner->enable_state == bp_permanent;
12114
12115   if (a->address != b->address)
12116     return (a->address > b->address) - (a->address < b->address);
12117
12118   /* Sort locations at the same address by their pspace number, keeping
12119      locations of the same inferior (in a multi-inferior environment)
12120      grouped.  */
12121
12122   if (a->pspace->num != b->pspace->num)
12123     return ((a->pspace->num > b->pspace->num)
12124             - (a->pspace->num < b->pspace->num));
12125
12126   /* Sort permanent breakpoints first.  */
12127   if (a_perm != b_perm)
12128     return (a_perm < b_perm) - (a_perm > b_perm);
12129
12130   /* Make the internal GDB representation stable across GDB runs
12131      where A and B memory inside GDB can differ.  Breakpoint locations of
12132      the same type at the same address can be sorted in arbitrary order.  */
12133
12134   if (a->owner->number != b->owner->number)
12135     return ((a->owner->number > b->owner->number)
12136             - (a->owner->number < b->owner->number));
12137
12138   return (a > b) - (a < b);
12139 }
12140
12141 /* Set bp_location_placed_address_before_address_max and
12142    bp_location_shadow_len_after_address_max according to the current
12143    content of the bp_location array.  */
12144
12145 static void
12146 bp_location_target_extensions_update (void)
12147 {
12148   struct bp_location *bl, **blp_tmp;
12149
12150   bp_location_placed_address_before_address_max = 0;
12151   bp_location_shadow_len_after_address_max = 0;
12152
12153   ALL_BP_LOCATIONS (bl, blp_tmp)
12154     {
12155       CORE_ADDR start, end, addr;
12156
12157       if (!bp_location_has_shadow (bl))
12158         continue;
12159
12160       start = bl->target_info.placed_address;
12161       end = start + bl->target_info.shadow_len;
12162
12163       gdb_assert (bl->address >= start);
12164       addr = bl->address - start;
12165       if (addr > bp_location_placed_address_before_address_max)
12166         bp_location_placed_address_before_address_max = addr;
12167
12168       /* Zero SHADOW_LEN would not pass bp_location_has_shadow.  */
12169
12170       gdb_assert (bl->address < end);
12171       addr = end - bl->address;
12172       if (addr > bp_location_shadow_len_after_address_max)
12173         bp_location_shadow_len_after_address_max = addr;
12174     }
12175 }
12176
12177 /* Download tracepoint locations if they haven't been.  */
12178
12179 static void
12180 download_tracepoint_locations (void)
12181 {
12182   struct breakpoint *b;
12183   struct cleanup *old_chain;
12184
12185   if (!target_can_download_tracepoint ())
12186     return;
12187
12188   old_chain = save_current_space_and_thread ();
12189
12190   ALL_TRACEPOINTS (b)
12191     {
12192       struct bp_location *bl;
12193       struct tracepoint *t;
12194       int bp_location_downloaded = 0;
12195
12196       if ((b->type == bp_fast_tracepoint
12197            ? !may_insert_fast_tracepoints
12198            : !may_insert_tracepoints))
12199         continue;
12200
12201       for (bl = b->loc; bl; bl = bl->next)
12202         {
12203           /* In tracepoint, locations are _never_ duplicated, so
12204              should_be_inserted is equivalent to
12205              unduplicated_should_be_inserted.  */
12206           if (!should_be_inserted (bl) || bl->inserted)
12207             continue;
12208
12209           switch_to_program_space_and_thread (bl->pspace);
12210
12211           target_download_tracepoint (bl);
12212
12213           bl->inserted = 1;
12214           bp_location_downloaded = 1;
12215         }
12216       t = (struct tracepoint *) b;
12217       t->number_on_target = b->number;
12218       if (bp_location_downloaded)
12219         observer_notify_breakpoint_modified (b);
12220     }
12221
12222   do_cleanups (old_chain);
12223 }
12224
12225 /* Swap the insertion/duplication state between two locations.  */
12226
12227 static void
12228 swap_insertion (struct bp_location *left, struct bp_location *right)
12229 {
12230   const int left_inserted = left->inserted;
12231   const int left_duplicate = left->duplicate;
12232   const int left_needs_update = left->needs_update;
12233   const struct bp_target_info left_target_info = left->target_info;
12234
12235   /* Locations of tracepoints can never be duplicated.  */
12236   if (is_tracepoint (left->owner))
12237     gdb_assert (!left->duplicate);
12238   if (is_tracepoint (right->owner))
12239     gdb_assert (!right->duplicate);
12240
12241   left->inserted = right->inserted;
12242   left->duplicate = right->duplicate;
12243   left->needs_update = right->needs_update;
12244   left->target_info = right->target_info;
12245   right->inserted = left_inserted;
12246   right->duplicate = left_duplicate;
12247   right->needs_update = left_needs_update;
12248   right->target_info = left_target_info;
12249 }
12250
12251 /* Force the re-insertion of the locations at ADDRESS.  This is called
12252    once a new/deleted/modified duplicate location is found and we are evaluating
12253    conditions on the target's side.  Such conditions need to be updated on
12254    the target.  */
12255
12256 static void
12257 force_breakpoint_reinsertion (struct bp_location *bl)
12258 {
12259   struct bp_location **locp = NULL, **loc2p;
12260   struct bp_location *loc;
12261   CORE_ADDR address = 0;
12262   int pspace_num;
12263
12264   address = bl->address;
12265   pspace_num = bl->pspace->num;
12266
12267   /* This is only meaningful if the target is
12268      evaluating conditions and if the user has
12269      opted for condition evaluation on the target's
12270      side.  */
12271   if (gdb_evaluates_breakpoint_condition_p ()
12272       || !target_supports_evaluation_of_breakpoint_conditions ())
12273     return;
12274
12275   /* Flag all breakpoint locations with this address and
12276      the same program space as the location
12277      as "its condition has changed".  We need to
12278      update the conditions on the target's side.  */
12279   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, address)
12280     {
12281       loc = *loc2p;
12282
12283       if (!is_breakpoint (loc->owner)
12284           || pspace_num != loc->pspace->num)
12285         continue;
12286
12287       /* Flag the location appropriately.  We use a different state to
12288          let everyone know that we already updated the set of locations
12289          with addr bl->address and program space bl->pspace.  This is so
12290          we don't have to keep calling these functions just to mark locations
12291          that have already been marked.  */
12292       loc->condition_changed = condition_updated;
12293
12294       /* Free the agent expression bytecode as well.  We will compute
12295          it later on.  */
12296       if (loc->cond_bytecode)
12297         {
12298           free_agent_expr (loc->cond_bytecode);
12299           loc->cond_bytecode = NULL;
12300         }
12301     }
12302 }
12303
12304 /* If SHOULD_INSERT is false, do not insert any breakpoint locations
12305    into the inferior, only remove already-inserted locations that no
12306    longer should be inserted.  Functions that delete a breakpoint or
12307    breakpoints should pass false, so that deleting a breakpoint
12308    doesn't have the side effect of inserting the locations of other
12309    breakpoints that are marked not-inserted, but should_be_inserted
12310    returns true on them.
12311
12312    This behaviour is useful is situations close to tear-down -- e.g.,
12313    after an exec, while the target still has execution, but breakpoint
12314    shadows of the previous executable image should *NOT* be restored
12315    to the new image; or before detaching, where the target still has
12316    execution and wants to delete breakpoints from GDB's lists, and all
12317    breakpoints had already been removed from the inferior.  */
12318
12319 static void
12320 update_global_location_list (int should_insert)
12321 {
12322   struct breakpoint *b;
12323   struct bp_location **locp, *loc;
12324   struct cleanup *cleanups;
12325   /* Last breakpoint location address that was marked for update.  */
12326   CORE_ADDR last_addr = 0;
12327   /* Last breakpoint location program space that was marked for update.  */
12328   int last_pspace_num = -1;
12329
12330   /* Used in the duplicates detection below.  When iterating over all
12331      bp_locations, points to the first bp_location of a given address.
12332      Breakpoints and watchpoints of different types are never
12333      duplicates of each other.  Keep one pointer for each type of
12334      breakpoint/watchpoint, so we only need to loop over all locations
12335      once.  */
12336   struct bp_location *bp_loc_first;  /* breakpoint */
12337   struct bp_location *wp_loc_first;  /* hardware watchpoint */
12338   struct bp_location *awp_loc_first; /* access watchpoint */
12339   struct bp_location *rwp_loc_first; /* read watchpoint */
12340
12341   /* Saved former bp_location array which we compare against the newly
12342      built bp_location from the current state of ALL_BREAKPOINTS.  */
12343   struct bp_location **old_location, **old_locp;
12344   unsigned old_location_count;
12345
12346   old_location = bp_location;
12347   old_location_count = bp_location_count;
12348   bp_location = NULL;
12349   bp_location_count = 0;
12350   cleanups = make_cleanup (xfree, old_location);
12351
12352   ALL_BREAKPOINTS (b)
12353     for (loc = b->loc; loc; loc = loc->next)
12354       bp_location_count++;
12355
12356   bp_location = xmalloc (sizeof (*bp_location) * bp_location_count);
12357   locp = bp_location;
12358   ALL_BREAKPOINTS (b)
12359     for (loc = b->loc; loc; loc = loc->next)
12360       *locp++ = loc;
12361   qsort (bp_location, bp_location_count, sizeof (*bp_location),
12362          bp_location_compare);
12363
12364   bp_location_target_extensions_update ();
12365
12366   /* Identify bp_location instances that are no longer present in the
12367      new list, and therefore should be freed.  Note that it's not
12368      necessary that those locations should be removed from inferior --
12369      if there's another location at the same address (previously
12370      marked as duplicate), we don't need to remove/insert the
12371      location.
12372      
12373      LOCP is kept in sync with OLD_LOCP, each pointing to the current
12374      and former bp_location array state respectively.  */
12375
12376   locp = bp_location;
12377   for (old_locp = old_location; old_locp < old_location + old_location_count;
12378        old_locp++)
12379     {
12380       struct bp_location *old_loc = *old_locp;
12381       struct bp_location **loc2p;
12382
12383       /* Tells if 'old_loc' is found among the new locations.  If
12384          not, we have to free it.  */
12385       int found_object = 0;
12386       /* Tells if the location should remain inserted in the target.  */
12387       int keep_in_target = 0;
12388       int removed = 0;
12389
12390       /* Skip LOCP entries which will definitely never be needed.
12391          Stop either at or being the one matching OLD_LOC.  */
12392       while (locp < bp_location + bp_location_count
12393              && (*locp)->address < old_loc->address)
12394         locp++;
12395
12396       for (loc2p = locp;
12397            (loc2p < bp_location + bp_location_count
12398             && (*loc2p)->address == old_loc->address);
12399            loc2p++)
12400         {
12401           /* Check if this is a new/duplicated location or a duplicated
12402              location that had its condition modified.  If so, we want to send
12403              its condition to the target if evaluation of conditions is taking
12404              place there.  */
12405           if ((*loc2p)->condition_changed == condition_modified
12406               && (last_addr != old_loc->address
12407                   || last_pspace_num != old_loc->pspace->num))
12408             {
12409               force_breakpoint_reinsertion (*loc2p);
12410               last_pspace_num = old_loc->pspace->num;
12411             }
12412
12413           if (*loc2p == old_loc)
12414             found_object = 1;
12415         }
12416
12417       /* We have already handled this address, update it so that we don't
12418          have to go through updates again.  */
12419       last_addr = old_loc->address;
12420
12421       /* Target-side condition evaluation: Handle deleted locations.  */
12422       if (!found_object)
12423         force_breakpoint_reinsertion (old_loc);
12424
12425       /* If this location is no longer present, and inserted, look if
12426          there's maybe a new location at the same address.  If so,
12427          mark that one inserted, and don't remove this one.  This is
12428          needed so that we don't have a time window where a breakpoint
12429          at certain location is not inserted.  */
12430
12431       if (old_loc->inserted)
12432         {
12433           /* If the location is inserted now, we might have to remove
12434              it.  */
12435
12436           if (found_object && should_be_inserted (old_loc))
12437             {
12438               /* The location is still present in the location list,
12439                  and still should be inserted.  Don't do anything.  */
12440               keep_in_target = 1;
12441             }
12442           else
12443             {
12444               /* This location still exists, but it won't be kept in the
12445                  target since it may have been disabled.  We proceed to
12446                  remove its target-side condition.  */
12447
12448               /* The location is either no longer present, or got
12449                  disabled.  See if there's another location at the
12450                  same address, in which case we don't need to remove
12451                  this one from the target.  */
12452
12453               /* OLD_LOC comes from existing struct breakpoint.  */
12454               if (breakpoint_address_is_meaningful (old_loc->owner))
12455                 {
12456                   for (loc2p = locp;
12457                        (loc2p < bp_location + bp_location_count
12458                         && (*loc2p)->address == old_loc->address);
12459                        loc2p++)
12460                     {
12461                       struct bp_location *loc2 = *loc2p;
12462
12463                       if (breakpoint_locations_match (loc2, old_loc))
12464                         {
12465                           /* Read watchpoint locations are switched to
12466                              access watchpoints, if the former are not
12467                              supported, but the latter are.  */
12468                           if (is_hardware_watchpoint (old_loc->owner))
12469                             {
12470                               gdb_assert (is_hardware_watchpoint (loc2->owner));
12471                               loc2->watchpoint_type = old_loc->watchpoint_type;
12472                             }
12473
12474                           /* loc2 is a duplicated location. We need to check
12475                              if it should be inserted in case it will be
12476                              unduplicated.  */
12477                           if (loc2 != old_loc
12478                               && unduplicated_should_be_inserted (loc2))
12479                             {
12480                               swap_insertion (old_loc, loc2);
12481                               keep_in_target = 1;
12482                               break;
12483                             }
12484                         }
12485                     }
12486                 }
12487             }
12488
12489           if (!keep_in_target)
12490             {
12491               if (remove_breakpoint (old_loc, mark_uninserted))
12492                 {
12493                   /* This is just about all we can do.  We could keep
12494                      this location on the global list, and try to
12495                      remove it next time, but there's no particular
12496                      reason why we will succeed next time.
12497                      
12498                      Note that at this point, old_loc->owner is still
12499                      valid, as delete_breakpoint frees the breakpoint
12500                      only after calling us.  */
12501                   printf_filtered (_("warning: Error removing "
12502                                      "breakpoint %d\n"), 
12503                                    old_loc->owner->number);
12504                 }
12505               removed = 1;
12506             }
12507         }
12508
12509       if (!found_object)
12510         {
12511           if (removed && non_stop
12512               && breakpoint_address_is_meaningful (old_loc->owner)
12513               && !is_hardware_watchpoint (old_loc->owner))
12514             {
12515               /* This location was removed from the target.  In
12516                  non-stop mode, a race condition is possible where
12517                  we've removed a breakpoint, but stop events for that
12518                  breakpoint are already queued and will arrive later.
12519                  We apply an heuristic to be able to distinguish such
12520                  SIGTRAPs from other random SIGTRAPs: we keep this
12521                  breakpoint location for a bit, and will retire it
12522                  after we see some number of events.  The theory here
12523                  is that reporting of events should, "on the average",
12524                  be fair, so after a while we'll see events from all
12525                  threads that have anything of interest, and no longer
12526                  need to keep this breakpoint location around.  We
12527                  don't hold locations forever so to reduce chances of
12528                  mistaking a non-breakpoint SIGTRAP for a breakpoint
12529                  SIGTRAP.
12530
12531                  The heuristic failing can be disastrous on
12532                  decr_pc_after_break targets.
12533
12534                  On decr_pc_after_break targets, like e.g., x86-linux,
12535                  if we fail to recognize a late breakpoint SIGTRAP,
12536                  because events_till_retirement has reached 0 too
12537                  soon, we'll fail to do the PC adjustment, and report
12538                  a random SIGTRAP to the user.  When the user resumes
12539                  the inferior, it will most likely immediately crash
12540                  with SIGILL/SIGBUS/SIGSEGV, or worse, get silently
12541                  corrupted, because of being resumed e.g., in the
12542                  middle of a multi-byte instruction, or skipped a
12543                  one-byte instruction.  This was actually seen happen
12544                  on native x86-linux, and should be less rare on
12545                  targets that do not support new thread events, like
12546                  remote, due to the heuristic depending on
12547                  thread_count.
12548
12549                  Mistaking a random SIGTRAP for a breakpoint trap
12550                  causes similar symptoms (PC adjustment applied when
12551                  it shouldn't), but then again, playing with SIGTRAPs
12552                  behind the debugger's back is asking for trouble.
12553
12554                  Since hardware watchpoint traps are always
12555                  distinguishable from other traps, so we don't need to
12556                  apply keep hardware watchpoint moribund locations
12557                  around.  We simply always ignore hardware watchpoint
12558                  traps we can no longer explain.  */
12559
12560               old_loc->events_till_retirement = 3 * (thread_count () + 1);
12561               old_loc->owner = NULL;
12562
12563               VEC_safe_push (bp_location_p, moribund_locations, old_loc);
12564             }
12565           else
12566             {
12567               old_loc->owner = NULL;
12568               decref_bp_location (&old_loc);
12569             }
12570         }
12571     }
12572
12573   /* Rescan breakpoints at the same address and section, marking the
12574      first one as "first" and any others as "duplicates".  This is so
12575      that the bpt instruction is only inserted once.  If we have a
12576      permanent breakpoint at the same place as BPT, make that one the
12577      official one, and the rest as duplicates.  Permanent breakpoints
12578      are sorted first for the same address.
12579
12580      Do the same for hardware watchpoints, but also considering the
12581      watchpoint's type (regular/access/read) and length.  */
12582
12583   bp_loc_first = NULL;
12584   wp_loc_first = NULL;
12585   awp_loc_first = NULL;
12586   rwp_loc_first = NULL;
12587   ALL_BP_LOCATIONS (loc, locp)
12588     {
12589       /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always
12590          non-NULL.  */
12591       struct bp_location **loc_first_p;
12592       b = loc->owner;
12593
12594       if (!unduplicated_should_be_inserted (loc)
12595           || !breakpoint_address_is_meaningful (b)
12596           /* Don't detect duplicate for tracepoint locations because they are
12597            never duplicated.  See the comments in field `duplicate' of
12598            `struct bp_location'.  */
12599           || is_tracepoint (b))
12600         {
12601           /* Clear the condition modification flag.  */
12602           loc->condition_changed = condition_unchanged;
12603           continue;
12604         }
12605
12606       /* Permanent breakpoint should always be inserted.  */
12607       if (b->enable_state == bp_permanent && ! loc->inserted)
12608         internal_error (__FILE__, __LINE__,
12609                         _("allegedly permanent breakpoint is not "
12610                         "actually inserted"));
12611
12612       if (b->type == bp_hardware_watchpoint)
12613         loc_first_p = &wp_loc_first;
12614       else if (b->type == bp_read_watchpoint)
12615         loc_first_p = &rwp_loc_first;
12616       else if (b->type == bp_access_watchpoint)
12617         loc_first_p = &awp_loc_first;
12618       else
12619         loc_first_p = &bp_loc_first;
12620
12621       if (*loc_first_p == NULL
12622           || (overlay_debugging && loc->section != (*loc_first_p)->section)
12623           || !breakpoint_locations_match (loc, *loc_first_p))
12624         {
12625           *loc_first_p = loc;
12626           loc->duplicate = 0;
12627
12628           if (is_breakpoint (loc->owner) && loc->condition_changed)
12629             {
12630               loc->needs_update = 1;
12631               /* Clear the condition modification flag.  */
12632               loc->condition_changed = condition_unchanged;
12633             }
12634           continue;
12635         }
12636
12637
12638       /* This and the above ensure the invariant that the first location
12639          is not duplicated, and is the inserted one.
12640          All following are marked as duplicated, and are not inserted.  */
12641       if (loc->inserted)
12642         swap_insertion (loc, *loc_first_p);
12643       loc->duplicate = 1;
12644
12645       /* Clear the condition modification flag.  */
12646       loc->condition_changed = condition_unchanged;
12647
12648       if ((*loc_first_p)->owner->enable_state == bp_permanent && loc->inserted
12649           && b->enable_state != bp_permanent)
12650         internal_error (__FILE__, __LINE__,
12651                         _("another breakpoint was inserted on top of "
12652                         "a permanent breakpoint"));
12653     }
12654
12655   if (breakpoints_always_inserted_mode ()
12656       && (have_live_inferiors ()
12657           || (gdbarch_has_global_breakpoints (target_gdbarch ()))))
12658     {
12659       if (should_insert)
12660         insert_breakpoint_locations ();
12661       else
12662         {
12663           /* Though should_insert is false, we may need to update conditions
12664              on the target's side if it is evaluating such conditions.  We
12665              only update conditions for locations that are marked
12666              "needs_update".  */
12667           update_inserted_breakpoint_locations ();
12668         }
12669     }
12670
12671   if (should_insert)
12672     download_tracepoint_locations ();
12673
12674   do_cleanups (cleanups);
12675 }
12676
12677 void
12678 breakpoint_retire_moribund (void)
12679 {
12680   struct bp_location *loc;
12681   int ix;
12682
12683   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
12684     if (--(loc->events_till_retirement) == 0)
12685       {
12686         decref_bp_location (&loc);
12687         VEC_unordered_remove (bp_location_p, moribund_locations, ix);
12688         --ix;
12689       }
12690 }
12691
12692 static void
12693 update_global_location_list_nothrow (int inserting)
12694 {
12695   volatile struct gdb_exception e;
12696
12697   TRY_CATCH (e, RETURN_MASK_ERROR)
12698     update_global_location_list (inserting);
12699 }
12700
12701 /* Clear BKP from a BPS.  */
12702
12703 static void
12704 bpstat_remove_bp_location (bpstat bps, struct breakpoint *bpt)
12705 {
12706   bpstat bs;
12707
12708   for (bs = bps; bs; bs = bs->next)
12709     if (bs->breakpoint_at == bpt)
12710       {
12711         bs->breakpoint_at = NULL;
12712         bs->old_val = NULL;
12713         /* bs->commands will be freed later.  */
12714       }
12715 }
12716
12717 /* Callback for iterate_over_threads.  */
12718 static int
12719 bpstat_remove_breakpoint_callback (struct thread_info *th, void *data)
12720 {
12721   struct breakpoint *bpt = data;
12722
12723   bpstat_remove_bp_location (th->control.stop_bpstat, bpt);
12724   return 0;
12725 }
12726
12727 /* Helper for breakpoint and tracepoint breakpoint_ops->mention
12728    callbacks.  */
12729
12730 static void
12731 say_where (struct breakpoint *b)
12732 {
12733   struct value_print_options opts;
12734
12735   get_user_print_options (&opts);
12736
12737   /* i18n: cagney/2005-02-11: Below needs to be merged into a
12738      single string.  */
12739   if (b->loc == NULL)
12740     {
12741       printf_filtered (_(" (%s) pending."), b->addr_string);
12742     }
12743   else
12744     {
12745       if (opts.addressprint || b->loc->symtab == NULL)
12746         {
12747           printf_filtered (" at ");
12748           fputs_filtered (paddress (b->loc->gdbarch, b->loc->address),
12749                           gdb_stdout);
12750         }
12751       if (b->loc->symtab != NULL)
12752         {
12753           /* If there is a single location, we can print the location
12754              more nicely.  */
12755           if (b->loc->next == NULL)
12756             printf_filtered (": file %s, line %d.",
12757                              symtab_to_filename_for_display (b->loc->symtab),
12758                              b->loc->line_number);
12759           else
12760             /* This is not ideal, but each location may have a
12761                different file name, and this at least reflects the
12762                real situation somewhat.  */
12763             printf_filtered (": %s.", b->addr_string);
12764         }
12765
12766       if (b->loc->next)
12767         {
12768           struct bp_location *loc = b->loc;
12769           int n = 0;
12770           for (; loc; loc = loc->next)
12771             ++n;
12772           printf_filtered (" (%d locations)", n);
12773         }
12774     }
12775 }
12776
12777 /* Default bp_location_ops methods.  */
12778
12779 static void
12780 bp_location_dtor (struct bp_location *self)
12781 {
12782   xfree (self->cond);
12783   if (self->cond_bytecode)
12784     free_agent_expr (self->cond_bytecode);
12785   xfree (self->function_name);
12786 }
12787
12788 static const struct bp_location_ops bp_location_ops =
12789 {
12790   bp_location_dtor
12791 };
12792
12793 /* Default breakpoint_ops methods all breakpoint_ops ultimately
12794    inherit from.  */
12795
12796 static void
12797 base_breakpoint_dtor (struct breakpoint *self)
12798 {
12799   decref_counted_command_line (&self->commands);
12800   xfree (self->cond_string);
12801   xfree (self->extra_string);
12802   xfree (self->addr_string);
12803   xfree (self->filter);
12804   xfree (self->addr_string_range_end);
12805 }
12806
12807 static struct bp_location *
12808 base_breakpoint_allocate_location (struct breakpoint *self)
12809 {
12810   struct bp_location *loc;
12811
12812   loc = XNEW (struct bp_location);
12813   init_bp_location (loc, &bp_location_ops, self);
12814   return loc;
12815 }
12816
12817 static void
12818 base_breakpoint_re_set (struct breakpoint *b)
12819 {
12820   /* Nothing to re-set. */
12821 }
12822
12823 #define internal_error_pure_virtual_called() \
12824   gdb_assert_not_reached ("pure virtual function called")
12825
12826 static int
12827 base_breakpoint_insert_location (struct bp_location *bl)
12828 {
12829   internal_error_pure_virtual_called ();
12830 }
12831
12832 static int
12833 base_breakpoint_remove_location (struct bp_location *bl)
12834 {
12835   internal_error_pure_virtual_called ();
12836 }
12837
12838 static int
12839 base_breakpoint_breakpoint_hit (const struct bp_location *bl,
12840                                 struct address_space *aspace,
12841                                 CORE_ADDR bp_addr,
12842                                 const struct target_waitstatus *ws)
12843 {
12844   internal_error_pure_virtual_called ();
12845 }
12846
12847 static void
12848 base_breakpoint_check_status (bpstat bs)
12849 {
12850   /* Always stop.   */
12851 }
12852
12853 /* A "works_in_software_mode" breakpoint_ops method that just internal
12854    errors.  */
12855
12856 static int
12857 base_breakpoint_works_in_software_mode (const struct breakpoint *b)
12858 {
12859   internal_error_pure_virtual_called ();
12860 }
12861
12862 /* A "resources_needed" breakpoint_ops method that just internal
12863    errors.  */
12864
12865 static int
12866 base_breakpoint_resources_needed (const struct bp_location *bl)
12867 {
12868   internal_error_pure_virtual_called ();
12869 }
12870
12871 static enum print_stop_action
12872 base_breakpoint_print_it (bpstat bs)
12873 {
12874   internal_error_pure_virtual_called ();
12875 }
12876
12877 static void
12878 base_breakpoint_print_one_detail (const struct breakpoint *self,
12879                                   struct ui_out *uiout)
12880 {
12881   /* nothing */
12882 }
12883
12884 static void
12885 base_breakpoint_print_mention (struct breakpoint *b)
12886 {
12887   internal_error_pure_virtual_called ();
12888 }
12889
12890 static void
12891 base_breakpoint_print_recreate (struct breakpoint *b, struct ui_file *fp)
12892 {
12893   internal_error_pure_virtual_called ();
12894 }
12895
12896 static void
12897 base_breakpoint_create_sals_from_address (char **arg,
12898                                           struct linespec_result *canonical,
12899                                           enum bptype type_wanted,
12900                                           char *addr_start,
12901                                           char **copy_arg)
12902 {
12903   internal_error_pure_virtual_called ();
12904 }
12905
12906 static void
12907 base_breakpoint_create_breakpoints_sal (struct gdbarch *gdbarch,
12908                                         struct linespec_result *c,
12909                                         struct linespec_sals *lsal,
12910                                         char *cond_string,
12911                                         char *extra_string,
12912                                         enum bptype type_wanted,
12913                                         enum bpdisp disposition,
12914                                         int thread,
12915                                         int task, int ignore_count,
12916                                         const struct breakpoint_ops *o,
12917                                         int from_tty, int enabled,
12918                                         int internal, unsigned flags)
12919 {
12920   internal_error_pure_virtual_called ();
12921 }
12922
12923 static void
12924 base_breakpoint_decode_linespec (struct breakpoint *b, char **s,
12925                                  struct symtabs_and_lines *sals)
12926 {
12927   internal_error_pure_virtual_called ();
12928 }
12929
12930 /* The default 'explains_signal' method.  */
12931
12932 static enum bpstat_signal_value
12933 base_breakpoint_explains_signal (struct breakpoint *b)
12934 {
12935   return BPSTAT_SIGNAL_HIDE;
12936 }
12937
12938 struct breakpoint_ops base_breakpoint_ops =
12939 {
12940   base_breakpoint_dtor,
12941   base_breakpoint_allocate_location,
12942   base_breakpoint_re_set,
12943   base_breakpoint_insert_location,
12944   base_breakpoint_remove_location,
12945   base_breakpoint_breakpoint_hit,
12946   base_breakpoint_check_status,
12947   base_breakpoint_resources_needed,
12948   base_breakpoint_works_in_software_mode,
12949   base_breakpoint_print_it,
12950   NULL,
12951   base_breakpoint_print_one_detail,
12952   base_breakpoint_print_mention,
12953   base_breakpoint_print_recreate,
12954   base_breakpoint_create_sals_from_address,
12955   base_breakpoint_create_breakpoints_sal,
12956   base_breakpoint_decode_linespec,
12957   base_breakpoint_explains_signal
12958 };
12959
12960 /* Default breakpoint_ops methods.  */
12961
12962 static void
12963 bkpt_re_set (struct breakpoint *b)
12964 {
12965   /* FIXME: is this still reachable?  */
12966   if (b->addr_string == NULL)
12967     {
12968       /* Anything without a string can't be re-set.  */
12969       delete_breakpoint (b);
12970       return;
12971     }
12972
12973   breakpoint_re_set_default (b);
12974 }
12975
12976 static int
12977 bkpt_insert_location (struct bp_location *bl)
12978 {
12979   if (bl->loc_type == bp_loc_hardware_breakpoint)
12980     return target_insert_hw_breakpoint (bl->gdbarch,
12981                                         &bl->target_info);
12982   else
12983     return target_insert_breakpoint (bl->gdbarch,
12984                                      &bl->target_info);
12985 }
12986
12987 static int
12988 bkpt_remove_location (struct bp_location *bl)
12989 {
12990   if (bl->loc_type == bp_loc_hardware_breakpoint)
12991     return target_remove_hw_breakpoint (bl->gdbarch, &bl->target_info);
12992   else
12993     return target_remove_breakpoint (bl->gdbarch, &bl->target_info);
12994 }
12995
12996 static int
12997 bkpt_breakpoint_hit (const struct bp_location *bl,
12998                      struct address_space *aspace, CORE_ADDR bp_addr,
12999                      const struct target_waitstatus *ws)
13000 {
13001   if (ws->kind != TARGET_WAITKIND_STOPPED
13002       || ws->value.sig != GDB_SIGNAL_TRAP)
13003     return 0;
13004
13005   if (!breakpoint_address_match (bl->pspace->aspace, bl->address,
13006                                  aspace, bp_addr))
13007     return 0;
13008
13009   if (overlay_debugging         /* unmapped overlay section */
13010       && section_is_overlay (bl->section)
13011       && !section_is_mapped (bl->section))
13012     return 0;
13013
13014   return 1;
13015 }
13016
13017 static int
13018 bkpt_resources_needed (const struct bp_location *bl)
13019 {
13020   gdb_assert (bl->owner->type == bp_hardware_breakpoint);
13021
13022   return 1;
13023 }
13024
13025 static enum print_stop_action
13026 bkpt_print_it (bpstat bs)
13027 {
13028   struct breakpoint *b;
13029   const struct bp_location *bl;
13030   int bp_temp;
13031   struct ui_out *uiout = current_uiout;
13032
13033   gdb_assert (bs->bp_location_at != NULL);
13034
13035   bl = bs->bp_location_at;
13036   b = bs->breakpoint_at;
13037
13038   bp_temp = b->disposition == disp_del;
13039   if (bl->address != bl->requested_address)
13040     breakpoint_adjustment_warning (bl->requested_address,
13041                                    bl->address,
13042                                    b->number, 1);
13043   annotate_breakpoint (b->number);
13044   if (bp_temp)
13045     ui_out_text (uiout, "\nTemporary breakpoint ");
13046   else
13047     ui_out_text (uiout, "\nBreakpoint ");
13048   if (ui_out_is_mi_like_p (uiout))
13049     {
13050       ui_out_field_string (uiout, "reason",
13051                            async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
13052       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
13053     }
13054   ui_out_field_int (uiout, "bkptno", b->number);
13055   ui_out_text (uiout, ", ");
13056
13057   return PRINT_SRC_AND_LOC;
13058 }
13059
13060 static void
13061 bkpt_print_mention (struct breakpoint *b)
13062 {
13063   if (ui_out_is_mi_like_p (current_uiout))
13064     return;
13065
13066   switch (b->type)
13067     {
13068     case bp_breakpoint:
13069     case bp_gnu_ifunc_resolver:
13070       if (b->disposition == disp_del)
13071         printf_filtered (_("Temporary breakpoint"));
13072       else
13073         printf_filtered (_("Breakpoint"));
13074       printf_filtered (_(" %d"), b->number);
13075       if (b->type == bp_gnu_ifunc_resolver)
13076         printf_filtered (_(" at gnu-indirect-function resolver"));
13077       break;
13078     case bp_hardware_breakpoint:
13079       printf_filtered (_("Hardware assisted breakpoint %d"), b->number);
13080       break;
13081     case bp_dprintf:
13082       printf_filtered (_("Dprintf %d"), b->number);
13083       break;
13084     }
13085
13086   say_where (b);
13087 }
13088
13089 static void
13090 bkpt_print_recreate (struct breakpoint *tp, struct ui_file *fp)
13091 {
13092   if (tp->type == bp_breakpoint && tp->disposition == disp_del)
13093     fprintf_unfiltered (fp, "tbreak");
13094   else if (tp->type == bp_breakpoint)
13095     fprintf_unfiltered (fp, "break");
13096   else if (tp->type == bp_hardware_breakpoint
13097            && tp->disposition == disp_del)
13098     fprintf_unfiltered (fp, "thbreak");
13099   else if (tp->type == bp_hardware_breakpoint)
13100     fprintf_unfiltered (fp, "hbreak");
13101   else
13102     internal_error (__FILE__, __LINE__,
13103                     _("unhandled breakpoint type %d"), (int) tp->type);
13104
13105   fprintf_unfiltered (fp, " %s", tp->addr_string);
13106   print_recreate_thread (tp, fp);
13107 }
13108
13109 static void
13110 bkpt_create_sals_from_address (char **arg,
13111                                struct linespec_result *canonical,
13112                                enum bptype type_wanted,
13113                                char *addr_start, char **copy_arg)
13114 {
13115   create_sals_from_address_default (arg, canonical, type_wanted,
13116                                     addr_start, copy_arg);
13117 }
13118
13119 static void
13120 bkpt_create_breakpoints_sal (struct gdbarch *gdbarch,
13121                              struct linespec_result *canonical,
13122                              struct linespec_sals *lsal,
13123                              char *cond_string,
13124                              char *extra_string,
13125                              enum bptype type_wanted,
13126                              enum bpdisp disposition,
13127                              int thread,
13128                              int task, int ignore_count,
13129                              const struct breakpoint_ops *ops,
13130                              int from_tty, int enabled,
13131                              int internal, unsigned flags)
13132 {
13133   create_breakpoints_sal_default (gdbarch, canonical, lsal,
13134                                   cond_string, extra_string,
13135                                   type_wanted,
13136                                   disposition, thread, task,
13137                                   ignore_count, ops, from_tty,
13138                                   enabled, internal, flags);
13139 }
13140
13141 static void
13142 bkpt_decode_linespec (struct breakpoint *b, char **s,
13143                       struct symtabs_and_lines *sals)
13144 {
13145   decode_linespec_default (b, s, sals);
13146 }
13147
13148 /* Virtual table for internal breakpoints.  */
13149
13150 static void
13151 internal_bkpt_re_set (struct breakpoint *b)
13152 {
13153   switch (b->type)
13154     {
13155       /* Delete overlay event and longjmp master breakpoints; they
13156          will be reset later by breakpoint_re_set.  */
13157     case bp_overlay_event:
13158     case bp_longjmp_master:
13159     case bp_std_terminate_master:
13160     case bp_exception_master:
13161       delete_breakpoint (b);
13162       break;
13163
13164       /* This breakpoint is special, it's set up when the inferior
13165          starts and we really don't want to touch it.  */
13166     case bp_shlib_event:
13167
13168       /* Like bp_shlib_event, this breakpoint type is special.  Once
13169          it is set up, we do not want to touch it.  */
13170     case bp_thread_event:
13171       break;
13172     }
13173 }
13174
13175 static void
13176 internal_bkpt_check_status (bpstat bs)
13177 {
13178   if (bs->breakpoint_at->type == bp_shlib_event)
13179     {
13180       /* If requested, stop when the dynamic linker notifies GDB of
13181          events.  This allows the user to get control and place
13182          breakpoints in initializer routines for dynamically loaded
13183          objects (among other things).  */
13184       bs->stop = stop_on_solib_events;
13185       bs->print = stop_on_solib_events;
13186     }
13187   else
13188     bs->stop = 0;
13189 }
13190
13191 static enum print_stop_action
13192 internal_bkpt_print_it (bpstat bs)
13193 {
13194   struct breakpoint *b;
13195
13196   b = bs->breakpoint_at;
13197
13198   switch (b->type)
13199     {
13200     case bp_shlib_event:
13201       /* Did we stop because the user set the stop_on_solib_events
13202          variable?  (If so, we report this as a generic, "Stopped due
13203          to shlib event" message.) */
13204       print_solib_event (0);
13205       break;
13206
13207     case bp_thread_event:
13208       /* Not sure how we will get here.
13209          GDB should not stop for these breakpoints.  */
13210       printf_filtered (_("Thread Event Breakpoint: gdb should not stop!\n"));
13211       break;
13212
13213     case bp_overlay_event:
13214       /* By analogy with the thread event, GDB should not stop for these.  */
13215       printf_filtered (_("Overlay Event Breakpoint: gdb should not stop!\n"));
13216       break;
13217
13218     case bp_longjmp_master:
13219       /* These should never be enabled.  */
13220       printf_filtered (_("Longjmp Master Breakpoint: gdb should not stop!\n"));
13221       break;
13222
13223     case bp_std_terminate_master:
13224       /* These should never be enabled.  */
13225       printf_filtered (_("std::terminate Master Breakpoint: "
13226                          "gdb should not stop!\n"));
13227       break;
13228
13229     case bp_exception_master:
13230       /* These should never be enabled.  */
13231       printf_filtered (_("Exception Master Breakpoint: "
13232                          "gdb should not stop!\n"));
13233       break;
13234     }
13235
13236   return PRINT_NOTHING;
13237 }
13238
13239 static void
13240 internal_bkpt_print_mention (struct breakpoint *b)
13241 {
13242   /* Nothing to mention.  These breakpoints are internal.  */
13243 }
13244
13245 /* Virtual table for momentary breakpoints  */
13246
13247 static void
13248 momentary_bkpt_re_set (struct breakpoint *b)
13249 {
13250   /* Keep temporary breakpoints, which can be encountered when we step
13251      over a dlopen call and SOLIB_ADD is resetting the breakpoints.
13252      Otherwise these should have been blown away via the cleanup chain
13253      or by breakpoint_init_inferior when we rerun the executable.  */
13254 }
13255
13256 static void
13257 momentary_bkpt_check_status (bpstat bs)
13258 {
13259   /* Nothing.  The point of these breakpoints is causing a stop.  */
13260 }
13261
13262 static enum print_stop_action
13263 momentary_bkpt_print_it (bpstat bs)
13264 {
13265   struct ui_out *uiout = current_uiout;
13266
13267   if (ui_out_is_mi_like_p (uiout))
13268     {
13269       struct breakpoint *b = bs->breakpoint_at;
13270
13271       switch (b->type)
13272         {
13273         case bp_finish:
13274           ui_out_field_string
13275             (uiout, "reason",
13276              async_reason_lookup (EXEC_ASYNC_FUNCTION_FINISHED));
13277           break;
13278
13279         case bp_until:
13280           ui_out_field_string
13281             (uiout, "reason",
13282              async_reason_lookup (EXEC_ASYNC_LOCATION_REACHED));
13283           break;
13284         }
13285     }
13286
13287   return PRINT_UNKNOWN;
13288 }
13289
13290 static void
13291 momentary_bkpt_print_mention (struct breakpoint *b)
13292 {
13293   /* Nothing to mention.  These breakpoints are internal.  */
13294 }
13295
13296 /* Ensure INITIATING_FRAME is cleared when no such breakpoint exists.
13297
13298    It gets cleared already on the removal of the first one of such placed
13299    breakpoints.  This is OK as they get all removed altogether.  */
13300
13301 static void
13302 longjmp_bkpt_dtor (struct breakpoint *self)
13303 {
13304   struct thread_info *tp = find_thread_id (self->thread);
13305
13306   if (tp)
13307     tp->initiating_frame = null_frame_id;
13308
13309   momentary_breakpoint_ops.dtor (self);
13310 }
13311
13312 /* Specific methods for probe breakpoints.  */
13313
13314 static int
13315 bkpt_probe_insert_location (struct bp_location *bl)
13316 {
13317   int v = bkpt_insert_location (bl);
13318
13319   if (v == 0)
13320     {
13321       /* The insertion was successful, now let's set the probe's semaphore
13322          if needed.  */
13323       bl->probe->pops->set_semaphore (bl->probe, bl->gdbarch);
13324     }
13325
13326   return v;
13327 }
13328
13329 static int
13330 bkpt_probe_remove_location (struct bp_location *bl)
13331 {
13332   /* Let's clear the semaphore before removing the location.  */
13333   bl->probe->pops->clear_semaphore (bl->probe, bl->gdbarch);
13334
13335   return bkpt_remove_location (bl);
13336 }
13337
13338 static void
13339 bkpt_probe_create_sals_from_address (char **arg,
13340                                      struct linespec_result *canonical,
13341                                      enum bptype type_wanted,
13342                                      char *addr_start, char **copy_arg)
13343 {
13344   struct linespec_sals lsal;
13345
13346   lsal.sals = parse_probes (arg, canonical);
13347
13348   *copy_arg = xstrdup (canonical->addr_string);
13349   lsal.canonical = xstrdup (*copy_arg);
13350
13351   VEC_safe_push (linespec_sals, canonical->sals, &lsal);
13352 }
13353
13354 static void
13355 bkpt_probe_decode_linespec (struct breakpoint *b, char **s,
13356                             struct symtabs_and_lines *sals)
13357 {
13358   *sals = parse_probes (s, NULL);
13359   if (!sals->sals)
13360     error (_("probe not found"));
13361 }
13362
13363 /* The breakpoint_ops structure to be used in tracepoints.  */
13364
13365 static void
13366 tracepoint_re_set (struct breakpoint *b)
13367 {
13368   breakpoint_re_set_default (b);
13369 }
13370
13371 static int
13372 tracepoint_breakpoint_hit (const struct bp_location *bl,
13373                            struct address_space *aspace, CORE_ADDR bp_addr,
13374                            const struct target_waitstatus *ws)
13375 {
13376   /* By definition, the inferior does not report stops at
13377      tracepoints.  */
13378   return 0;
13379 }
13380
13381 static void
13382 tracepoint_print_one_detail (const struct breakpoint *self,
13383                              struct ui_out *uiout)
13384 {
13385   struct tracepoint *tp = (struct tracepoint *) self;
13386   if (tp->static_trace_marker_id)
13387     {
13388       gdb_assert (self->type == bp_static_tracepoint);
13389
13390       ui_out_text (uiout, "\tmarker id is ");
13391       ui_out_field_string (uiout, "static-tracepoint-marker-string-id",
13392                            tp->static_trace_marker_id);
13393       ui_out_text (uiout, "\n");
13394     }
13395 }
13396
13397 static void
13398 tracepoint_print_mention (struct breakpoint *b)
13399 {
13400   if (ui_out_is_mi_like_p (current_uiout))
13401     return;
13402
13403   switch (b->type)
13404     {
13405     case bp_tracepoint:
13406       printf_filtered (_("Tracepoint"));
13407       printf_filtered (_(" %d"), b->number);
13408       break;
13409     case bp_fast_tracepoint:
13410       printf_filtered (_("Fast tracepoint"));
13411       printf_filtered (_(" %d"), b->number);
13412       break;
13413     case bp_static_tracepoint:
13414       printf_filtered (_("Static tracepoint"));
13415       printf_filtered (_(" %d"), b->number);
13416       break;
13417     default:
13418       internal_error (__FILE__, __LINE__,
13419                       _("unhandled tracepoint type %d"), (int) b->type);
13420     }
13421
13422   say_where (b);
13423 }
13424
13425 static void
13426 tracepoint_print_recreate (struct breakpoint *self, struct ui_file *fp)
13427 {
13428   struct tracepoint *tp = (struct tracepoint *) self;
13429
13430   if (self->type == bp_fast_tracepoint)
13431     fprintf_unfiltered (fp, "ftrace");
13432   if (self->type == bp_static_tracepoint)
13433     fprintf_unfiltered (fp, "strace");
13434   else if (self->type == bp_tracepoint)
13435     fprintf_unfiltered (fp, "trace");
13436   else
13437     internal_error (__FILE__, __LINE__,
13438                     _("unhandled tracepoint type %d"), (int) self->type);
13439
13440   fprintf_unfiltered (fp, " %s", self->addr_string);
13441   print_recreate_thread (self, fp);
13442
13443   if (tp->pass_count)
13444     fprintf_unfiltered (fp, "  passcount %d\n", tp->pass_count);
13445 }
13446
13447 static void
13448 tracepoint_create_sals_from_address (char **arg,
13449                                      struct linespec_result *canonical,
13450                                      enum bptype type_wanted,
13451                                      char *addr_start, char **copy_arg)
13452 {
13453   create_sals_from_address_default (arg, canonical, type_wanted,
13454                                     addr_start, copy_arg);
13455 }
13456
13457 static void
13458 tracepoint_create_breakpoints_sal (struct gdbarch *gdbarch,
13459                                    struct linespec_result *canonical,
13460                                    struct linespec_sals *lsal,
13461                                    char *cond_string,
13462                                    char *extra_string,
13463                                    enum bptype type_wanted,
13464                                    enum bpdisp disposition,
13465                                    int thread,
13466                                    int task, int ignore_count,
13467                                    const struct breakpoint_ops *ops,
13468                                    int from_tty, int enabled,
13469                                    int internal, unsigned flags)
13470 {
13471   create_breakpoints_sal_default (gdbarch, canonical, lsal,
13472                                   cond_string, extra_string,
13473                                   type_wanted,
13474                                   disposition, thread, task,
13475                                   ignore_count, ops, from_tty,
13476                                   enabled, internal, flags);
13477 }
13478
13479 static void
13480 tracepoint_decode_linespec (struct breakpoint *b, char **s,
13481                             struct symtabs_and_lines *sals)
13482 {
13483   decode_linespec_default (b, s, sals);
13484 }
13485
13486 struct breakpoint_ops tracepoint_breakpoint_ops;
13487
13488 /* The breakpoint_ops structure to be use on tracepoints placed in a
13489    static probe.  */
13490
13491 static void
13492 tracepoint_probe_create_sals_from_address (char **arg,
13493                                            struct linespec_result *canonical,
13494                                            enum bptype type_wanted,
13495                                            char *addr_start, char **copy_arg)
13496 {
13497   /* We use the same method for breakpoint on probes.  */
13498   bkpt_probe_create_sals_from_address (arg, canonical, type_wanted,
13499                                        addr_start, copy_arg);
13500 }
13501
13502 static void
13503 tracepoint_probe_decode_linespec (struct breakpoint *b, char **s,
13504                                   struct symtabs_and_lines *sals)
13505 {
13506   /* We use the same method for breakpoint on probes.  */
13507   bkpt_probe_decode_linespec (b, s, sals);
13508 }
13509
13510 static struct breakpoint_ops tracepoint_probe_breakpoint_ops;
13511
13512 /* The breakpoint_ops structure to be used on static tracepoints with
13513    markers (`-m').  */
13514
13515 static void
13516 strace_marker_create_sals_from_address (char **arg,
13517                                         struct linespec_result *canonical,
13518                                         enum bptype type_wanted,
13519                                         char *addr_start, char **copy_arg)
13520 {
13521   struct linespec_sals lsal;
13522
13523   lsal.sals = decode_static_tracepoint_spec (arg);
13524
13525   *copy_arg = savestring (addr_start, *arg - addr_start);
13526
13527   canonical->addr_string = xstrdup (*copy_arg);
13528   lsal.canonical = xstrdup (*copy_arg);
13529   VEC_safe_push (linespec_sals, canonical->sals, &lsal);
13530 }
13531
13532 static void
13533 strace_marker_create_breakpoints_sal (struct gdbarch *gdbarch,
13534                                       struct linespec_result *canonical,
13535                                       struct linespec_sals *lsal,
13536                                       char *cond_string,
13537                                       char *extra_string,
13538                                       enum bptype type_wanted,
13539                                       enum bpdisp disposition,
13540                                       int thread,
13541                                       int task, int ignore_count,
13542                                       const struct breakpoint_ops *ops,
13543                                       int from_tty, int enabled,
13544                                       int internal, unsigned flags)
13545 {
13546   int i;
13547
13548   /* If the user is creating a static tracepoint by marker id
13549      (strace -m MARKER_ID), then store the sals index, so that
13550      breakpoint_re_set can try to match up which of the newly
13551      found markers corresponds to this one, and, don't try to
13552      expand multiple locations for each sal, given than SALS
13553      already should contain all sals for MARKER_ID.  */
13554
13555   for (i = 0; i < lsal->sals.nelts; ++i)
13556     {
13557       struct symtabs_and_lines expanded;
13558       struct tracepoint *tp;
13559       struct cleanup *old_chain;
13560       char *addr_string;
13561
13562       expanded.nelts = 1;
13563       expanded.sals = &lsal->sals.sals[i];
13564
13565       addr_string = xstrdup (canonical->addr_string);
13566       old_chain = make_cleanup (xfree, addr_string);
13567
13568       tp = XCNEW (struct tracepoint);
13569       init_breakpoint_sal (&tp->base, gdbarch, expanded,
13570                            addr_string, NULL,
13571                            cond_string, extra_string,
13572                            type_wanted, disposition,
13573                            thread, task, ignore_count, ops,
13574                            from_tty, enabled, internal, flags,
13575                            canonical->special_display);
13576       /* Given that its possible to have multiple markers with
13577          the same string id, if the user is creating a static
13578          tracepoint by marker id ("strace -m MARKER_ID"), then
13579          store the sals index, so that breakpoint_re_set can
13580          try to match up which of the newly found markers
13581          corresponds to this one  */
13582       tp->static_trace_marker_id_idx = i;
13583
13584       install_breakpoint (internal, &tp->base, 0);
13585
13586       discard_cleanups (old_chain);
13587     }
13588 }
13589
13590 static void
13591 strace_marker_decode_linespec (struct breakpoint *b, char **s,
13592                                struct symtabs_and_lines *sals)
13593 {
13594   struct tracepoint *tp = (struct tracepoint *) b;
13595
13596   *sals = decode_static_tracepoint_spec (s);
13597   if (sals->nelts > tp->static_trace_marker_id_idx)
13598     {
13599       sals->sals[0] = sals->sals[tp->static_trace_marker_id_idx];
13600       sals->nelts = 1;
13601     }
13602   else
13603     error (_("marker %s not found"), tp->static_trace_marker_id);
13604 }
13605
13606 static struct breakpoint_ops strace_marker_breakpoint_ops;
13607
13608 static int
13609 strace_marker_p (struct breakpoint *b)
13610 {
13611   return b->ops == &strace_marker_breakpoint_ops;
13612 }
13613
13614 /* Delete a breakpoint and clean up all traces of it in the data
13615    structures.  */
13616
13617 void
13618 delete_breakpoint (struct breakpoint *bpt)
13619 {
13620   struct breakpoint *b;
13621
13622   gdb_assert (bpt != NULL);
13623
13624   /* Has this bp already been deleted?  This can happen because
13625      multiple lists can hold pointers to bp's.  bpstat lists are
13626      especial culprits.
13627
13628      One example of this happening is a watchpoint's scope bp.  When
13629      the scope bp triggers, we notice that the watchpoint is out of
13630      scope, and delete it.  We also delete its scope bp.  But the
13631      scope bp is marked "auto-deleting", and is already on a bpstat.
13632      That bpstat is then checked for auto-deleting bp's, which are
13633      deleted.
13634
13635      A real solution to this problem might involve reference counts in
13636      bp's, and/or giving them pointers back to their referencing
13637      bpstat's, and teaching delete_breakpoint to only free a bp's
13638      storage when no more references were extent.  A cheaper bandaid
13639      was chosen.  */
13640   if (bpt->type == bp_none)
13641     return;
13642
13643   /* At least avoid this stale reference until the reference counting
13644      of breakpoints gets resolved.  */
13645   if (bpt->related_breakpoint != bpt)
13646     {
13647       struct breakpoint *related;
13648       struct watchpoint *w;
13649
13650       if (bpt->type == bp_watchpoint_scope)
13651         w = (struct watchpoint *) bpt->related_breakpoint;
13652       else if (bpt->related_breakpoint->type == bp_watchpoint_scope)
13653         w = (struct watchpoint *) bpt;
13654       else
13655         w = NULL;
13656       if (w != NULL)
13657         watchpoint_del_at_next_stop (w);
13658
13659       /* Unlink bpt from the bpt->related_breakpoint ring.  */
13660       for (related = bpt; related->related_breakpoint != bpt;
13661            related = related->related_breakpoint);
13662       related->related_breakpoint = bpt->related_breakpoint;
13663       bpt->related_breakpoint = bpt;
13664     }
13665
13666   /* watch_command_1 creates a watchpoint but only sets its number if
13667      update_watchpoint succeeds in creating its bp_locations.  If there's
13668      a problem in that process, we'll be asked to delete the half-created
13669      watchpoint.  In that case, don't announce the deletion.  */
13670   if (bpt->number)
13671     observer_notify_breakpoint_deleted (bpt);
13672
13673   if (breakpoint_chain == bpt)
13674     breakpoint_chain = bpt->next;
13675
13676   ALL_BREAKPOINTS (b)
13677     if (b->next == bpt)
13678     {
13679       b->next = bpt->next;
13680       break;
13681     }
13682
13683   /* Be sure no bpstat's are pointing at the breakpoint after it's
13684      been freed.  */
13685   /* FIXME, how can we find all bpstat's?  We just check stop_bpstat
13686      in all threads for now.  Note that we cannot just remove bpstats
13687      pointing at bpt from the stop_bpstat list entirely, as breakpoint
13688      commands are associated with the bpstat; if we remove it here,
13689      then the later call to bpstat_do_actions (&stop_bpstat); in
13690      event-top.c won't do anything, and temporary breakpoints with
13691      commands won't work.  */
13692
13693   iterate_over_threads (bpstat_remove_breakpoint_callback, bpt);
13694
13695   /* Now that breakpoint is removed from breakpoint list, update the
13696      global location list.  This will remove locations that used to
13697      belong to this breakpoint.  Do this before freeing the breakpoint
13698      itself, since remove_breakpoint looks at location's owner.  It
13699      might be better design to have location completely
13700      self-contained, but it's not the case now.  */
13701   update_global_location_list (0);
13702
13703   bpt->ops->dtor (bpt);
13704   /* On the chance that someone will soon try again to delete this
13705      same bp, we mark it as deleted before freeing its storage.  */
13706   bpt->type = bp_none;
13707   xfree (bpt);
13708 }
13709
13710 static void
13711 do_delete_breakpoint_cleanup (void *b)
13712 {
13713   delete_breakpoint (b);
13714 }
13715
13716 struct cleanup *
13717 make_cleanup_delete_breakpoint (struct breakpoint *b)
13718 {
13719   return make_cleanup (do_delete_breakpoint_cleanup, b);
13720 }
13721
13722 /* Iterator function to call a user-provided callback function once
13723    for each of B and its related breakpoints.  */
13724
13725 static void
13726 iterate_over_related_breakpoints (struct breakpoint *b,
13727                                   void (*function) (struct breakpoint *,
13728                                                     void *),
13729                                   void *data)
13730 {
13731   struct breakpoint *related;
13732
13733   related = b;
13734   do
13735     {
13736       struct breakpoint *next;
13737
13738       /* FUNCTION may delete RELATED.  */
13739       next = related->related_breakpoint;
13740
13741       if (next == related)
13742         {
13743           /* RELATED is the last ring entry.  */
13744           function (related, data);
13745
13746           /* FUNCTION may have deleted it, so we'd never reach back to
13747              B.  There's nothing left to do anyway, so just break
13748              out.  */
13749           break;
13750         }
13751       else
13752         function (related, data);
13753
13754       related = next;
13755     }
13756   while (related != b);
13757 }
13758
13759 static void
13760 do_delete_breakpoint (struct breakpoint *b, void *ignore)
13761 {
13762   delete_breakpoint (b);
13763 }
13764
13765 /* A callback for map_breakpoint_numbers that calls
13766    delete_breakpoint.  */
13767
13768 static void
13769 do_map_delete_breakpoint (struct breakpoint *b, void *ignore)
13770 {
13771   iterate_over_related_breakpoints (b, do_delete_breakpoint, NULL);
13772 }
13773
13774 void
13775 delete_command (char *arg, int from_tty)
13776 {
13777   struct breakpoint *b, *b_tmp;
13778
13779   dont_repeat ();
13780
13781   if (arg == 0)
13782     {
13783       int breaks_to_delete = 0;
13784
13785       /* Delete all breakpoints if no argument.  Do not delete
13786          internal breakpoints, these have to be deleted with an
13787          explicit breakpoint number argument.  */
13788       ALL_BREAKPOINTS (b)
13789         if (user_breakpoint_p (b))
13790           {
13791             breaks_to_delete = 1;
13792             break;
13793           }
13794
13795       /* Ask user only if there are some breakpoints to delete.  */
13796       if (!from_tty
13797           || (breaks_to_delete && query (_("Delete all breakpoints? "))))
13798         {
13799           ALL_BREAKPOINTS_SAFE (b, b_tmp)
13800             if (user_breakpoint_p (b))
13801               delete_breakpoint (b);
13802         }
13803     }
13804   else
13805     map_breakpoint_numbers (arg, do_map_delete_breakpoint, NULL);
13806 }
13807
13808 static int
13809 all_locations_are_pending (struct bp_location *loc)
13810 {
13811   for (; loc; loc = loc->next)
13812     if (!loc->shlib_disabled
13813         && !loc->pspace->executing_startup)
13814       return 0;
13815   return 1;
13816 }
13817
13818 /* Subroutine of update_breakpoint_locations to simplify it.
13819    Return non-zero if multiple fns in list LOC have the same name.
13820    Null names are ignored.  */
13821
13822 static int
13823 ambiguous_names_p (struct bp_location *loc)
13824 {
13825   struct bp_location *l;
13826   htab_t htab = htab_create_alloc (13, htab_hash_string,
13827                                    (int (*) (const void *, 
13828                                              const void *)) streq,
13829                                    NULL, xcalloc, xfree);
13830
13831   for (l = loc; l != NULL; l = l->next)
13832     {
13833       const char **slot;
13834       const char *name = l->function_name;
13835
13836       /* Allow for some names to be NULL, ignore them.  */
13837       if (name == NULL)
13838         continue;
13839
13840       slot = (const char **) htab_find_slot (htab, (const void *) name,
13841                                              INSERT);
13842       /* NOTE: We can assume slot != NULL here because xcalloc never
13843          returns NULL.  */
13844       if (*slot != NULL)
13845         {
13846           htab_delete (htab);
13847           return 1;
13848         }
13849       *slot = name;
13850     }
13851
13852   htab_delete (htab);
13853   return 0;
13854 }
13855
13856 /* When symbols change, it probably means the sources changed as well,
13857    and it might mean the static tracepoint markers are no longer at
13858    the same address or line numbers they used to be at last we
13859    checked.  Losing your static tracepoints whenever you rebuild is
13860    undesirable.  This function tries to resync/rematch gdb static
13861    tracepoints with the markers on the target, for static tracepoints
13862    that have not been set by marker id.  Static tracepoint that have
13863    been set by marker id are reset by marker id in breakpoint_re_set.
13864    The heuristic is:
13865
13866    1) For a tracepoint set at a specific address, look for a marker at
13867    the old PC.  If one is found there, assume to be the same marker.
13868    If the name / string id of the marker found is different from the
13869    previous known name, assume that means the user renamed the marker
13870    in the sources, and output a warning.
13871
13872    2) For a tracepoint set at a given line number, look for a marker
13873    at the new address of the old line number.  If one is found there,
13874    assume to be the same marker.  If the name / string id of the
13875    marker found is different from the previous known name, assume that
13876    means the user renamed the marker in the sources, and output a
13877    warning.
13878
13879    3) If a marker is no longer found at the same address or line, it
13880    may mean the marker no longer exists.  But it may also just mean
13881    the code changed a bit.  Maybe the user added a few lines of code
13882    that made the marker move up or down (in line number terms).  Ask
13883    the target for info about the marker with the string id as we knew
13884    it.  If found, update line number and address in the matching
13885    static tracepoint.  This will get confused if there's more than one
13886    marker with the same ID (possible in UST, although unadvised
13887    precisely because it confuses tools).  */
13888
13889 static struct symtab_and_line
13890 update_static_tracepoint (struct breakpoint *b, struct symtab_and_line sal)
13891 {
13892   struct tracepoint *tp = (struct tracepoint *) b;
13893   struct static_tracepoint_marker marker;
13894   CORE_ADDR pc;
13895
13896   pc = sal.pc;
13897   if (sal.line)
13898     find_line_pc (sal.symtab, sal.line, &pc);
13899
13900   if (target_static_tracepoint_marker_at (pc, &marker))
13901     {
13902       if (strcmp (tp->static_trace_marker_id, marker.str_id) != 0)
13903         warning (_("static tracepoint %d changed probed marker from %s to %s"),
13904                  b->number,
13905                  tp->static_trace_marker_id, marker.str_id);
13906
13907       xfree (tp->static_trace_marker_id);
13908       tp->static_trace_marker_id = xstrdup (marker.str_id);
13909       release_static_tracepoint_marker (&marker);
13910
13911       return sal;
13912     }
13913
13914   /* Old marker wasn't found on target at lineno.  Try looking it up
13915      by string ID.  */
13916   if (!sal.explicit_pc
13917       && sal.line != 0
13918       && sal.symtab != NULL
13919       && tp->static_trace_marker_id != NULL)
13920     {
13921       VEC(static_tracepoint_marker_p) *markers;
13922
13923       markers
13924         = target_static_tracepoint_markers_by_strid (tp->static_trace_marker_id);
13925
13926       if (!VEC_empty(static_tracepoint_marker_p, markers))
13927         {
13928           struct symtab_and_line sal2;
13929           struct symbol *sym;
13930           struct static_tracepoint_marker *tpmarker;
13931           struct ui_out *uiout = current_uiout;
13932
13933           tpmarker = VEC_index (static_tracepoint_marker_p, markers, 0);
13934
13935           xfree (tp->static_trace_marker_id);
13936           tp->static_trace_marker_id = xstrdup (tpmarker->str_id);
13937
13938           warning (_("marker for static tracepoint %d (%s) not "
13939                      "found at previous line number"),
13940                    b->number, tp->static_trace_marker_id);
13941
13942           init_sal (&sal2);
13943
13944           sal2.pc = tpmarker->address;
13945
13946           sal2 = find_pc_line (tpmarker->address, 0);
13947           sym = find_pc_sect_function (tpmarker->address, NULL);
13948           ui_out_text (uiout, "Now in ");
13949           if (sym)
13950             {
13951               ui_out_field_string (uiout, "func",
13952                                    SYMBOL_PRINT_NAME (sym));
13953               ui_out_text (uiout, " at ");
13954             }
13955           ui_out_field_string (uiout, "file",
13956                                symtab_to_filename_for_display (sal2.symtab));
13957           ui_out_text (uiout, ":");
13958
13959           if (ui_out_is_mi_like_p (uiout))
13960             {
13961               const char *fullname = symtab_to_fullname (sal2.symtab);
13962
13963               ui_out_field_string (uiout, "fullname", fullname);
13964             }
13965
13966           ui_out_field_int (uiout, "line", sal2.line);
13967           ui_out_text (uiout, "\n");
13968
13969           b->loc->line_number = sal2.line;
13970           b->loc->symtab = sym != NULL ? sal2.symtab : NULL;
13971
13972           xfree (b->addr_string);
13973           b->addr_string = xstrprintf ("%s:%d",
13974                                    symtab_to_filename_for_display (sal2.symtab),
13975                                        b->loc->line_number);
13976
13977           /* Might be nice to check if function changed, and warn if
13978              so.  */
13979
13980           release_static_tracepoint_marker (tpmarker);
13981         }
13982     }
13983   return sal;
13984 }
13985
13986 /* Returns 1 iff locations A and B are sufficiently same that
13987    we don't need to report breakpoint as changed.  */
13988
13989 static int
13990 locations_are_equal (struct bp_location *a, struct bp_location *b)
13991 {
13992   while (a && b)
13993     {
13994       if (a->address != b->address)
13995         return 0;
13996
13997       if (a->shlib_disabled != b->shlib_disabled)
13998         return 0;
13999
14000       if (a->enabled != b->enabled)
14001         return 0;
14002
14003       a = a->next;
14004       b = b->next;
14005     }
14006
14007   if ((a == NULL) != (b == NULL))
14008     return 0;
14009
14010   return 1;
14011 }
14012
14013 /* Create new breakpoint locations for B (a hardware or software breakpoint)
14014    based on SALS and SALS_END.  If SALS_END.NELTS is not zero, then B is
14015    a ranged breakpoint.  */
14016
14017 void
14018 update_breakpoint_locations (struct breakpoint *b,
14019                              struct symtabs_and_lines sals,
14020                              struct symtabs_and_lines sals_end)
14021 {
14022   int i;
14023   struct bp_location *existing_locations = b->loc;
14024
14025   if (sals_end.nelts != 0 && (sals.nelts != 1 || sals_end.nelts != 1))
14026     {
14027       /* Ranged breakpoints have only one start location and one end
14028          location.  */
14029       b->enable_state = bp_disabled;
14030       update_global_location_list (1);
14031       printf_unfiltered (_("Could not reset ranged breakpoint %d: "
14032                            "multiple locations found\n"),
14033                          b->number);
14034       return;
14035     }
14036
14037   /* If there's no new locations, and all existing locations are
14038      pending, don't do anything.  This optimizes the common case where
14039      all locations are in the same shared library, that was unloaded.
14040      We'd like to retain the location, so that when the library is
14041      loaded again, we don't loose the enabled/disabled status of the
14042      individual locations.  */
14043   if (all_locations_are_pending (existing_locations) && sals.nelts == 0)
14044     return;
14045
14046   b->loc = NULL;
14047
14048   for (i = 0; i < sals.nelts; ++i)
14049     {
14050       struct bp_location *new_loc;
14051
14052       switch_to_program_space_and_thread (sals.sals[i].pspace);
14053
14054       new_loc = add_location_to_breakpoint (b, &(sals.sals[i]));
14055
14056       /* Reparse conditions, they might contain references to the
14057          old symtab.  */
14058       if (b->cond_string != NULL)
14059         {
14060           const char *s;
14061           volatile struct gdb_exception e;
14062
14063           s = b->cond_string;
14064           TRY_CATCH (e, RETURN_MASK_ERROR)
14065             {
14066               new_loc->cond = parse_exp_1 (&s, sals.sals[i].pc,
14067                                            block_for_pc (sals.sals[i].pc), 
14068                                            0);
14069             }
14070           if (e.reason < 0)
14071             {
14072               warning (_("failed to reevaluate condition "
14073                          "for breakpoint %d: %s"), 
14074                        b->number, e.message);
14075               new_loc->enabled = 0;
14076             }
14077         }
14078
14079       if (sals_end.nelts)
14080         {
14081           CORE_ADDR end = find_breakpoint_range_end (sals_end.sals[0]);
14082
14083           new_loc->length = end - sals.sals[0].pc + 1;
14084         }
14085     }
14086
14087   /* Update locations of permanent breakpoints.  */
14088   if (b->enable_state == bp_permanent)
14089     make_breakpoint_permanent (b);
14090
14091   /* If possible, carry over 'disable' status from existing
14092      breakpoints.  */
14093   {
14094     struct bp_location *e = existing_locations;
14095     /* If there are multiple breakpoints with the same function name,
14096        e.g. for inline functions, comparing function names won't work.
14097        Instead compare pc addresses; this is just a heuristic as things
14098        may have moved, but in practice it gives the correct answer
14099        often enough until a better solution is found.  */
14100     int have_ambiguous_names = ambiguous_names_p (b->loc);
14101
14102     for (; e; e = e->next)
14103       {
14104         if (!e->enabled && e->function_name)
14105           {
14106             struct bp_location *l = b->loc;
14107             if (have_ambiguous_names)
14108               {
14109                 for (; l; l = l->next)
14110                   if (breakpoint_locations_match (e, l))
14111                     {
14112                       l->enabled = 0;
14113                       break;
14114                     }
14115               }
14116             else
14117               {
14118                 for (; l; l = l->next)
14119                   if (l->function_name
14120                       && strcmp (e->function_name, l->function_name) == 0)
14121                     {
14122                       l->enabled = 0;
14123                       break;
14124                     }
14125               }
14126           }
14127       }
14128   }
14129
14130   if (!locations_are_equal (existing_locations, b->loc))
14131     observer_notify_breakpoint_modified (b);
14132
14133   update_global_location_list (1);
14134 }
14135
14136 /* Find the SaL locations corresponding to the given ADDR_STRING.
14137    On return, FOUND will be 1 if any SaL was found, zero otherwise.  */
14138
14139 static struct symtabs_and_lines
14140 addr_string_to_sals (struct breakpoint *b, char *addr_string, int *found)
14141 {
14142   char *s;
14143   struct symtabs_and_lines sals = {0};
14144   volatile struct gdb_exception e;
14145
14146   gdb_assert (b->ops != NULL);
14147   s = addr_string;
14148
14149   TRY_CATCH (e, RETURN_MASK_ERROR)
14150     {
14151       b->ops->decode_linespec (b, &s, &sals);
14152     }
14153   if (e.reason < 0)
14154     {
14155       int not_found_and_ok = 0;
14156       /* For pending breakpoints, it's expected that parsing will
14157          fail until the right shared library is loaded.  User has
14158          already told to create pending breakpoints and don't need
14159          extra messages.  If breakpoint is in bp_shlib_disabled
14160          state, then user already saw the message about that
14161          breakpoint being disabled, and don't want to see more
14162          errors.  */
14163       if (e.error == NOT_FOUND_ERROR
14164           && (b->condition_not_parsed 
14165               || (b->loc && b->loc->shlib_disabled)
14166               || (b->loc && b->loc->pspace->executing_startup)
14167               || b->enable_state == bp_disabled))
14168         not_found_and_ok = 1;
14169
14170       if (!not_found_and_ok)
14171         {
14172           /* We surely don't want to warn about the same breakpoint
14173              10 times.  One solution, implemented here, is disable
14174              the breakpoint on error.  Another solution would be to
14175              have separate 'warning emitted' flag.  Since this
14176              happens only when a binary has changed, I don't know
14177              which approach is better.  */
14178           b->enable_state = bp_disabled;
14179           throw_exception (e);
14180         }
14181     }
14182
14183   if (e.reason == 0 || e.error != NOT_FOUND_ERROR)
14184     {
14185       int i;
14186
14187       for (i = 0; i < sals.nelts; ++i)
14188         resolve_sal_pc (&sals.sals[i]);
14189       if (b->condition_not_parsed && s && s[0])
14190         {
14191           char *cond_string, *extra_string;
14192           int thread, task;
14193
14194           find_condition_and_thread (s, sals.sals[0].pc,
14195                                      &cond_string, &thread, &task,
14196                                      &extra_string);
14197           if (cond_string)
14198             b->cond_string = cond_string;
14199           b->thread = thread;
14200           b->task = task;
14201           if (extra_string)
14202             b->extra_string = extra_string;
14203           b->condition_not_parsed = 0;
14204         }
14205
14206       if (b->type == bp_static_tracepoint && !strace_marker_p (b))
14207         sals.sals[0] = update_static_tracepoint (b, sals.sals[0]);
14208
14209       *found = 1;
14210     }
14211   else
14212     *found = 0;
14213
14214   return sals;
14215 }
14216
14217 /* The default re_set method, for typical hardware or software
14218    breakpoints.  Reevaluate the breakpoint and recreate its
14219    locations.  */
14220
14221 static void
14222 breakpoint_re_set_default (struct breakpoint *b)
14223 {
14224   int found;
14225   struct symtabs_and_lines sals, sals_end;
14226   struct symtabs_and_lines expanded = {0};
14227   struct symtabs_and_lines expanded_end = {0};
14228
14229   sals = addr_string_to_sals (b, b->addr_string, &found);
14230   if (found)
14231     {
14232       make_cleanup (xfree, sals.sals);
14233       expanded = sals;
14234     }
14235
14236   if (b->addr_string_range_end)
14237     {
14238       sals_end = addr_string_to_sals (b, b->addr_string_range_end, &found);
14239       if (found)
14240         {
14241           make_cleanup (xfree, sals_end.sals);
14242           expanded_end = sals_end;
14243         }
14244     }
14245
14246   update_breakpoint_locations (b, expanded, expanded_end);
14247 }
14248
14249 /* Default method for creating SALs from an address string.  It basically
14250    calls parse_breakpoint_sals.  Return 1 for success, zero for failure.  */
14251
14252 static void
14253 create_sals_from_address_default (char **arg,
14254                                   struct linespec_result *canonical,
14255                                   enum bptype type_wanted,
14256                                   char *addr_start, char **copy_arg)
14257 {
14258   parse_breakpoint_sals (arg, canonical);
14259 }
14260
14261 /* Call create_breakpoints_sal for the given arguments.  This is the default
14262    function for the `create_breakpoints_sal' method of
14263    breakpoint_ops.  */
14264
14265 static void
14266 create_breakpoints_sal_default (struct gdbarch *gdbarch,
14267                                 struct linespec_result *canonical,
14268                                 struct linespec_sals *lsal,
14269                                 char *cond_string,
14270                                 char *extra_string,
14271                                 enum bptype type_wanted,
14272                                 enum bpdisp disposition,
14273                                 int thread,
14274                                 int task, int ignore_count,
14275                                 const struct breakpoint_ops *ops,
14276                                 int from_tty, int enabled,
14277                                 int internal, unsigned flags)
14278 {
14279   create_breakpoints_sal (gdbarch, canonical, cond_string,
14280                           extra_string,
14281                           type_wanted, disposition,
14282                           thread, task, ignore_count, ops, from_tty,
14283                           enabled, internal, flags);
14284 }
14285
14286 /* Decode the line represented by S by calling decode_line_full.  This is the
14287    default function for the `decode_linespec' method of breakpoint_ops.  */
14288
14289 static void
14290 decode_linespec_default (struct breakpoint *b, char **s,
14291                          struct symtabs_and_lines *sals)
14292 {
14293   struct linespec_result canonical;
14294
14295   init_linespec_result (&canonical);
14296   decode_line_full (s, DECODE_LINE_FUNFIRSTLINE,
14297                     (struct symtab *) NULL, 0,
14298                     &canonical, multiple_symbols_all,
14299                     b->filter);
14300
14301   /* We should get 0 or 1 resulting SALs.  */
14302   gdb_assert (VEC_length (linespec_sals, canonical.sals) < 2);
14303
14304   if (VEC_length (linespec_sals, canonical.sals) > 0)
14305     {
14306       struct linespec_sals *lsal;
14307
14308       lsal = VEC_index (linespec_sals, canonical.sals, 0);
14309       *sals = lsal->sals;
14310       /* Arrange it so the destructor does not free the
14311          contents.  */
14312       lsal->sals.sals = NULL;
14313     }
14314
14315   destroy_linespec_result (&canonical);
14316 }
14317
14318 /* Prepare the global context for a re-set of breakpoint B.  */
14319
14320 static struct cleanup *
14321 prepare_re_set_context (struct breakpoint *b)
14322 {
14323   struct cleanup *cleanups;
14324
14325   input_radix = b->input_radix;
14326   cleanups = save_current_space_and_thread ();
14327   if (b->pspace != NULL)
14328     switch_to_program_space_and_thread (b->pspace);
14329   set_language (b->language);
14330
14331   return cleanups;
14332 }
14333
14334 /* Reset a breakpoint given it's struct breakpoint * BINT.
14335    The value we return ends up being the return value from catch_errors.
14336    Unused in this case.  */
14337
14338 static int
14339 breakpoint_re_set_one (void *bint)
14340 {
14341   /* Get past catch_errs.  */
14342   struct breakpoint *b = (struct breakpoint *) bint;
14343   struct cleanup *cleanups;
14344
14345   cleanups = prepare_re_set_context (b);
14346   b->ops->re_set (b);
14347   do_cleanups (cleanups);
14348   return 0;
14349 }
14350
14351 /* Re-set all breakpoints after symbols have been re-loaded.  */
14352 void
14353 breakpoint_re_set (void)
14354 {
14355   struct breakpoint *b, *b_tmp;
14356   enum language save_language;
14357   int save_input_radix;
14358   struct cleanup *old_chain;
14359
14360   save_language = current_language->la_language;
14361   save_input_radix = input_radix;
14362   old_chain = save_current_program_space ();
14363
14364   ALL_BREAKPOINTS_SAFE (b, b_tmp)
14365   {
14366     /* Format possible error msg.  */
14367     char *message = xstrprintf ("Error in re-setting breakpoint %d: ",
14368                                 b->number);
14369     struct cleanup *cleanups = make_cleanup (xfree, message);
14370     catch_errors (breakpoint_re_set_one, b, message, RETURN_MASK_ALL);
14371     do_cleanups (cleanups);
14372   }
14373   set_language (save_language);
14374   input_radix = save_input_radix;
14375
14376   jit_breakpoint_re_set ();
14377
14378   do_cleanups (old_chain);
14379
14380   create_overlay_event_breakpoint ();
14381   create_longjmp_master_breakpoint ();
14382   create_std_terminate_master_breakpoint ();
14383   create_exception_master_breakpoint ();
14384 }
14385 \f
14386 /* Reset the thread number of this breakpoint:
14387
14388    - If the breakpoint is for all threads, leave it as-is.
14389    - Else, reset it to the current thread for inferior_ptid.  */
14390 void
14391 breakpoint_re_set_thread (struct breakpoint *b)
14392 {
14393   if (b->thread != -1)
14394     {
14395       if (in_thread_list (inferior_ptid))
14396         b->thread = pid_to_thread_id (inferior_ptid);
14397
14398       /* We're being called after following a fork.  The new fork is
14399          selected as current, and unless this was a vfork will have a
14400          different program space from the original thread.  Reset that
14401          as well.  */
14402       b->loc->pspace = current_program_space;
14403     }
14404 }
14405
14406 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
14407    If from_tty is nonzero, it prints a message to that effect,
14408    which ends with a period (no newline).  */
14409
14410 void
14411 set_ignore_count (int bptnum, int count, int from_tty)
14412 {
14413   struct breakpoint *b;
14414
14415   if (count < 0)
14416     count = 0;
14417
14418   ALL_BREAKPOINTS (b)
14419     if (b->number == bptnum)
14420     {
14421       if (is_tracepoint (b))
14422         {
14423           if (from_tty && count != 0)
14424             printf_filtered (_("Ignore count ignored for tracepoint %d."),
14425                              bptnum);
14426           return;
14427         }
14428       
14429       b->ignore_count = count;
14430       if (from_tty)
14431         {
14432           if (count == 0)
14433             printf_filtered (_("Will stop next time "
14434                                "breakpoint %d is reached."),
14435                              bptnum);
14436           else if (count == 1)
14437             printf_filtered (_("Will ignore next crossing of breakpoint %d."),
14438                              bptnum);
14439           else
14440             printf_filtered (_("Will ignore next %d "
14441                                "crossings of breakpoint %d."),
14442                              count, bptnum);
14443         }
14444       observer_notify_breakpoint_modified (b);
14445       return;
14446     }
14447
14448   error (_("No breakpoint number %d."), bptnum);
14449 }
14450
14451 /* Command to set ignore-count of breakpoint N to COUNT.  */
14452
14453 static void
14454 ignore_command (char *args, int from_tty)
14455 {
14456   char *p = args;
14457   int num;
14458
14459   if (p == 0)
14460     error_no_arg (_("a breakpoint number"));
14461
14462   num = get_number (&p);
14463   if (num == 0)
14464     error (_("bad breakpoint number: '%s'"), args);
14465   if (*p == 0)
14466     error (_("Second argument (specified ignore-count) is missing."));
14467
14468   set_ignore_count (num,
14469                     longest_to_int (value_as_long (parse_and_eval (p))),
14470                     from_tty);
14471   if (from_tty)
14472     printf_filtered ("\n");
14473 }
14474 \f
14475 /* Call FUNCTION on each of the breakpoints
14476    whose numbers are given in ARGS.  */
14477
14478 static void
14479 map_breakpoint_numbers (char *args, void (*function) (struct breakpoint *,
14480                                                       void *),
14481                         void *data)
14482 {
14483   int num;
14484   struct breakpoint *b, *tmp;
14485   int match;
14486   struct get_number_or_range_state state;
14487
14488   if (args == 0)
14489     error_no_arg (_("one or more breakpoint numbers"));
14490
14491   init_number_or_range (&state, args);
14492
14493   while (!state.finished)
14494     {
14495       char *p = state.string;
14496
14497       match = 0;
14498
14499       num = get_number_or_range (&state);
14500       if (num == 0)
14501         {
14502           warning (_("bad breakpoint number at or near '%s'"), p);
14503         }
14504       else
14505         {
14506           ALL_BREAKPOINTS_SAFE (b, tmp)
14507             if (b->number == num)
14508               {
14509                 match = 1;
14510                 function (b, data);
14511                 break;
14512               }
14513           if (match == 0)
14514             printf_unfiltered (_("No breakpoint number %d.\n"), num);
14515         }
14516     }
14517 }
14518
14519 static struct bp_location *
14520 find_location_by_number (char *number)
14521 {
14522   char *dot = strchr (number, '.');
14523   char *p1;
14524   int bp_num;
14525   int loc_num;
14526   struct breakpoint *b;
14527   struct bp_location *loc;  
14528
14529   *dot = '\0';
14530
14531   p1 = number;
14532   bp_num = get_number (&p1);
14533   if (bp_num == 0)
14534     error (_("Bad breakpoint number '%s'"), number);
14535
14536   ALL_BREAKPOINTS (b)
14537     if (b->number == bp_num)
14538       {
14539         break;
14540       }
14541
14542   if (!b || b->number != bp_num)
14543     error (_("Bad breakpoint number '%s'"), number);
14544   
14545   p1 = dot+1;
14546   loc_num = get_number (&p1);
14547   if (loc_num == 0)
14548     error (_("Bad breakpoint location number '%s'"), number);
14549
14550   --loc_num;
14551   loc = b->loc;
14552   for (;loc_num && loc; --loc_num, loc = loc->next)
14553     ;
14554   if (!loc)
14555     error (_("Bad breakpoint location number '%s'"), dot+1);
14556     
14557   return loc;  
14558 }
14559
14560
14561 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
14562    If from_tty is nonzero, it prints a message to that effect,
14563    which ends with a period (no newline).  */
14564
14565 void
14566 disable_breakpoint (struct breakpoint *bpt)
14567 {
14568   /* Never disable a watchpoint scope breakpoint; we want to
14569      hit them when we leave scope so we can delete both the
14570      watchpoint and its scope breakpoint at that time.  */
14571   if (bpt->type == bp_watchpoint_scope)
14572     return;
14573
14574   /* You can't disable permanent breakpoints.  */
14575   if (bpt->enable_state == bp_permanent)
14576     return;
14577
14578   bpt->enable_state = bp_disabled;
14579
14580   /* Mark breakpoint locations modified.  */
14581   mark_breakpoint_modified (bpt);
14582
14583   if (target_supports_enable_disable_tracepoint ()
14584       && current_trace_status ()->running && is_tracepoint (bpt))
14585     {
14586       struct bp_location *location;
14587      
14588       for (location = bpt->loc; location; location = location->next)
14589         target_disable_tracepoint (location);
14590     }
14591
14592   update_global_location_list (0);
14593
14594   observer_notify_breakpoint_modified (bpt);
14595 }
14596
14597 /* A callback for iterate_over_related_breakpoints.  */
14598
14599 static void
14600 do_disable_breakpoint (struct breakpoint *b, void *ignore)
14601 {
14602   disable_breakpoint (b);
14603 }
14604
14605 /* A callback for map_breakpoint_numbers that calls
14606    disable_breakpoint.  */
14607
14608 static void
14609 do_map_disable_breakpoint (struct breakpoint *b, void *ignore)
14610 {
14611   iterate_over_related_breakpoints (b, do_disable_breakpoint, NULL);
14612 }
14613
14614 static void
14615 disable_command (char *args, int from_tty)
14616 {
14617   if (args == 0)
14618     {
14619       struct breakpoint *bpt;
14620
14621       ALL_BREAKPOINTS (bpt)
14622         if (user_breakpoint_p (bpt))
14623           disable_breakpoint (bpt);
14624     }
14625   else if (strchr (args, '.'))
14626     {
14627       struct bp_location *loc = find_location_by_number (args);
14628       if (loc)
14629         {
14630           if (loc->enabled)
14631             {
14632               loc->enabled = 0;
14633               mark_breakpoint_location_modified (loc);
14634             }
14635           if (target_supports_enable_disable_tracepoint ()
14636               && current_trace_status ()->running && loc->owner
14637               && is_tracepoint (loc->owner))
14638             target_disable_tracepoint (loc);
14639         }
14640       update_global_location_list (0);
14641     }
14642   else
14643     map_breakpoint_numbers (args, do_map_disable_breakpoint, NULL);
14644 }
14645
14646 static void
14647 enable_breakpoint_disp (struct breakpoint *bpt, enum bpdisp disposition,
14648                         int count)
14649 {
14650   int target_resources_ok;
14651
14652   if (bpt->type == bp_hardware_breakpoint)
14653     {
14654       int i;
14655       i = hw_breakpoint_used_count ();
14656       target_resources_ok = 
14657         target_can_use_hardware_watchpoint (bp_hardware_breakpoint, 
14658                                             i + 1, 0);
14659       if (target_resources_ok == 0)
14660         error (_("No hardware breakpoint support in the target."));
14661       else if (target_resources_ok < 0)
14662         error (_("Hardware breakpoints used exceeds limit."));
14663     }
14664
14665   if (is_watchpoint (bpt))
14666     {
14667       /* Initialize it just to avoid a GCC false warning.  */
14668       enum enable_state orig_enable_state = 0;
14669       volatile struct gdb_exception e;
14670
14671       TRY_CATCH (e, RETURN_MASK_ALL)
14672         {
14673           struct watchpoint *w = (struct watchpoint *) bpt;
14674
14675           orig_enable_state = bpt->enable_state;
14676           bpt->enable_state = bp_enabled;
14677           update_watchpoint (w, 1 /* reparse */);
14678         }
14679       if (e.reason < 0)
14680         {
14681           bpt->enable_state = orig_enable_state;
14682           exception_fprintf (gdb_stderr, e, _("Cannot enable watchpoint %d: "),
14683                              bpt->number);
14684           return;
14685         }
14686     }
14687
14688   if (bpt->enable_state != bp_permanent)
14689     bpt->enable_state = bp_enabled;
14690
14691   bpt->enable_state = bp_enabled;
14692
14693   /* Mark breakpoint locations modified.  */
14694   mark_breakpoint_modified (bpt);
14695
14696   if (target_supports_enable_disable_tracepoint ()
14697       && current_trace_status ()->running && is_tracepoint (bpt))
14698     {
14699       struct bp_location *location;
14700
14701       for (location = bpt->loc; location; location = location->next)
14702         target_enable_tracepoint (location);
14703     }
14704
14705   bpt->disposition = disposition;
14706   bpt->enable_count = count;
14707   update_global_location_list (1);
14708
14709   observer_notify_breakpoint_modified (bpt);
14710 }
14711
14712
14713 void
14714 enable_breakpoint (struct breakpoint *bpt)
14715 {
14716   enable_breakpoint_disp (bpt, bpt->disposition, 0);
14717 }
14718
14719 static void
14720 do_enable_breakpoint (struct breakpoint *bpt, void *arg)
14721 {
14722   enable_breakpoint (bpt);
14723 }
14724
14725 /* A callback for map_breakpoint_numbers that calls
14726    enable_breakpoint.  */
14727
14728 static void
14729 do_map_enable_breakpoint (struct breakpoint *b, void *ignore)
14730 {
14731   iterate_over_related_breakpoints (b, do_enable_breakpoint, NULL);
14732 }
14733
14734 /* The enable command enables the specified breakpoints (or all defined
14735    breakpoints) so they once again become (or continue to be) effective
14736    in stopping the inferior.  */
14737
14738 static void
14739 enable_command (char *args, int from_tty)
14740 {
14741   if (args == 0)
14742     {
14743       struct breakpoint *bpt;
14744
14745       ALL_BREAKPOINTS (bpt)
14746         if (user_breakpoint_p (bpt))
14747           enable_breakpoint (bpt);
14748     }
14749   else if (strchr (args, '.'))
14750     {
14751       struct bp_location *loc = find_location_by_number (args);
14752       if (loc)
14753         {
14754           if (!loc->enabled)
14755             {
14756               loc->enabled = 1;
14757               mark_breakpoint_location_modified (loc);
14758             }
14759           if (target_supports_enable_disable_tracepoint ()
14760               && current_trace_status ()->running && loc->owner
14761               && is_tracepoint (loc->owner))
14762             target_enable_tracepoint (loc);
14763         }
14764       update_global_location_list (1);
14765     }
14766   else
14767     map_breakpoint_numbers (args, do_map_enable_breakpoint, NULL);
14768 }
14769
14770 /* This struct packages up disposition data for application to multiple
14771    breakpoints.  */
14772
14773 struct disp_data
14774 {
14775   enum bpdisp disp;
14776   int count;
14777 };
14778
14779 static void
14780 do_enable_breakpoint_disp (struct breakpoint *bpt, void *arg)
14781 {
14782   struct disp_data disp_data = *(struct disp_data *) arg;
14783
14784   enable_breakpoint_disp (bpt, disp_data.disp, disp_data.count);
14785 }
14786
14787 static void
14788 do_map_enable_once_breakpoint (struct breakpoint *bpt, void *ignore)
14789 {
14790   struct disp_data disp = { disp_disable, 1 };
14791
14792   iterate_over_related_breakpoints (bpt, do_enable_breakpoint_disp, &disp);
14793 }
14794
14795 static void
14796 enable_once_command (char *args, int from_tty)
14797 {
14798   map_breakpoint_numbers (args, do_map_enable_once_breakpoint, NULL);
14799 }
14800
14801 static void
14802 do_map_enable_count_breakpoint (struct breakpoint *bpt, void *countptr)
14803 {
14804   struct disp_data disp = { disp_disable, *(int *) countptr };
14805
14806   iterate_over_related_breakpoints (bpt, do_enable_breakpoint_disp, &disp);
14807 }
14808
14809 static void
14810 enable_count_command (char *args, int from_tty)
14811 {
14812   int count = get_number (&args);
14813
14814   map_breakpoint_numbers (args, do_map_enable_count_breakpoint, &count);
14815 }
14816
14817 static void
14818 do_map_enable_delete_breakpoint (struct breakpoint *bpt, void *ignore)
14819 {
14820   struct disp_data disp = { disp_del, 1 };
14821
14822   iterate_over_related_breakpoints (bpt, do_enable_breakpoint_disp, &disp);
14823 }
14824
14825 static void
14826 enable_delete_command (char *args, int from_tty)
14827 {
14828   map_breakpoint_numbers (args, do_map_enable_delete_breakpoint, NULL);
14829 }
14830 \f
14831 static void
14832 set_breakpoint_cmd (char *args, int from_tty)
14833 {
14834 }
14835
14836 static void
14837 show_breakpoint_cmd (char *args, int from_tty)
14838 {
14839 }
14840
14841 /* Invalidate last known value of any hardware watchpoint if
14842    the memory which that value represents has been written to by
14843    GDB itself.  */
14844
14845 static void
14846 invalidate_bp_value_on_memory_change (struct inferior *inferior,
14847                                       CORE_ADDR addr, ssize_t len,
14848                                       const bfd_byte *data)
14849 {
14850   struct breakpoint *bp;
14851
14852   ALL_BREAKPOINTS (bp)
14853     if (bp->enable_state == bp_enabled
14854         && bp->type == bp_hardware_watchpoint)
14855       {
14856         struct watchpoint *wp = (struct watchpoint *) bp;
14857
14858         if (wp->val_valid && wp->val)
14859           {
14860             struct bp_location *loc;
14861
14862             for (loc = bp->loc; loc != NULL; loc = loc->next)
14863               if (loc->loc_type == bp_loc_hardware_watchpoint
14864                   && loc->address + loc->length > addr
14865                   && addr + len > loc->address)
14866                 {
14867                   value_free (wp->val);
14868                   wp->val = NULL;
14869                   wp->val_valid = 0;
14870                 }
14871           }
14872       }
14873 }
14874
14875 /* Create and insert a raw software breakpoint at PC.  Return an
14876    identifier, which should be used to remove the breakpoint later.
14877    In general, places which call this should be using something on the
14878    breakpoint chain instead; this function should be eliminated
14879    someday.  */
14880
14881 void *
14882 deprecated_insert_raw_breakpoint (struct gdbarch *gdbarch,
14883                                   struct address_space *aspace, CORE_ADDR pc)
14884 {
14885   struct bp_target_info *bp_tgt;
14886
14887   bp_tgt = XZALLOC (struct bp_target_info);
14888
14889   bp_tgt->placed_address_space = aspace;
14890   bp_tgt->placed_address = pc;
14891
14892   if (target_insert_breakpoint (gdbarch, bp_tgt) != 0)
14893     {
14894       /* Could not insert the breakpoint.  */
14895       xfree (bp_tgt);
14896       return NULL;
14897     }
14898
14899   return bp_tgt;
14900 }
14901
14902 /* Remove a breakpoint BP inserted by
14903    deprecated_insert_raw_breakpoint.  */
14904
14905 int
14906 deprecated_remove_raw_breakpoint (struct gdbarch *gdbarch, void *bp)
14907 {
14908   struct bp_target_info *bp_tgt = bp;
14909   int ret;
14910
14911   ret = target_remove_breakpoint (gdbarch, bp_tgt);
14912   xfree (bp_tgt);
14913
14914   return ret;
14915 }
14916
14917 /* One (or perhaps two) breakpoints used for software single
14918    stepping.  */
14919
14920 static void *single_step_breakpoints[2];
14921 static struct gdbarch *single_step_gdbarch[2];
14922
14923 /* Create and insert a breakpoint for software single step.  */
14924
14925 void
14926 insert_single_step_breakpoint (struct gdbarch *gdbarch,
14927                                struct address_space *aspace, 
14928                                CORE_ADDR next_pc)
14929 {
14930   void **bpt_p;
14931
14932   if (single_step_breakpoints[0] == NULL)
14933     {
14934       bpt_p = &single_step_breakpoints[0];
14935       single_step_gdbarch[0] = gdbarch;
14936     }
14937   else
14938     {
14939       gdb_assert (single_step_breakpoints[1] == NULL);
14940       bpt_p = &single_step_breakpoints[1];
14941       single_step_gdbarch[1] = gdbarch;
14942     }
14943
14944   /* NOTE drow/2006-04-11: A future improvement to this function would
14945      be to only create the breakpoints once, and actually put them on
14946      the breakpoint chain.  That would let us use set_raw_breakpoint.
14947      We could adjust the addresses each time they were needed.  Doing
14948      this requires corresponding changes elsewhere where single step
14949      breakpoints are handled, however.  So, for now, we use this.  */
14950
14951   *bpt_p = deprecated_insert_raw_breakpoint (gdbarch, aspace, next_pc);
14952   if (*bpt_p == NULL)
14953     error (_("Could not insert single-step breakpoint at %s"),
14954              paddress (gdbarch, next_pc));
14955 }
14956
14957 /* Check if the breakpoints used for software single stepping
14958    were inserted or not.  */
14959
14960 int
14961 single_step_breakpoints_inserted (void)
14962 {
14963   return (single_step_breakpoints[0] != NULL
14964           || single_step_breakpoints[1] != NULL);
14965 }
14966
14967 /* Remove and delete any breakpoints used for software single step.  */
14968
14969 void
14970 remove_single_step_breakpoints (void)
14971 {
14972   gdb_assert (single_step_breakpoints[0] != NULL);
14973
14974   /* See insert_single_step_breakpoint for more about this deprecated
14975      call.  */
14976   deprecated_remove_raw_breakpoint (single_step_gdbarch[0],
14977                                     single_step_breakpoints[0]);
14978   single_step_gdbarch[0] = NULL;
14979   single_step_breakpoints[0] = NULL;
14980
14981   if (single_step_breakpoints[1] != NULL)
14982     {
14983       deprecated_remove_raw_breakpoint (single_step_gdbarch[1],
14984                                         single_step_breakpoints[1]);
14985       single_step_gdbarch[1] = NULL;
14986       single_step_breakpoints[1] = NULL;
14987     }
14988 }
14989
14990 /* Delete software single step breakpoints without removing them from
14991    the inferior.  This is intended to be used if the inferior's address
14992    space where they were inserted is already gone, e.g. after exit or
14993    exec.  */
14994
14995 void
14996 cancel_single_step_breakpoints (void)
14997 {
14998   int i;
14999
15000   for (i = 0; i < 2; i++)
15001     if (single_step_breakpoints[i])
15002       {
15003         xfree (single_step_breakpoints[i]);
15004         single_step_breakpoints[i] = NULL;
15005         single_step_gdbarch[i] = NULL;
15006       }
15007 }
15008
15009 /* Detach software single-step breakpoints from INFERIOR_PTID without
15010    removing them.  */
15011
15012 static void
15013 detach_single_step_breakpoints (void)
15014 {
15015   int i;
15016
15017   for (i = 0; i < 2; i++)
15018     if (single_step_breakpoints[i])
15019       target_remove_breakpoint (single_step_gdbarch[i],
15020                                 single_step_breakpoints[i]);
15021 }
15022
15023 /* Check whether a software single-step breakpoint is inserted at
15024    PC.  */
15025
15026 static int
15027 single_step_breakpoint_inserted_here_p (struct address_space *aspace, 
15028                                         CORE_ADDR pc)
15029 {
15030   int i;
15031
15032   for (i = 0; i < 2; i++)
15033     {
15034       struct bp_target_info *bp_tgt = single_step_breakpoints[i];
15035       if (bp_tgt
15036           && breakpoint_address_match (bp_tgt->placed_address_space,
15037                                        bp_tgt->placed_address,
15038                                        aspace, pc))
15039         return 1;
15040     }
15041
15042   return 0;
15043 }
15044
15045 /* Returns 0 if 'bp' is NOT a syscall catchpoint,
15046    non-zero otherwise.  */
15047 static int
15048 is_syscall_catchpoint_enabled (struct breakpoint *bp)
15049 {
15050   if (syscall_catchpoint_p (bp)
15051       && bp->enable_state != bp_disabled
15052       && bp->enable_state != bp_call_disabled)
15053     return 1;
15054   else
15055     return 0;
15056 }
15057
15058 int
15059 catch_syscall_enabled (void)
15060 {
15061   struct catch_syscall_inferior_data *inf_data
15062     = get_catch_syscall_inferior_data (current_inferior ());
15063
15064   return inf_data->total_syscalls_count != 0;
15065 }
15066
15067 int
15068 catching_syscall_number (int syscall_number)
15069 {
15070   struct breakpoint *bp;
15071
15072   ALL_BREAKPOINTS (bp)
15073     if (is_syscall_catchpoint_enabled (bp))
15074       {
15075         struct syscall_catchpoint *c = (struct syscall_catchpoint *) bp;
15076
15077         if (c->syscalls_to_be_caught)
15078           {
15079             int i, iter;
15080             for (i = 0;
15081                  VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
15082                  i++)
15083               if (syscall_number == iter)
15084                 return 1;
15085           }
15086         else
15087           return 1;
15088       }
15089
15090   return 0;
15091 }
15092
15093 /* Complete syscall names.  Used by "catch syscall".  */
15094 static VEC (char_ptr) *
15095 catch_syscall_completer (struct cmd_list_element *cmd,
15096                          const char *text, const char *word)
15097 {
15098   const char **list = get_syscall_names ();
15099   VEC (char_ptr) *retlist
15100     = (list == NULL) ? NULL : complete_on_enum (list, word, word);
15101
15102   xfree (list);
15103   return retlist;
15104 }
15105
15106 /* Tracepoint-specific operations.  */
15107
15108 /* Set tracepoint count to NUM.  */
15109 static void
15110 set_tracepoint_count (int num)
15111 {
15112   tracepoint_count = num;
15113   set_internalvar_integer (lookup_internalvar ("tpnum"), num);
15114 }
15115
15116 static void
15117 trace_command (char *arg, int from_tty)
15118 {
15119   struct breakpoint_ops *ops;
15120   const char *arg_cp = arg;
15121
15122   if (arg && probe_linespec_to_ops (&arg_cp))
15123     ops = &tracepoint_probe_breakpoint_ops;
15124   else
15125     ops = &tracepoint_breakpoint_ops;
15126
15127   create_breakpoint (get_current_arch (),
15128                      arg,
15129                      NULL, 0, NULL, 1 /* parse arg */,
15130                      0 /* tempflag */,
15131                      bp_tracepoint /* type_wanted */,
15132                      0 /* Ignore count */,
15133                      pending_break_support,
15134                      ops,
15135                      from_tty,
15136                      1 /* enabled */,
15137                      0 /* internal */, 0);
15138 }
15139
15140 static void
15141 ftrace_command (char *arg, int from_tty)
15142 {
15143   create_breakpoint (get_current_arch (),
15144                      arg,
15145                      NULL, 0, NULL, 1 /* parse arg */,
15146                      0 /* tempflag */,
15147                      bp_fast_tracepoint /* type_wanted */,
15148                      0 /* Ignore count */,
15149                      pending_break_support,
15150                      &tracepoint_breakpoint_ops,
15151                      from_tty,
15152                      1 /* enabled */,
15153                      0 /* internal */, 0);
15154 }
15155
15156 /* strace command implementation.  Creates a static tracepoint.  */
15157
15158 static void
15159 strace_command (char *arg, int from_tty)
15160 {
15161   struct breakpoint_ops *ops;
15162
15163   /* Decide if we are dealing with a static tracepoint marker (`-m'),
15164      or with a normal static tracepoint.  */
15165   if (arg && strncmp (arg, "-m", 2) == 0 && isspace (arg[2]))
15166     ops = &strace_marker_breakpoint_ops;
15167   else
15168     ops = &tracepoint_breakpoint_ops;
15169
15170   create_breakpoint (get_current_arch (),
15171                      arg,
15172                      NULL, 0, NULL, 1 /* parse arg */,
15173                      0 /* tempflag */,
15174                      bp_static_tracepoint /* type_wanted */,
15175                      0 /* Ignore count */,
15176                      pending_break_support,
15177                      ops,
15178                      from_tty,
15179                      1 /* enabled */,
15180                      0 /* internal */, 0);
15181 }
15182
15183 /* Set up a fake reader function that gets command lines from a linked
15184    list that was acquired during tracepoint uploading.  */
15185
15186 static struct uploaded_tp *this_utp;
15187 static int next_cmd;
15188
15189 static char *
15190 read_uploaded_action (void)
15191 {
15192   char *rslt;
15193
15194   VEC_iterate (char_ptr, this_utp->cmd_strings, next_cmd, rslt);
15195
15196   next_cmd++;
15197
15198   return rslt;
15199 }
15200
15201 /* Given information about a tracepoint as recorded on a target (which
15202    can be either a live system or a trace file), attempt to create an
15203    equivalent GDB tracepoint.  This is not a reliable process, since
15204    the target does not necessarily have all the information used when
15205    the tracepoint was originally defined.  */
15206   
15207 struct tracepoint *
15208 create_tracepoint_from_upload (struct uploaded_tp *utp)
15209 {
15210   char *addr_str, small_buf[100];
15211   struct tracepoint *tp;
15212
15213   if (utp->at_string)
15214     addr_str = utp->at_string;
15215   else
15216     {
15217       /* In the absence of a source location, fall back to raw
15218          address.  Since there is no way to confirm that the address
15219          means the same thing as when the trace was started, warn the
15220          user.  */
15221       warning (_("Uploaded tracepoint %d has no "
15222                  "source location, using raw address"),
15223                utp->number);
15224       xsnprintf (small_buf, sizeof (small_buf), "*%s", hex_string (utp->addr));
15225       addr_str = small_buf;
15226     }
15227
15228   /* There's not much we can do with a sequence of bytecodes.  */
15229   if (utp->cond && !utp->cond_string)
15230     warning (_("Uploaded tracepoint %d condition "
15231                "has no source form, ignoring it"),
15232              utp->number);
15233
15234   if (!create_breakpoint (get_current_arch (),
15235                           addr_str,
15236                           utp->cond_string, -1, NULL,
15237                           0 /* parse cond/thread */,
15238                           0 /* tempflag */,
15239                           utp->type /* type_wanted */,
15240                           0 /* Ignore count */,
15241                           pending_break_support,
15242                           &tracepoint_breakpoint_ops,
15243                           0 /* from_tty */,
15244                           utp->enabled /* enabled */,
15245                           0 /* internal */,
15246                           CREATE_BREAKPOINT_FLAGS_INSERTED))
15247     return NULL;
15248
15249   /* Get the tracepoint we just created.  */
15250   tp = get_tracepoint (tracepoint_count);
15251   gdb_assert (tp != NULL);
15252
15253   if (utp->pass > 0)
15254     {
15255       xsnprintf (small_buf, sizeof (small_buf), "%d %d", utp->pass,
15256                  tp->base.number);
15257
15258       trace_pass_command (small_buf, 0);
15259     }
15260
15261   /* If we have uploaded versions of the original commands, set up a
15262      special-purpose "reader" function and call the usual command line
15263      reader, then pass the result to the breakpoint command-setting
15264      function.  */
15265   if (!VEC_empty (char_ptr, utp->cmd_strings))
15266     {
15267       struct command_line *cmd_list;
15268
15269       this_utp = utp;
15270       next_cmd = 0;
15271
15272       cmd_list = read_command_lines_1 (read_uploaded_action, 1, NULL, NULL);
15273
15274       breakpoint_set_commands (&tp->base, cmd_list);
15275     }
15276   else if (!VEC_empty (char_ptr, utp->actions)
15277            || !VEC_empty (char_ptr, utp->step_actions))
15278     warning (_("Uploaded tracepoint %d actions "
15279                "have no source form, ignoring them"),
15280              utp->number);
15281
15282   /* Copy any status information that might be available.  */
15283   tp->base.hit_count = utp->hit_count;
15284   tp->traceframe_usage = utp->traceframe_usage;
15285
15286   return tp;
15287 }
15288   
15289 /* Print information on tracepoint number TPNUM_EXP, or all if
15290    omitted.  */
15291
15292 static void
15293 tracepoints_info (char *args, int from_tty)
15294 {
15295   struct ui_out *uiout = current_uiout;
15296   int num_printed;
15297
15298   num_printed = breakpoint_1 (args, 0, is_tracepoint);
15299
15300   if (num_printed == 0)
15301     {
15302       if (args == NULL || *args == '\0')
15303         ui_out_message (uiout, 0, "No tracepoints.\n");
15304       else
15305         ui_out_message (uiout, 0, "No tracepoint matching '%s'.\n", args);
15306     }
15307
15308   default_collect_info ();
15309 }
15310
15311 /* The 'enable trace' command enables tracepoints.
15312    Not supported by all targets.  */
15313 static void
15314 enable_trace_command (char *args, int from_tty)
15315 {
15316   enable_command (args, from_tty);
15317 }
15318
15319 /* The 'disable trace' command disables tracepoints.
15320    Not supported by all targets.  */
15321 static void
15322 disable_trace_command (char *args, int from_tty)
15323 {
15324   disable_command (args, from_tty);
15325 }
15326
15327 /* Remove a tracepoint (or all if no argument).  */
15328 static void
15329 delete_trace_command (char *arg, int from_tty)
15330 {
15331   struct breakpoint *b, *b_tmp;
15332
15333   dont_repeat ();
15334
15335   if (arg == 0)
15336     {
15337       int breaks_to_delete = 0;
15338
15339       /* Delete all breakpoints if no argument.
15340          Do not delete internal or call-dummy breakpoints, these
15341          have to be deleted with an explicit breakpoint number 
15342          argument.  */
15343       ALL_TRACEPOINTS (b)
15344         if (is_tracepoint (b) && user_breakpoint_p (b))
15345           {
15346             breaks_to_delete = 1;
15347             break;
15348           }
15349
15350       /* Ask user only if there are some breakpoints to delete.  */
15351       if (!from_tty
15352           || (breaks_to_delete && query (_("Delete all tracepoints? "))))
15353         {
15354           ALL_BREAKPOINTS_SAFE (b, b_tmp)
15355             if (is_tracepoint (b) && user_breakpoint_p (b))
15356               delete_breakpoint (b);
15357         }
15358     }
15359   else
15360     map_breakpoint_numbers (arg, do_map_delete_breakpoint, NULL);
15361 }
15362
15363 /* Helper function for trace_pass_command.  */
15364
15365 static void
15366 trace_pass_set_count (struct tracepoint *tp, int count, int from_tty)
15367 {
15368   tp->pass_count = count;
15369   observer_notify_breakpoint_modified (&tp->base);
15370   if (from_tty)
15371     printf_filtered (_("Setting tracepoint %d's passcount to %d\n"),
15372                      tp->base.number, count);
15373 }
15374
15375 /* Set passcount for tracepoint.
15376
15377    First command argument is passcount, second is tracepoint number.
15378    If tracepoint number omitted, apply to most recently defined.
15379    Also accepts special argument "all".  */
15380
15381 static void
15382 trace_pass_command (char *args, int from_tty)
15383 {
15384   struct tracepoint *t1;
15385   unsigned int count;
15386
15387   if (args == 0 || *args == 0)
15388     error (_("passcount command requires an "
15389              "argument (count + optional TP num)"));
15390
15391   count = strtoul (args, &args, 10);    /* Count comes first, then TP num.  */
15392
15393   args = skip_spaces (args);
15394   if (*args && strncasecmp (args, "all", 3) == 0)
15395     {
15396       struct breakpoint *b;
15397
15398       args += 3;                        /* Skip special argument "all".  */
15399       if (*args)
15400         error (_("Junk at end of arguments."));
15401
15402       ALL_TRACEPOINTS (b)
15403       {
15404         t1 = (struct tracepoint *) b;
15405         trace_pass_set_count (t1, count, from_tty);
15406       }
15407     }
15408   else if (*args == '\0')
15409     {
15410       t1 = get_tracepoint_by_number (&args, NULL, 1);
15411       if (t1)
15412         trace_pass_set_count (t1, count, from_tty);
15413     }
15414   else
15415     {
15416       struct get_number_or_range_state state;
15417
15418       init_number_or_range (&state, args);
15419       while (!state.finished)
15420         {
15421           t1 = get_tracepoint_by_number (&args, &state, 1);
15422           if (t1)
15423             trace_pass_set_count (t1, count, from_tty);
15424         }
15425     }
15426 }
15427
15428 struct tracepoint *
15429 get_tracepoint (int num)
15430 {
15431   struct breakpoint *t;
15432
15433   ALL_TRACEPOINTS (t)
15434     if (t->number == num)
15435       return (struct tracepoint *) t;
15436
15437   return NULL;
15438 }
15439
15440 /* Find the tracepoint with the given target-side number (which may be
15441    different from the tracepoint number after disconnecting and
15442    reconnecting).  */
15443
15444 struct tracepoint *
15445 get_tracepoint_by_number_on_target (int num)
15446 {
15447   struct breakpoint *b;
15448
15449   ALL_TRACEPOINTS (b)
15450     {
15451       struct tracepoint *t = (struct tracepoint *) b;
15452
15453       if (t->number_on_target == num)
15454         return t;
15455     }
15456
15457   return NULL;
15458 }
15459
15460 /* Utility: parse a tracepoint number and look it up in the list.
15461    If STATE is not NULL, use, get_number_or_range_state and ignore ARG.
15462    If OPTIONAL_P is true, then if the argument is missing, the most
15463    recent tracepoint (tracepoint_count) is returned.  */
15464 struct tracepoint *
15465 get_tracepoint_by_number (char **arg,
15466                           struct get_number_or_range_state *state,
15467                           int optional_p)
15468 {
15469   struct breakpoint *t;
15470   int tpnum;
15471   char *instring = arg == NULL ? NULL : *arg;
15472
15473   if (state)
15474     {
15475       gdb_assert (!state->finished);
15476       tpnum = get_number_or_range (state);
15477     }
15478   else if (arg == NULL || *arg == NULL || ! **arg)
15479     {
15480       if (optional_p)
15481         tpnum = tracepoint_count;
15482       else
15483         error_no_arg (_("tracepoint number"));
15484     }
15485   else
15486     tpnum = get_number (arg);
15487
15488   if (tpnum <= 0)
15489     {
15490       if (instring && *instring)
15491         printf_filtered (_("bad tracepoint number at or near '%s'\n"), 
15492                          instring);
15493       else
15494         printf_filtered (_("Tracepoint argument missing "
15495                            "and no previous tracepoint\n"));
15496       return NULL;
15497     }
15498
15499   ALL_TRACEPOINTS (t)
15500     if (t->number == tpnum)
15501     {
15502       return (struct tracepoint *) t;
15503     }
15504
15505   printf_unfiltered ("No tracepoint number %d.\n", tpnum);
15506   return NULL;
15507 }
15508
15509 void
15510 print_recreate_thread (struct breakpoint *b, struct ui_file *fp)
15511 {
15512   if (b->thread != -1)
15513     fprintf_unfiltered (fp, " thread %d", b->thread);
15514
15515   if (b->task != 0)
15516     fprintf_unfiltered (fp, " task %d", b->task);
15517
15518   fprintf_unfiltered (fp, "\n");
15519 }
15520
15521 /* Save information on user settable breakpoints (watchpoints, etc) to
15522    a new script file named FILENAME.  If FILTER is non-NULL, call it
15523    on each breakpoint and only include the ones for which it returns
15524    non-zero.  */
15525
15526 static void
15527 save_breakpoints (char *filename, int from_tty,
15528                   int (*filter) (const struct breakpoint *))
15529 {
15530   struct breakpoint *tp;
15531   int any = 0;
15532   char *pathname;
15533   struct cleanup *cleanup;
15534   struct ui_file *fp;
15535   int extra_trace_bits = 0;
15536
15537   if (filename == 0 || *filename == 0)
15538     error (_("Argument required (file name in which to save)"));
15539
15540   /* See if we have anything to save.  */
15541   ALL_BREAKPOINTS (tp)
15542   {
15543     /* Skip internal and momentary breakpoints.  */
15544     if (!user_breakpoint_p (tp))
15545       continue;
15546
15547     /* If we have a filter, only save the breakpoints it accepts.  */
15548     if (filter && !filter (tp))
15549       continue;
15550
15551     any = 1;
15552
15553     if (is_tracepoint (tp))
15554       {
15555         extra_trace_bits = 1;
15556
15557         /* We can stop searching.  */
15558         break;
15559       }
15560   }
15561
15562   if (!any)
15563     {
15564       warning (_("Nothing to save."));
15565       return;
15566     }
15567
15568   pathname = tilde_expand (filename);
15569   cleanup = make_cleanup (xfree, pathname);
15570   fp = gdb_fopen (pathname, "w");
15571   if (!fp)
15572     error (_("Unable to open file '%s' for saving (%s)"),
15573            filename, safe_strerror (errno));
15574   make_cleanup_ui_file_delete (fp);
15575
15576   if (extra_trace_bits)
15577     save_trace_state_variables (fp);
15578
15579   ALL_BREAKPOINTS (tp)
15580   {
15581     /* Skip internal and momentary breakpoints.  */
15582     if (!user_breakpoint_p (tp))
15583       continue;
15584
15585     /* If we have a filter, only save the breakpoints it accepts.  */
15586     if (filter && !filter (tp))
15587       continue;
15588
15589     tp->ops->print_recreate (tp, fp);
15590
15591     /* Note, we can't rely on tp->number for anything, as we can't
15592        assume the recreated breakpoint numbers will match.  Use $bpnum
15593        instead.  */
15594
15595     if (tp->cond_string)
15596       fprintf_unfiltered (fp, "  condition $bpnum %s\n", tp->cond_string);
15597
15598     if (tp->ignore_count)
15599       fprintf_unfiltered (fp, "  ignore $bpnum %d\n", tp->ignore_count);
15600
15601     if (tp->commands)
15602       {
15603         volatile struct gdb_exception ex;       
15604
15605         fprintf_unfiltered (fp, "  commands\n");
15606         
15607         ui_out_redirect (current_uiout, fp);
15608         TRY_CATCH (ex, RETURN_MASK_ALL)
15609           {
15610             print_command_lines (current_uiout, tp->commands->commands, 2);
15611           }
15612         ui_out_redirect (current_uiout, NULL);
15613
15614         if (ex.reason < 0)
15615           throw_exception (ex);
15616
15617         fprintf_unfiltered (fp, "  end\n");
15618       }
15619
15620     if (tp->enable_state == bp_disabled)
15621       fprintf_unfiltered (fp, "disable\n");
15622
15623     /* If this is a multi-location breakpoint, check if the locations
15624        should be individually disabled.  Watchpoint locations are
15625        special, and not user visible.  */
15626     if (!is_watchpoint (tp) && tp->loc && tp->loc->next)
15627       {
15628         struct bp_location *loc;
15629         int n = 1;
15630
15631         for (loc = tp->loc; loc != NULL; loc = loc->next, n++)
15632           if (!loc->enabled)
15633             fprintf_unfiltered (fp, "disable $bpnum.%d\n", n);
15634       }
15635   }
15636
15637   if (extra_trace_bits && *default_collect)
15638     fprintf_unfiltered (fp, "set default-collect %s\n", default_collect);
15639
15640   do_cleanups (cleanup);
15641   if (from_tty)
15642     printf_filtered (_("Saved to file '%s'.\n"), filename);
15643 }
15644
15645 /* The `save breakpoints' command.  */
15646
15647 static void
15648 save_breakpoints_command (char *args, int from_tty)
15649 {
15650   save_breakpoints (args, from_tty, NULL);
15651 }
15652
15653 /* The `save tracepoints' command.  */
15654
15655 static void
15656 save_tracepoints_command (char *args, int from_tty)
15657 {
15658   save_breakpoints (args, from_tty, is_tracepoint);
15659 }
15660
15661 /* Create a vector of all tracepoints.  */
15662
15663 VEC(breakpoint_p) *
15664 all_tracepoints (void)
15665 {
15666   VEC(breakpoint_p) *tp_vec = 0;
15667   struct breakpoint *tp;
15668
15669   ALL_TRACEPOINTS (tp)
15670   {
15671     VEC_safe_push (breakpoint_p, tp_vec, tp);
15672   }
15673
15674   return tp_vec;
15675 }
15676
15677 \f
15678 /* This help string is used for the break, hbreak, tbreak and thbreak
15679    commands.  It is defined as a macro to prevent duplication.
15680    COMMAND should be a string constant containing the name of the
15681    command.  */
15682 #define BREAK_ARGS_HELP(command) \
15683 command" [PROBE_MODIFIER] [LOCATION] [thread THREADNUM] [if CONDITION]\n\
15684 PROBE_MODIFIER shall be present if the command is to be placed in a\n\
15685 probe point.  Accepted values are `-probe' (for a generic, automatically\n\
15686 guessed probe type) or `-probe-stap' (for a SystemTap probe).\n\
15687 LOCATION may be a line number, function name, or \"*\" and an address.\n\
15688 If a line number is specified, break at start of code for that line.\n\
15689 If a function is specified, break at start of code for that function.\n\
15690 If an address is specified, break at that exact address.\n\
15691 With no LOCATION, uses current execution address of the selected\n\
15692 stack frame.  This is useful for breaking on return to a stack frame.\n\
15693 \n\
15694 THREADNUM is the number from \"info threads\".\n\
15695 CONDITION is a boolean expression.\n\
15696 \n\
15697 Multiple breakpoints at one place are permitted, and useful if their\n\
15698 conditions are different.\n\
15699 \n\
15700 Do \"help breakpoints\" for info on other commands dealing with breakpoints."
15701
15702 /* List of subcommands for "catch".  */
15703 static struct cmd_list_element *catch_cmdlist;
15704
15705 /* List of subcommands for "tcatch".  */
15706 static struct cmd_list_element *tcatch_cmdlist;
15707
15708 void
15709 add_catch_command (char *name, char *docstring,
15710                    void (*sfunc) (char *args, int from_tty,
15711                                   struct cmd_list_element *command),
15712                    completer_ftype *completer,
15713                    void *user_data_catch,
15714                    void *user_data_tcatch)
15715 {
15716   struct cmd_list_element *command;
15717
15718   command = add_cmd (name, class_breakpoint, NULL, docstring,
15719                      &catch_cmdlist);
15720   set_cmd_sfunc (command, sfunc);
15721   set_cmd_context (command, user_data_catch);
15722   set_cmd_completer (command, completer);
15723
15724   command = add_cmd (name, class_breakpoint, NULL, docstring,
15725                      &tcatch_cmdlist);
15726   set_cmd_sfunc (command, sfunc);
15727   set_cmd_context (command, user_data_tcatch);
15728   set_cmd_completer (command, completer);
15729 }
15730
15731 static void
15732 clear_syscall_counts (struct inferior *inf)
15733 {
15734   struct catch_syscall_inferior_data *inf_data
15735     = get_catch_syscall_inferior_data (inf);
15736
15737   inf_data->total_syscalls_count = 0;
15738   inf_data->any_syscall_count = 0;
15739   VEC_free (int, inf_data->syscalls_counts);
15740 }
15741
15742 static void
15743 save_command (char *arg, int from_tty)
15744 {
15745   printf_unfiltered (_("\"save\" must be followed by "
15746                        "the name of a save subcommand.\n"));
15747   help_list (save_cmdlist, "save ", -1, gdb_stdout);
15748 }
15749
15750 struct breakpoint *
15751 iterate_over_breakpoints (int (*callback) (struct breakpoint *, void *),
15752                           void *data)
15753 {
15754   struct breakpoint *b, *b_tmp;
15755
15756   ALL_BREAKPOINTS_SAFE (b, b_tmp)
15757     {
15758       if ((*callback) (b, data))
15759         return b;
15760     }
15761
15762   return NULL;
15763 }
15764
15765 /* Zero if any of the breakpoint's locations could be a location where
15766    functions have been inlined, nonzero otherwise.  */
15767
15768 static int
15769 is_non_inline_function (struct breakpoint *b)
15770 {
15771   /* The shared library event breakpoint is set on the address of a
15772      non-inline function.  */
15773   if (b->type == bp_shlib_event)
15774     return 1;
15775
15776   return 0;
15777 }
15778
15779 /* Nonzero if the specified PC cannot be a location where functions
15780    have been inlined.  */
15781
15782 int
15783 pc_at_non_inline_function (struct address_space *aspace, CORE_ADDR pc,
15784                            const struct target_waitstatus *ws)
15785 {
15786   struct breakpoint *b;
15787   struct bp_location *bl;
15788
15789   ALL_BREAKPOINTS (b)
15790     {
15791       if (!is_non_inline_function (b))
15792         continue;
15793
15794       for (bl = b->loc; bl != NULL; bl = bl->next)
15795         {
15796           if (!bl->shlib_disabled
15797               && bpstat_check_location (bl, aspace, pc, ws))
15798             return 1;
15799         }
15800     }
15801
15802   return 0;
15803 }
15804
15805 /* Remove any references to OBJFILE which is going to be freed.  */
15806
15807 void
15808 breakpoint_free_objfile (struct objfile *objfile)
15809 {
15810   struct bp_location **locp, *loc;
15811
15812   ALL_BP_LOCATIONS (loc, locp)
15813     if (loc->symtab != NULL && loc->symtab->objfile == objfile)
15814       loc->symtab = NULL;
15815 }
15816
15817 void
15818 initialize_breakpoint_ops (void)
15819 {
15820   static int initialized = 0;
15821
15822   struct breakpoint_ops *ops;
15823
15824   if (initialized)
15825     return;
15826   initialized = 1;
15827
15828   /* The breakpoint_ops structure to be inherit by all kinds of
15829      breakpoints (real breakpoints, i.e., user "break" breakpoints,
15830      internal and momentary breakpoints, etc.).  */
15831   ops = &bkpt_base_breakpoint_ops;
15832   *ops = base_breakpoint_ops;
15833   ops->re_set = bkpt_re_set;
15834   ops->insert_location = bkpt_insert_location;
15835   ops->remove_location = bkpt_remove_location;
15836   ops->breakpoint_hit = bkpt_breakpoint_hit;
15837   ops->create_sals_from_address = bkpt_create_sals_from_address;
15838   ops->create_breakpoints_sal = bkpt_create_breakpoints_sal;
15839   ops->decode_linespec = bkpt_decode_linespec;
15840
15841   /* The breakpoint_ops structure to be used in regular breakpoints.  */
15842   ops = &bkpt_breakpoint_ops;
15843   *ops = bkpt_base_breakpoint_ops;
15844   ops->re_set = bkpt_re_set;
15845   ops->resources_needed = bkpt_resources_needed;
15846   ops->print_it = bkpt_print_it;
15847   ops->print_mention = bkpt_print_mention;
15848   ops->print_recreate = bkpt_print_recreate;
15849
15850   /* Ranged breakpoints.  */
15851   ops = &ranged_breakpoint_ops;
15852   *ops = bkpt_breakpoint_ops;
15853   ops->breakpoint_hit = breakpoint_hit_ranged_breakpoint;
15854   ops->resources_needed = resources_needed_ranged_breakpoint;
15855   ops->print_it = print_it_ranged_breakpoint;
15856   ops->print_one = print_one_ranged_breakpoint;
15857   ops->print_one_detail = print_one_detail_ranged_breakpoint;
15858   ops->print_mention = print_mention_ranged_breakpoint;
15859   ops->print_recreate = print_recreate_ranged_breakpoint;
15860
15861   /* Internal breakpoints.  */
15862   ops = &internal_breakpoint_ops;
15863   *ops = bkpt_base_breakpoint_ops;
15864   ops->re_set = internal_bkpt_re_set;
15865   ops->check_status = internal_bkpt_check_status;
15866   ops->print_it = internal_bkpt_print_it;
15867   ops->print_mention = internal_bkpt_print_mention;
15868
15869   /* Momentary breakpoints.  */
15870   ops = &momentary_breakpoint_ops;
15871   *ops = bkpt_base_breakpoint_ops;
15872   ops->re_set = momentary_bkpt_re_set;
15873   ops->check_status = momentary_bkpt_check_status;
15874   ops->print_it = momentary_bkpt_print_it;
15875   ops->print_mention = momentary_bkpt_print_mention;
15876
15877   /* Momentary breakpoints for bp_longjmp and bp_exception.  */
15878   ops = &longjmp_breakpoint_ops;
15879   *ops = momentary_breakpoint_ops;
15880   ops->dtor = longjmp_bkpt_dtor;
15881
15882   /* Probe breakpoints.  */
15883   ops = &bkpt_probe_breakpoint_ops;
15884   *ops = bkpt_breakpoint_ops;
15885   ops->insert_location = bkpt_probe_insert_location;
15886   ops->remove_location = bkpt_probe_remove_location;
15887   ops->create_sals_from_address = bkpt_probe_create_sals_from_address;
15888   ops->decode_linespec = bkpt_probe_decode_linespec;
15889
15890   /* GNU v3 exception catchpoints.  */
15891   ops = &gnu_v3_exception_catchpoint_ops;
15892   *ops = bkpt_breakpoint_ops;
15893   ops->print_it = print_it_exception_catchpoint;
15894   ops->print_one = print_one_exception_catchpoint;
15895   ops->print_mention = print_mention_exception_catchpoint;
15896   ops->print_recreate = print_recreate_exception_catchpoint;
15897
15898   /* Watchpoints.  */
15899   ops = &watchpoint_breakpoint_ops;
15900   *ops = base_breakpoint_ops;
15901   ops->dtor = dtor_watchpoint;
15902   ops->re_set = re_set_watchpoint;
15903   ops->insert_location = insert_watchpoint;
15904   ops->remove_location = remove_watchpoint;
15905   ops->breakpoint_hit = breakpoint_hit_watchpoint;
15906   ops->check_status = check_status_watchpoint;
15907   ops->resources_needed = resources_needed_watchpoint;
15908   ops->works_in_software_mode = works_in_software_mode_watchpoint;
15909   ops->print_it = print_it_watchpoint;
15910   ops->print_mention = print_mention_watchpoint;
15911   ops->print_recreate = print_recreate_watchpoint;
15912
15913   /* Masked watchpoints.  */
15914   ops = &masked_watchpoint_breakpoint_ops;
15915   *ops = watchpoint_breakpoint_ops;
15916   ops->insert_location = insert_masked_watchpoint;
15917   ops->remove_location = remove_masked_watchpoint;
15918   ops->resources_needed = resources_needed_masked_watchpoint;
15919   ops->works_in_software_mode = works_in_software_mode_masked_watchpoint;
15920   ops->print_it = print_it_masked_watchpoint;
15921   ops->print_one_detail = print_one_detail_masked_watchpoint;
15922   ops->print_mention = print_mention_masked_watchpoint;
15923   ops->print_recreate = print_recreate_masked_watchpoint;
15924
15925   /* Tracepoints.  */
15926   ops = &tracepoint_breakpoint_ops;
15927   *ops = base_breakpoint_ops;
15928   ops->re_set = tracepoint_re_set;
15929   ops->breakpoint_hit = tracepoint_breakpoint_hit;
15930   ops->print_one_detail = tracepoint_print_one_detail;
15931   ops->print_mention = tracepoint_print_mention;
15932   ops->print_recreate = tracepoint_print_recreate;
15933   ops->create_sals_from_address = tracepoint_create_sals_from_address;
15934   ops->create_breakpoints_sal = tracepoint_create_breakpoints_sal;
15935   ops->decode_linespec = tracepoint_decode_linespec;
15936
15937   /* Probe tracepoints.  */
15938   ops = &tracepoint_probe_breakpoint_ops;
15939   *ops = tracepoint_breakpoint_ops;
15940   ops->create_sals_from_address = tracepoint_probe_create_sals_from_address;
15941   ops->decode_linespec = tracepoint_probe_decode_linespec;
15942
15943   /* Static tracepoints with marker (`-m').  */
15944   ops = &strace_marker_breakpoint_ops;
15945   *ops = tracepoint_breakpoint_ops;
15946   ops->create_sals_from_address = strace_marker_create_sals_from_address;
15947   ops->create_breakpoints_sal = strace_marker_create_breakpoints_sal;
15948   ops->decode_linespec = strace_marker_decode_linespec;
15949
15950   /* Fork catchpoints.  */
15951   ops = &catch_fork_breakpoint_ops;
15952   *ops = base_breakpoint_ops;
15953   ops->insert_location = insert_catch_fork;
15954   ops->remove_location = remove_catch_fork;
15955   ops->breakpoint_hit = breakpoint_hit_catch_fork;
15956   ops->print_it = print_it_catch_fork;
15957   ops->print_one = print_one_catch_fork;
15958   ops->print_mention = print_mention_catch_fork;
15959   ops->print_recreate = print_recreate_catch_fork;
15960
15961   /* Vfork catchpoints.  */
15962   ops = &catch_vfork_breakpoint_ops;
15963   *ops = base_breakpoint_ops;
15964   ops->insert_location = insert_catch_vfork;
15965   ops->remove_location = remove_catch_vfork;
15966   ops->breakpoint_hit = breakpoint_hit_catch_vfork;
15967   ops->print_it = print_it_catch_vfork;
15968   ops->print_one = print_one_catch_vfork;
15969   ops->print_mention = print_mention_catch_vfork;
15970   ops->print_recreate = print_recreate_catch_vfork;
15971
15972   /* Exec catchpoints.  */
15973   ops = &catch_exec_breakpoint_ops;
15974   *ops = base_breakpoint_ops;
15975   ops->dtor = dtor_catch_exec;
15976   ops->insert_location = insert_catch_exec;
15977   ops->remove_location = remove_catch_exec;
15978   ops->breakpoint_hit = breakpoint_hit_catch_exec;
15979   ops->print_it = print_it_catch_exec;
15980   ops->print_one = print_one_catch_exec;
15981   ops->print_mention = print_mention_catch_exec;
15982   ops->print_recreate = print_recreate_catch_exec;
15983
15984   /* Syscall catchpoints.  */
15985   ops = &catch_syscall_breakpoint_ops;
15986   *ops = base_breakpoint_ops;
15987   ops->dtor = dtor_catch_syscall;
15988   ops->insert_location = insert_catch_syscall;
15989   ops->remove_location = remove_catch_syscall;
15990   ops->breakpoint_hit = breakpoint_hit_catch_syscall;
15991   ops->print_it = print_it_catch_syscall;
15992   ops->print_one = print_one_catch_syscall;
15993   ops->print_mention = print_mention_catch_syscall;
15994   ops->print_recreate = print_recreate_catch_syscall;
15995
15996   /* Solib-related catchpoints.  */
15997   ops = &catch_solib_breakpoint_ops;
15998   *ops = base_breakpoint_ops;
15999   ops->dtor = dtor_catch_solib;
16000   ops->insert_location = insert_catch_solib;
16001   ops->remove_location = remove_catch_solib;
16002   ops->breakpoint_hit = breakpoint_hit_catch_solib;
16003   ops->check_status = check_status_catch_solib;
16004   ops->print_it = print_it_catch_solib;
16005   ops->print_one = print_one_catch_solib;
16006   ops->print_mention = print_mention_catch_solib;
16007   ops->print_recreate = print_recreate_catch_solib;
16008
16009   ops = &dprintf_breakpoint_ops;
16010   *ops = bkpt_base_breakpoint_ops;
16011   ops->re_set = bkpt_re_set;
16012   ops->resources_needed = bkpt_resources_needed;
16013   ops->print_it = bkpt_print_it;
16014   ops->print_mention = bkpt_print_mention;
16015   ops->print_recreate = bkpt_print_recreate;
16016 }
16017
16018 /* Chain containing all defined "enable breakpoint" subcommands.  */
16019
16020 static struct cmd_list_element *enablebreaklist = NULL;
16021
16022 void
16023 _initialize_breakpoint (void)
16024 {
16025   struct cmd_list_element *c;
16026
16027   initialize_breakpoint_ops ();
16028
16029   observer_attach_solib_unloaded (disable_breakpoints_in_unloaded_shlib);
16030   observer_attach_inferior_exit (clear_syscall_counts);
16031   observer_attach_memory_changed (invalidate_bp_value_on_memory_change);
16032
16033   breakpoint_objfile_key
16034     = register_objfile_data_with_cleanup (NULL, free_breakpoint_probes);
16035
16036   catch_syscall_inferior_data
16037     = register_inferior_data_with_cleanup (NULL,
16038                                            catch_syscall_inferior_data_cleanup);
16039
16040   breakpoint_chain = 0;
16041   /* Don't bother to call set_breakpoint_count.  $bpnum isn't useful
16042      before a breakpoint is set.  */
16043   breakpoint_count = 0;
16044
16045   tracepoint_count = 0;
16046
16047   add_com ("ignore", class_breakpoint, ignore_command, _("\
16048 Set ignore-count of breakpoint number N to COUNT.\n\
16049 Usage is `ignore N COUNT'."));
16050   if (xdb_commands)
16051     add_com_alias ("bc", "ignore", class_breakpoint, 1);
16052
16053   add_com ("commands", class_breakpoint, commands_command, _("\
16054 Set commands to be executed when a breakpoint is hit.\n\
16055 Give breakpoint number as argument after \"commands\".\n\
16056 With no argument, the targeted breakpoint is the last one set.\n\
16057 The commands themselves follow starting on the next line.\n\
16058 Type a line containing \"end\" to indicate the end of them.\n\
16059 Give \"silent\" as the first line to make the breakpoint silent;\n\
16060 then no output is printed when it is hit, except what the commands print."));
16061
16062   c = add_com ("condition", class_breakpoint, condition_command, _("\
16063 Specify breakpoint number N to break only if COND is true.\n\
16064 Usage is `condition N COND', where N is an integer and COND is an\n\
16065 expression to be evaluated whenever breakpoint N is reached."));
16066   set_cmd_completer (c, condition_completer);
16067
16068   c = add_com ("tbreak", class_breakpoint, tbreak_command, _("\
16069 Set a temporary breakpoint.\n\
16070 Like \"break\" except the breakpoint is only temporary,\n\
16071 so it will be deleted when hit.  Equivalent to \"break\" followed\n\
16072 by using \"enable delete\" on the breakpoint number.\n\
16073 \n"
16074 BREAK_ARGS_HELP ("tbreak")));
16075   set_cmd_completer (c, location_completer);
16076
16077   c = add_com ("hbreak", class_breakpoint, hbreak_command, _("\
16078 Set a hardware assisted breakpoint.\n\
16079 Like \"break\" except the breakpoint requires hardware support,\n\
16080 some target hardware may not have this support.\n\
16081 \n"
16082 BREAK_ARGS_HELP ("hbreak")));
16083   set_cmd_completer (c, location_completer);
16084
16085   c = add_com ("thbreak", class_breakpoint, thbreak_command, _("\
16086 Set a temporary hardware assisted breakpoint.\n\
16087 Like \"hbreak\" except the breakpoint is only temporary,\n\
16088 so it will be deleted when hit.\n\
16089 \n"
16090 BREAK_ARGS_HELP ("thbreak")));
16091   set_cmd_completer (c, location_completer);
16092
16093   add_prefix_cmd ("enable", class_breakpoint, enable_command, _("\
16094 Enable some breakpoints.\n\
16095 Give breakpoint numbers (separated by spaces) as arguments.\n\
16096 With no subcommand, breakpoints are enabled until you command otherwise.\n\
16097 This is used to cancel the effect of the \"disable\" command.\n\
16098 With a subcommand you can enable temporarily."),
16099                   &enablelist, "enable ", 1, &cmdlist);
16100   if (xdb_commands)
16101     add_com ("ab", class_breakpoint, enable_command, _("\
16102 Enable some breakpoints.\n\
16103 Give breakpoint numbers (separated by spaces) as arguments.\n\
16104 With no subcommand, breakpoints are enabled until you command otherwise.\n\
16105 This is used to cancel the effect of the \"disable\" command.\n\
16106 With a subcommand you can enable temporarily."));
16107
16108   add_com_alias ("en", "enable", class_breakpoint, 1);
16109
16110   add_prefix_cmd ("breakpoints", class_breakpoint, enable_command, _("\
16111 Enable some breakpoints.\n\
16112 Give breakpoint numbers (separated by spaces) as arguments.\n\
16113 This is used to cancel the effect of the \"disable\" command.\n\
16114 May be abbreviated to simply \"enable\".\n"),
16115                    &enablebreaklist, "enable breakpoints ", 1, &enablelist);
16116
16117   add_cmd ("once", no_class, enable_once_command, _("\
16118 Enable breakpoints for one hit.  Give breakpoint numbers.\n\
16119 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
16120            &enablebreaklist);
16121
16122   add_cmd ("delete", no_class, enable_delete_command, _("\
16123 Enable breakpoints and delete when hit.  Give breakpoint numbers.\n\
16124 If a breakpoint is hit while enabled in this fashion, it is deleted."),
16125            &enablebreaklist);
16126
16127   add_cmd ("count", no_class, enable_count_command, _("\
16128 Enable breakpoints for COUNT hits.  Give count and then breakpoint numbers.\n\
16129 If a breakpoint is hit while enabled in this fashion,\n\
16130 the count is decremented; when it reaches zero, the breakpoint is disabled."),
16131            &enablebreaklist);
16132
16133   add_cmd ("delete", no_class, enable_delete_command, _("\
16134 Enable breakpoints and delete when hit.  Give breakpoint numbers.\n\
16135 If a breakpoint is hit while enabled in this fashion, it is deleted."),
16136            &enablelist);
16137
16138   add_cmd ("once", no_class, enable_once_command, _("\
16139 Enable breakpoints for one hit.  Give breakpoint numbers.\n\
16140 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
16141            &enablelist);
16142
16143   add_cmd ("count", no_class, enable_count_command, _("\
16144 Enable breakpoints for COUNT hits.  Give count and then breakpoint numbers.\n\
16145 If a breakpoint is hit while enabled in this fashion,\n\
16146 the count is decremented; when it reaches zero, the breakpoint is disabled."),
16147            &enablelist);
16148
16149   add_prefix_cmd ("disable", class_breakpoint, disable_command, _("\
16150 Disable some breakpoints.\n\
16151 Arguments are breakpoint numbers with spaces in between.\n\
16152 To disable all breakpoints, give no argument.\n\
16153 A disabled breakpoint is not forgotten, but has no effect until re-enabled."),
16154                   &disablelist, "disable ", 1, &cmdlist);
16155   add_com_alias ("dis", "disable", class_breakpoint, 1);
16156   add_com_alias ("disa", "disable", class_breakpoint, 1);
16157   if (xdb_commands)
16158     add_com ("sb", class_breakpoint, disable_command, _("\
16159 Disable some breakpoints.\n\
16160 Arguments are breakpoint numbers with spaces in between.\n\
16161 To disable all breakpoints, give no argument.\n\
16162 A disabled breakpoint is not forgotten, but has no effect until re-enabled."));
16163
16164   add_cmd ("breakpoints", class_alias, disable_command, _("\
16165 Disable some breakpoints.\n\
16166 Arguments are breakpoint numbers with spaces in between.\n\
16167 To disable all breakpoints, give no argument.\n\
16168 A disabled breakpoint is not forgotten, but has no effect until re-enabled.\n\
16169 This command may be abbreviated \"disable\"."),
16170            &disablelist);
16171
16172   add_prefix_cmd ("delete", class_breakpoint, delete_command, _("\
16173 Delete some breakpoints or auto-display expressions.\n\
16174 Arguments are breakpoint numbers with spaces in between.\n\
16175 To delete all breakpoints, give no argument.\n\
16176 \n\
16177 Also a prefix command for deletion of other GDB objects.\n\
16178 The \"unset\" command is also an alias for \"delete\"."),
16179                   &deletelist, "delete ", 1, &cmdlist);
16180   add_com_alias ("d", "delete", class_breakpoint, 1);
16181   add_com_alias ("del", "delete", class_breakpoint, 1);
16182   if (xdb_commands)
16183     add_com ("db", class_breakpoint, delete_command, _("\
16184 Delete some breakpoints.\n\
16185 Arguments are breakpoint numbers with spaces in between.\n\
16186 To delete all breakpoints, give no argument.\n"));
16187
16188   add_cmd ("breakpoints", class_alias, delete_command, _("\
16189 Delete some breakpoints or auto-display expressions.\n\
16190 Arguments are breakpoint numbers with spaces in between.\n\
16191 To delete all breakpoints, give no argument.\n\
16192 This command may be abbreviated \"delete\"."),
16193            &deletelist);
16194
16195   add_com ("clear", class_breakpoint, clear_command, _("\
16196 Clear breakpoint at specified line or function.\n\
16197 Argument may be line number, function name, or \"*\" and an address.\n\
16198 If line number is specified, all breakpoints in that line are cleared.\n\
16199 If function is specified, breakpoints at beginning of function are cleared.\n\
16200 If an address is specified, breakpoints at that address are cleared.\n\
16201 \n\
16202 With no argument, clears all breakpoints in the line that the selected frame\n\
16203 is executing in.\n\
16204 \n\
16205 See also the \"delete\" command which clears breakpoints by number."));
16206   add_com_alias ("cl", "clear", class_breakpoint, 1);
16207
16208   c = add_com ("break", class_breakpoint, break_command, _("\
16209 Set breakpoint at specified line or function.\n"
16210 BREAK_ARGS_HELP ("break")));
16211   set_cmd_completer (c, location_completer);
16212
16213   add_com_alias ("b", "break", class_run, 1);
16214   add_com_alias ("br", "break", class_run, 1);
16215   add_com_alias ("bre", "break", class_run, 1);
16216   add_com_alias ("brea", "break", class_run, 1);
16217
16218   if (xdb_commands)
16219    add_com_alias ("ba", "break", class_breakpoint, 1);
16220
16221   if (dbx_commands)
16222     {
16223       add_abbrev_prefix_cmd ("stop", class_breakpoint, stop_command, _("\
16224 Break in function/address or break at a line in the current file."),
16225                              &stoplist, "stop ", 1, &cmdlist);
16226       add_cmd ("in", class_breakpoint, stopin_command,
16227                _("Break in function or address."), &stoplist);
16228       add_cmd ("at", class_breakpoint, stopat_command,
16229                _("Break at a line in the current file."), &stoplist);
16230       add_com ("status", class_info, breakpoints_info, _("\
16231 Status of user-settable breakpoints, or breakpoint number NUMBER.\n\
16232 The \"Type\" column indicates one of:\n\
16233 \tbreakpoint     - normal breakpoint\n\
16234 \twatchpoint     - watchpoint\n\
16235 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
16236 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
16237 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
16238 address and file/line number respectively.\n\
16239 \n\
16240 Convenience variable \"$_\" and default examine address for \"x\"\n\
16241 are set to the address of the last breakpoint listed unless the command\n\
16242 is prefixed with \"server \".\n\n\
16243 Convenience variable \"$bpnum\" contains the number of the last\n\
16244 breakpoint set."));
16245     }
16246
16247   add_info ("breakpoints", breakpoints_info, _("\
16248 Status of specified breakpoints (all user-settable breakpoints if no argument).\n\
16249 The \"Type\" column indicates one of:\n\
16250 \tbreakpoint     - normal breakpoint\n\
16251 \twatchpoint     - watchpoint\n\
16252 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
16253 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
16254 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
16255 address and file/line number respectively.\n\
16256 \n\
16257 Convenience variable \"$_\" and default examine address for \"x\"\n\
16258 are set to the address of the last breakpoint listed unless the command\n\
16259 is prefixed with \"server \".\n\n\
16260 Convenience variable \"$bpnum\" contains the number of the last\n\
16261 breakpoint set."));
16262
16263   add_info_alias ("b", "breakpoints", 1);
16264
16265   if (xdb_commands)
16266     add_com ("lb", class_breakpoint, breakpoints_info, _("\
16267 Status of user-settable breakpoints, or breakpoint number NUMBER.\n\
16268 The \"Type\" column indicates one of:\n\
16269 \tbreakpoint     - normal breakpoint\n\
16270 \twatchpoint     - watchpoint\n\
16271 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
16272 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
16273 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
16274 address and file/line number respectively.\n\
16275 \n\
16276 Convenience variable \"$_\" and default examine address for \"x\"\n\
16277 are set to the address of the last breakpoint listed unless the command\n\
16278 is prefixed with \"server \".\n\n\
16279 Convenience variable \"$bpnum\" contains the number of the last\n\
16280 breakpoint set."));
16281
16282   add_cmd ("breakpoints", class_maintenance, maintenance_info_breakpoints, _("\
16283 Status of all breakpoints, or breakpoint number NUMBER.\n\
16284 The \"Type\" column indicates one of:\n\
16285 \tbreakpoint     - normal breakpoint\n\
16286 \twatchpoint     - watchpoint\n\
16287 \tlongjmp        - internal breakpoint used to step through longjmp()\n\
16288 \tlongjmp resume - internal breakpoint at the target of longjmp()\n\
16289 \tuntil          - internal breakpoint used by the \"until\" command\n\
16290 \tfinish         - internal breakpoint used by the \"finish\" command\n\
16291 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
16292 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
16293 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
16294 address and file/line number respectively.\n\
16295 \n\
16296 Convenience variable \"$_\" and default examine address for \"x\"\n\
16297 are set to the address of the last breakpoint listed unless the command\n\
16298 is prefixed with \"server \".\n\n\
16299 Convenience variable \"$bpnum\" contains the number of the last\n\
16300 breakpoint set."),
16301            &maintenanceinfolist);
16302
16303   add_prefix_cmd ("catch", class_breakpoint, catch_command, _("\
16304 Set catchpoints to catch events."),
16305                   &catch_cmdlist, "catch ",
16306                   0/*allow-unknown*/, &cmdlist);
16307
16308   add_prefix_cmd ("tcatch", class_breakpoint, tcatch_command, _("\
16309 Set temporary catchpoints to catch events."),
16310                   &tcatch_cmdlist, "tcatch ",
16311                   0/*allow-unknown*/, &cmdlist);
16312
16313   /* Add catch and tcatch sub-commands.  */
16314   add_catch_command ("catch", _("\
16315 Catch an exception, when caught."),
16316                      catch_catch_command,
16317                      NULL,
16318                      CATCH_PERMANENT,
16319                      CATCH_TEMPORARY);
16320   add_catch_command ("throw", _("\
16321 Catch an exception, when thrown."),
16322                      catch_throw_command,
16323                      NULL,
16324                      CATCH_PERMANENT,
16325                      CATCH_TEMPORARY);
16326   add_catch_command ("fork", _("Catch calls to fork."),
16327                      catch_fork_command_1,
16328                      NULL,
16329                      (void *) (uintptr_t) catch_fork_permanent,
16330                      (void *) (uintptr_t) catch_fork_temporary);
16331   add_catch_command ("vfork", _("Catch calls to vfork."),
16332                      catch_fork_command_1,
16333                      NULL,
16334                      (void *) (uintptr_t) catch_vfork_permanent,
16335                      (void *) (uintptr_t) catch_vfork_temporary);
16336   add_catch_command ("exec", _("Catch calls to exec."),
16337                      catch_exec_command_1,
16338                      NULL,
16339                      CATCH_PERMANENT,
16340                      CATCH_TEMPORARY);
16341   add_catch_command ("load", _("Catch loads of shared libraries.\n\
16342 Usage: catch load [REGEX]\n\
16343 If REGEX is given, only stop for libraries matching the regular expression."),
16344                      catch_load_command_1,
16345                      NULL,
16346                      CATCH_PERMANENT,
16347                      CATCH_TEMPORARY);
16348   add_catch_command ("unload", _("Catch unloads of shared libraries.\n\
16349 Usage: catch unload [REGEX]\n\
16350 If REGEX is given, only stop for libraries matching the regular expression."),
16351                      catch_unload_command_1,
16352                      NULL,
16353                      CATCH_PERMANENT,
16354                      CATCH_TEMPORARY);
16355   add_catch_command ("syscall", _("\
16356 Catch system calls by their names and/or numbers.\n\
16357 Arguments say which system calls to catch.  If no arguments\n\
16358 are given, every system call will be caught.\n\
16359 Arguments, if given, should be one or more system call names\n\
16360 (if your system supports that), or system call numbers."),
16361                      catch_syscall_command_1,
16362                      catch_syscall_completer,
16363                      CATCH_PERMANENT,
16364                      CATCH_TEMPORARY);
16365
16366   c = add_com ("watch", class_breakpoint, watch_command, _("\
16367 Set a watchpoint for an expression.\n\
16368 Usage: watch [-l|-location] EXPRESSION\n\
16369 A watchpoint stops execution of your program whenever the value of\n\
16370 an expression changes.\n\
16371 If -l or -location is given, this evaluates EXPRESSION and watches\n\
16372 the memory to which it refers."));
16373   set_cmd_completer (c, expression_completer);
16374
16375   c = add_com ("rwatch", class_breakpoint, rwatch_command, _("\
16376 Set a read watchpoint for an expression.\n\
16377 Usage: rwatch [-l|-location] EXPRESSION\n\
16378 A watchpoint stops execution of your program whenever the value of\n\
16379 an expression is read.\n\
16380 If -l or -location is given, this evaluates EXPRESSION and watches\n\
16381 the memory to which it refers."));
16382   set_cmd_completer (c, expression_completer);
16383
16384   c = add_com ("awatch", class_breakpoint, awatch_command, _("\
16385 Set a watchpoint for an expression.\n\
16386 Usage: awatch [-l|-location] EXPRESSION\n\
16387 A watchpoint stops execution of your program whenever the value of\n\
16388 an expression is either read or written.\n\
16389 If -l or -location is given, this evaluates EXPRESSION and watches\n\
16390 the memory to which it refers."));
16391   set_cmd_completer (c, expression_completer);
16392
16393   add_info ("watchpoints", watchpoints_info, _("\
16394 Status of specified watchpoints (all watchpoints if no argument)."));
16395
16396   /* XXX: cagney/2005-02-23: This should be a boolean, and should
16397      respond to changes - contrary to the description.  */
16398   add_setshow_zinteger_cmd ("can-use-hw-watchpoints", class_support,
16399                             &can_use_hw_watchpoints, _("\
16400 Set debugger's willingness to use watchpoint hardware."), _("\
16401 Show debugger's willingness to use watchpoint hardware."), _("\
16402 If zero, gdb will not use hardware for new watchpoints, even if\n\
16403 such is available.  (However, any hardware watchpoints that were\n\
16404 created before setting this to nonzero, will continue to use watchpoint\n\
16405 hardware.)"),
16406                             NULL,
16407                             show_can_use_hw_watchpoints,
16408                             &setlist, &showlist);
16409
16410   can_use_hw_watchpoints = 1;
16411
16412   /* Tracepoint manipulation commands.  */
16413
16414   c = add_com ("trace", class_breakpoint, trace_command, _("\
16415 Set a tracepoint at specified line or function.\n\
16416 \n"
16417 BREAK_ARGS_HELP ("trace") "\n\
16418 Do \"help tracepoints\" for info on other tracepoint commands."));
16419   set_cmd_completer (c, location_completer);
16420
16421   add_com_alias ("tp", "trace", class_alias, 0);
16422   add_com_alias ("tr", "trace", class_alias, 1);
16423   add_com_alias ("tra", "trace", class_alias, 1);
16424   add_com_alias ("trac", "trace", class_alias, 1);
16425
16426   c = add_com ("ftrace", class_breakpoint, ftrace_command, _("\
16427 Set a fast tracepoint at specified line or function.\n\
16428 \n"
16429 BREAK_ARGS_HELP ("ftrace") "\n\
16430 Do \"help tracepoints\" for info on other tracepoint commands."));
16431   set_cmd_completer (c, location_completer);
16432
16433   c = add_com ("strace", class_breakpoint, strace_command, _("\
16434 Set a static tracepoint at specified line, function or marker.\n\
16435 \n\
16436 strace [LOCATION] [if CONDITION]\n\
16437 LOCATION may be a line number, function name, \"*\" and an address,\n\
16438 or -m MARKER_ID.\n\
16439 If a line number is specified, probe the marker at start of code\n\
16440 for that line.  If a function is specified, probe the marker at start\n\
16441 of code for that function.  If an address is specified, probe the marker\n\
16442 at that exact address.  If a marker id is specified, probe the marker\n\
16443 with that name.  With no LOCATION, uses current execution address of\n\
16444 the selected stack frame.\n\
16445 Static tracepoints accept an extra collect action -- ``collect $_sdata''.\n\
16446 This collects arbitrary user data passed in the probe point call to the\n\
16447 tracing library.  You can inspect it when analyzing the trace buffer,\n\
16448 by printing the $_sdata variable like any other convenience variable.\n\
16449 \n\
16450 CONDITION is a boolean expression.\n\
16451 \n\
16452 Multiple tracepoints at one place are permitted, and useful if their\n\
16453 conditions are different.\n\
16454 \n\
16455 Do \"help breakpoints\" for info on other commands dealing with breakpoints.\n\
16456 Do \"help tracepoints\" for info on other tracepoint commands."));
16457   set_cmd_completer (c, location_completer);
16458
16459   add_info ("tracepoints", tracepoints_info, _("\
16460 Status of specified tracepoints (all tracepoints if no argument).\n\
16461 Convenience variable \"$tpnum\" contains the number of the\n\
16462 last tracepoint set."));
16463
16464   add_info_alias ("tp", "tracepoints", 1);
16465
16466   add_cmd ("tracepoints", class_trace, delete_trace_command, _("\
16467 Delete specified tracepoints.\n\
16468 Arguments are tracepoint numbers, separated by spaces.\n\
16469 No argument means delete all tracepoints."),
16470            &deletelist);
16471   add_alias_cmd ("tr", "tracepoints", class_trace, 1, &deletelist);
16472
16473   c = add_cmd ("tracepoints", class_trace, disable_trace_command, _("\
16474 Disable specified tracepoints.\n\
16475 Arguments are tracepoint numbers, separated by spaces.\n\
16476 No argument means disable all tracepoints."),
16477            &disablelist);
16478   deprecate_cmd (c, "disable");
16479
16480   c = add_cmd ("tracepoints", class_trace, enable_trace_command, _("\
16481 Enable specified tracepoints.\n\
16482 Arguments are tracepoint numbers, separated by spaces.\n\
16483 No argument means enable all tracepoints."),
16484            &enablelist);
16485   deprecate_cmd (c, "enable");
16486
16487   add_com ("passcount", class_trace, trace_pass_command, _("\
16488 Set the passcount for a tracepoint.\n\
16489 The trace will end when the tracepoint has been passed 'count' times.\n\
16490 Usage: passcount COUNT TPNUM, where TPNUM may also be \"all\";\n\
16491 if TPNUM is omitted, passcount refers to the last tracepoint defined."));
16492
16493   add_prefix_cmd ("save", class_breakpoint, save_command,
16494                   _("Save breakpoint definitions as a script."),
16495                   &save_cmdlist, "save ",
16496                   0/*allow-unknown*/, &cmdlist);
16497
16498   c = add_cmd ("breakpoints", class_breakpoint, save_breakpoints_command, _("\
16499 Save current breakpoint definitions as a script.\n\
16500 This includes all types of breakpoints (breakpoints, watchpoints,\n\
16501 catchpoints, tracepoints).  Use the 'source' command in another debug\n\
16502 session to restore them."),
16503                &save_cmdlist);
16504   set_cmd_completer (c, filename_completer);
16505
16506   c = add_cmd ("tracepoints", class_trace, save_tracepoints_command, _("\
16507 Save current tracepoint definitions as a script.\n\
16508 Use the 'source' command in another debug session to restore them."),
16509                &save_cmdlist);
16510   set_cmd_completer (c, filename_completer);
16511
16512   c = add_com_alias ("save-tracepoints", "save tracepoints", class_trace, 0);
16513   deprecate_cmd (c, "save tracepoints");
16514
16515   add_prefix_cmd ("breakpoint", class_maintenance, set_breakpoint_cmd, _("\
16516 Breakpoint specific settings\n\
16517 Configure various breakpoint-specific variables such as\n\
16518 pending breakpoint behavior"),
16519                   &breakpoint_set_cmdlist, "set breakpoint ",
16520                   0/*allow-unknown*/, &setlist);
16521   add_prefix_cmd ("breakpoint", class_maintenance, show_breakpoint_cmd, _("\
16522 Breakpoint specific settings\n\
16523 Configure various breakpoint-specific variables such as\n\
16524 pending breakpoint behavior"),
16525                   &breakpoint_show_cmdlist, "show breakpoint ",
16526                   0/*allow-unknown*/, &showlist);
16527
16528   add_setshow_auto_boolean_cmd ("pending", no_class,
16529                                 &pending_break_support, _("\
16530 Set debugger's behavior regarding pending breakpoints."), _("\
16531 Show debugger's behavior regarding pending breakpoints."), _("\
16532 If on, an unrecognized breakpoint location will cause gdb to create a\n\
16533 pending breakpoint.  If off, an unrecognized breakpoint location results in\n\
16534 an error.  If auto, an unrecognized breakpoint location results in a\n\
16535 user-query to see if a pending breakpoint should be created."),
16536                                 NULL,
16537                                 show_pending_break_support,
16538                                 &breakpoint_set_cmdlist,
16539                                 &breakpoint_show_cmdlist);
16540
16541   pending_break_support = AUTO_BOOLEAN_AUTO;
16542
16543   add_setshow_boolean_cmd ("auto-hw", no_class,
16544                            &automatic_hardware_breakpoints, _("\
16545 Set automatic usage of hardware breakpoints."), _("\
16546 Show automatic usage of hardware breakpoints."), _("\
16547 If set, the debugger will automatically use hardware breakpoints for\n\
16548 breakpoints set with \"break\" but falling in read-only memory.  If not set,\n\
16549 a warning will be emitted for such breakpoints."),
16550                            NULL,
16551                            show_automatic_hardware_breakpoints,
16552                            &breakpoint_set_cmdlist,
16553                            &breakpoint_show_cmdlist);
16554
16555   add_setshow_auto_boolean_cmd ("always-inserted", class_support,
16556                                 &always_inserted_mode, _("\
16557 Set mode for inserting breakpoints."), _("\
16558 Show mode for inserting breakpoints."), _("\
16559 When this mode is off, breakpoints are inserted in inferior when it is\n\
16560 resumed, and removed when execution stops.  When this mode is on,\n\
16561 breakpoints are inserted immediately and removed only when the user\n\
16562 deletes the breakpoint.  When this mode is auto (which is the default),\n\
16563 the behaviour depends on the non-stop setting (see help set non-stop).\n\
16564 In this case, if gdb is controlling the inferior in non-stop mode, gdb\n\
16565 behaves as if always-inserted mode is on; if gdb is controlling the\n\
16566 inferior in all-stop mode, gdb behaves as if always-inserted mode is off."),
16567                                 NULL,
16568                                 &show_always_inserted_mode,
16569                                 &breakpoint_set_cmdlist,
16570                                 &breakpoint_show_cmdlist);
16571
16572   add_setshow_enum_cmd ("condition-evaluation", class_breakpoint,
16573                         condition_evaluation_enums,
16574                         &condition_evaluation_mode_1, _("\
16575 Set mode of breakpoint condition evaluation."), _("\
16576 Show mode of breakpoint condition evaluation."), _("\
16577 When this is set to \"host\", breakpoint conditions will be\n\
16578 evaluated on the host's side by GDB.  When it is set to \"target\",\n\
16579 breakpoint conditions will be downloaded to the target (if the target\n\
16580 supports such feature) and conditions will be evaluated on the target's side.\n\
16581 If this is set to \"auto\" (default), this will be automatically set to\n\
16582 \"target\" if it supports condition evaluation, otherwise it will\n\
16583 be set to \"gdb\""),
16584                            &set_condition_evaluation_mode,
16585                            &show_condition_evaluation_mode,
16586                            &breakpoint_set_cmdlist,
16587                            &breakpoint_show_cmdlist);
16588
16589   add_com ("break-range", class_breakpoint, break_range_command, _("\
16590 Set a breakpoint for an address range.\n\
16591 break-range START-LOCATION, END-LOCATION\n\
16592 where START-LOCATION and END-LOCATION can be one of the following:\n\
16593   LINENUM, for that line in the current file,\n\
16594   FILE:LINENUM, for that line in that file,\n\
16595   +OFFSET, for that number of lines after the current line\n\
16596            or the start of the range\n\
16597   FUNCTION, for the first line in that function,\n\
16598   FILE:FUNCTION, to distinguish among like-named static functions.\n\
16599   *ADDRESS, for the instruction at that address.\n\
16600 \n\
16601 The breakpoint will stop execution of the inferior whenever it executes\n\
16602 an instruction at any address within the [START-LOCATION, END-LOCATION]\n\
16603 range (including START-LOCATION and END-LOCATION)."));
16604
16605   c = add_com ("dprintf", class_breakpoint, dprintf_command, _("\
16606 Set a dynamic printf at specified line or function.\n\
16607 dprintf location,format string,arg1,arg2,...\n\
16608 location may be a line number, function name, or \"*\" and an address.\n\
16609 If a line number is specified, break at start of code for that line.\n\
16610 If a function is specified, break at start of code for that function.\n\
16611 "));
16612   set_cmd_completer (c, location_completer);
16613
16614   add_setshow_enum_cmd ("dprintf-style", class_support,
16615                         dprintf_style_enums, &dprintf_style, _("\
16616 Set the style of usage for dynamic printf."), _("\
16617 Show the style of usage for dynamic printf."), _("\
16618 This setting chooses how GDB will do a dynamic printf.\n\
16619 If the value is \"gdb\", then the printing is done by GDB to its own\n\
16620 console, as with the \"printf\" command.\n\
16621 If the value is \"call\", the print is done by calling a function in your\n\
16622 program; by default printf(), but you can choose a different function or\n\
16623 output stream by setting dprintf-function and dprintf-channel."),
16624                         update_dprintf_commands, NULL,
16625                         &setlist, &showlist);
16626
16627   dprintf_function = xstrdup ("printf");
16628   add_setshow_string_cmd ("dprintf-function", class_support,
16629                           &dprintf_function, _("\
16630 Set the function to use for dynamic printf"), _("\
16631 Show the function to use for dynamic printf"), NULL,
16632                           update_dprintf_commands, NULL,
16633                           &setlist, &showlist);
16634
16635   dprintf_channel = xstrdup ("");
16636   add_setshow_string_cmd ("dprintf-channel", class_support,
16637                           &dprintf_channel, _("\
16638 Set the channel to use for dynamic printf"), _("\
16639 Show the channel to use for dynamic printf"), NULL,
16640                           update_dprintf_commands, NULL,
16641                           &setlist, &showlist);
16642
16643   add_setshow_boolean_cmd ("disconnected-dprintf", no_class,
16644                            &disconnected_dprintf, _("\
16645 Set whether dprintf continues after GDB disconnects."), _("\
16646 Show whether dprintf continues after GDB disconnects."), _("\
16647 Use this to let dprintf commands continue to hit and produce output\n\
16648 even if GDB disconnects or detaches from the target."),
16649                            NULL,
16650                            NULL,
16651                            &setlist, &showlist);
16652
16653   add_com ("agent-printf", class_vars, agent_printf_command, _("\
16654 agent-printf \"printf format string\", arg1, arg2, arg3, ..., argn\n\
16655 (target agent only) This is useful for formatted output in user-defined commands."));
16656
16657   automatic_hardware_breakpoints = 1;
16658
16659   observer_attach_about_to_proceed (breakpoint_about_to_proceed);
16660 }