* minsyms.h (struct bound_minimal_symbol): New.
[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_ARG parameter.  If
9514    non-zero, the function will parse ARG, extracting location,
9515    condition, thread and extra string.  Otherwise, ARG is just the
9516    breakpoint's location, with condition, thread, and extra string
9517    specified by the COND_STRING, THREAD and EXTRA_STRING parameters.
9518    If INTERNAL is non-zero, the breakpoint number will be allocated
9519    from the internal breakpoint count.  Returns true if any breakpoint
9520    was created; 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_arg,
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_arg)
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             if (*arg != '\0')
9664               error (_("Garbage '%s' at end of location"), arg);
9665
9666             /* Create a private copy of condition string.  */
9667             if (cond_string)
9668             {
9669                 cond_string = xstrdup (cond_string);
9670                 make_cleanup (xfree, cond_string);
9671             }
9672             /* Create a private copy of any extra string.  */
9673             if (extra_string)
9674               {
9675                 extra_string = xstrdup (extra_string);
9676                 make_cleanup (xfree, extra_string);
9677               }
9678         }
9679
9680       ops->create_breakpoints_sal (gdbarch, &canonical, lsal,
9681                                    cond_string, extra_string, type_wanted,
9682                                    tempflag ? disp_del : disp_donttouch,
9683                                    thread, task, ignore_count, ops,
9684                                    from_tty, enabled, internal, flags);
9685     }
9686   else
9687     {
9688       struct breakpoint *b;
9689
9690       make_cleanup (xfree, copy_arg);
9691
9692       if (is_tracepoint_type (type_wanted))
9693         {
9694           struct tracepoint *t;
9695
9696           t = XCNEW (struct tracepoint);
9697           b = &t->base;
9698         }
9699       else
9700         b = XNEW (struct breakpoint);
9701
9702       init_raw_breakpoint_without_location (b, gdbarch, type_wanted, ops);
9703
9704       b->addr_string = copy_arg;
9705       if (parse_arg)
9706         b->cond_string = NULL;
9707       else
9708         {
9709           /* Create a private copy of condition string.  */
9710           if (cond_string)
9711             {
9712               cond_string = xstrdup (cond_string);
9713               make_cleanup (xfree, cond_string);
9714             }
9715           b->cond_string = cond_string;
9716         }
9717       b->extra_string = NULL;
9718       b->ignore_count = ignore_count;
9719       b->disposition = tempflag ? disp_del : disp_donttouch;
9720       b->condition_not_parsed = 1;
9721       b->enable_state = enabled ? bp_enabled : bp_disabled;
9722       if ((type_wanted != bp_breakpoint
9723            && type_wanted != bp_hardware_breakpoint) || thread != -1)
9724         b->pspace = current_program_space;
9725
9726       install_breakpoint (internal, b, 0);
9727     }
9728   
9729   if (VEC_length (linespec_sals, canonical.sals) > 1)
9730     {
9731       warning (_("Multiple breakpoints were set.\nUse the "
9732                  "\"delete\" command to delete unwanted breakpoints."));
9733       prev_breakpoint_count = prev_bkpt_count;
9734     }
9735
9736   /* That's it.  Discard the cleanups for data inserted into the
9737      breakpoint.  */
9738   discard_cleanups (bkpt_chain);
9739   /* But cleanup everything else.  */
9740   do_cleanups (old_chain);
9741
9742   /* error call may happen here - have BKPT_CHAIN already discarded.  */
9743   update_global_location_list (1);
9744
9745   return 1;
9746 }
9747
9748 /* Set a breakpoint.
9749    ARG is a string describing breakpoint address,
9750    condition, and thread.
9751    FLAG specifies if a breakpoint is hardware on,
9752    and if breakpoint is temporary, using BP_HARDWARE_FLAG
9753    and BP_TEMPFLAG.  */
9754
9755 static void
9756 break_command_1 (char *arg, int flag, int from_tty)
9757 {
9758   int tempflag = flag & BP_TEMPFLAG;
9759   enum bptype type_wanted = (flag & BP_HARDWAREFLAG
9760                              ? bp_hardware_breakpoint
9761                              : bp_breakpoint);
9762   struct breakpoint_ops *ops;
9763   const char *arg_cp = arg;
9764
9765   /* Matching breakpoints on probes.  */
9766   if (arg && probe_linespec_to_ops (&arg_cp) != NULL)
9767     ops = &bkpt_probe_breakpoint_ops;
9768   else
9769     ops = &bkpt_breakpoint_ops;
9770
9771   create_breakpoint (get_current_arch (),
9772                      arg,
9773                      NULL, 0, NULL, 1 /* parse arg */,
9774                      tempflag, type_wanted,
9775                      0 /* Ignore count */,
9776                      pending_break_support,
9777                      ops,
9778                      from_tty,
9779                      1 /* enabled */,
9780                      0 /* internal */,
9781                      0);
9782 }
9783
9784 /* Helper function for break_command_1 and disassemble_command.  */
9785
9786 void
9787 resolve_sal_pc (struct symtab_and_line *sal)
9788 {
9789   CORE_ADDR pc;
9790
9791   if (sal->pc == 0 && sal->symtab != NULL)
9792     {
9793       if (!find_line_pc (sal->symtab, sal->line, &pc))
9794         error (_("No line %d in file \"%s\"."),
9795                sal->line, symtab_to_filename_for_display (sal->symtab));
9796       sal->pc = pc;
9797
9798       /* If this SAL corresponds to a breakpoint inserted using a line
9799          number, then skip the function prologue if necessary.  */
9800       if (sal->explicit_line)
9801         skip_prologue_sal (sal);
9802     }
9803
9804   if (sal->section == 0 && sal->symtab != NULL)
9805     {
9806       struct blockvector *bv;
9807       struct block *b;
9808       struct symbol *sym;
9809
9810       bv = blockvector_for_pc_sect (sal->pc, 0, &b, sal->symtab);
9811       if (bv != NULL)
9812         {
9813           sym = block_linkage_function (b);
9814           if (sym != NULL)
9815             {
9816               fixup_symbol_section (sym, sal->symtab->objfile);
9817               sal->section = SYMBOL_OBJ_SECTION (sym);
9818             }
9819           else
9820             {
9821               /* It really is worthwhile to have the section, so we'll
9822                  just have to look harder. This case can be executed
9823                  if we have line numbers but no functions (as can
9824                  happen in assembly source).  */
9825
9826               struct bound_minimal_symbol msym;
9827               struct cleanup *old_chain = save_current_space_and_thread ();
9828
9829               switch_to_program_space_and_thread (sal->pspace);
9830
9831               msym = lookup_minimal_symbol_by_pc (sal->pc);
9832               if (msym.minsym)
9833                 sal->section = SYMBOL_OBJ_SECTION (msym.minsym);
9834
9835               do_cleanups (old_chain);
9836             }
9837         }
9838     }
9839 }
9840
9841 void
9842 break_command (char *arg, int from_tty)
9843 {
9844   break_command_1 (arg, 0, from_tty);
9845 }
9846
9847 void
9848 tbreak_command (char *arg, int from_tty)
9849 {
9850   break_command_1 (arg, BP_TEMPFLAG, from_tty);
9851 }
9852
9853 static void
9854 hbreak_command (char *arg, int from_tty)
9855 {
9856   break_command_1 (arg, BP_HARDWAREFLAG, from_tty);
9857 }
9858
9859 static void
9860 thbreak_command (char *arg, int from_tty)
9861 {
9862   break_command_1 (arg, (BP_TEMPFLAG | BP_HARDWAREFLAG), from_tty);
9863 }
9864
9865 static void
9866 stop_command (char *arg, int from_tty)
9867 {
9868   printf_filtered (_("Specify the type of breakpoint to set.\n\
9869 Usage: stop in <function | address>\n\
9870        stop at <line>\n"));
9871 }
9872
9873 static void
9874 stopin_command (char *arg, int from_tty)
9875 {
9876   int badInput = 0;
9877
9878   if (arg == (char *) NULL)
9879     badInput = 1;
9880   else if (*arg != '*')
9881     {
9882       char *argptr = arg;
9883       int hasColon = 0;
9884
9885       /* Look for a ':'.  If this is a line number specification, then
9886          say it is bad, otherwise, it should be an address or
9887          function/method name.  */
9888       while (*argptr && !hasColon)
9889         {
9890           hasColon = (*argptr == ':');
9891           argptr++;
9892         }
9893
9894       if (hasColon)
9895         badInput = (*argptr != ':');    /* Not a class::method */
9896       else
9897         badInput = isdigit (*arg);      /* a simple line number */
9898     }
9899
9900   if (badInput)
9901     printf_filtered (_("Usage: stop in <function | address>\n"));
9902   else
9903     break_command_1 (arg, 0, from_tty);
9904 }
9905
9906 static void
9907 stopat_command (char *arg, int from_tty)
9908 {
9909   int badInput = 0;
9910
9911   if (arg == (char *) NULL || *arg == '*')      /* no line number */
9912     badInput = 1;
9913   else
9914     {
9915       char *argptr = arg;
9916       int hasColon = 0;
9917
9918       /* Look for a ':'.  If there is a '::' then get out, otherwise
9919          it is probably a line number.  */
9920       while (*argptr && !hasColon)
9921         {
9922           hasColon = (*argptr == ':');
9923           argptr++;
9924         }
9925
9926       if (hasColon)
9927         badInput = (*argptr == ':');    /* we have class::method */
9928       else
9929         badInput = !isdigit (*arg);     /* not a line number */
9930     }
9931
9932   if (badInput)
9933     printf_filtered (_("Usage: stop at <line>\n"));
9934   else
9935     break_command_1 (arg, 0, from_tty);
9936 }
9937
9938 /* The dynamic printf command is mostly like a regular breakpoint, but
9939    with a prewired command list consisting of a single output command,
9940    built from extra arguments supplied on the dprintf command
9941    line.  */
9942
9943 static void
9944 dprintf_command (char *arg, int from_tty)
9945 {
9946   create_breakpoint (get_current_arch (),
9947                      arg,
9948                      NULL, 0, NULL, 1 /* parse arg */,
9949                      0, bp_dprintf,
9950                      0 /* Ignore count */,
9951                      pending_break_support,
9952                      &dprintf_breakpoint_ops,
9953                      from_tty,
9954                      1 /* enabled */,
9955                      0 /* internal */,
9956                      0);
9957 }
9958
9959 static void
9960 agent_printf_command (char *arg, int from_tty)
9961 {
9962   error (_("May only run agent-printf on the target"));
9963 }
9964
9965 /* Implement the "breakpoint_hit" breakpoint_ops method for
9966    ranged breakpoints.  */
9967
9968 static int
9969 breakpoint_hit_ranged_breakpoint (const struct bp_location *bl,
9970                                   struct address_space *aspace,
9971                                   CORE_ADDR bp_addr,
9972                                   const struct target_waitstatus *ws)
9973 {
9974   if (ws->kind != TARGET_WAITKIND_STOPPED
9975       || ws->value.sig != GDB_SIGNAL_TRAP)
9976     return 0;
9977
9978   return breakpoint_address_match_range (bl->pspace->aspace, bl->address,
9979                                          bl->length, aspace, bp_addr);
9980 }
9981
9982 /* Implement the "resources_needed" breakpoint_ops method for
9983    ranged breakpoints.  */
9984
9985 static int
9986 resources_needed_ranged_breakpoint (const struct bp_location *bl)
9987 {
9988   return target_ranged_break_num_registers ();
9989 }
9990
9991 /* Implement the "print_it" breakpoint_ops method for
9992    ranged breakpoints.  */
9993
9994 static enum print_stop_action
9995 print_it_ranged_breakpoint (bpstat bs)
9996 {
9997   struct breakpoint *b = bs->breakpoint_at;
9998   struct bp_location *bl = b->loc;
9999   struct ui_out *uiout = current_uiout;
10000
10001   gdb_assert (b->type == bp_hardware_breakpoint);
10002
10003   /* Ranged breakpoints have only one location.  */
10004   gdb_assert (bl && bl->next == NULL);
10005
10006   annotate_breakpoint (b->number);
10007   if (b->disposition == disp_del)
10008     ui_out_text (uiout, "\nTemporary ranged breakpoint ");
10009   else
10010     ui_out_text (uiout, "\nRanged breakpoint ");
10011   if (ui_out_is_mi_like_p (uiout))
10012     {
10013       ui_out_field_string (uiout, "reason",
10014                       async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
10015       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
10016     }
10017   ui_out_field_int (uiout, "bkptno", b->number);
10018   ui_out_text (uiout, ", ");
10019
10020   return PRINT_SRC_AND_LOC;
10021 }
10022
10023 /* Implement the "print_one" breakpoint_ops method for
10024    ranged breakpoints.  */
10025
10026 static void
10027 print_one_ranged_breakpoint (struct breakpoint *b,
10028                              struct bp_location **last_loc)
10029 {
10030   struct bp_location *bl = b->loc;
10031   struct value_print_options opts;
10032   struct ui_out *uiout = current_uiout;
10033
10034   /* Ranged breakpoints have only one location.  */
10035   gdb_assert (bl && bl->next == NULL);
10036
10037   get_user_print_options (&opts);
10038
10039   if (opts.addressprint)
10040     /* We don't print the address range here, it will be printed later
10041        by print_one_detail_ranged_breakpoint.  */
10042     ui_out_field_skip (uiout, "addr");
10043   annotate_field (5);
10044   print_breakpoint_location (b, bl);
10045   *last_loc = bl;
10046 }
10047
10048 /* Implement the "print_one_detail" breakpoint_ops method for
10049    ranged breakpoints.  */
10050
10051 static void
10052 print_one_detail_ranged_breakpoint (const struct breakpoint *b,
10053                                     struct ui_out *uiout)
10054 {
10055   CORE_ADDR address_start, address_end;
10056   struct bp_location *bl = b->loc;
10057   struct ui_file *stb = mem_fileopen ();
10058   struct cleanup *cleanup = make_cleanup_ui_file_delete (stb);
10059
10060   gdb_assert (bl);
10061
10062   address_start = bl->address;
10063   address_end = address_start + bl->length - 1;
10064
10065   ui_out_text (uiout, "\taddress range: ");
10066   fprintf_unfiltered (stb, "[%s, %s]",
10067                       print_core_address (bl->gdbarch, address_start),
10068                       print_core_address (bl->gdbarch, address_end));
10069   ui_out_field_stream (uiout, "addr", stb);
10070   ui_out_text (uiout, "\n");
10071
10072   do_cleanups (cleanup);
10073 }
10074
10075 /* Implement the "print_mention" breakpoint_ops method for
10076    ranged breakpoints.  */
10077
10078 static void
10079 print_mention_ranged_breakpoint (struct breakpoint *b)
10080 {
10081   struct bp_location *bl = b->loc;
10082   struct ui_out *uiout = current_uiout;
10083
10084   gdb_assert (bl);
10085   gdb_assert (b->type == bp_hardware_breakpoint);
10086
10087   if (ui_out_is_mi_like_p (uiout))
10088     return;
10089
10090   printf_filtered (_("Hardware assisted ranged breakpoint %d from %s to %s."),
10091                    b->number, paddress (bl->gdbarch, bl->address),
10092                    paddress (bl->gdbarch, bl->address + bl->length - 1));
10093 }
10094
10095 /* Implement the "print_recreate" breakpoint_ops method for
10096    ranged breakpoints.  */
10097
10098 static void
10099 print_recreate_ranged_breakpoint (struct breakpoint *b, struct ui_file *fp)
10100 {
10101   fprintf_unfiltered (fp, "break-range %s, %s", b->addr_string,
10102                       b->addr_string_range_end);
10103   print_recreate_thread (b, fp);
10104 }
10105
10106 /* The breakpoint_ops structure to be used in ranged breakpoints.  */
10107
10108 static struct breakpoint_ops ranged_breakpoint_ops;
10109
10110 /* Find the address where the end of the breakpoint range should be
10111    placed, given the SAL of the end of the range.  This is so that if
10112    the user provides a line number, the end of the range is set to the
10113    last instruction of the given line.  */
10114
10115 static CORE_ADDR
10116 find_breakpoint_range_end (struct symtab_and_line sal)
10117 {
10118   CORE_ADDR end;
10119
10120   /* If the user provided a PC value, use it.  Otherwise,
10121      find the address of the end of the given location.  */
10122   if (sal.explicit_pc)
10123     end = sal.pc;
10124   else
10125     {
10126       int ret;
10127       CORE_ADDR start;
10128
10129       ret = find_line_pc_range (sal, &start, &end);
10130       if (!ret)
10131         error (_("Could not find location of the end of the range."));
10132
10133       /* find_line_pc_range returns the start of the next line.  */
10134       end--;
10135     }
10136
10137   return end;
10138 }
10139
10140 /* Implement the "break-range" CLI command.  */
10141
10142 static void
10143 break_range_command (char *arg, int from_tty)
10144 {
10145   char *arg_start, *addr_string_start, *addr_string_end;
10146   struct linespec_result canonical_start, canonical_end;
10147   int bp_count, can_use_bp, length;
10148   CORE_ADDR end;
10149   struct breakpoint *b;
10150   struct symtab_and_line sal_start, sal_end;
10151   struct cleanup *cleanup_bkpt;
10152   struct linespec_sals *lsal_start, *lsal_end;
10153
10154   /* We don't support software ranged breakpoints.  */
10155   if (target_ranged_break_num_registers () < 0)
10156     error (_("This target does not support hardware ranged breakpoints."));
10157
10158   bp_count = hw_breakpoint_used_count ();
10159   bp_count += target_ranged_break_num_registers ();
10160   can_use_bp = target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
10161                                                    bp_count, 0);
10162   if (can_use_bp < 0)
10163     error (_("Hardware breakpoints used exceeds limit."));
10164
10165   arg = skip_spaces (arg);
10166   if (arg == NULL || arg[0] == '\0')
10167     error(_("No address range specified."));
10168
10169   init_linespec_result (&canonical_start);
10170
10171   arg_start = arg;
10172   parse_breakpoint_sals (&arg, &canonical_start);
10173
10174   cleanup_bkpt = make_cleanup_destroy_linespec_result (&canonical_start);
10175
10176   if (arg[0] != ',')
10177     error (_("Too few arguments."));
10178   else if (VEC_empty (linespec_sals, canonical_start.sals))
10179     error (_("Could not find location of the beginning of the range."));
10180
10181   lsal_start = VEC_index (linespec_sals, canonical_start.sals, 0);
10182
10183   if (VEC_length (linespec_sals, canonical_start.sals) > 1
10184       || lsal_start->sals.nelts != 1)
10185     error (_("Cannot create a ranged breakpoint with multiple locations."));
10186
10187   sal_start = lsal_start->sals.sals[0];
10188   addr_string_start = savestring (arg_start, arg - arg_start);
10189   make_cleanup (xfree, addr_string_start);
10190
10191   arg++;        /* Skip the comma.  */
10192   arg = skip_spaces (arg);
10193
10194   /* Parse the end location.  */
10195
10196   init_linespec_result (&canonical_end);
10197   arg_start = arg;
10198
10199   /* We call decode_line_full directly here instead of using
10200      parse_breakpoint_sals because we need to specify the start location's
10201      symtab and line as the default symtab and line for the end of the
10202      range.  This makes it possible to have ranges like "foo.c:27, +14",
10203      where +14 means 14 lines from the start location.  */
10204   decode_line_full (&arg, DECODE_LINE_FUNFIRSTLINE,
10205                     sal_start.symtab, sal_start.line,
10206                     &canonical_end, NULL, NULL);
10207
10208   make_cleanup_destroy_linespec_result (&canonical_end);
10209
10210   if (VEC_empty (linespec_sals, canonical_end.sals))
10211     error (_("Could not find location of the end of the range."));
10212
10213   lsal_end = VEC_index (linespec_sals, canonical_end.sals, 0);
10214   if (VEC_length (linespec_sals, canonical_end.sals) > 1
10215       || lsal_end->sals.nelts != 1)
10216     error (_("Cannot create a ranged breakpoint with multiple locations."));
10217
10218   sal_end = lsal_end->sals.sals[0];
10219   addr_string_end = savestring (arg_start, arg - arg_start);
10220   make_cleanup (xfree, addr_string_end);
10221
10222   end = find_breakpoint_range_end (sal_end);
10223   if (sal_start.pc > end)
10224     error (_("Invalid address range, end precedes start."));
10225
10226   length = end - sal_start.pc + 1;
10227   if (length < 0)
10228     /* Length overflowed.  */
10229     error (_("Address range too large."));
10230   else if (length == 1)
10231     {
10232       /* This range is simple enough to be handled by
10233          the `hbreak' command.  */
10234       hbreak_command (addr_string_start, 1);
10235
10236       do_cleanups (cleanup_bkpt);
10237
10238       return;
10239     }
10240
10241   /* Now set up the breakpoint.  */
10242   b = set_raw_breakpoint (get_current_arch (), sal_start,
10243                           bp_hardware_breakpoint, &ranged_breakpoint_ops);
10244   set_breakpoint_count (breakpoint_count + 1);
10245   b->number = breakpoint_count;
10246   b->disposition = disp_donttouch;
10247   b->addr_string = xstrdup (addr_string_start);
10248   b->addr_string_range_end = xstrdup (addr_string_end);
10249   b->loc->length = length;
10250
10251   do_cleanups (cleanup_bkpt);
10252
10253   mention (b);
10254   observer_notify_breakpoint_created (b);
10255   update_global_location_list (1);
10256 }
10257
10258 /*  Return non-zero if EXP is verified as constant.  Returned zero
10259     means EXP is variable.  Also the constant detection may fail for
10260     some constant expressions and in such case still falsely return
10261     zero.  */
10262
10263 static int
10264 watchpoint_exp_is_const (const struct expression *exp)
10265 {
10266   int i = exp->nelts;
10267
10268   while (i > 0)
10269     {
10270       int oplenp, argsp;
10271
10272       /* We are only interested in the descriptor of each element.  */
10273       operator_length (exp, i, &oplenp, &argsp);
10274       i -= oplenp;
10275
10276       switch (exp->elts[i].opcode)
10277         {
10278         case BINOP_ADD:
10279         case BINOP_SUB:
10280         case BINOP_MUL:
10281         case BINOP_DIV:
10282         case BINOP_REM:
10283         case BINOP_MOD:
10284         case BINOP_LSH:
10285         case BINOP_RSH:
10286         case BINOP_LOGICAL_AND:
10287         case BINOP_LOGICAL_OR:
10288         case BINOP_BITWISE_AND:
10289         case BINOP_BITWISE_IOR:
10290         case BINOP_BITWISE_XOR:
10291         case BINOP_EQUAL:
10292         case BINOP_NOTEQUAL:
10293         case BINOP_LESS:
10294         case BINOP_GTR:
10295         case BINOP_LEQ:
10296         case BINOP_GEQ:
10297         case BINOP_REPEAT:
10298         case BINOP_COMMA:
10299         case BINOP_EXP:
10300         case BINOP_MIN:
10301         case BINOP_MAX:
10302         case BINOP_INTDIV:
10303         case BINOP_CONCAT:
10304         case BINOP_IN:
10305         case BINOP_RANGE:
10306         case TERNOP_COND:
10307         case TERNOP_SLICE:
10308
10309         case OP_LONG:
10310         case OP_DOUBLE:
10311         case OP_DECFLOAT:
10312         case OP_LAST:
10313         case OP_COMPLEX:
10314         case OP_STRING:
10315         case OP_ARRAY:
10316         case OP_TYPE:
10317         case OP_TYPEOF:
10318         case OP_DECLTYPE:
10319         case OP_NAME:
10320         case OP_OBJC_NSSTRING:
10321
10322         case UNOP_NEG:
10323         case UNOP_LOGICAL_NOT:
10324         case UNOP_COMPLEMENT:
10325         case UNOP_ADDR:
10326         case UNOP_HIGH:
10327         case UNOP_CAST:
10328
10329         case UNOP_CAST_TYPE:
10330         case UNOP_REINTERPRET_CAST:
10331         case UNOP_DYNAMIC_CAST:
10332           /* Unary, binary and ternary operators: We have to check
10333              their operands.  If they are constant, then so is the
10334              result of that operation.  For instance, if A and B are
10335              determined to be constants, then so is "A + B".
10336
10337              UNOP_IND is one exception to the rule above, because the
10338              value of *ADDR is not necessarily a constant, even when
10339              ADDR is.  */
10340           break;
10341
10342         case OP_VAR_VALUE:
10343           /* Check whether the associated symbol is a constant.
10344
10345              We use SYMBOL_CLASS rather than TYPE_CONST because it's
10346              possible that a buggy compiler could mark a variable as
10347              constant even when it is not, and TYPE_CONST would return
10348              true in this case, while SYMBOL_CLASS wouldn't.
10349
10350              We also have to check for function symbols because they
10351              are always constant.  */
10352           {
10353             struct symbol *s = exp->elts[i + 2].symbol;
10354
10355             if (SYMBOL_CLASS (s) != LOC_BLOCK
10356                 && SYMBOL_CLASS (s) != LOC_CONST
10357                 && SYMBOL_CLASS (s) != LOC_CONST_BYTES)
10358               return 0;
10359             break;
10360           }
10361
10362         /* The default action is to return 0 because we are using
10363            the optimistic approach here: If we don't know something,
10364            then it is not a constant.  */
10365         default:
10366           return 0;
10367         }
10368     }
10369
10370   return 1;
10371 }
10372
10373 /* Implement the "dtor" breakpoint_ops method for watchpoints.  */
10374
10375 static void
10376 dtor_watchpoint (struct breakpoint *self)
10377 {
10378   struct watchpoint *w = (struct watchpoint *) self;
10379
10380   xfree (w->cond_exp);
10381   xfree (w->exp);
10382   xfree (w->exp_string);
10383   xfree (w->exp_string_reparse);
10384   value_free (w->val);
10385
10386   base_breakpoint_ops.dtor (self);
10387 }
10388
10389 /* Implement the "re_set" breakpoint_ops method for watchpoints.  */
10390
10391 static void
10392 re_set_watchpoint (struct breakpoint *b)
10393 {
10394   struct watchpoint *w = (struct watchpoint *) b;
10395
10396   /* Watchpoint can be either on expression using entirely global
10397      variables, or it can be on local variables.
10398
10399      Watchpoints of the first kind are never auto-deleted, and even
10400      persist across program restarts.  Since they can use variables
10401      from shared libraries, we need to reparse expression as libraries
10402      are loaded and unloaded.
10403
10404      Watchpoints on local variables can also change meaning as result
10405      of solib event.  For example, if a watchpoint uses both a local
10406      and a global variables in expression, it's a local watchpoint,
10407      but unloading of a shared library will make the expression
10408      invalid.  This is not a very common use case, but we still
10409      re-evaluate expression, to avoid surprises to the user.
10410
10411      Note that for local watchpoints, we re-evaluate it only if
10412      watchpoints frame id is still valid.  If it's not, it means the
10413      watchpoint is out of scope and will be deleted soon.  In fact,
10414      I'm not sure we'll ever be called in this case.
10415
10416      If a local watchpoint's frame id is still valid, then
10417      w->exp_valid_block is likewise valid, and we can safely use it.
10418
10419      Don't do anything about disabled watchpoints, since they will be
10420      reevaluated again when enabled.  */
10421   update_watchpoint (w, 1 /* reparse */);
10422 }
10423
10424 /* Implement the "insert" breakpoint_ops method for hardware watchpoints.  */
10425
10426 static int
10427 insert_watchpoint (struct bp_location *bl)
10428 {
10429   struct watchpoint *w = (struct watchpoint *) bl->owner;
10430   int length = w->exact ? 1 : bl->length;
10431
10432   return target_insert_watchpoint (bl->address, length, bl->watchpoint_type,
10433                                    w->cond_exp);
10434 }
10435
10436 /* Implement the "remove" breakpoint_ops method for hardware watchpoints.  */
10437
10438 static int
10439 remove_watchpoint (struct bp_location *bl)
10440 {
10441   struct watchpoint *w = (struct watchpoint *) bl->owner;
10442   int length = w->exact ? 1 : bl->length;
10443
10444   return target_remove_watchpoint (bl->address, length, bl->watchpoint_type,
10445                                    w->cond_exp);
10446 }
10447
10448 static int
10449 breakpoint_hit_watchpoint (const struct bp_location *bl,
10450                            struct address_space *aspace, CORE_ADDR bp_addr,
10451                            const struct target_waitstatus *ws)
10452 {
10453   struct breakpoint *b = bl->owner;
10454   struct watchpoint *w = (struct watchpoint *) b;
10455
10456   /* Continuable hardware watchpoints are treated as non-existent if the
10457      reason we stopped wasn't a hardware watchpoint (we didn't stop on
10458      some data address).  Otherwise gdb won't stop on a break instruction
10459      in the code (not from a breakpoint) when a hardware watchpoint has
10460      been defined.  Also skip watchpoints which we know did not trigger
10461      (did not match the data address).  */
10462   if (is_hardware_watchpoint (b)
10463       && w->watchpoint_triggered == watch_triggered_no)
10464     return 0;
10465
10466   return 1;
10467 }
10468
10469 static void
10470 check_status_watchpoint (bpstat bs)
10471 {
10472   gdb_assert (is_watchpoint (bs->breakpoint_at));
10473
10474   bpstat_check_watchpoint (bs);
10475 }
10476
10477 /* Implement the "resources_needed" breakpoint_ops method for
10478    hardware watchpoints.  */
10479
10480 static int
10481 resources_needed_watchpoint (const struct bp_location *bl)
10482 {
10483   struct watchpoint *w = (struct watchpoint *) bl->owner;
10484   int length = w->exact? 1 : bl->length;
10485
10486   return target_region_ok_for_hw_watchpoint (bl->address, length);
10487 }
10488
10489 /* Implement the "works_in_software_mode" breakpoint_ops method for
10490    hardware watchpoints.  */
10491
10492 static int
10493 works_in_software_mode_watchpoint (const struct breakpoint *b)
10494 {
10495   /* Read and access watchpoints only work with hardware support.  */
10496   return b->type == bp_watchpoint || b->type == bp_hardware_watchpoint;
10497 }
10498
10499 static enum print_stop_action
10500 print_it_watchpoint (bpstat bs)
10501 {
10502   struct cleanup *old_chain;
10503   struct breakpoint *b;
10504   struct ui_file *stb;
10505   enum print_stop_action result;
10506   struct watchpoint *w;
10507   struct ui_out *uiout = current_uiout;
10508
10509   gdb_assert (bs->bp_location_at != NULL);
10510
10511   b = bs->breakpoint_at;
10512   w = (struct watchpoint *) b;
10513
10514   stb = mem_fileopen ();
10515   old_chain = make_cleanup_ui_file_delete (stb);
10516
10517   switch (b->type)
10518     {
10519     case bp_watchpoint:
10520     case bp_hardware_watchpoint:
10521       annotate_watchpoint (b->number);
10522       if (ui_out_is_mi_like_p (uiout))
10523         ui_out_field_string
10524           (uiout, "reason",
10525            async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
10526       mention (b);
10527       make_cleanup_ui_out_tuple_begin_end (uiout, "value");
10528       ui_out_text (uiout, "\nOld value = ");
10529       watchpoint_value_print (bs->old_val, stb);
10530       ui_out_field_stream (uiout, "old", stb);
10531       ui_out_text (uiout, "\nNew value = ");
10532       watchpoint_value_print (w->val, stb);
10533       ui_out_field_stream (uiout, "new", stb);
10534       ui_out_text (uiout, "\n");
10535       /* More than one watchpoint may have been triggered.  */
10536       result = PRINT_UNKNOWN;
10537       break;
10538
10539     case bp_read_watchpoint:
10540       if (ui_out_is_mi_like_p (uiout))
10541         ui_out_field_string
10542           (uiout, "reason",
10543            async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
10544       mention (b);
10545       make_cleanup_ui_out_tuple_begin_end (uiout, "value");
10546       ui_out_text (uiout, "\nValue = ");
10547       watchpoint_value_print (w->val, stb);
10548       ui_out_field_stream (uiout, "value", stb);
10549       ui_out_text (uiout, "\n");
10550       result = PRINT_UNKNOWN;
10551       break;
10552
10553     case bp_access_watchpoint:
10554       if (bs->old_val != NULL)
10555         {
10556           annotate_watchpoint (b->number);
10557           if (ui_out_is_mi_like_p (uiout))
10558             ui_out_field_string
10559               (uiout, "reason",
10560                async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10561           mention (b);
10562           make_cleanup_ui_out_tuple_begin_end (uiout, "value");
10563           ui_out_text (uiout, "\nOld value = ");
10564           watchpoint_value_print (bs->old_val, stb);
10565           ui_out_field_stream (uiout, "old", stb);
10566           ui_out_text (uiout, "\nNew value = ");
10567         }
10568       else
10569         {
10570           mention (b);
10571           if (ui_out_is_mi_like_p (uiout))
10572             ui_out_field_string
10573               (uiout, "reason",
10574                async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10575           make_cleanup_ui_out_tuple_begin_end (uiout, "value");
10576           ui_out_text (uiout, "\nValue = ");
10577         }
10578       watchpoint_value_print (w->val, stb);
10579       ui_out_field_stream (uiout, "new", stb);
10580       ui_out_text (uiout, "\n");
10581       result = PRINT_UNKNOWN;
10582       break;
10583     default:
10584       result = PRINT_UNKNOWN;
10585     }
10586
10587   do_cleanups (old_chain);
10588   return result;
10589 }
10590
10591 /* Implement the "print_mention" breakpoint_ops method for hardware
10592    watchpoints.  */
10593
10594 static void
10595 print_mention_watchpoint (struct breakpoint *b)
10596 {
10597   struct cleanup *ui_out_chain;
10598   struct watchpoint *w = (struct watchpoint *) b;
10599   struct ui_out *uiout = current_uiout;
10600
10601   switch (b->type)
10602     {
10603     case bp_watchpoint:
10604       ui_out_text (uiout, "Watchpoint ");
10605       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "wpt");
10606       break;
10607     case bp_hardware_watchpoint:
10608       ui_out_text (uiout, "Hardware watchpoint ");
10609       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "wpt");
10610       break;
10611     case bp_read_watchpoint:
10612       ui_out_text (uiout, "Hardware read watchpoint ");
10613       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-rwpt");
10614       break;
10615     case bp_access_watchpoint:
10616       ui_out_text (uiout, "Hardware access (read/write) watchpoint ");
10617       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-awpt");
10618       break;
10619     default:
10620       internal_error (__FILE__, __LINE__,
10621                       _("Invalid hardware watchpoint type."));
10622     }
10623
10624   ui_out_field_int (uiout, "number", b->number);
10625   ui_out_text (uiout, ": ");
10626   ui_out_field_string (uiout, "exp", w->exp_string);
10627   do_cleanups (ui_out_chain);
10628 }
10629
10630 /* Implement the "print_recreate" breakpoint_ops method for
10631    watchpoints.  */
10632
10633 static void
10634 print_recreate_watchpoint (struct breakpoint *b, struct ui_file *fp)
10635 {
10636   struct watchpoint *w = (struct watchpoint *) b;
10637
10638   switch (b->type)
10639     {
10640     case bp_watchpoint:
10641     case bp_hardware_watchpoint:
10642       fprintf_unfiltered (fp, "watch");
10643       break;
10644     case bp_read_watchpoint:
10645       fprintf_unfiltered (fp, "rwatch");
10646       break;
10647     case bp_access_watchpoint:
10648       fprintf_unfiltered (fp, "awatch");
10649       break;
10650     default:
10651       internal_error (__FILE__, __LINE__,
10652                       _("Invalid watchpoint type."));
10653     }
10654
10655   fprintf_unfiltered (fp, " %s", w->exp_string);
10656   print_recreate_thread (b, fp);
10657 }
10658
10659 /* The breakpoint_ops structure to be used in hardware watchpoints.  */
10660
10661 static struct breakpoint_ops watchpoint_breakpoint_ops;
10662
10663 /* Implement the "insert" breakpoint_ops method for
10664    masked hardware watchpoints.  */
10665
10666 static int
10667 insert_masked_watchpoint (struct bp_location *bl)
10668 {
10669   struct watchpoint *w = (struct watchpoint *) bl->owner;
10670
10671   return target_insert_mask_watchpoint (bl->address, w->hw_wp_mask,
10672                                         bl->watchpoint_type);
10673 }
10674
10675 /* Implement the "remove" breakpoint_ops method for
10676    masked hardware watchpoints.  */
10677
10678 static int
10679 remove_masked_watchpoint (struct bp_location *bl)
10680 {
10681   struct watchpoint *w = (struct watchpoint *) bl->owner;
10682
10683   return target_remove_mask_watchpoint (bl->address, w->hw_wp_mask,
10684                                         bl->watchpoint_type);
10685 }
10686
10687 /* Implement the "resources_needed" breakpoint_ops method for
10688    masked hardware watchpoints.  */
10689
10690 static int
10691 resources_needed_masked_watchpoint (const struct bp_location *bl)
10692 {
10693   struct watchpoint *w = (struct watchpoint *) bl->owner;
10694
10695   return target_masked_watch_num_registers (bl->address, w->hw_wp_mask);
10696 }
10697
10698 /* Implement the "works_in_software_mode" breakpoint_ops method for
10699    masked hardware watchpoints.  */
10700
10701 static int
10702 works_in_software_mode_masked_watchpoint (const struct breakpoint *b)
10703 {
10704   return 0;
10705 }
10706
10707 /* Implement the "print_it" breakpoint_ops method for
10708    masked hardware watchpoints.  */
10709
10710 static enum print_stop_action
10711 print_it_masked_watchpoint (bpstat bs)
10712 {
10713   struct breakpoint *b = bs->breakpoint_at;
10714   struct ui_out *uiout = current_uiout;
10715
10716   /* Masked watchpoints have only one location.  */
10717   gdb_assert (b->loc && b->loc->next == NULL);
10718
10719   switch (b->type)
10720     {
10721     case bp_hardware_watchpoint:
10722       annotate_watchpoint (b->number);
10723       if (ui_out_is_mi_like_p (uiout))
10724         ui_out_field_string
10725           (uiout, "reason",
10726            async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
10727       break;
10728
10729     case bp_read_watchpoint:
10730       if (ui_out_is_mi_like_p (uiout))
10731         ui_out_field_string
10732           (uiout, "reason",
10733            async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
10734       break;
10735
10736     case bp_access_watchpoint:
10737       if (ui_out_is_mi_like_p (uiout))
10738         ui_out_field_string
10739           (uiout, "reason",
10740            async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10741       break;
10742     default:
10743       internal_error (__FILE__, __LINE__,
10744                       _("Invalid hardware watchpoint type."));
10745     }
10746
10747   mention (b);
10748   ui_out_text (uiout, _("\n\
10749 Check the underlying instruction at PC for the memory\n\
10750 address and value which triggered this watchpoint.\n"));
10751   ui_out_text (uiout, "\n");
10752
10753   /* More than one watchpoint may have been triggered.  */
10754   return PRINT_UNKNOWN;
10755 }
10756
10757 /* Implement the "print_one_detail" breakpoint_ops method for
10758    masked hardware watchpoints.  */
10759
10760 static void
10761 print_one_detail_masked_watchpoint (const struct breakpoint *b,
10762                                     struct ui_out *uiout)
10763 {
10764   struct watchpoint *w = (struct watchpoint *) b;
10765
10766   /* Masked watchpoints have only one location.  */
10767   gdb_assert (b->loc && b->loc->next == NULL);
10768
10769   ui_out_text (uiout, "\tmask ");
10770   ui_out_field_core_addr (uiout, "mask", b->loc->gdbarch, w->hw_wp_mask);
10771   ui_out_text (uiout, "\n");
10772 }
10773
10774 /* Implement the "print_mention" breakpoint_ops method for
10775    masked hardware watchpoints.  */
10776
10777 static void
10778 print_mention_masked_watchpoint (struct breakpoint *b)
10779 {
10780   struct watchpoint *w = (struct watchpoint *) b;
10781   struct ui_out *uiout = current_uiout;
10782   struct cleanup *ui_out_chain;
10783
10784   switch (b->type)
10785     {
10786     case bp_hardware_watchpoint:
10787       ui_out_text (uiout, "Masked hardware watchpoint ");
10788       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "wpt");
10789       break;
10790     case bp_read_watchpoint:
10791       ui_out_text (uiout, "Masked hardware read watchpoint ");
10792       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-rwpt");
10793       break;
10794     case bp_access_watchpoint:
10795       ui_out_text (uiout, "Masked hardware access (read/write) watchpoint ");
10796       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-awpt");
10797       break;
10798     default:
10799       internal_error (__FILE__, __LINE__,
10800                       _("Invalid hardware watchpoint type."));
10801     }
10802
10803   ui_out_field_int (uiout, "number", b->number);
10804   ui_out_text (uiout, ": ");
10805   ui_out_field_string (uiout, "exp", w->exp_string);
10806   do_cleanups (ui_out_chain);
10807 }
10808
10809 /* Implement the "print_recreate" breakpoint_ops method for
10810    masked hardware watchpoints.  */
10811
10812 static void
10813 print_recreate_masked_watchpoint (struct breakpoint *b, struct ui_file *fp)
10814 {
10815   struct watchpoint *w = (struct watchpoint *) b;
10816   char tmp[40];
10817
10818   switch (b->type)
10819     {
10820     case bp_hardware_watchpoint:
10821       fprintf_unfiltered (fp, "watch");
10822       break;
10823     case bp_read_watchpoint:
10824       fprintf_unfiltered (fp, "rwatch");
10825       break;
10826     case bp_access_watchpoint:
10827       fprintf_unfiltered (fp, "awatch");
10828       break;
10829     default:
10830       internal_error (__FILE__, __LINE__,
10831                       _("Invalid hardware watchpoint type."));
10832     }
10833
10834   sprintf_vma (tmp, w->hw_wp_mask);
10835   fprintf_unfiltered (fp, " %s mask 0x%s", w->exp_string, tmp);
10836   print_recreate_thread (b, fp);
10837 }
10838
10839 /* The breakpoint_ops structure to be used in masked hardware watchpoints.  */
10840
10841 static struct breakpoint_ops masked_watchpoint_breakpoint_ops;
10842
10843 /* Tell whether the given watchpoint is a masked hardware watchpoint.  */
10844
10845 static int
10846 is_masked_watchpoint (const struct breakpoint *b)
10847 {
10848   return b->ops == &masked_watchpoint_breakpoint_ops;
10849 }
10850
10851 /* accessflag:  hw_write:  watch write, 
10852                 hw_read:   watch read, 
10853                 hw_access: watch access (read or write) */
10854 static void
10855 watch_command_1 (const char *arg, int accessflag, int from_tty,
10856                  int just_location, int internal)
10857 {
10858   volatile struct gdb_exception e;
10859   struct breakpoint *b, *scope_breakpoint = NULL;
10860   struct expression *exp;
10861   const struct block *exp_valid_block = NULL, *cond_exp_valid_block = NULL;
10862   struct value *val, *mark, *result;
10863   struct frame_info *frame;
10864   const char *exp_start = NULL;
10865   const char *exp_end = NULL;
10866   const char *tok, *end_tok;
10867   int toklen = -1;
10868   const char *cond_start = NULL;
10869   const char *cond_end = NULL;
10870   enum bptype bp_type;
10871   int thread = -1;
10872   int pc = 0;
10873   /* Flag to indicate whether we are going to use masks for
10874      the hardware watchpoint.  */
10875   int use_mask = 0;
10876   CORE_ADDR mask = 0;
10877   struct watchpoint *w;
10878   char *expression;
10879   struct cleanup *back_to;
10880
10881   /* Make sure that we actually have parameters to parse.  */
10882   if (arg != NULL && arg[0] != '\0')
10883     {
10884       const char *value_start;
10885
10886       exp_end = arg + strlen (arg);
10887
10888       /* Look for "parameter value" pairs at the end
10889          of the arguments string.  */
10890       for (tok = exp_end - 1; tok > arg; tok--)
10891         {
10892           /* Skip whitespace at the end of the argument list.  */
10893           while (tok > arg && (*tok == ' ' || *tok == '\t'))
10894             tok--;
10895
10896           /* Find the beginning of the last token.
10897              This is the value of the parameter.  */
10898           while (tok > arg && (*tok != ' ' && *tok != '\t'))
10899             tok--;
10900           value_start = tok + 1;
10901
10902           /* Skip whitespace.  */
10903           while (tok > arg && (*tok == ' ' || *tok == '\t'))
10904             tok--;
10905
10906           end_tok = tok;
10907
10908           /* Find the beginning of the second to last token.
10909              This is the parameter itself.  */
10910           while (tok > arg && (*tok != ' ' && *tok != '\t'))
10911             tok--;
10912           tok++;
10913           toklen = end_tok - tok + 1;
10914
10915           if (toklen == 6 && !strncmp (tok, "thread", 6))
10916             {
10917               /* At this point we've found a "thread" token, which means
10918                  the user is trying to set a watchpoint that triggers
10919                  only in a specific thread.  */
10920               char *endp;
10921
10922               if (thread != -1)
10923                 error(_("You can specify only one thread."));
10924
10925               /* Extract the thread ID from the next token.  */
10926               thread = strtol (value_start, &endp, 0);
10927
10928               /* Check if the user provided a valid numeric value for the
10929                  thread ID.  */
10930               if (*endp != ' ' && *endp != '\t' && *endp != '\0')
10931                 error (_("Invalid thread ID specification %s."), value_start);
10932
10933               /* Check if the thread actually exists.  */
10934               if (!valid_thread_id (thread))
10935                 invalid_thread_id_error (thread);
10936             }
10937           else if (toklen == 4 && !strncmp (tok, "mask", 4))
10938             {
10939               /* We've found a "mask" token, which means the user wants to
10940                  create a hardware watchpoint that is going to have the mask
10941                  facility.  */
10942               struct value *mask_value, *mark;
10943
10944               if (use_mask)
10945                 error(_("You can specify only one mask."));
10946
10947               use_mask = just_location = 1;
10948
10949               mark = value_mark ();
10950               mask_value = parse_to_comma_and_eval (&value_start);
10951               mask = value_as_address (mask_value);
10952               value_free_to_mark (mark);
10953             }
10954           else
10955             /* We didn't recognize what we found.  We should stop here.  */
10956             break;
10957
10958           /* Truncate the string and get rid of the "parameter value" pair before
10959              the arguments string is parsed by the parse_exp_1 function.  */
10960           exp_end = tok;
10961         }
10962     }
10963   else
10964     exp_end = arg;
10965
10966   /* Parse the rest of the arguments.  From here on out, everything
10967      is in terms of a newly allocated string instead of the original
10968      ARG.  */
10969   innermost_block = NULL;
10970   expression = savestring (arg, exp_end - arg);
10971   back_to = make_cleanup (xfree, expression);
10972   exp_start = arg = expression;
10973   exp = parse_exp_1 (&arg, 0, 0, 0);
10974   exp_end = arg;
10975   /* Remove trailing whitespace from the expression before saving it.
10976      This makes the eventual display of the expression string a bit
10977      prettier.  */
10978   while (exp_end > exp_start && (exp_end[-1] == ' ' || exp_end[-1] == '\t'))
10979     --exp_end;
10980
10981   /* Checking if the expression is not constant.  */
10982   if (watchpoint_exp_is_const (exp))
10983     {
10984       int len;
10985
10986       len = exp_end - exp_start;
10987       while (len > 0 && isspace (exp_start[len - 1]))
10988         len--;
10989       error (_("Cannot watch constant value `%.*s'."), len, exp_start);
10990     }
10991
10992   exp_valid_block = innermost_block;
10993   mark = value_mark ();
10994   fetch_subexp_value (exp, &pc, &val, &result, NULL);
10995
10996   if (just_location)
10997     {
10998       int ret;
10999
11000       exp_valid_block = NULL;
11001       val = value_addr (result);
11002       release_value (val);
11003       value_free_to_mark (mark);
11004
11005       if (use_mask)
11006         {
11007           ret = target_masked_watch_num_registers (value_as_address (val),
11008                                                    mask);
11009           if (ret == -1)
11010             error (_("This target does not support masked watchpoints."));
11011           else if (ret == -2)
11012             error (_("Invalid mask or memory region."));
11013         }
11014     }
11015   else if (val != NULL)
11016     release_value (val);
11017
11018   tok = skip_spaces_const (arg);
11019   end_tok = skip_to_space_const (tok);
11020
11021   toklen = end_tok - tok;
11022   if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
11023     {
11024       struct expression *cond;
11025
11026       innermost_block = NULL;
11027       tok = cond_start = end_tok + 1;
11028       cond = parse_exp_1 (&tok, 0, 0, 0);
11029
11030       /* The watchpoint expression may not be local, but the condition
11031          may still be.  E.g.: `watch global if local > 0'.  */
11032       cond_exp_valid_block = innermost_block;
11033
11034       xfree (cond);
11035       cond_end = tok;
11036     }
11037   if (*tok)
11038     error (_("Junk at end of command."));
11039
11040   if (accessflag == hw_read)
11041     bp_type = bp_read_watchpoint;
11042   else if (accessflag == hw_access)
11043     bp_type = bp_access_watchpoint;
11044   else
11045     bp_type = bp_hardware_watchpoint;
11046
11047   frame = block_innermost_frame (exp_valid_block);
11048
11049   /* If the expression is "local", then set up a "watchpoint scope"
11050      breakpoint at the point where we've left the scope of the watchpoint
11051      expression.  Create the scope breakpoint before the watchpoint, so
11052      that we will encounter it first in bpstat_stop_status.  */
11053   if (exp_valid_block && frame)
11054     {
11055       if (frame_id_p (frame_unwind_caller_id (frame)))
11056         {
11057           scope_breakpoint
11058             = create_internal_breakpoint (frame_unwind_caller_arch (frame),
11059                                           frame_unwind_caller_pc (frame),
11060                                           bp_watchpoint_scope,
11061                                           &momentary_breakpoint_ops);
11062
11063           scope_breakpoint->enable_state = bp_enabled;
11064
11065           /* Automatically delete the breakpoint when it hits.  */
11066           scope_breakpoint->disposition = disp_del;
11067
11068           /* Only break in the proper frame (help with recursion).  */
11069           scope_breakpoint->frame_id = frame_unwind_caller_id (frame);
11070
11071           /* Set the address at which we will stop.  */
11072           scope_breakpoint->loc->gdbarch
11073             = frame_unwind_caller_arch (frame);
11074           scope_breakpoint->loc->requested_address
11075             = frame_unwind_caller_pc (frame);
11076           scope_breakpoint->loc->address
11077             = adjust_breakpoint_address (scope_breakpoint->loc->gdbarch,
11078                                          scope_breakpoint->loc->requested_address,
11079                                          scope_breakpoint->type);
11080         }
11081     }
11082
11083   /* Now set up the breakpoint.  */
11084
11085   w = XCNEW (struct watchpoint);
11086   b = &w->base;
11087   if (use_mask)
11088     init_raw_breakpoint_without_location (b, NULL, bp_type,
11089                                           &masked_watchpoint_breakpoint_ops);
11090   else
11091     init_raw_breakpoint_without_location (b, NULL, bp_type,
11092                                           &watchpoint_breakpoint_ops);
11093   b->thread = thread;
11094   b->disposition = disp_donttouch;
11095   b->pspace = current_program_space;
11096   w->exp = exp;
11097   w->exp_valid_block = exp_valid_block;
11098   w->cond_exp_valid_block = cond_exp_valid_block;
11099   if (just_location)
11100     {
11101       struct type *t = value_type (val);
11102       CORE_ADDR addr = value_as_address (val);
11103       char *name;
11104
11105       t = check_typedef (TYPE_TARGET_TYPE (check_typedef (t)));
11106       name = type_to_string (t);
11107
11108       w->exp_string_reparse = xstrprintf ("* (%s *) %s", name,
11109                                           core_addr_to_string (addr));
11110       xfree (name);
11111
11112       w->exp_string = xstrprintf ("-location %.*s",
11113                                   (int) (exp_end - exp_start), exp_start);
11114
11115       /* The above expression is in C.  */
11116       b->language = language_c;
11117     }
11118   else
11119     w->exp_string = savestring (exp_start, exp_end - exp_start);
11120
11121   if (use_mask)
11122     {
11123       w->hw_wp_mask = mask;
11124     }
11125   else
11126     {
11127       w->val = val;
11128       w->val_valid = 1;
11129     }
11130
11131   if (cond_start)
11132     b->cond_string = savestring (cond_start, cond_end - cond_start);
11133   else
11134     b->cond_string = 0;
11135
11136   if (frame)
11137     {
11138       w->watchpoint_frame = get_frame_id (frame);
11139       w->watchpoint_thread = inferior_ptid;
11140     }
11141   else
11142     {
11143       w->watchpoint_frame = null_frame_id;
11144       w->watchpoint_thread = null_ptid;
11145     }
11146
11147   if (scope_breakpoint != NULL)
11148     {
11149       /* The scope breakpoint is related to the watchpoint.  We will
11150          need to act on them together.  */
11151       b->related_breakpoint = scope_breakpoint;
11152       scope_breakpoint->related_breakpoint = b;
11153     }
11154
11155   if (!just_location)
11156     value_free_to_mark (mark);
11157
11158   TRY_CATCH (e, RETURN_MASK_ALL)
11159     {
11160       /* Finally update the new watchpoint.  This creates the locations
11161          that should be inserted.  */
11162       update_watchpoint (w, 1);
11163     }
11164   if (e.reason < 0)
11165     {
11166       delete_breakpoint (b);
11167       throw_exception (e);
11168     }
11169
11170   install_breakpoint (internal, b, 1);
11171   do_cleanups (back_to);
11172 }
11173
11174 /* Return count of debug registers needed to watch the given expression.
11175    If the watchpoint cannot be handled in hardware return zero.  */
11176
11177 static int
11178 can_use_hardware_watchpoint (struct value *v)
11179 {
11180   int found_memory_cnt = 0;
11181   struct value *head = v;
11182
11183   /* Did the user specifically forbid us to use hardware watchpoints? */
11184   if (!can_use_hw_watchpoints)
11185     return 0;
11186
11187   /* Make sure that the value of the expression depends only upon
11188      memory contents, and values computed from them within GDB.  If we
11189      find any register references or function calls, we can't use a
11190      hardware watchpoint.
11191
11192      The idea here is that evaluating an expression generates a series
11193      of values, one holding the value of every subexpression.  (The
11194      expression a*b+c has five subexpressions: a, b, a*b, c, and
11195      a*b+c.)  GDB's values hold almost enough information to establish
11196      the criteria given above --- they identify memory lvalues,
11197      register lvalues, computed values, etcetera.  So we can evaluate
11198      the expression, and then scan the chain of values that leaves
11199      behind to decide whether we can detect any possible change to the
11200      expression's final value using only hardware watchpoints.
11201
11202      However, I don't think that the values returned by inferior
11203      function calls are special in any way.  So this function may not
11204      notice that an expression involving an inferior function call
11205      can't be watched with hardware watchpoints.  FIXME.  */
11206   for (; v; v = value_next (v))
11207     {
11208       if (VALUE_LVAL (v) == lval_memory)
11209         {
11210           if (v != head && value_lazy (v))
11211             /* A lazy memory lvalue in the chain is one that GDB never
11212                needed to fetch; we either just used its address (e.g.,
11213                `a' in `a.b') or we never needed it at all (e.g., `a'
11214                in `a,b').  This doesn't apply to HEAD; if that is
11215                lazy then it was not readable, but watch it anyway.  */
11216             ;
11217           else
11218             {
11219               /* Ahh, memory we actually used!  Check if we can cover
11220                  it with hardware watchpoints.  */
11221               struct type *vtype = check_typedef (value_type (v));
11222
11223               /* We only watch structs and arrays if user asked for it
11224                  explicitly, never if they just happen to appear in a
11225                  middle of some value chain.  */
11226               if (v == head
11227                   || (TYPE_CODE (vtype) != TYPE_CODE_STRUCT
11228                       && TYPE_CODE (vtype) != TYPE_CODE_ARRAY))
11229                 {
11230                   CORE_ADDR vaddr = value_address (v);
11231                   int len;
11232                   int num_regs;
11233
11234                   len = (target_exact_watchpoints
11235                          && is_scalar_type_recursive (vtype))?
11236                     1 : TYPE_LENGTH (value_type (v));
11237
11238                   num_regs = target_region_ok_for_hw_watchpoint (vaddr, len);
11239                   if (!num_regs)
11240                     return 0;
11241                   else
11242                     found_memory_cnt += num_regs;
11243                 }
11244             }
11245         }
11246       else if (VALUE_LVAL (v) != not_lval
11247                && deprecated_value_modifiable (v) == 0)
11248         return 0;       /* These are values from the history (e.g., $1).  */
11249       else if (VALUE_LVAL (v) == lval_register)
11250         return 0;       /* Cannot watch a register with a HW watchpoint.  */
11251     }
11252
11253   /* The expression itself looks suitable for using a hardware
11254      watchpoint, but give the target machine a chance to reject it.  */
11255   return found_memory_cnt;
11256 }
11257
11258 void
11259 watch_command_wrapper (char *arg, int from_tty, int internal)
11260 {
11261   watch_command_1 (arg, hw_write, from_tty, 0, internal);
11262 }
11263
11264 /* A helper function that looks for the "-location" argument and then
11265    calls watch_command_1.  */
11266
11267 static void
11268 watch_maybe_just_location (char *arg, int accessflag, int from_tty)
11269 {
11270   int just_location = 0;
11271
11272   if (arg
11273       && (check_for_argument (&arg, "-location", sizeof ("-location") - 1)
11274           || check_for_argument (&arg, "-l", sizeof ("-l") - 1)))
11275     {
11276       arg = skip_spaces (arg);
11277       just_location = 1;
11278     }
11279
11280   watch_command_1 (arg, accessflag, from_tty, just_location, 0);
11281 }
11282
11283 static void
11284 watch_command (char *arg, int from_tty)
11285 {
11286   watch_maybe_just_location (arg, hw_write, from_tty);
11287 }
11288
11289 void
11290 rwatch_command_wrapper (char *arg, int from_tty, int internal)
11291 {
11292   watch_command_1 (arg, hw_read, from_tty, 0, internal);
11293 }
11294
11295 static void
11296 rwatch_command (char *arg, int from_tty)
11297 {
11298   watch_maybe_just_location (arg, hw_read, from_tty);
11299 }
11300
11301 void
11302 awatch_command_wrapper (char *arg, int from_tty, int internal)
11303 {
11304   watch_command_1 (arg, hw_access, from_tty, 0, internal);
11305 }
11306
11307 static void
11308 awatch_command (char *arg, int from_tty)
11309 {
11310   watch_maybe_just_location (arg, hw_access, from_tty);
11311 }
11312 \f
11313
11314 /* Helper routines for the until_command routine in infcmd.c.  Here
11315    because it uses the mechanisms of breakpoints.  */
11316
11317 struct until_break_command_continuation_args
11318 {
11319   struct breakpoint *breakpoint;
11320   struct breakpoint *breakpoint2;
11321   int thread_num;
11322 };
11323
11324 /* This function is called by fetch_inferior_event via the
11325    cmd_continuation pointer, to complete the until command.  It takes
11326    care of cleaning up the temporary breakpoints set up by the until
11327    command.  */
11328 static void
11329 until_break_command_continuation (void *arg, int err)
11330 {
11331   struct until_break_command_continuation_args *a = arg;
11332
11333   delete_breakpoint (a->breakpoint);
11334   if (a->breakpoint2)
11335     delete_breakpoint (a->breakpoint2);
11336   delete_longjmp_breakpoint (a->thread_num);
11337 }
11338
11339 void
11340 until_break_command (char *arg, int from_tty, int anywhere)
11341 {
11342   struct symtabs_and_lines sals;
11343   struct symtab_and_line sal;
11344   struct frame_info *frame;
11345   struct gdbarch *frame_gdbarch;
11346   struct frame_id stack_frame_id;
11347   struct frame_id caller_frame_id;
11348   struct breakpoint *breakpoint;
11349   struct breakpoint *breakpoint2 = NULL;
11350   struct cleanup *old_chain;
11351   int thread;
11352   struct thread_info *tp;
11353
11354   clear_proceed_status ();
11355
11356   /* Set a breakpoint where the user wants it and at return from
11357      this function.  */
11358
11359   if (last_displayed_sal_is_valid ())
11360     sals = decode_line_1 (&arg, DECODE_LINE_FUNFIRSTLINE,
11361                           get_last_displayed_symtab (),
11362                           get_last_displayed_line ());
11363   else
11364     sals = decode_line_1 (&arg, DECODE_LINE_FUNFIRSTLINE,
11365                           (struct symtab *) NULL, 0);
11366
11367   if (sals.nelts != 1)
11368     error (_("Couldn't get information on specified line."));
11369
11370   sal = sals.sals[0];
11371   xfree (sals.sals);    /* malloc'd, so freed.  */
11372
11373   if (*arg)
11374     error (_("Junk at end of arguments."));
11375
11376   resolve_sal_pc (&sal);
11377
11378   tp = inferior_thread ();
11379   thread = tp->num;
11380
11381   old_chain = make_cleanup (null_cleanup, NULL);
11382
11383   /* Note linespec handling above invalidates the frame chain.
11384      Installing a breakpoint also invalidates the frame chain (as it
11385      may need to switch threads), so do any frame handling before
11386      that.  */
11387
11388   frame = get_selected_frame (NULL);
11389   frame_gdbarch = get_frame_arch (frame);
11390   stack_frame_id = get_stack_frame_id (frame);
11391   caller_frame_id = frame_unwind_caller_id (frame);
11392
11393   /* Keep within the current frame, or in frames called by the current
11394      one.  */
11395
11396   if (frame_id_p (caller_frame_id))
11397     {
11398       struct symtab_and_line sal2;
11399
11400       sal2 = find_pc_line (frame_unwind_caller_pc (frame), 0);
11401       sal2.pc = frame_unwind_caller_pc (frame);
11402       breakpoint2 = set_momentary_breakpoint (frame_unwind_caller_arch (frame),
11403                                               sal2,
11404                                               caller_frame_id,
11405                                               bp_until);
11406       make_cleanup_delete_breakpoint (breakpoint2);
11407
11408       set_longjmp_breakpoint (tp, caller_frame_id);
11409       make_cleanup (delete_longjmp_breakpoint_cleanup, &thread);
11410     }
11411
11412   /* set_momentary_breakpoint could invalidate FRAME.  */
11413   frame = NULL;
11414
11415   if (anywhere)
11416     /* If the user told us to continue until a specified location,
11417        we don't specify a frame at which we need to stop.  */
11418     breakpoint = set_momentary_breakpoint (frame_gdbarch, sal,
11419                                            null_frame_id, bp_until);
11420   else
11421     /* Otherwise, specify the selected frame, because we want to stop
11422        only at the very same frame.  */
11423     breakpoint = set_momentary_breakpoint (frame_gdbarch, sal,
11424                                            stack_frame_id, bp_until);
11425   make_cleanup_delete_breakpoint (breakpoint);
11426
11427   proceed (-1, GDB_SIGNAL_DEFAULT, 0);
11428
11429   /* If we are running asynchronously, and proceed call above has
11430      actually managed to start the target, arrange for breakpoints to
11431      be deleted when the target stops.  Otherwise, we're already
11432      stopped and delete breakpoints via cleanup chain.  */
11433
11434   if (target_can_async_p () && is_running (inferior_ptid))
11435     {
11436       struct until_break_command_continuation_args *args;
11437       args = xmalloc (sizeof (*args));
11438
11439       args->breakpoint = breakpoint;
11440       args->breakpoint2 = breakpoint2;
11441       args->thread_num = thread;
11442
11443       discard_cleanups (old_chain);
11444       add_continuation (inferior_thread (),
11445                         until_break_command_continuation, args,
11446                         xfree);
11447     }
11448   else
11449     do_cleanups (old_chain);
11450 }
11451
11452 /* This function attempts to parse an optional "if <cond>" clause
11453    from the arg string.  If one is not found, it returns NULL.
11454
11455    Else, it returns a pointer to the condition string.  (It does not
11456    attempt to evaluate the string against a particular block.)  And,
11457    it updates arg to point to the first character following the parsed
11458    if clause in the arg string.  */
11459
11460 static char *
11461 ep_parse_optional_if_clause (char **arg)
11462 {
11463   char *cond_string;
11464
11465   if (((*arg)[0] != 'i') || ((*arg)[1] != 'f') || !isspace ((*arg)[2]))
11466     return NULL;
11467
11468   /* Skip the "if" keyword.  */
11469   (*arg) += 2;
11470
11471   /* Skip any extra leading whitespace, and record the start of the
11472      condition string.  */
11473   *arg = skip_spaces (*arg);
11474   cond_string = *arg;
11475
11476   /* Assume that the condition occupies the remainder of the arg
11477      string.  */
11478   (*arg) += strlen (cond_string);
11479
11480   return cond_string;
11481 }
11482
11483 /* Commands to deal with catching events, such as signals, exceptions,
11484    process start/exit, etc.  */
11485
11486 typedef enum
11487 {
11488   catch_fork_temporary, catch_vfork_temporary,
11489   catch_fork_permanent, catch_vfork_permanent
11490 }
11491 catch_fork_kind;
11492
11493 static void
11494 catch_fork_command_1 (char *arg, int from_tty, 
11495                       struct cmd_list_element *command)
11496 {
11497   struct gdbarch *gdbarch = get_current_arch ();
11498   char *cond_string = NULL;
11499   catch_fork_kind fork_kind;
11500   int tempflag;
11501
11502   fork_kind = (catch_fork_kind) (uintptr_t) get_cmd_context (command);
11503   tempflag = (fork_kind == catch_fork_temporary
11504               || fork_kind == catch_vfork_temporary);
11505
11506   if (!arg)
11507     arg = "";
11508   arg = skip_spaces (arg);
11509
11510   /* The allowed syntax is:
11511      catch [v]fork
11512      catch [v]fork if <cond>
11513
11514      First, check if there's an if clause.  */
11515   cond_string = ep_parse_optional_if_clause (&arg);
11516
11517   if ((*arg != '\0') && !isspace (*arg))
11518     error (_("Junk at end of arguments."));
11519
11520   /* If this target supports it, create a fork or vfork catchpoint
11521      and enable reporting of such events.  */
11522   switch (fork_kind)
11523     {
11524     case catch_fork_temporary:
11525     case catch_fork_permanent:
11526       create_fork_vfork_event_catchpoint (gdbarch, tempflag, cond_string,
11527                                           &catch_fork_breakpoint_ops);
11528       break;
11529     case catch_vfork_temporary:
11530     case catch_vfork_permanent:
11531       create_fork_vfork_event_catchpoint (gdbarch, tempflag, cond_string,
11532                                           &catch_vfork_breakpoint_ops);
11533       break;
11534     default:
11535       error (_("unsupported or unknown fork kind; cannot catch it"));
11536       break;
11537     }
11538 }
11539
11540 static void
11541 catch_exec_command_1 (char *arg, int from_tty, 
11542                       struct cmd_list_element *command)
11543 {
11544   struct exec_catchpoint *c;
11545   struct gdbarch *gdbarch = get_current_arch ();
11546   int tempflag;
11547   char *cond_string = NULL;
11548
11549   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
11550
11551   if (!arg)
11552     arg = "";
11553   arg = skip_spaces (arg);
11554
11555   /* The allowed syntax is:
11556      catch exec
11557      catch exec if <cond>
11558
11559      First, check if there's an if clause.  */
11560   cond_string = ep_parse_optional_if_clause (&arg);
11561
11562   if ((*arg != '\0') && !isspace (*arg))
11563     error (_("Junk at end of arguments."));
11564
11565   c = XNEW (struct exec_catchpoint);
11566   init_catchpoint (&c->base, gdbarch, tempflag, cond_string,
11567                    &catch_exec_breakpoint_ops);
11568   c->exec_pathname = NULL;
11569
11570   install_breakpoint (0, &c->base, 1);
11571 }
11572
11573 static enum print_stop_action
11574 print_it_exception_catchpoint (bpstat bs)
11575 {
11576   struct ui_out *uiout = current_uiout;
11577   struct breakpoint *b = bs->breakpoint_at;
11578   int bp_temp, bp_throw;
11579
11580   annotate_catchpoint (b->number);
11581
11582   bp_throw = strstr (b->addr_string, "throw") != NULL;
11583   if (b->loc->address != b->loc->requested_address)
11584     breakpoint_adjustment_warning (b->loc->requested_address,
11585                                    b->loc->address,
11586                                    b->number, 1);
11587   bp_temp = b->disposition == disp_del;
11588   ui_out_text (uiout, 
11589                bp_temp ? "Temporary catchpoint "
11590                        : "Catchpoint ");
11591   if (!ui_out_is_mi_like_p (uiout))
11592     ui_out_field_int (uiout, "bkptno", b->number);
11593   ui_out_text (uiout,
11594                bp_throw ? " (exception thrown), "
11595                         : " (exception caught), ");
11596   if (ui_out_is_mi_like_p (uiout))
11597     {
11598       ui_out_field_string (uiout, "reason", 
11599                            async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
11600       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
11601       ui_out_field_int (uiout, "bkptno", b->number);
11602     }
11603   return PRINT_SRC_AND_LOC;
11604 }
11605
11606 static void
11607 print_one_exception_catchpoint (struct breakpoint *b, 
11608                                 struct bp_location **last_loc)
11609 {
11610   struct value_print_options opts;
11611   struct ui_out *uiout = current_uiout;
11612
11613   get_user_print_options (&opts);
11614   if (opts.addressprint)
11615     {
11616       annotate_field (4);
11617       if (b->loc == NULL || b->loc->shlib_disabled)
11618         ui_out_field_string (uiout, "addr", "<PENDING>");
11619       else
11620         ui_out_field_core_addr (uiout, "addr",
11621                                 b->loc->gdbarch, b->loc->address);
11622     }
11623   annotate_field (5);
11624   if (b->loc)
11625     *last_loc = b->loc;
11626   if (strstr (b->addr_string, "throw") != NULL)
11627     {
11628       ui_out_field_string (uiout, "what", "exception throw");
11629       if (ui_out_is_mi_like_p (uiout))
11630         ui_out_field_string (uiout, "catch-type", "throw");
11631     }
11632   else
11633     {
11634       ui_out_field_string (uiout, "what", "exception catch");
11635       if (ui_out_is_mi_like_p (uiout))
11636         ui_out_field_string (uiout, "catch-type", "catch");
11637     }
11638 }
11639
11640 static void
11641 print_mention_exception_catchpoint (struct breakpoint *b)
11642 {
11643   struct ui_out *uiout = current_uiout;
11644   int bp_temp;
11645   int bp_throw;
11646
11647   bp_temp = b->disposition == disp_del;
11648   bp_throw = strstr (b->addr_string, "throw") != NULL;
11649   ui_out_text (uiout, bp_temp ? _("Temporary catchpoint ")
11650                               : _("Catchpoint "));
11651   ui_out_field_int (uiout, "bkptno", b->number);
11652   ui_out_text (uiout, bp_throw ? _(" (throw)")
11653                                : _(" (catch)"));
11654 }
11655
11656 /* Implement the "print_recreate" breakpoint_ops method for throw and
11657    catch catchpoints.  */
11658
11659 static void
11660 print_recreate_exception_catchpoint (struct breakpoint *b, 
11661                                      struct ui_file *fp)
11662 {
11663   int bp_temp;
11664   int bp_throw;
11665
11666   bp_temp = b->disposition == disp_del;
11667   bp_throw = strstr (b->addr_string, "throw") != NULL;
11668   fprintf_unfiltered (fp, bp_temp ? "tcatch " : "catch ");
11669   fprintf_unfiltered (fp, bp_throw ? "throw" : "catch");
11670   print_recreate_thread (b, fp);
11671 }
11672
11673 static struct breakpoint_ops gnu_v3_exception_catchpoint_ops;
11674
11675 static int
11676 handle_gnu_v3_exceptions (int tempflag, char *cond_string,
11677                           enum exception_event_kind ex_event, int from_tty)
11678 {
11679   char *trigger_func_name;
11680  
11681   if (ex_event == EX_EVENT_CATCH)
11682     trigger_func_name = "__cxa_begin_catch";
11683   else
11684     trigger_func_name = "__cxa_throw";
11685
11686   create_breakpoint (get_current_arch (),
11687                      trigger_func_name, cond_string, -1, NULL,
11688                      0 /* condition and thread are valid.  */,
11689                      tempflag, bp_breakpoint,
11690                      0,
11691                      AUTO_BOOLEAN_TRUE /* pending */,
11692                      &gnu_v3_exception_catchpoint_ops, from_tty,
11693                      1 /* enabled */,
11694                      0 /* internal */,
11695                      0);
11696
11697   return 1;
11698 }
11699
11700 /* Deal with "catch catch" and "catch throw" commands.  */
11701
11702 static void
11703 catch_exception_command_1 (enum exception_event_kind ex_event, char *arg,
11704                            int tempflag, int from_tty)
11705 {
11706   char *cond_string = NULL;
11707
11708   if (!arg)
11709     arg = "";
11710   arg = skip_spaces (arg);
11711
11712   cond_string = ep_parse_optional_if_clause (&arg);
11713
11714   if ((*arg != '\0') && !isspace (*arg))
11715     error (_("Junk at end of arguments."));
11716
11717   if (ex_event != EX_EVENT_THROW
11718       && ex_event != EX_EVENT_CATCH)
11719     error (_("Unsupported or unknown exception event; cannot catch it"));
11720
11721   if (handle_gnu_v3_exceptions (tempflag, cond_string, ex_event, from_tty))
11722     return;
11723
11724   warning (_("Unsupported with this platform/compiler combination."));
11725 }
11726
11727 /* Implementation of "catch catch" command.  */
11728
11729 static void
11730 catch_catch_command (char *arg, int from_tty, struct cmd_list_element *command)
11731 {
11732   int tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
11733
11734   catch_exception_command_1 (EX_EVENT_CATCH, arg, tempflag, from_tty);
11735 }
11736
11737 /* Implementation of "catch throw" command.  */
11738
11739 static void
11740 catch_throw_command (char *arg, int from_tty, struct cmd_list_element *command)
11741 {
11742   int tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
11743
11744   catch_exception_command_1 (EX_EVENT_THROW, arg, tempflag, from_tty);
11745 }
11746
11747 void
11748 init_ada_exception_breakpoint (struct breakpoint *b,
11749                                struct gdbarch *gdbarch,
11750                                struct symtab_and_line sal,
11751                                char *addr_string,
11752                                const struct breakpoint_ops *ops,
11753                                int tempflag,
11754                                int from_tty)
11755 {
11756   if (from_tty)
11757     {
11758       struct gdbarch *loc_gdbarch = get_sal_arch (sal);
11759       if (!loc_gdbarch)
11760         loc_gdbarch = gdbarch;
11761
11762       describe_other_breakpoints (loc_gdbarch,
11763                                   sal.pspace, sal.pc, sal.section, -1);
11764       /* FIXME: brobecker/2006-12-28: Actually, re-implement a special
11765          version for exception catchpoints, because two catchpoints
11766          used for different exception names will use the same address.
11767          In this case, a "breakpoint ... also set at..." warning is
11768          unproductive.  Besides, the warning phrasing is also a bit
11769          inappropriate, we should use the word catchpoint, and tell
11770          the user what type of catchpoint it is.  The above is good
11771          enough for now, though.  */
11772     }
11773
11774   init_raw_breakpoint (b, gdbarch, sal, bp_breakpoint, ops);
11775
11776   b->enable_state = bp_enabled;
11777   b->disposition = tempflag ? disp_del : disp_donttouch;
11778   b->addr_string = addr_string;
11779   b->language = language_ada;
11780 }
11781
11782 /* Splits the argument using space as delimiter.  Returns an xmalloc'd
11783    filter list, or NULL if no filtering is required.  */
11784 static VEC(int) *
11785 catch_syscall_split_args (char *arg)
11786 {
11787   VEC(int) *result = NULL;
11788   struct cleanup *cleanup = make_cleanup (VEC_cleanup (int), &result);
11789
11790   while (*arg != '\0')
11791     {
11792       int i, syscall_number;
11793       char *endptr;
11794       char cur_name[128];
11795       struct syscall s;
11796
11797       /* Skip whitespace.  */
11798       arg = skip_spaces (arg);
11799
11800       for (i = 0; i < 127 && arg[i] && !isspace (arg[i]); ++i)
11801         cur_name[i] = arg[i];
11802       cur_name[i] = '\0';
11803       arg += i;
11804
11805       /* Check if the user provided a syscall name or a number.  */
11806       syscall_number = (int) strtol (cur_name, &endptr, 0);
11807       if (*endptr == '\0')
11808         get_syscall_by_number (syscall_number, &s);
11809       else
11810         {
11811           /* We have a name.  Let's check if it's valid and convert it
11812              to a number.  */
11813           get_syscall_by_name (cur_name, &s);
11814
11815           if (s.number == UNKNOWN_SYSCALL)
11816             /* Here we have to issue an error instead of a warning,
11817                because GDB cannot do anything useful if there's no
11818                syscall number to be caught.  */
11819             error (_("Unknown syscall name '%s'."), cur_name);
11820         }
11821
11822       /* Ok, it's valid.  */
11823       VEC_safe_push (int, result, s.number);
11824     }
11825
11826   discard_cleanups (cleanup);
11827   return result;
11828 }
11829
11830 /* Implement the "catch syscall" command.  */
11831
11832 static void
11833 catch_syscall_command_1 (char *arg, int from_tty, 
11834                          struct cmd_list_element *command)
11835 {
11836   int tempflag;
11837   VEC(int) *filter;
11838   struct syscall s;
11839   struct gdbarch *gdbarch = get_current_arch ();
11840
11841   /* Checking if the feature if supported.  */
11842   if (gdbarch_get_syscall_number_p (gdbarch) == 0)
11843     error (_("The feature 'catch syscall' is not supported on \
11844 this architecture yet."));
11845
11846   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
11847
11848   arg = skip_spaces (arg);
11849
11850   /* We need to do this first "dummy" translation in order
11851      to get the syscall XML file loaded or, most important,
11852      to display a warning to the user if there's no XML file
11853      for his/her architecture.  */
11854   get_syscall_by_number (0, &s);
11855
11856   /* The allowed syntax is:
11857      catch syscall
11858      catch syscall <name | number> [<name | number> ... <name | number>]
11859
11860      Let's check if there's a syscall name.  */
11861
11862   if (arg != NULL)
11863     filter = catch_syscall_split_args (arg);
11864   else
11865     filter = NULL;
11866
11867   create_syscall_event_catchpoint (tempflag, filter,
11868                                    &catch_syscall_breakpoint_ops);
11869 }
11870
11871 static void
11872 catch_command (char *arg, int from_tty)
11873 {
11874   error (_("Catch requires an event name."));
11875 }
11876 \f
11877
11878 static void
11879 tcatch_command (char *arg, int from_tty)
11880 {
11881   error (_("Catch requires an event name."));
11882 }
11883
11884 /* A qsort comparison function that sorts breakpoints in order.  */
11885
11886 static int
11887 compare_breakpoints (const void *a, const void *b)
11888 {
11889   const breakpoint_p *ba = a;
11890   uintptr_t ua = (uintptr_t) *ba;
11891   const breakpoint_p *bb = b;
11892   uintptr_t ub = (uintptr_t) *bb;
11893
11894   if ((*ba)->number < (*bb)->number)
11895     return -1;
11896   else if ((*ba)->number > (*bb)->number)
11897     return 1;
11898
11899   /* Now sort by address, in case we see, e..g, two breakpoints with
11900      the number 0.  */
11901   if (ua < ub)
11902     return -1;
11903   return ua > ub ? 1 : 0;
11904 }
11905
11906 /* Delete breakpoints by address or line.  */
11907
11908 static void
11909 clear_command (char *arg, int from_tty)
11910 {
11911   struct breakpoint *b, *prev;
11912   VEC(breakpoint_p) *found = 0;
11913   int ix;
11914   int default_match;
11915   struct symtabs_and_lines sals;
11916   struct symtab_and_line sal;
11917   int i;
11918   struct cleanup *cleanups = make_cleanup (null_cleanup, NULL);
11919
11920   if (arg)
11921     {
11922       sals = decode_line_with_current_source (arg,
11923                                               (DECODE_LINE_FUNFIRSTLINE
11924                                                | DECODE_LINE_LIST_MODE));
11925       make_cleanup (xfree, sals.sals);
11926       default_match = 0;
11927     }
11928   else
11929     {
11930       sals.sals = (struct symtab_and_line *)
11931         xmalloc (sizeof (struct symtab_and_line));
11932       make_cleanup (xfree, sals.sals);
11933       init_sal (&sal);          /* Initialize to zeroes.  */
11934
11935       /* Set sal's line, symtab, pc, and pspace to the values
11936          corresponding to the last call to print_frame_info.  If the
11937          codepoint is not valid, this will set all the fields to 0.  */
11938       get_last_displayed_sal (&sal);
11939       if (sal.symtab == 0)
11940         error (_("No source file specified."));
11941
11942       sals.sals[0] = sal;
11943       sals.nelts = 1;
11944
11945       default_match = 1;
11946     }
11947
11948   /* We don't call resolve_sal_pc here.  That's not as bad as it
11949      seems, because all existing breakpoints typically have both
11950      file/line and pc set.  So, if clear is given file/line, we can
11951      match this to existing breakpoint without obtaining pc at all.
11952
11953      We only support clearing given the address explicitly 
11954      present in breakpoint table.  Say, we've set breakpoint 
11955      at file:line.  There were several PC values for that file:line,
11956      due to optimization, all in one block.
11957
11958      We've picked one PC value.  If "clear" is issued with another
11959      PC corresponding to the same file:line, the breakpoint won't
11960      be cleared.  We probably can still clear the breakpoint, but 
11961      since the other PC value is never presented to user, user
11962      can only find it by guessing, and it does not seem important
11963      to support that.  */
11964
11965   /* For each line spec given, delete bps which correspond to it.  Do
11966      it in two passes, solely to preserve the current behavior that
11967      from_tty is forced true if we delete more than one
11968      breakpoint.  */
11969
11970   found = NULL;
11971   make_cleanup (VEC_cleanup (breakpoint_p), &found);
11972   for (i = 0; i < sals.nelts; i++)
11973     {
11974       const char *sal_fullname;
11975
11976       /* If exact pc given, clear bpts at that pc.
11977          If line given (pc == 0), clear all bpts on specified line.
11978          If defaulting, clear all bpts on default line
11979          or at default pc.
11980
11981          defaulting    sal.pc != 0    tests to do
11982
11983          0              1             pc
11984          1              1             pc _and_ line
11985          0              0             line
11986          1              0             <can't happen> */
11987
11988       sal = sals.sals[i];
11989       sal_fullname = (sal.symtab == NULL
11990                       ? NULL : symtab_to_fullname (sal.symtab));
11991
11992       /* Find all matching breakpoints and add them to 'found'.  */
11993       ALL_BREAKPOINTS (b)
11994         {
11995           int match = 0;
11996           /* Are we going to delete b?  */
11997           if (b->type != bp_none && !is_watchpoint (b))
11998             {
11999               struct bp_location *loc = b->loc;
12000               for (; loc; loc = loc->next)
12001                 {
12002                   /* If the user specified file:line, don't allow a PC
12003                      match.  This matches historical gdb behavior.  */
12004                   int pc_match = (!sal.explicit_line
12005                                   && sal.pc
12006                                   && (loc->pspace == sal.pspace)
12007                                   && (loc->address == sal.pc)
12008                                   && (!section_is_overlay (loc->section)
12009                                       || loc->section == sal.section));
12010                   int line_match = 0;
12011
12012                   if ((default_match || sal.explicit_line)
12013                       && loc->symtab != NULL
12014                       && sal_fullname != NULL
12015                       && sal.pspace == loc->pspace
12016                       && loc->line_number == sal.line
12017                       && filename_cmp (symtab_to_fullname (loc->symtab),
12018                                        sal_fullname) == 0)
12019                     line_match = 1;
12020
12021                   if (pc_match || line_match)
12022                     {
12023                       match = 1;
12024                       break;
12025                     }
12026                 }
12027             }
12028
12029           if (match)
12030             VEC_safe_push(breakpoint_p, found, b);
12031         }
12032     }
12033
12034   /* Now go thru the 'found' chain and delete them.  */
12035   if (VEC_empty(breakpoint_p, found))
12036     {
12037       if (arg)
12038         error (_("No breakpoint at %s."), arg);
12039       else
12040         error (_("No breakpoint at this line."));
12041     }
12042
12043   /* Remove duplicates from the vec.  */
12044   qsort (VEC_address (breakpoint_p, found),
12045          VEC_length (breakpoint_p, found),
12046          sizeof (breakpoint_p),
12047          compare_breakpoints);
12048   prev = VEC_index (breakpoint_p, found, 0);
12049   for (ix = 1; VEC_iterate (breakpoint_p, found, ix, b); ++ix)
12050     {
12051       if (b == prev)
12052         {
12053           VEC_ordered_remove (breakpoint_p, found, ix);
12054           --ix;
12055         }
12056     }
12057
12058   if (VEC_length(breakpoint_p, found) > 1)
12059     from_tty = 1;       /* Always report if deleted more than one.  */
12060   if (from_tty)
12061     {
12062       if (VEC_length(breakpoint_p, found) == 1)
12063         printf_unfiltered (_("Deleted breakpoint "));
12064       else
12065         printf_unfiltered (_("Deleted breakpoints "));
12066     }
12067
12068   for (ix = 0; VEC_iterate(breakpoint_p, found, ix, b); ix++)
12069     {
12070       if (from_tty)
12071         printf_unfiltered ("%d ", b->number);
12072       delete_breakpoint (b);
12073     }
12074   if (from_tty)
12075     putchar_unfiltered ('\n');
12076
12077   do_cleanups (cleanups);
12078 }
12079 \f
12080 /* Delete breakpoint in BS if they are `delete' breakpoints and
12081    all breakpoints that are marked for deletion, whether hit or not.
12082    This is called after any breakpoint is hit, or after errors.  */
12083
12084 void
12085 breakpoint_auto_delete (bpstat bs)
12086 {
12087   struct breakpoint *b, *b_tmp;
12088
12089   for (; bs; bs = bs->next)
12090     if (bs->breakpoint_at
12091         && bs->breakpoint_at->disposition == disp_del
12092         && bs->stop)
12093       delete_breakpoint (bs->breakpoint_at);
12094
12095   ALL_BREAKPOINTS_SAFE (b, b_tmp)
12096   {
12097     if (b->disposition == disp_del_at_next_stop)
12098       delete_breakpoint (b);
12099   }
12100 }
12101
12102 /* A comparison function for bp_location AP and BP being interfaced to
12103    qsort.  Sort elements primarily by their ADDRESS (no matter what
12104    does breakpoint_address_is_meaningful say for its OWNER),
12105    secondarily by ordering first bp_permanent OWNERed elements and
12106    terciarily just ensuring the array is sorted stable way despite
12107    qsort being an unstable algorithm.  */
12108
12109 static int
12110 bp_location_compare (const void *ap, const void *bp)
12111 {
12112   struct bp_location *a = *(void **) ap;
12113   struct bp_location *b = *(void **) bp;
12114   /* A and B come from existing breakpoints having non-NULL OWNER.  */
12115   int a_perm = a->owner->enable_state == bp_permanent;
12116   int b_perm = b->owner->enable_state == bp_permanent;
12117
12118   if (a->address != b->address)
12119     return (a->address > b->address) - (a->address < b->address);
12120
12121   /* Sort locations at the same address by their pspace number, keeping
12122      locations of the same inferior (in a multi-inferior environment)
12123      grouped.  */
12124
12125   if (a->pspace->num != b->pspace->num)
12126     return ((a->pspace->num > b->pspace->num)
12127             - (a->pspace->num < b->pspace->num));
12128
12129   /* Sort permanent breakpoints first.  */
12130   if (a_perm != b_perm)
12131     return (a_perm < b_perm) - (a_perm > b_perm);
12132
12133   /* Make the internal GDB representation stable across GDB runs
12134      where A and B memory inside GDB can differ.  Breakpoint locations of
12135      the same type at the same address can be sorted in arbitrary order.  */
12136
12137   if (a->owner->number != b->owner->number)
12138     return ((a->owner->number > b->owner->number)
12139             - (a->owner->number < b->owner->number));
12140
12141   return (a > b) - (a < b);
12142 }
12143
12144 /* Set bp_location_placed_address_before_address_max and
12145    bp_location_shadow_len_after_address_max according to the current
12146    content of the bp_location array.  */
12147
12148 static void
12149 bp_location_target_extensions_update (void)
12150 {
12151   struct bp_location *bl, **blp_tmp;
12152
12153   bp_location_placed_address_before_address_max = 0;
12154   bp_location_shadow_len_after_address_max = 0;
12155
12156   ALL_BP_LOCATIONS (bl, blp_tmp)
12157     {
12158       CORE_ADDR start, end, addr;
12159
12160       if (!bp_location_has_shadow (bl))
12161         continue;
12162
12163       start = bl->target_info.placed_address;
12164       end = start + bl->target_info.shadow_len;
12165
12166       gdb_assert (bl->address >= start);
12167       addr = bl->address - start;
12168       if (addr > bp_location_placed_address_before_address_max)
12169         bp_location_placed_address_before_address_max = addr;
12170
12171       /* Zero SHADOW_LEN would not pass bp_location_has_shadow.  */
12172
12173       gdb_assert (bl->address < end);
12174       addr = end - bl->address;
12175       if (addr > bp_location_shadow_len_after_address_max)
12176         bp_location_shadow_len_after_address_max = addr;
12177     }
12178 }
12179
12180 /* Download tracepoint locations if they haven't been.  */
12181
12182 static void
12183 download_tracepoint_locations (void)
12184 {
12185   struct breakpoint *b;
12186   struct cleanup *old_chain;
12187
12188   if (!target_can_download_tracepoint ())
12189     return;
12190
12191   old_chain = save_current_space_and_thread ();
12192
12193   ALL_TRACEPOINTS (b)
12194     {
12195       struct bp_location *bl;
12196       struct tracepoint *t;
12197       int bp_location_downloaded = 0;
12198
12199       if ((b->type == bp_fast_tracepoint
12200            ? !may_insert_fast_tracepoints
12201            : !may_insert_tracepoints))
12202         continue;
12203
12204       for (bl = b->loc; bl; bl = bl->next)
12205         {
12206           /* In tracepoint, locations are _never_ duplicated, so
12207              should_be_inserted is equivalent to
12208              unduplicated_should_be_inserted.  */
12209           if (!should_be_inserted (bl) || bl->inserted)
12210             continue;
12211
12212           switch_to_program_space_and_thread (bl->pspace);
12213
12214           target_download_tracepoint (bl);
12215
12216           bl->inserted = 1;
12217           bp_location_downloaded = 1;
12218         }
12219       t = (struct tracepoint *) b;
12220       t->number_on_target = b->number;
12221       if (bp_location_downloaded)
12222         observer_notify_breakpoint_modified (b);
12223     }
12224
12225   do_cleanups (old_chain);
12226 }
12227
12228 /* Swap the insertion/duplication state between two locations.  */
12229
12230 static void
12231 swap_insertion (struct bp_location *left, struct bp_location *right)
12232 {
12233   const int left_inserted = left->inserted;
12234   const int left_duplicate = left->duplicate;
12235   const int left_needs_update = left->needs_update;
12236   const struct bp_target_info left_target_info = left->target_info;
12237
12238   /* Locations of tracepoints can never be duplicated.  */
12239   if (is_tracepoint (left->owner))
12240     gdb_assert (!left->duplicate);
12241   if (is_tracepoint (right->owner))
12242     gdb_assert (!right->duplicate);
12243
12244   left->inserted = right->inserted;
12245   left->duplicate = right->duplicate;
12246   left->needs_update = right->needs_update;
12247   left->target_info = right->target_info;
12248   right->inserted = left_inserted;
12249   right->duplicate = left_duplicate;
12250   right->needs_update = left_needs_update;
12251   right->target_info = left_target_info;
12252 }
12253
12254 /* Force the re-insertion of the locations at ADDRESS.  This is called
12255    once a new/deleted/modified duplicate location is found and we are evaluating
12256    conditions on the target's side.  Such conditions need to be updated on
12257    the target.  */
12258
12259 static void
12260 force_breakpoint_reinsertion (struct bp_location *bl)
12261 {
12262   struct bp_location **locp = NULL, **loc2p;
12263   struct bp_location *loc;
12264   CORE_ADDR address = 0;
12265   int pspace_num;
12266
12267   address = bl->address;
12268   pspace_num = bl->pspace->num;
12269
12270   /* This is only meaningful if the target is
12271      evaluating conditions and if the user has
12272      opted for condition evaluation on the target's
12273      side.  */
12274   if (gdb_evaluates_breakpoint_condition_p ()
12275       || !target_supports_evaluation_of_breakpoint_conditions ())
12276     return;
12277
12278   /* Flag all breakpoint locations with this address and
12279      the same program space as the location
12280      as "its condition has changed".  We need to
12281      update the conditions on the target's side.  */
12282   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, address)
12283     {
12284       loc = *loc2p;
12285
12286       if (!is_breakpoint (loc->owner)
12287           || pspace_num != loc->pspace->num)
12288         continue;
12289
12290       /* Flag the location appropriately.  We use a different state to
12291          let everyone know that we already updated the set of locations
12292          with addr bl->address and program space bl->pspace.  This is so
12293          we don't have to keep calling these functions just to mark locations
12294          that have already been marked.  */
12295       loc->condition_changed = condition_updated;
12296
12297       /* Free the agent expression bytecode as well.  We will compute
12298          it later on.  */
12299       if (loc->cond_bytecode)
12300         {
12301           free_agent_expr (loc->cond_bytecode);
12302           loc->cond_bytecode = NULL;
12303         }
12304     }
12305 }
12306
12307 /* If SHOULD_INSERT is false, do not insert any breakpoint locations
12308    into the inferior, only remove already-inserted locations that no
12309    longer should be inserted.  Functions that delete a breakpoint or
12310    breakpoints should pass false, so that deleting a breakpoint
12311    doesn't have the side effect of inserting the locations of other
12312    breakpoints that are marked not-inserted, but should_be_inserted
12313    returns true on them.
12314
12315    This behaviour is useful is situations close to tear-down -- e.g.,
12316    after an exec, while the target still has execution, but breakpoint
12317    shadows of the previous executable image should *NOT* be restored
12318    to the new image; or before detaching, where the target still has
12319    execution and wants to delete breakpoints from GDB's lists, and all
12320    breakpoints had already been removed from the inferior.  */
12321
12322 static void
12323 update_global_location_list (int should_insert)
12324 {
12325   struct breakpoint *b;
12326   struct bp_location **locp, *loc;
12327   struct cleanup *cleanups;
12328   /* Last breakpoint location address that was marked for update.  */
12329   CORE_ADDR last_addr = 0;
12330   /* Last breakpoint location program space that was marked for update.  */
12331   int last_pspace_num = -1;
12332
12333   /* Used in the duplicates detection below.  When iterating over all
12334      bp_locations, points to the first bp_location of a given address.
12335      Breakpoints and watchpoints of different types are never
12336      duplicates of each other.  Keep one pointer for each type of
12337      breakpoint/watchpoint, so we only need to loop over all locations
12338      once.  */
12339   struct bp_location *bp_loc_first;  /* breakpoint */
12340   struct bp_location *wp_loc_first;  /* hardware watchpoint */
12341   struct bp_location *awp_loc_first; /* access watchpoint */
12342   struct bp_location *rwp_loc_first; /* read watchpoint */
12343
12344   /* Saved former bp_location array which we compare against the newly
12345      built bp_location from the current state of ALL_BREAKPOINTS.  */
12346   struct bp_location **old_location, **old_locp;
12347   unsigned old_location_count;
12348
12349   old_location = bp_location;
12350   old_location_count = bp_location_count;
12351   bp_location = NULL;
12352   bp_location_count = 0;
12353   cleanups = make_cleanup (xfree, old_location);
12354
12355   ALL_BREAKPOINTS (b)
12356     for (loc = b->loc; loc; loc = loc->next)
12357       bp_location_count++;
12358
12359   bp_location = xmalloc (sizeof (*bp_location) * bp_location_count);
12360   locp = bp_location;
12361   ALL_BREAKPOINTS (b)
12362     for (loc = b->loc; loc; loc = loc->next)
12363       *locp++ = loc;
12364   qsort (bp_location, bp_location_count, sizeof (*bp_location),
12365          bp_location_compare);
12366
12367   bp_location_target_extensions_update ();
12368
12369   /* Identify bp_location instances that are no longer present in the
12370      new list, and therefore should be freed.  Note that it's not
12371      necessary that those locations should be removed from inferior --
12372      if there's another location at the same address (previously
12373      marked as duplicate), we don't need to remove/insert the
12374      location.
12375      
12376      LOCP is kept in sync with OLD_LOCP, each pointing to the current
12377      and former bp_location array state respectively.  */
12378
12379   locp = bp_location;
12380   for (old_locp = old_location; old_locp < old_location + old_location_count;
12381        old_locp++)
12382     {
12383       struct bp_location *old_loc = *old_locp;
12384       struct bp_location **loc2p;
12385
12386       /* Tells if 'old_loc' is found among the new locations.  If
12387          not, we have to free it.  */
12388       int found_object = 0;
12389       /* Tells if the location should remain inserted in the target.  */
12390       int keep_in_target = 0;
12391       int removed = 0;
12392
12393       /* Skip LOCP entries which will definitely never be needed.
12394          Stop either at or being the one matching OLD_LOC.  */
12395       while (locp < bp_location + bp_location_count
12396              && (*locp)->address < old_loc->address)
12397         locp++;
12398
12399       for (loc2p = locp;
12400            (loc2p < bp_location + bp_location_count
12401             && (*loc2p)->address == old_loc->address);
12402            loc2p++)
12403         {
12404           /* Check if this is a new/duplicated location or a duplicated
12405              location that had its condition modified.  If so, we want to send
12406              its condition to the target if evaluation of conditions is taking
12407              place there.  */
12408           if ((*loc2p)->condition_changed == condition_modified
12409               && (last_addr != old_loc->address
12410                   || last_pspace_num != old_loc->pspace->num))
12411             {
12412               force_breakpoint_reinsertion (*loc2p);
12413               last_pspace_num = old_loc->pspace->num;
12414             }
12415
12416           if (*loc2p == old_loc)
12417             found_object = 1;
12418         }
12419
12420       /* We have already handled this address, update it so that we don't
12421          have to go through updates again.  */
12422       last_addr = old_loc->address;
12423
12424       /* Target-side condition evaluation: Handle deleted locations.  */
12425       if (!found_object)
12426         force_breakpoint_reinsertion (old_loc);
12427
12428       /* If this location is no longer present, and inserted, look if
12429          there's maybe a new location at the same address.  If so,
12430          mark that one inserted, and don't remove this one.  This is
12431          needed so that we don't have a time window where a breakpoint
12432          at certain location is not inserted.  */
12433
12434       if (old_loc->inserted)
12435         {
12436           /* If the location is inserted now, we might have to remove
12437              it.  */
12438
12439           if (found_object && should_be_inserted (old_loc))
12440             {
12441               /* The location is still present in the location list,
12442                  and still should be inserted.  Don't do anything.  */
12443               keep_in_target = 1;
12444             }
12445           else
12446             {
12447               /* This location still exists, but it won't be kept in the
12448                  target since it may have been disabled.  We proceed to
12449                  remove its target-side condition.  */
12450
12451               /* The location is either no longer present, or got
12452                  disabled.  See if there's another location at the
12453                  same address, in which case we don't need to remove
12454                  this one from the target.  */
12455
12456               /* OLD_LOC comes from existing struct breakpoint.  */
12457               if (breakpoint_address_is_meaningful (old_loc->owner))
12458                 {
12459                   for (loc2p = locp;
12460                        (loc2p < bp_location + bp_location_count
12461                         && (*loc2p)->address == old_loc->address);
12462                        loc2p++)
12463                     {
12464                       struct bp_location *loc2 = *loc2p;
12465
12466                       if (breakpoint_locations_match (loc2, old_loc))
12467                         {
12468                           /* Read watchpoint locations are switched to
12469                              access watchpoints, if the former are not
12470                              supported, but the latter are.  */
12471                           if (is_hardware_watchpoint (old_loc->owner))
12472                             {
12473                               gdb_assert (is_hardware_watchpoint (loc2->owner));
12474                               loc2->watchpoint_type = old_loc->watchpoint_type;
12475                             }
12476
12477                           /* loc2 is a duplicated location. We need to check
12478                              if it should be inserted in case it will be
12479                              unduplicated.  */
12480                           if (loc2 != old_loc
12481                               && unduplicated_should_be_inserted (loc2))
12482                             {
12483                               swap_insertion (old_loc, loc2);
12484                               keep_in_target = 1;
12485                               break;
12486                             }
12487                         }
12488                     }
12489                 }
12490             }
12491
12492           if (!keep_in_target)
12493             {
12494               if (remove_breakpoint (old_loc, mark_uninserted))
12495                 {
12496                   /* This is just about all we can do.  We could keep
12497                      this location on the global list, and try to
12498                      remove it next time, but there's no particular
12499                      reason why we will succeed next time.
12500                      
12501                      Note that at this point, old_loc->owner is still
12502                      valid, as delete_breakpoint frees the breakpoint
12503                      only after calling us.  */
12504                   printf_filtered (_("warning: Error removing "
12505                                      "breakpoint %d\n"), 
12506                                    old_loc->owner->number);
12507                 }
12508               removed = 1;
12509             }
12510         }
12511
12512       if (!found_object)
12513         {
12514           if (removed && non_stop
12515               && breakpoint_address_is_meaningful (old_loc->owner)
12516               && !is_hardware_watchpoint (old_loc->owner))
12517             {
12518               /* This location was removed from the target.  In
12519                  non-stop mode, a race condition is possible where
12520                  we've removed a breakpoint, but stop events for that
12521                  breakpoint are already queued and will arrive later.
12522                  We apply an heuristic to be able to distinguish such
12523                  SIGTRAPs from other random SIGTRAPs: we keep this
12524                  breakpoint location for a bit, and will retire it
12525                  after we see some number of events.  The theory here
12526                  is that reporting of events should, "on the average",
12527                  be fair, so after a while we'll see events from all
12528                  threads that have anything of interest, and no longer
12529                  need to keep this breakpoint location around.  We
12530                  don't hold locations forever so to reduce chances of
12531                  mistaking a non-breakpoint SIGTRAP for a breakpoint
12532                  SIGTRAP.
12533
12534                  The heuristic failing can be disastrous on
12535                  decr_pc_after_break targets.
12536
12537                  On decr_pc_after_break targets, like e.g., x86-linux,
12538                  if we fail to recognize a late breakpoint SIGTRAP,
12539                  because events_till_retirement has reached 0 too
12540                  soon, we'll fail to do the PC adjustment, and report
12541                  a random SIGTRAP to the user.  When the user resumes
12542                  the inferior, it will most likely immediately crash
12543                  with SIGILL/SIGBUS/SIGSEGV, or worse, get silently
12544                  corrupted, because of being resumed e.g., in the
12545                  middle of a multi-byte instruction, or skipped a
12546                  one-byte instruction.  This was actually seen happen
12547                  on native x86-linux, and should be less rare on
12548                  targets that do not support new thread events, like
12549                  remote, due to the heuristic depending on
12550                  thread_count.
12551
12552                  Mistaking a random SIGTRAP for a breakpoint trap
12553                  causes similar symptoms (PC adjustment applied when
12554                  it shouldn't), but then again, playing with SIGTRAPs
12555                  behind the debugger's back is asking for trouble.
12556
12557                  Since hardware watchpoint traps are always
12558                  distinguishable from other traps, so we don't need to
12559                  apply keep hardware watchpoint moribund locations
12560                  around.  We simply always ignore hardware watchpoint
12561                  traps we can no longer explain.  */
12562
12563               old_loc->events_till_retirement = 3 * (thread_count () + 1);
12564               old_loc->owner = NULL;
12565
12566               VEC_safe_push (bp_location_p, moribund_locations, old_loc);
12567             }
12568           else
12569             {
12570               old_loc->owner = NULL;
12571               decref_bp_location (&old_loc);
12572             }
12573         }
12574     }
12575
12576   /* Rescan breakpoints at the same address and section, marking the
12577      first one as "first" and any others as "duplicates".  This is so
12578      that the bpt instruction is only inserted once.  If we have a
12579      permanent breakpoint at the same place as BPT, make that one the
12580      official one, and the rest as duplicates.  Permanent breakpoints
12581      are sorted first for the same address.
12582
12583      Do the same for hardware watchpoints, but also considering the
12584      watchpoint's type (regular/access/read) and length.  */
12585
12586   bp_loc_first = NULL;
12587   wp_loc_first = NULL;
12588   awp_loc_first = NULL;
12589   rwp_loc_first = NULL;
12590   ALL_BP_LOCATIONS (loc, locp)
12591     {
12592       /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always
12593          non-NULL.  */
12594       struct bp_location **loc_first_p;
12595       b = loc->owner;
12596
12597       if (!unduplicated_should_be_inserted (loc)
12598           || !breakpoint_address_is_meaningful (b)
12599           /* Don't detect duplicate for tracepoint locations because they are
12600            never duplicated.  See the comments in field `duplicate' of
12601            `struct bp_location'.  */
12602           || is_tracepoint (b))
12603         {
12604           /* Clear the condition modification flag.  */
12605           loc->condition_changed = condition_unchanged;
12606           continue;
12607         }
12608
12609       /* Permanent breakpoint should always be inserted.  */
12610       if (b->enable_state == bp_permanent && ! loc->inserted)
12611         internal_error (__FILE__, __LINE__,
12612                         _("allegedly permanent breakpoint is not "
12613                         "actually inserted"));
12614
12615       if (b->type == bp_hardware_watchpoint)
12616         loc_first_p = &wp_loc_first;
12617       else if (b->type == bp_read_watchpoint)
12618         loc_first_p = &rwp_loc_first;
12619       else if (b->type == bp_access_watchpoint)
12620         loc_first_p = &awp_loc_first;
12621       else
12622         loc_first_p = &bp_loc_first;
12623
12624       if (*loc_first_p == NULL
12625           || (overlay_debugging && loc->section != (*loc_first_p)->section)
12626           || !breakpoint_locations_match (loc, *loc_first_p))
12627         {
12628           *loc_first_p = loc;
12629           loc->duplicate = 0;
12630
12631           if (is_breakpoint (loc->owner) && loc->condition_changed)
12632             {
12633               loc->needs_update = 1;
12634               /* Clear the condition modification flag.  */
12635               loc->condition_changed = condition_unchanged;
12636             }
12637           continue;
12638         }
12639
12640
12641       /* This and the above ensure the invariant that the first location
12642          is not duplicated, and is the inserted one.
12643          All following are marked as duplicated, and are not inserted.  */
12644       if (loc->inserted)
12645         swap_insertion (loc, *loc_first_p);
12646       loc->duplicate = 1;
12647
12648       /* Clear the condition modification flag.  */
12649       loc->condition_changed = condition_unchanged;
12650
12651       if ((*loc_first_p)->owner->enable_state == bp_permanent && loc->inserted
12652           && b->enable_state != bp_permanent)
12653         internal_error (__FILE__, __LINE__,
12654                         _("another breakpoint was inserted on top of "
12655                         "a permanent breakpoint"));
12656     }
12657
12658   if (breakpoints_always_inserted_mode ()
12659       && (have_live_inferiors ()
12660           || (gdbarch_has_global_breakpoints (target_gdbarch ()))))
12661     {
12662       if (should_insert)
12663         insert_breakpoint_locations ();
12664       else
12665         {
12666           /* Though should_insert is false, we may need to update conditions
12667              on the target's side if it is evaluating such conditions.  We
12668              only update conditions for locations that are marked
12669              "needs_update".  */
12670           update_inserted_breakpoint_locations ();
12671         }
12672     }
12673
12674   if (should_insert)
12675     download_tracepoint_locations ();
12676
12677   do_cleanups (cleanups);
12678 }
12679
12680 void
12681 breakpoint_retire_moribund (void)
12682 {
12683   struct bp_location *loc;
12684   int ix;
12685
12686   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
12687     if (--(loc->events_till_retirement) == 0)
12688       {
12689         decref_bp_location (&loc);
12690         VEC_unordered_remove (bp_location_p, moribund_locations, ix);
12691         --ix;
12692       }
12693 }
12694
12695 static void
12696 update_global_location_list_nothrow (int inserting)
12697 {
12698   volatile struct gdb_exception e;
12699
12700   TRY_CATCH (e, RETURN_MASK_ERROR)
12701     update_global_location_list (inserting);
12702 }
12703
12704 /* Clear BKP from a BPS.  */
12705
12706 static void
12707 bpstat_remove_bp_location (bpstat bps, struct breakpoint *bpt)
12708 {
12709   bpstat bs;
12710
12711   for (bs = bps; bs; bs = bs->next)
12712     if (bs->breakpoint_at == bpt)
12713       {
12714         bs->breakpoint_at = NULL;
12715         bs->old_val = NULL;
12716         /* bs->commands will be freed later.  */
12717       }
12718 }
12719
12720 /* Callback for iterate_over_threads.  */
12721 static int
12722 bpstat_remove_breakpoint_callback (struct thread_info *th, void *data)
12723 {
12724   struct breakpoint *bpt = data;
12725
12726   bpstat_remove_bp_location (th->control.stop_bpstat, bpt);
12727   return 0;
12728 }
12729
12730 /* Helper for breakpoint and tracepoint breakpoint_ops->mention
12731    callbacks.  */
12732
12733 static void
12734 say_where (struct breakpoint *b)
12735 {
12736   struct value_print_options opts;
12737
12738   get_user_print_options (&opts);
12739
12740   /* i18n: cagney/2005-02-11: Below needs to be merged into a
12741      single string.  */
12742   if (b->loc == NULL)
12743     {
12744       printf_filtered (_(" (%s) pending."), b->addr_string);
12745     }
12746   else
12747     {
12748       if (opts.addressprint || b->loc->symtab == NULL)
12749         {
12750           printf_filtered (" at ");
12751           fputs_filtered (paddress (b->loc->gdbarch, b->loc->address),
12752                           gdb_stdout);
12753         }
12754       if (b->loc->symtab != NULL)
12755         {
12756           /* If there is a single location, we can print the location
12757              more nicely.  */
12758           if (b->loc->next == NULL)
12759             printf_filtered (": file %s, line %d.",
12760                              symtab_to_filename_for_display (b->loc->symtab),
12761                              b->loc->line_number);
12762           else
12763             /* This is not ideal, but each location may have a
12764                different file name, and this at least reflects the
12765                real situation somewhat.  */
12766             printf_filtered (": %s.", b->addr_string);
12767         }
12768
12769       if (b->loc->next)
12770         {
12771           struct bp_location *loc = b->loc;
12772           int n = 0;
12773           for (; loc; loc = loc->next)
12774             ++n;
12775           printf_filtered (" (%d locations)", n);
12776         }
12777     }
12778 }
12779
12780 /* Default bp_location_ops methods.  */
12781
12782 static void
12783 bp_location_dtor (struct bp_location *self)
12784 {
12785   xfree (self->cond);
12786   if (self->cond_bytecode)
12787     free_agent_expr (self->cond_bytecode);
12788   xfree (self->function_name);
12789 }
12790
12791 static const struct bp_location_ops bp_location_ops =
12792 {
12793   bp_location_dtor
12794 };
12795
12796 /* Default breakpoint_ops methods all breakpoint_ops ultimately
12797    inherit from.  */
12798
12799 static void
12800 base_breakpoint_dtor (struct breakpoint *self)
12801 {
12802   decref_counted_command_line (&self->commands);
12803   xfree (self->cond_string);
12804   xfree (self->extra_string);
12805   xfree (self->addr_string);
12806   xfree (self->filter);
12807   xfree (self->addr_string_range_end);
12808 }
12809
12810 static struct bp_location *
12811 base_breakpoint_allocate_location (struct breakpoint *self)
12812 {
12813   struct bp_location *loc;
12814
12815   loc = XNEW (struct bp_location);
12816   init_bp_location (loc, &bp_location_ops, self);
12817   return loc;
12818 }
12819
12820 static void
12821 base_breakpoint_re_set (struct breakpoint *b)
12822 {
12823   /* Nothing to re-set. */
12824 }
12825
12826 #define internal_error_pure_virtual_called() \
12827   gdb_assert_not_reached ("pure virtual function called")
12828
12829 static int
12830 base_breakpoint_insert_location (struct bp_location *bl)
12831 {
12832   internal_error_pure_virtual_called ();
12833 }
12834
12835 static int
12836 base_breakpoint_remove_location (struct bp_location *bl)
12837 {
12838   internal_error_pure_virtual_called ();
12839 }
12840
12841 static int
12842 base_breakpoint_breakpoint_hit (const struct bp_location *bl,
12843                                 struct address_space *aspace,
12844                                 CORE_ADDR bp_addr,
12845                                 const struct target_waitstatus *ws)
12846 {
12847   internal_error_pure_virtual_called ();
12848 }
12849
12850 static void
12851 base_breakpoint_check_status (bpstat bs)
12852 {
12853   /* Always stop.   */
12854 }
12855
12856 /* A "works_in_software_mode" breakpoint_ops method that just internal
12857    errors.  */
12858
12859 static int
12860 base_breakpoint_works_in_software_mode (const struct breakpoint *b)
12861 {
12862   internal_error_pure_virtual_called ();
12863 }
12864
12865 /* A "resources_needed" breakpoint_ops method that just internal
12866    errors.  */
12867
12868 static int
12869 base_breakpoint_resources_needed (const struct bp_location *bl)
12870 {
12871   internal_error_pure_virtual_called ();
12872 }
12873
12874 static enum print_stop_action
12875 base_breakpoint_print_it (bpstat bs)
12876 {
12877   internal_error_pure_virtual_called ();
12878 }
12879
12880 static void
12881 base_breakpoint_print_one_detail (const struct breakpoint *self,
12882                                   struct ui_out *uiout)
12883 {
12884   /* nothing */
12885 }
12886
12887 static void
12888 base_breakpoint_print_mention (struct breakpoint *b)
12889 {
12890   internal_error_pure_virtual_called ();
12891 }
12892
12893 static void
12894 base_breakpoint_print_recreate (struct breakpoint *b, struct ui_file *fp)
12895 {
12896   internal_error_pure_virtual_called ();
12897 }
12898
12899 static void
12900 base_breakpoint_create_sals_from_address (char **arg,
12901                                           struct linespec_result *canonical,
12902                                           enum bptype type_wanted,
12903                                           char *addr_start,
12904                                           char **copy_arg)
12905 {
12906   internal_error_pure_virtual_called ();
12907 }
12908
12909 static void
12910 base_breakpoint_create_breakpoints_sal (struct gdbarch *gdbarch,
12911                                         struct linespec_result *c,
12912                                         struct linespec_sals *lsal,
12913                                         char *cond_string,
12914                                         char *extra_string,
12915                                         enum bptype type_wanted,
12916                                         enum bpdisp disposition,
12917                                         int thread,
12918                                         int task, int ignore_count,
12919                                         const struct breakpoint_ops *o,
12920                                         int from_tty, int enabled,
12921                                         int internal, unsigned flags)
12922 {
12923   internal_error_pure_virtual_called ();
12924 }
12925
12926 static void
12927 base_breakpoint_decode_linespec (struct breakpoint *b, char **s,
12928                                  struct symtabs_and_lines *sals)
12929 {
12930   internal_error_pure_virtual_called ();
12931 }
12932
12933 /* The default 'explains_signal' method.  */
12934
12935 static enum bpstat_signal_value
12936 base_breakpoint_explains_signal (struct breakpoint *b)
12937 {
12938   return BPSTAT_SIGNAL_HIDE;
12939 }
12940
12941 struct breakpoint_ops base_breakpoint_ops =
12942 {
12943   base_breakpoint_dtor,
12944   base_breakpoint_allocate_location,
12945   base_breakpoint_re_set,
12946   base_breakpoint_insert_location,
12947   base_breakpoint_remove_location,
12948   base_breakpoint_breakpoint_hit,
12949   base_breakpoint_check_status,
12950   base_breakpoint_resources_needed,
12951   base_breakpoint_works_in_software_mode,
12952   base_breakpoint_print_it,
12953   NULL,
12954   base_breakpoint_print_one_detail,
12955   base_breakpoint_print_mention,
12956   base_breakpoint_print_recreate,
12957   base_breakpoint_create_sals_from_address,
12958   base_breakpoint_create_breakpoints_sal,
12959   base_breakpoint_decode_linespec,
12960   base_breakpoint_explains_signal
12961 };
12962
12963 /* Default breakpoint_ops methods.  */
12964
12965 static void
12966 bkpt_re_set (struct breakpoint *b)
12967 {
12968   /* FIXME: is this still reachable?  */
12969   if (b->addr_string == NULL)
12970     {
12971       /* Anything without a string can't be re-set.  */
12972       delete_breakpoint (b);
12973       return;
12974     }
12975
12976   breakpoint_re_set_default (b);
12977 }
12978
12979 static int
12980 bkpt_insert_location (struct bp_location *bl)
12981 {
12982   if (bl->loc_type == bp_loc_hardware_breakpoint)
12983     return target_insert_hw_breakpoint (bl->gdbarch,
12984                                         &bl->target_info);
12985   else
12986     return target_insert_breakpoint (bl->gdbarch,
12987                                      &bl->target_info);
12988 }
12989
12990 static int
12991 bkpt_remove_location (struct bp_location *bl)
12992 {
12993   if (bl->loc_type == bp_loc_hardware_breakpoint)
12994     return target_remove_hw_breakpoint (bl->gdbarch, &bl->target_info);
12995   else
12996     return target_remove_breakpoint (bl->gdbarch, &bl->target_info);
12997 }
12998
12999 static int
13000 bkpt_breakpoint_hit (const struct bp_location *bl,
13001                      struct address_space *aspace, CORE_ADDR bp_addr,
13002                      const struct target_waitstatus *ws)
13003 {
13004   if (ws->kind != TARGET_WAITKIND_STOPPED
13005       || ws->value.sig != GDB_SIGNAL_TRAP)
13006     return 0;
13007
13008   if (!breakpoint_address_match (bl->pspace->aspace, bl->address,
13009                                  aspace, bp_addr))
13010     return 0;
13011
13012   if (overlay_debugging         /* unmapped overlay section */
13013       && section_is_overlay (bl->section)
13014       && !section_is_mapped (bl->section))
13015     return 0;
13016
13017   return 1;
13018 }
13019
13020 static int
13021 bkpt_resources_needed (const struct bp_location *bl)
13022 {
13023   gdb_assert (bl->owner->type == bp_hardware_breakpoint);
13024
13025   return 1;
13026 }
13027
13028 static enum print_stop_action
13029 bkpt_print_it (bpstat bs)
13030 {
13031   struct breakpoint *b;
13032   const struct bp_location *bl;
13033   int bp_temp;
13034   struct ui_out *uiout = current_uiout;
13035
13036   gdb_assert (bs->bp_location_at != NULL);
13037
13038   bl = bs->bp_location_at;
13039   b = bs->breakpoint_at;
13040
13041   bp_temp = b->disposition == disp_del;
13042   if (bl->address != bl->requested_address)
13043     breakpoint_adjustment_warning (bl->requested_address,
13044                                    bl->address,
13045                                    b->number, 1);
13046   annotate_breakpoint (b->number);
13047   if (bp_temp)
13048     ui_out_text (uiout, "\nTemporary breakpoint ");
13049   else
13050     ui_out_text (uiout, "\nBreakpoint ");
13051   if (ui_out_is_mi_like_p (uiout))
13052     {
13053       ui_out_field_string (uiout, "reason",
13054                            async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
13055       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
13056     }
13057   ui_out_field_int (uiout, "bkptno", b->number);
13058   ui_out_text (uiout, ", ");
13059
13060   return PRINT_SRC_AND_LOC;
13061 }
13062
13063 static void
13064 bkpt_print_mention (struct breakpoint *b)
13065 {
13066   if (ui_out_is_mi_like_p (current_uiout))
13067     return;
13068
13069   switch (b->type)
13070     {
13071     case bp_breakpoint:
13072     case bp_gnu_ifunc_resolver:
13073       if (b->disposition == disp_del)
13074         printf_filtered (_("Temporary breakpoint"));
13075       else
13076         printf_filtered (_("Breakpoint"));
13077       printf_filtered (_(" %d"), b->number);
13078       if (b->type == bp_gnu_ifunc_resolver)
13079         printf_filtered (_(" at gnu-indirect-function resolver"));
13080       break;
13081     case bp_hardware_breakpoint:
13082       printf_filtered (_("Hardware assisted breakpoint %d"), b->number);
13083       break;
13084     case bp_dprintf:
13085       printf_filtered (_("Dprintf %d"), b->number);
13086       break;
13087     }
13088
13089   say_where (b);
13090 }
13091
13092 static void
13093 bkpt_print_recreate (struct breakpoint *tp, struct ui_file *fp)
13094 {
13095   if (tp->type == bp_breakpoint && tp->disposition == disp_del)
13096     fprintf_unfiltered (fp, "tbreak");
13097   else if (tp->type == bp_breakpoint)
13098     fprintf_unfiltered (fp, "break");
13099   else if (tp->type == bp_hardware_breakpoint
13100            && tp->disposition == disp_del)
13101     fprintf_unfiltered (fp, "thbreak");
13102   else if (tp->type == bp_hardware_breakpoint)
13103     fprintf_unfiltered (fp, "hbreak");
13104   else
13105     internal_error (__FILE__, __LINE__,
13106                     _("unhandled breakpoint type %d"), (int) tp->type);
13107
13108   fprintf_unfiltered (fp, " %s", tp->addr_string);
13109   print_recreate_thread (tp, fp);
13110 }
13111
13112 static void
13113 bkpt_create_sals_from_address (char **arg,
13114                                struct linespec_result *canonical,
13115                                enum bptype type_wanted,
13116                                char *addr_start, char **copy_arg)
13117 {
13118   create_sals_from_address_default (arg, canonical, type_wanted,
13119                                     addr_start, copy_arg);
13120 }
13121
13122 static void
13123 bkpt_create_breakpoints_sal (struct gdbarch *gdbarch,
13124                              struct linespec_result *canonical,
13125                              struct linespec_sals *lsal,
13126                              char *cond_string,
13127                              char *extra_string,
13128                              enum bptype type_wanted,
13129                              enum bpdisp disposition,
13130                              int thread,
13131                              int task, int ignore_count,
13132                              const struct breakpoint_ops *ops,
13133                              int from_tty, int enabled,
13134                              int internal, unsigned flags)
13135 {
13136   create_breakpoints_sal_default (gdbarch, canonical, lsal,
13137                                   cond_string, extra_string,
13138                                   type_wanted,
13139                                   disposition, thread, task,
13140                                   ignore_count, ops, from_tty,
13141                                   enabled, internal, flags);
13142 }
13143
13144 static void
13145 bkpt_decode_linespec (struct breakpoint *b, char **s,
13146                       struct symtabs_and_lines *sals)
13147 {
13148   decode_linespec_default (b, s, sals);
13149 }
13150
13151 /* Virtual table for internal breakpoints.  */
13152
13153 static void
13154 internal_bkpt_re_set (struct breakpoint *b)
13155 {
13156   switch (b->type)
13157     {
13158       /* Delete overlay event and longjmp master breakpoints; they
13159          will be reset later by breakpoint_re_set.  */
13160     case bp_overlay_event:
13161     case bp_longjmp_master:
13162     case bp_std_terminate_master:
13163     case bp_exception_master:
13164       delete_breakpoint (b);
13165       break;
13166
13167       /* This breakpoint is special, it's set up when the inferior
13168          starts and we really don't want to touch it.  */
13169     case bp_shlib_event:
13170
13171       /* Like bp_shlib_event, this breakpoint type is special.  Once
13172          it is set up, we do not want to touch it.  */
13173     case bp_thread_event:
13174       break;
13175     }
13176 }
13177
13178 static void
13179 internal_bkpt_check_status (bpstat bs)
13180 {
13181   if (bs->breakpoint_at->type == bp_shlib_event)
13182     {
13183       /* If requested, stop when the dynamic linker notifies GDB of
13184          events.  This allows the user to get control and place
13185          breakpoints in initializer routines for dynamically loaded
13186          objects (among other things).  */
13187       bs->stop = stop_on_solib_events;
13188       bs->print = stop_on_solib_events;
13189     }
13190   else
13191     bs->stop = 0;
13192 }
13193
13194 static enum print_stop_action
13195 internal_bkpt_print_it (bpstat bs)
13196 {
13197   struct breakpoint *b;
13198
13199   b = bs->breakpoint_at;
13200
13201   switch (b->type)
13202     {
13203     case bp_shlib_event:
13204       /* Did we stop because the user set the stop_on_solib_events
13205          variable?  (If so, we report this as a generic, "Stopped due
13206          to shlib event" message.) */
13207       print_solib_event (0);
13208       break;
13209
13210     case bp_thread_event:
13211       /* Not sure how we will get here.
13212          GDB should not stop for these breakpoints.  */
13213       printf_filtered (_("Thread Event Breakpoint: gdb should not stop!\n"));
13214       break;
13215
13216     case bp_overlay_event:
13217       /* By analogy with the thread event, GDB should not stop for these.  */
13218       printf_filtered (_("Overlay Event Breakpoint: gdb should not stop!\n"));
13219       break;
13220
13221     case bp_longjmp_master:
13222       /* These should never be enabled.  */
13223       printf_filtered (_("Longjmp Master Breakpoint: gdb should not stop!\n"));
13224       break;
13225
13226     case bp_std_terminate_master:
13227       /* These should never be enabled.  */
13228       printf_filtered (_("std::terminate Master Breakpoint: "
13229                          "gdb should not stop!\n"));
13230       break;
13231
13232     case bp_exception_master:
13233       /* These should never be enabled.  */
13234       printf_filtered (_("Exception Master Breakpoint: "
13235                          "gdb should not stop!\n"));
13236       break;
13237     }
13238
13239   return PRINT_NOTHING;
13240 }
13241
13242 static void
13243 internal_bkpt_print_mention (struct breakpoint *b)
13244 {
13245   /* Nothing to mention.  These breakpoints are internal.  */
13246 }
13247
13248 /* Virtual table for momentary breakpoints  */
13249
13250 static void
13251 momentary_bkpt_re_set (struct breakpoint *b)
13252 {
13253   /* Keep temporary breakpoints, which can be encountered when we step
13254      over a dlopen call and SOLIB_ADD is resetting the breakpoints.
13255      Otherwise these should have been blown away via the cleanup chain
13256      or by breakpoint_init_inferior when we rerun the executable.  */
13257 }
13258
13259 static void
13260 momentary_bkpt_check_status (bpstat bs)
13261 {
13262   /* Nothing.  The point of these breakpoints is causing a stop.  */
13263 }
13264
13265 static enum print_stop_action
13266 momentary_bkpt_print_it (bpstat bs)
13267 {
13268   struct ui_out *uiout = current_uiout;
13269
13270   if (ui_out_is_mi_like_p (uiout))
13271     {
13272       struct breakpoint *b = bs->breakpoint_at;
13273
13274       switch (b->type)
13275         {
13276         case bp_finish:
13277           ui_out_field_string
13278             (uiout, "reason",
13279              async_reason_lookup (EXEC_ASYNC_FUNCTION_FINISHED));
13280           break;
13281
13282         case bp_until:
13283           ui_out_field_string
13284             (uiout, "reason",
13285              async_reason_lookup (EXEC_ASYNC_LOCATION_REACHED));
13286           break;
13287         }
13288     }
13289
13290   return PRINT_UNKNOWN;
13291 }
13292
13293 static void
13294 momentary_bkpt_print_mention (struct breakpoint *b)
13295 {
13296   /* Nothing to mention.  These breakpoints are internal.  */
13297 }
13298
13299 /* Ensure INITIATING_FRAME is cleared when no such breakpoint exists.
13300
13301    It gets cleared already on the removal of the first one of such placed
13302    breakpoints.  This is OK as they get all removed altogether.  */
13303
13304 static void
13305 longjmp_bkpt_dtor (struct breakpoint *self)
13306 {
13307   struct thread_info *tp = find_thread_id (self->thread);
13308
13309   if (tp)
13310     tp->initiating_frame = null_frame_id;
13311
13312   momentary_breakpoint_ops.dtor (self);
13313 }
13314
13315 /* Specific methods for probe breakpoints.  */
13316
13317 static int
13318 bkpt_probe_insert_location (struct bp_location *bl)
13319 {
13320   int v = bkpt_insert_location (bl);
13321
13322   if (v == 0)
13323     {
13324       /* The insertion was successful, now let's set the probe's semaphore
13325          if needed.  */
13326       bl->probe->pops->set_semaphore (bl->probe, bl->gdbarch);
13327     }
13328
13329   return v;
13330 }
13331
13332 static int
13333 bkpt_probe_remove_location (struct bp_location *bl)
13334 {
13335   /* Let's clear the semaphore before removing the location.  */
13336   bl->probe->pops->clear_semaphore (bl->probe, bl->gdbarch);
13337
13338   return bkpt_remove_location (bl);
13339 }
13340
13341 static void
13342 bkpt_probe_create_sals_from_address (char **arg,
13343                                      struct linespec_result *canonical,
13344                                      enum bptype type_wanted,
13345                                      char *addr_start, char **copy_arg)
13346 {
13347   struct linespec_sals lsal;
13348
13349   lsal.sals = parse_probes (arg, canonical);
13350
13351   *copy_arg = xstrdup (canonical->addr_string);
13352   lsal.canonical = xstrdup (*copy_arg);
13353
13354   VEC_safe_push (linespec_sals, canonical->sals, &lsal);
13355 }
13356
13357 static void
13358 bkpt_probe_decode_linespec (struct breakpoint *b, char **s,
13359                             struct symtabs_and_lines *sals)
13360 {
13361   *sals = parse_probes (s, NULL);
13362   if (!sals->sals)
13363     error (_("probe not found"));
13364 }
13365
13366 /* The breakpoint_ops structure to be used in tracepoints.  */
13367
13368 static void
13369 tracepoint_re_set (struct breakpoint *b)
13370 {
13371   breakpoint_re_set_default (b);
13372 }
13373
13374 static int
13375 tracepoint_breakpoint_hit (const struct bp_location *bl,
13376                            struct address_space *aspace, CORE_ADDR bp_addr,
13377                            const struct target_waitstatus *ws)
13378 {
13379   /* By definition, the inferior does not report stops at
13380      tracepoints.  */
13381   return 0;
13382 }
13383
13384 static void
13385 tracepoint_print_one_detail (const struct breakpoint *self,
13386                              struct ui_out *uiout)
13387 {
13388   struct tracepoint *tp = (struct tracepoint *) self;
13389   if (tp->static_trace_marker_id)
13390     {
13391       gdb_assert (self->type == bp_static_tracepoint);
13392
13393       ui_out_text (uiout, "\tmarker id is ");
13394       ui_out_field_string (uiout, "static-tracepoint-marker-string-id",
13395                            tp->static_trace_marker_id);
13396       ui_out_text (uiout, "\n");
13397     }
13398 }
13399
13400 static void
13401 tracepoint_print_mention (struct breakpoint *b)
13402 {
13403   if (ui_out_is_mi_like_p (current_uiout))
13404     return;
13405
13406   switch (b->type)
13407     {
13408     case bp_tracepoint:
13409       printf_filtered (_("Tracepoint"));
13410       printf_filtered (_(" %d"), b->number);
13411       break;
13412     case bp_fast_tracepoint:
13413       printf_filtered (_("Fast tracepoint"));
13414       printf_filtered (_(" %d"), b->number);
13415       break;
13416     case bp_static_tracepoint:
13417       printf_filtered (_("Static tracepoint"));
13418       printf_filtered (_(" %d"), b->number);
13419       break;
13420     default:
13421       internal_error (__FILE__, __LINE__,
13422                       _("unhandled tracepoint type %d"), (int) b->type);
13423     }
13424
13425   say_where (b);
13426 }
13427
13428 static void
13429 tracepoint_print_recreate (struct breakpoint *self, struct ui_file *fp)
13430 {
13431   struct tracepoint *tp = (struct tracepoint *) self;
13432
13433   if (self->type == bp_fast_tracepoint)
13434     fprintf_unfiltered (fp, "ftrace");
13435   if (self->type == bp_static_tracepoint)
13436     fprintf_unfiltered (fp, "strace");
13437   else if (self->type == bp_tracepoint)
13438     fprintf_unfiltered (fp, "trace");
13439   else
13440     internal_error (__FILE__, __LINE__,
13441                     _("unhandled tracepoint type %d"), (int) self->type);
13442
13443   fprintf_unfiltered (fp, " %s", self->addr_string);
13444   print_recreate_thread (self, fp);
13445
13446   if (tp->pass_count)
13447     fprintf_unfiltered (fp, "  passcount %d\n", tp->pass_count);
13448 }
13449
13450 static void
13451 tracepoint_create_sals_from_address (char **arg,
13452                                      struct linespec_result *canonical,
13453                                      enum bptype type_wanted,
13454                                      char *addr_start, char **copy_arg)
13455 {
13456   create_sals_from_address_default (arg, canonical, type_wanted,
13457                                     addr_start, copy_arg);
13458 }
13459
13460 static void
13461 tracepoint_create_breakpoints_sal (struct gdbarch *gdbarch,
13462                                    struct linespec_result *canonical,
13463                                    struct linespec_sals *lsal,
13464                                    char *cond_string,
13465                                    char *extra_string,
13466                                    enum bptype type_wanted,
13467                                    enum bpdisp disposition,
13468                                    int thread,
13469                                    int task, int ignore_count,
13470                                    const struct breakpoint_ops *ops,
13471                                    int from_tty, int enabled,
13472                                    int internal, unsigned flags)
13473 {
13474   create_breakpoints_sal_default (gdbarch, canonical, lsal,
13475                                   cond_string, extra_string,
13476                                   type_wanted,
13477                                   disposition, thread, task,
13478                                   ignore_count, ops, from_tty,
13479                                   enabled, internal, flags);
13480 }
13481
13482 static void
13483 tracepoint_decode_linespec (struct breakpoint *b, char **s,
13484                             struct symtabs_and_lines *sals)
13485 {
13486   decode_linespec_default (b, s, sals);
13487 }
13488
13489 struct breakpoint_ops tracepoint_breakpoint_ops;
13490
13491 /* The breakpoint_ops structure to be use on tracepoints placed in a
13492    static probe.  */
13493
13494 static void
13495 tracepoint_probe_create_sals_from_address (char **arg,
13496                                            struct linespec_result *canonical,
13497                                            enum bptype type_wanted,
13498                                            char *addr_start, char **copy_arg)
13499 {
13500   /* We use the same method for breakpoint on probes.  */
13501   bkpt_probe_create_sals_from_address (arg, canonical, type_wanted,
13502                                        addr_start, copy_arg);
13503 }
13504
13505 static void
13506 tracepoint_probe_decode_linespec (struct breakpoint *b, char **s,
13507                                   struct symtabs_and_lines *sals)
13508 {
13509   /* We use the same method for breakpoint on probes.  */
13510   bkpt_probe_decode_linespec (b, s, sals);
13511 }
13512
13513 static struct breakpoint_ops tracepoint_probe_breakpoint_ops;
13514
13515 /* The breakpoint_ops structure to be used on static tracepoints with
13516    markers (`-m').  */
13517
13518 static void
13519 strace_marker_create_sals_from_address (char **arg,
13520                                         struct linespec_result *canonical,
13521                                         enum bptype type_wanted,
13522                                         char *addr_start, char **copy_arg)
13523 {
13524   struct linespec_sals lsal;
13525
13526   lsal.sals = decode_static_tracepoint_spec (arg);
13527
13528   *copy_arg = savestring (addr_start, *arg - addr_start);
13529
13530   canonical->addr_string = xstrdup (*copy_arg);
13531   lsal.canonical = xstrdup (*copy_arg);
13532   VEC_safe_push (linespec_sals, canonical->sals, &lsal);
13533 }
13534
13535 static void
13536 strace_marker_create_breakpoints_sal (struct gdbarch *gdbarch,
13537                                       struct linespec_result *canonical,
13538                                       struct linespec_sals *lsal,
13539                                       char *cond_string,
13540                                       char *extra_string,
13541                                       enum bptype type_wanted,
13542                                       enum bpdisp disposition,
13543                                       int thread,
13544                                       int task, int ignore_count,
13545                                       const struct breakpoint_ops *ops,
13546                                       int from_tty, int enabled,
13547                                       int internal, unsigned flags)
13548 {
13549   int i;
13550
13551   /* If the user is creating a static tracepoint by marker id
13552      (strace -m MARKER_ID), then store the sals index, so that
13553      breakpoint_re_set can try to match up which of the newly
13554      found markers corresponds to this one, and, don't try to
13555      expand multiple locations for each sal, given than SALS
13556      already should contain all sals for MARKER_ID.  */
13557
13558   for (i = 0; i < lsal->sals.nelts; ++i)
13559     {
13560       struct symtabs_and_lines expanded;
13561       struct tracepoint *tp;
13562       struct cleanup *old_chain;
13563       char *addr_string;
13564
13565       expanded.nelts = 1;
13566       expanded.sals = &lsal->sals.sals[i];
13567
13568       addr_string = xstrdup (canonical->addr_string);
13569       old_chain = make_cleanup (xfree, addr_string);
13570
13571       tp = XCNEW (struct tracepoint);
13572       init_breakpoint_sal (&tp->base, gdbarch, expanded,
13573                            addr_string, NULL,
13574                            cond_string, extra_string,
13575                            type_wanted, disposition,
13576                            thread, task, ignore_count, ops,
13577                            from_tty, enabled, internal, flags,
13578                            canonical->special_display);
13579       /* Given that its possible to have multiple markers with
13580          the same string id, if the user is creating a static
13581          tracepoint by marker id ("strace -m MARKER_ID"), then
13582          store the sals index, so that breakpoint_re_set can
13583          try to match up which of the newly found markers
13584          corresponds to this one  */
13585       tp->static_trace_marker_id_idx = i;
13586
13587       install_breakpoint (internal, &tp->base, 0);
13588
13589       discard_cleanups (old_chain);
13590     }
13591 }
13592
13593 static void
13594 strace_marker_decode_linespec (struct breakpoint *b, char **s,
13595                                struct symtabs_and_lines *sals)
13596 {
13597   struct tracepoint *tp = (struct tracepoint *) b;
13598
13599   *sals = decode_static_tracepoint_spec (s);
13600   if (sals->nelts > tp->static_trace_marker_id_idx)
13601     {
13602       sals->sals[0] = sals->sals[tp->static_trace_marker_id_idx];
13603       sals->nelts = 1;
13604     }
13605   else
13606     error (_("marker %s not found"), tp->static_trace_marker_id);
13607 }
13608
13609 static struct breakpoint_ops strace_marker_breakpoint_ops;
13610
13611 static int
13612 strace_marker_p (struct breakpoint *b)
13613 {
13614   return b->ops == &strace_marker_breakpoint_ops;
13615 }
13616
13617 /* Delete a breakpoint and clean up all traces of it in the data
13618    structures.  */
13619
13620 void
13621 delete_breakpoint (struct breakpoint *bpt)
13622 {
13623   struct breakpoint *b;
13624
13625   gdb_assert (bpt != NULL);
13626
13627   /* Has this bp already been deleted?  This can happen because
13628      multiple lists can hold pointers to bp's.  bpstat lists are
13629      especial culprits.
13630
13631      One example of this happening is a watchpoint's scope bp.  When
13632      the scope bp triggers, we notice that the watchpoint is out of
13633      scope, and delete it.  We also delete its scope bp.  But the
13634      scope bp is marked "auto-deleting", and is already on a bpstat.
13635      That bpstat is then checked for auto-deleting bp's, which are
13636      deleted.
13637
13638      A real solution to this problem might involve reference counts in
13639      bp's, and/or giving them pointers back to their referencing
13640      bpstat's, and teaching delete_breakpoint to only free a bp's
13641      storage when no more references were extent.  A cheaper bandaid
13642      was chosen.  */
13643   if (bpt->type == bp_none)
13644     return;
13645
13646   /* At least avoid this stale reference until the reference counting
13647      of breakpoints gets resolved.  */
13648   if (bpt->related_breakpoint != bpt)
13649     {
13650       struct breakpoint *related;
13651       struct watchpoint *w;
13652
13653       if (bpt->type == bp_watchpoint_scope)
13654         w = (struct watchpoint *) bpt->related_breakpoint;
13655       else if (bpt->related_breakpoint->type == bp_watchpoint_scope)
13656         w = (struct watchpoint *) bpt;
13657       else
13658         w = NULL;
13659       if (w != NULL)
13660         watchpoint_del_at_next_stop (w);
13661
13662       /* Unlink bpt from the bpt->related_breakpoint ring.  */
13663       for (related = bpt; related->related_breakpoint != bpt;
13664            related = related->related_breakpoint);
13665       related->related_breakpoint = bpt->related_breakpoint;
13666       bpt->related_breakpoint = bpt;
13667     }
13668
13669   /* watch_command_1 creates a watchpoint but only sets its number if
13670      update_watchpoint succeeds in creating its bp_locations.  If there's
13671      a problem in that process, we'll be asked to delete the half-created
13672      watchpoint.  In that case, don't announce the deletion.  */
13673   if (bpt->number)
13674     observer_notify_breakpoint_deleted (bpt);
13675
13676   if (breakpoint_chain == bpt)
13677     breakpoint_chain = bpt->next;
13678
13679   ALL_BREAKPOINTS (b)
13680     if (b->next == bpt)
13681     {
13682       b->next = bpt->next;
13683       break;
13684     }
13685
13686   /* Be sure no bpstat's are pointing at the breakpoint after it's
13687      been freed.  */
13688   /* FIXME, how can we find all bpstat's?  We just check stop_bpstat
13689      in all threads for now.  Note that we cannot just remove bpstats
13690      pointing at bpt from the stop_bpstat list entirely, as breakpoint
13691      commands are associated with the bpstat; if we remove it here,
13692      then the later call to bpstat_do_actions (&stop_bpstat); in
13693      event-top.c won't do anything, and temporary breakpoints with
13694      commands won't work.  */
13695
13696   iterate_over_threads (bpstat_remove_breakpoint_callback, bpt);
13697
13698   /* Now that breakpoint is removed from breakpoint list, update the
13699      global location list.  This will remove locations that used to
13700      belong to this breakpoint.  Do this before freeing the breakpoint
13701      itself, since remove_breakpoint looks at location's owner.  It
13702      might be better design to have location completely
13703      self-contained, but it's not the case now.  */
13704   update_global_location_list (0);
13705
13706   bpt->ops->dtor (bpt);
13707   /* On the chance that someone will soon try again to delete this
13708      same bp, we mark it as deleted before freeing its storage.  */
13709   bpt->type = bp_none;
13710   xfree (bpt);
13711 }
13712
13713 static void
13714 do_delete_breakpoint_cleanup (void *b)
13715 {
13716   delete_breakpoint (b);
13717 }
13718
13719 struct cleanup *
13720 make_cleanup_delete_breakpoint (struct breakpoint *b)
13721 {
13722   return make_cleanup (do_delete_breakpoint_cleanup, b);
13723 }
13724
13725 /* Iterator function to call a user-provided callback function once
13726    for each of B and its related breakpoints.  */
13727
13728 static void
13729 iterate_over_related_breakpoints (struct breakpoint *b,
13730                                   void (*function) (struct breakpoint *,
13731                                                     void *),
13732                                   void *data)
13733 {
13734   struct breakpoint *related;
13735
13736   related = b;
13737   do
13738     {
13739       struct breakpoint *next;
13740
13741       /* FUNCTION may delete RELATED.  */
13742       next = related->related_breakpoint;
13743
13744       if (next == related)
13745         {
13746           /* RELATED is the last ring entry.  */
13747           function (related, data);
13748
13749           /* FUNCTION may have deleted it, so we'd never reach back to
13750              B.  There's nothing left to do anyway, so just break
13751              out.  */
13752           break;
13753         }
13754       else
13755         function (related, data);
13756
13757       related = next;
13758     }
13759   while (related != b);
13760 }
13761
13762 static void
13763 do_delete_breakpoint (struct breakpoint *b, void *ignore)
13764 {
13765   delete_breakpoint (b);
13766 }
13767
13768 /* A callback for map_breakpoint_numbers that calls
13769    delete_breakpoint.  */
13770
13771 static void
13772 do_map_delete_breakpoint (struct breakpoint *b, void *ignore)
13773 {
13774   iterate_over_related_breakpoints (b, do_delete_breakpoint, NULL);
13775 }
13776
13777 void
13778 delete_command (char *arg, int from_tty)
13779 {
13780   struct breakpoint *b, *b_tmp;
13781
13782   dont_repeat ();
13783
13784   if (arg == 0)
13785     {
13786       int breaks_to_delete = 0;
13787
13788       /* Delete all breakpoints if no argument.  Do not delete
13789          internal breakpoints, these have to be deleted with an
13790          explicit breakpoint number argument.  */
13791       ALL_BREAKPOINTS (b)
13792         if (user_breakpoint_p (b))
13793           {
13794             breaks_to_delete = 1;
13795             break;
13796           }
13797
13798       /* Ask user only if there are some breakpoints to delete.  */
13799       if (!from_tty
13800           || (breaks_to_delete && query (_("Delete all breakpoints? "))))
13801         {
13802           ALL_BREAKPOINTS_SAFE (b, b_tmp)
13803             if (user_breakpoint_p (b))
13804               delete_breakpoint (b);
13805         }
13806     }
13807   else
13808     map_breakpoint_numbers (arg, do_map_delete_breakpoint, NULL);
13809 }
13810
13811 static int
13812 all_locations_are_pending (struct bp_location *loc)
13813 {
13814   for (; loc; loc = loc->next)
13815     if (!loc->shlib_disabled
13816         && !loc->pspace->executing_startup)
13817       return 0;
13818   return 1;
13819 }
13820
13821 /* Subroutine of update_breakpoint_locations to simplify it.
13822    Return non-zero if multiple fns in list LOC have the same name.
13823    Null names are ignored.  */
13824
13825 static int
13826 ambiguous_names_p (struct bp_location *loc)
13827 {
13828   struct bp_location *l;
13829   htab_t htab = htab_create_alloc (13, htab_hash_string,
13830                                    (int (*) (const void *, 
13831                                              const void *)) streq,
13832                                    NULL, xcalloc, xfree);
13833
13834   for (l = loc; l != NULL; l = l->next)
13835     {
13836       const char **slot;
13837       const char *name = l->function_name;
13838
13839       /* Allow for some names to be NULL, ignore them.  */
13840       if (name == NULL)
13841         continue;
13842
13843       slot = (const char **) htab_find_slot (htab, (const void *) name,
13844                                              INSERT);
13845       /* NOTE: We can assume slot != NULL here because xcalloc never
13846          returns NULL.  */
13847       if (*slot != NULL)
13848         {
13849           htab_delete (htab);
13850           return 1;
13851         }
13852       *slot = name;
13853     }
13854
13855   htab_delete (htab);
13856   return 0;
13857 }
13858
13859 /* When symbols change, it probably means the sources changed as well,
13860    and it might mean the static tracepoint markers are no longer at
13861    the same address or line numbers they used to be at last we
13862    checked.  Losing your static tracepoints whenever you rebuild is
13863    undesirable.  This function tries to resync/rematch gdb static
13864    tracepoints with the markers on the target, for static tracepoints
13865    that have not been set by marker id.  Static tracepoint that have
13866    been set by marker id are reset by marker id in breakpoint_re_set.
13867    The heuristic is:
13868
13869    1) For a tracepoint set at a specific address, look for a marker at
13870    the old PC.  If one is found there, assume to be the same marker.
13871    If the name / string id of the marker found is different from the
13872    previous known name, assume that means the user renamed the marker
13873    in the sources, and output a warning.
13874
13875    2) For a tracepoint set at a given line number, look for a marker
13876    at the new address of the old line number.  If one is found there,
13877    assume to be the same marker.  If the name / string id of the
13878    marker found is different from the previous known name, assume that
13879    means the user renamed the marker in the sources, and output a
13880    warning.
13881
13882    3) If a marker is no longer found at the same address or line, it
13883    may mean the marker no longer exists.  But it may also just mean
13884    the code changed a bit.  Maybe the user added a few lines of code
13885    that made the marker move up or down (in line number terms).  Ask
13886    the target for info about the marker with the string id as we knew
13887    it.  If found, update line number and address in the matching
13888    static tracepoint.  This will get confused if there's more than one
13889    marker with the same ID (possible in UST, although unadvised
13890    precisely because it confuses tools).  */
13891
13892 static struct symtab_and_line
13893 update_static_tracepoint (struct breakpoint *b, struct symtab_and_line sal)
13894 {
13895   struct tracepoint *tp = (struct tracepoint *) b;
13896   struct static_tracepoint_marker marker;
13897   CORE_ADDR pc;
13898
13899   pc = sal.pc;
13900   if (sal.line)
13901     find_line_pc (sal.symtab, sal.line, &pc);
13902
13903   if (target_static_tracepoint_marker_at (pc, &marker))
13904     {
13905       if (strcmp (tp->static_trace_marker_id, marker.str_id) != 0)
13906         warning (_("static tracepoint %d changed probed marker from %s to %s"),
13907                  b->number,
13908                  tp->static_trace_marker_id, marker.str_id);
13909
13910       xfree (tp->static_trace_marker_id);
13911       tp->static_trace_marker_id = xstrdup (marker.str_id);
13912       release_static_tracepoint_marker (&marker);
13913
13914       return sal;
13915     }
13916
13917   /* Old marker wasn't found on target at lineno.  Try looking it up
13918      by string ID.  */
13919   if (!sal.explicit_pc
13920       && sal.line != 0
13921       && sal.symtab != NULL
13922       && tp->static_trace_marker_id != NULL)
13923     {
13924       VEC(static_tracepoint_marker_p) *markers;
13925
13926       markers
13927         = target_static_tracepoint_markers_by_strid (tp->static_trace_marker_id);
13928
13929       if (!VEC_empty(static_tracepoint_marker_p, markers))
13930         {
13931           struct symtab_and_line sal2;
13932           struct symbol *sym;
13933           struct static_tracepoint_marker *tpmarker;
13934           struct ui_out *uiout = current_uiout;
13935
13936           tpmarker = VEC_index (static_tracepoint_marker_p, markers, 0);
13937
13938           xfree (tp->static_trace_marker_id);
13939           tp->static_trace_marker_id = xstrdup (tpmarker->str_id);
13940
13941           warning (_("marker for static tracepoint %d (%s) not "
13942                      "found at previous line number"),
13943                    b->number, tp->static_trace_marker_id);
13944
13945           init_sal (&sal2);
13946
13947           sal2.pc = tpmarker->address;
13948
13949           sal2 = find_pc_line (tpmarker->address, 0);
13950           sym = find_pc_sect_function (tpmarker->address, NULL);
13951           ui_out_text (uiout, "Now in ");
13952           if (sym)
13953             {
13954               ui_out_field_string (uiout, "func",
13955                                    SYMBOL_PRINT_NAME (sym));
13956               ui_out_text (uiout, " at ");
13957             }
13958           ui_out_field_string (uiout, "file",
13959                                symtab_to_filename_for_display (sal2.symtab));
13960           ui_out_text (uiout, ":");
13961
13962           if (ui_out_is_mi_like_p (uiout))
13963             {
13964               const char *fullname = symtab_to_fullname (sal2.symtab);
13965
13966               ui_out_field_string (uiout, "fullname", fullname);
13967             }
13968
13969           ui_out_field_int (uiout, "line", sal2.line);
13970           ui_out_text (uiout, "\n");
13971
13972           b->loc->line_number = sal2.line;
13973           b->loc->symtab = sym != NULL ? sal2.symtab : NULL;
13974
13975           xfree (b->addr_string);
13976           b->addr_string = xstrprintf ("%s:%d",
13977                                    symtab_to_filename_for_display (sal2.symtab),
13978                                        b->loc->line_number);
13979
13980           /* Might be nice to check if function changed, and warn if
13981              so.  */
13982
13983           release_static_tracepoint_marker (tpmarker);
13984         }
13985     }
13986   return sal;
13987 }
13988
13989 /* Returns 1 iff locations A and B are sufficiently same that
13990    we don't need to report breakpoint as changed.  */
13991
13992 static int
13993 locations_are_equal (struct bp_location *a, struct bp_location *b)
13994 {
13995   while (a && b)
13996     {
13997       if (a->address != b->address)
13998         return 0;
13999
14000       if (a->shlib_disabled != b->shlib_disabled)
14001         return 0;
14002
14003       if (a->enabled != b->enabled)
14004         return 0;
14005
14006       a = a->next;
14007       b = b->next;
14008     }
14009
14010   if ((a == NULL) != (b == NULL))
14011     return 0;
14012
14013   return 1;
14014 }
14015
14016 /* Create new breakpoint locations for B (a hardware or software breakpoint)
14017    based on SALS and SALS_END.  If SALS_END.NELTS is not zero, then B is
14018    a ranged breakpoint.  */
14019
14020 void
14021 update_breakpoint_locations (struct breakpoint *b,
14022                              struct symtabs_and_lines sals,
14023                              struct symtabs_and_lines sals_end)
14024 {
14025   int i;
14026   struct bp_location *existing_locations = b->loc;
14027
14028   if (sals_end.nelts != 0 && (sals.nelts != 1 || sals_end.nelts != 1))
14029     {
14030       /* Ranged breakpoints have only one start location and one end
14031          location.  */
14032       b->enable_state = bp_disabled;
14033       update_global_location_list (1);
14034       printf_unfiltered (_("Could not reset ranged breakpoint %d: "
14035                            "multiple locations found\n"),
14036                          b->number);
14037       return;
14038     }
14039
14040   /* If there's no new locations, and all existing locations are
14041      pending, don't do anything.  This optimizes the common case where
14042      all locations are in the same shared library, that was unloaded.
14043      We'd like to retain the location, so that when the library is
14044      loaded again, we don't loose the enabled/disabled status of the
14045      individual locations.  */
14046   if (all_locations_are_pending (existing_locations) && sals.nelts == 0)
14047     return;
14048
14049   b->loc = NULL;
14050
14051   for (i = 0; i < sals.nelts; ++i)
14052     {
14053       struct bp_location *new_loc;
14054
14055       switch_to_program_space_and_thread (sals.sals[i].pspace);
14056
14057       new_loc = add_location_to_breakpoint (b, &(sals.sals[i]));
14058
14059       /* Reparse conditions, they might contain references to the
14060          old symtab.  */
14061       if (b->cond_string != NULL)
14062         {
14063           const char *s;
14064           volatile struct gdb_exception e;
14065
14066           s = b->cond_string;
14067           TRY_CATCH (e, RETURN_MASK_ERROR)
14068             {
14069               new_loc->cond = parse_exp_1 (&s, sals.sals[i].pc,
14070                                            block_for_pc (sals.sals[i].pc), 
14071                                            0);
14072             }
14073           if (e.reason < 0)
14074             {
14075               warning (_("failed to reevaluate condition "
14076                          "for breakpoint %d: %s"), 
14077                        b->number, e.message);
14078               new_loc->enabled = 0;
14079             }
14080         }
14081
14082       if (sals_end.nelts)
14083         {
14084           CORE_ADDR end = find_breakpoint_range_end (sals_end.sals[0]);
14085
14086           new_loc->length = end - sals.sals[0].pc + 1;
14087         }
14088     }
14089
14090   /* Update locations of permanent breakpoints.  */
14091   if (b->enable_state == bp_permanent)
14092     make_breakpoint_permanent (b);
14093
14094   /* If possible, carry over 'disable' status from existing
14095      breakpoints.  */
14096   {
14097     struct bp_location *e = existing_locations;
14098     /* If there are multiple breakpoints with the same function name,
14099        e.g. for inline functions, comparing function names won't work.
14100        Instead compare pc addresses; this is just a heuristic as things
14101        may have moved, but in practice it gives the correct answer
14102        often enough until a better solution is found.  */
14103     int have_ambiguous_names = ambiguous_names_p (b->loc);
14104
14105     for (; e; e = e->next)
14106       {
14107         if (!e->enabled && e->function_name)
14108           {
14109             struct bp_location *l = b->loc;
14110             if (have_ambiguous_names)
14111               {
14112                 for (; l; l = l->next)
14113                   if (breakpoint_locations_match (e, l))
14114                     {
14115                       l->enabled = 0;
14116                       break;
14117                     }
14118               }
14119             else
14120               {
14121                 for (; l; l = l->next)
14122                   if (l->function_name
14123                       && strcmp (e->function_name, l->function_name) == 0)
14124                     {
14125                       l->enabled = 0;
14126                       break;
14127                     }
14128               }
14129           }
14130       }
14131   }
14132
14133   if (!locations_are_equal (existing_locations, b->loc))
14134     observer_notify_breakpoint_modified (b);
14135
14136   update_global_location_list (1);
14137 }
14138
14139 /* Find the SaL locations corresponding to the given ADDR_STRING.
14140    On return, FOUND will be 1 if any SaL was found, zero otherwise.  */
14141
14142 static struct symtabs_and_lines
14143 addr_string_to_sals (struct breakpoint *b, char *addr_string, int *found)
14144 {
14145   char *s;
14146   struct symtabs_and_lines sals = {0};
14147   volatile struct gdb_exception e;
14148
14149   gdb_assert (b->ops != NULL);
14150   s = addr_string;
14151
14152   TRY_CATCH (e, RETURN_MASK_ERROR)
14153     {
14154       b->ops->decode_linespec (b, &s, &sals);
14155     }
14156   if (e.reason < 0)
14157     {
14158       int not_found_and_ok = 0;
14159       /* For pending breakpoints, it's expected that parsing will
14160          fail until the right shared library is loaded.  User has
14161          already told to create pending breakpoints and don't need
14162          extra messages.  If breakpoint is in bp_shlib_disabled
14163          state, then user already saw the message about that
14164          breakpoint being disabled, and don't want to see more
14165          errors.  */
14166       if (e.error == NOT_FOUND_ERROR
14167           && (b->condition_not_parsed 
14168               || (b->loc && b->loc->shlib_disabled)
14169               || (b->loc && b->loc->pspace->executing_startup)
14170               || b->enable_state == bp_disabled))
14171         not_found_and_ok = 1;
14172
14173       if (!not_found_and_ok)
14174         {
14175           /* We surely don't want to warn about the same breakpoint
14176              10 times.  One solution, implemented here, is disable
14177              the breakpoint on error.  Another solution would be to
14178              have separate 'warning emitted' flag.  Since this
14179              happens only when a binary has changed, I don't know
14180              which approach is better.  */
14181           b->enable_state = bp_disabled;
14182           throw_exception (e);
14183         }
14184     }
14185
14186   if (e.reason == 0 || e.error != NOT_FOUND_ERROR)
14187     {
14188       int i;
14189
14190       for (i = 0; i < sals.nelts; ++i)
14191         resolve_sal_pc (&sals.sals[i]);
14192       if (b->condition_not_parsed && s && s[0])
14193         {
14194           char *cond_string, *extra_string;
14195           int thread, task;
14196
14197           find_condition_and_thread (s, sals.sals[0].pc,
14198                                      &cond_string, &thread, &task,
14199                                      &extra_string);
14200           if (cond_string)
14201             b->cond_string = cond_string;
14202           b->thread = thread;
14203           b->task = task;
14204           if (extra_string)
14205             b->extra_string = extra_string;
14206           b->condition_not_parsed = 0;
14207         }
14208
14209       if (b->type == bp_static_tracepoint && !strace_marker_p (b))
14210         sals.sals[0] = update_static_tracepoint (b, sals.sals[0]);
14211
14212       *found = 1;
14213     }
14214   else
14215     *found = 0;
14216
14217   return sals;
14218 }
14219
14220 /* The default re_set method, for typical hardware or software
14221    breakpoints.  Reevaluate the breakpoint and recreate its
14222    locations.  */
14223
14224 static void
14225 breakpoint_re_set_default (struct breakpoint *b)
14226 {
14227   int found;
14228   struct symtabs_and_lines sals, sals_end;
14229   struct symtabs_and_lines expanded = {0};
14230   struct symtabs_and_lines expanded_end = {0};
14231
14232   sals = addr_string_to_sals (b, b->addr_string, &found);
14233   if (found)
14234     {
14235       make_cleanup (xfree, sals.sals);
14236       expanded = sals;
14237     }
14238
14239   if (b->addr_string_range_end)
14240     {
14241       sals_end = addr_string_to_sals (b, b->addr_string_range_end, &found);
14242       if (found)
14243         {
14244           make_cleanup (xfree, sals_end.sals);
14245           expanded_end = sals_end;
14246         }
14247     }
14248
14249   update_breakpoint_locations (b, expanded, expanded_end);
14250 }
14251
14252 /* Default method for creating SALs from an address string.  It basically
14253    calls parse_breakpoint_sals.  Return 1 for success, zero for failure.  */
14254
14255 static void
14256 create_sals_from_address_default (char **arg,
14257                                   struct linespec_result *canonical,
14258                                   enum bptype type_wanted,
14259                                   char *addr_start, char **copy_arg)
14260 {
14261   parse_breakpoint_sals (arg, canonical);
14262 }
14263
14264 /* Call create_breakpoints_sal for the given arguments.  This is the default
14265    function for the `create_breakpoints_sal' method of
14266    breakpoint_ops.  */
14267
14268 static void
14269 create_breakpoints_sal_default (struct gdbarch *gdbarch,
14270                                 struct linespec_result *canonical,
14271                                 struct linespec_sals *lsal,
14272                                 char *cond_string,
14273                                 char *extra_string,
14274                                 enum bptype type_wanted,
14275                                 enum bpdisp disposition,
14276                                 int thread,
14277                                 int task, int ignore_count,
14278                                 const struct breakpoint_ops *ops,
14279                                 int from_tty, int enabled,
14280                                 int internal, unsigned flags)
14281 {
14282   create_breakpoints_sal (gdbarch, canonical, cond_string,
14283                           extra_string,
14284                           type_wanted, disposition,
14285                           thread, task, ignore_count, ops, from_tty,
14286                           enabled, internal, flags);
14287 }
14288
14289 /* Decode the line represented by S by calling decode_line_full.  This is the
14290    default function for the `decode_linespec' method of breakpoint_ops.  */
14291
14292 static void
14293 decode_linespec_default (struct breakpoint *b, char **s,
14294                          struct symtabs_and_lines *sals)
14295 {
14296   struct linespec_result canonical;
14297
14298   init_linespec_result (&canonical);
14299   decode_line_full (s, DECODE_LINE_FUNFIRSTLINE,
14300                     (struct symtab *) NULL, 0,
14301                     &canonical, multiple_symbols_all,
14302                     b->filter);
14303
14304   /* We should get 0 or 1 resulting SALs.  */
14305   gdb_assert (VEC_length (linespec_sals, canonical.sals) < 2);
14306
14307   if (VEC_length (linespec_sals, canonical.sals) > 0)
14308     {
14309       struct linespec_sals *lsal;
14310
14311       lsal = VEC_index (linespec_sals, canonical.sals, 0);
14312       *sals = lsal->sals;
14313       /* Arrange it so the destructor does not free the
14314          contents.  */
14315       lsal->sals.sals = NULL;
14316     }
14317
14318   destroy_linespec_result (&canonical);
14319 }
14320
14321 /* Prepare the global context for a re-set of breakpoint B.  */
14322
14323 static struct cleanup *
14324 prepare_re_set_context (struct breakpoint *b)
14325 {
14326   struct cleanup *cleanups;
14327
14328   input_radix = b->input_radix;
14329   cleanups = save_current_space_and_thread ();
14330   if (b->pspace != NULL)
14331     switch_to_program_space_and_thread (b->pspace);
14332   set_language (b->language);
14333
14334   return cleanups;
14335 }
14336
14337 /* Reset a breakpoint given it's struct breakpoint * BINT.
14338    The value we return ends up being the return value from catch_errors.
14339    Unused in this case.  */
14340
14341 static int
14342 breakpoint_re_set_one (void *bint)
14343 {
14344   /* Get past catch_errs.  */
14345   struct breakpoint *b = (struct breakpoint *) bint;
14346   struct cleanup *cleanups;
14347
14348   cleanups = prepare_re_set_context (b);
14349   b->ops->re_set (b);
14350   do_cleanups (cleanups);
14351   return 0;
14352 }
14353
14354 /* Re-set all breakpoints after symbols have been re-loaded.  */
14355 void
14356 breakpoint_re_set (void)
14357 {
14358   struct breakpoint *b, *b_tmp;
14359   enum language save_language;
14360   int save_input_radix;
14361   struct cleanup *old_chain;
14362
14363   save_language = current_language->la_language;
14364   save_input_radix = input_radix;
14365   old_chain = save_current_program_space ();
14366
14367   ALL_BREAKPOINTS_SAFE (b, b_tmp)
14368   {
14369     /* Format possible error msg.  */
14370     char *message = xstrprintf ("Error in re-setting breakpoint %d: ",
14371                                 b->number);
14372     struct cleanup *cleanups = make_cleanup (xfree, message);
14373     catch_errors (breakpoint_re_set_one, b, message, RETURN_MASK_ALL);
14374     do_cleanups (cleanups);
14375   }
14376   set_language (save_language);
14377   input_radix = save_input_radix;
14378
14379   jit_breakpoint_re_set ();
14380
14381   do_cleanups (old_chain);
14382
14383   create_overlay_event_breakpoint ();
14384   create_longjmp_master_breakpoint ();
14385   create_std_terminate_master_breakpoint ();
14386   create_exception_master_breakpoint ();
14387 }
14388 \f
14389 /* Reset the thread number of this breakpoint:
14390
14391    - If the breakpoint is for all threads, leave it as-is.
14392    - Else, reset it to the current thread for inferior_ptid.  */
14393 void
14394 breakpoint_re_set_thread (struct breakpoint *b)
14395 {
14396   if (b->thread != -1)
14397     {
14398       if (in_thread_list (inferior_ptid))
14399         b->thread = pid_to_thread_id (inferior_ptid);
14400
14401       /* We're being called after following a fork.  The new fork is
14402          selected as current, and unless this was a vfork will have a
14403          different program space from the original thread.  Reset that
14404          as well.  */
14405       b->loc->pspace = current_program_space;
14406     }
14407 }
14408
14409 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
14410    If from_tty is nonzero, it prints a message to that effect,
14411    which ends with a period (no newline).  */
14412
14413 void
14414 set_ignore_count (int bptnum, int count, int from_tty)
14415 {
14416   struct breakpoint *b;
14417
14418   if (count < 0)
14419     count = 0;
14420
14421   ALL_BREAKPOINTS (b)
14422     if (b->number == bptnum)
14423     {
14424       if (is_tracepoint (b))
14425         {
14426           if (from_tty && count != 0)
14427             printf_filtered (_("Ignore count ignored for tracepoint %d."),
14428                              bptnum);
14429           return;
14430         }
14431       
14432       b->ignore_count = count;
14433       if (from_tty)
14434         {
14435           if (count == 0)
14436             printf_filtered (_("Will stop next time "
14437                                "breakpoint %d is reached."),
14438                              bptnum);
14439           else if (count == 1)
14440             printf_filtered (_("Will ignore next crossing of breakpoint %d."),
14441                              bptnum);
14442           else
14443             printf_filtered (_("Will ignore next %d "
14444                                "crossings of breakpoint %d."),
14445                              count, bptnum);
14446         }
14447       observer_notify_breakpoint_modified (b);
14448       return;
14449     }
14450
14451   error (_("No breakpoint number %d."), bptnum);
14452 }
14453
14454 /* Command to set ignore-count of breakpoint N to COUNT.  */
14455
14456 static void
14457 ignore_command (char *args, int from_tty)
14458 {
14459   char *p = args;
14460   int num;
14461
14462   if (p == 0)
14463     error_no_arg (_("a breakpoint number"));
14464
14465   num = get_number (&p);
14466   if (num == 0)
14467     error (_("bad breakpoint number: '%s'"), args);
14468   if (*p == 0)
14469     error (_("Second argument (specified ignore-count) is missing."));
14470
14471   set_ignore_count (num,
14472                     longest_to_int (value_as_long (parse_and_eval (p))),
14473                     from_tty);
14474   if (from_tty)
14475     printf_filtered ("\n");
14476 }
14477 \f
14478 /* Call FUNCTION on each of the breakpoints
14479    whose numbers are given in ARGS.  */
14480
14481 static void
14482 map_breakpoint_numbers (char *args, void (*function) (struct breakpoint *,
14483                                                       void *),
14484                         void *data)
14485 {
14486   int num;
14487   struct breakpoint *b, *tmp;
14488   int match;
14489   struct get_number_or_range_state state;
14490
14491   if (args == 0)
14492     error_no_arg (_("one or more breakpoint numbers"));
14493
14494   init_number_or_range (&state, args);
14495
14496   while (!state.finished)
14497     {
14498       char *p = state.string;
14499
14500       match = 0;
14501
14502       num = get_number_or_range (&state);
14503       if (num == 0)
14504         {
14505           warning (_("bad breakpoint number at or near '%s'"), p);
14506         }
14507       else
14508         {
14509           ALL_BREAKPOINTS_SAFE (b, tmp)
14510             if (b->number == num)
14511               {
14512                 match = 1;
14513                 function (b, data);
14514                 break;
14515               }
14516           if (match == 0)
14517             printf_unfiltered (_("No breakpoint number %d.\n"), num);
14518         }
14519     }
14520 }
14521
14522 static struct bp_location *
14523 find_location_by_number (char *number)
14524 {
14525   char *dot = strchr (number, '.');
14526   char *p1;
14527   int bp_num;
14528   int loc_num;
14529   struct breakpoint *b;
14530   struct bp_location *loc;  
14531
14532   *dot = '\0';
14533
14534   p1 = number;
14535   bp_num = get_number (&p1);
14536   if (bp_num == 0)
14537     error (_("Bad breakpoint number '%s'"), number);
14538
14539   ALL_BREAKPOINTS (b)
14540     if (b->number == bp_num)
14541       {
14542         break;
14543       }
14544
14545   if (!b || b->number != bp_num)
14546     error (_("Bad breakpoint number '%s'"), number);
14547   
14548   p1 = dot+1;
14549   loc_num = get_number (&p1);
14550   if (loc_num == 0)
14551     error (_("Bad breakpoint location number '%s'"), number);
14552
14553   --loc_num;
14554   loc = b->loc;
14555   for (;loc_num && loc; --loc_num, loc = loc->next)
14556     ;
14557   if (!loc)
14558     error (_("Bad breakpoint location number '%s'"), dot+1);
14559     
14560   return loc;  
14561 }
14562
14563
14564 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
14565    If from_tty is nonzero, it prints a message to that effect,
14566    which ends with a period (no newline).  */
14567
14568 void
14569 disable_breakpoint (struct breakpoint *bpt)
14570 {
14571   /* Never disable a watchpoint scope breakpoint; we want to
14572      hit them when we leave scope so we can delete both the
14573      watchpoint and its scope breakpoint at that time.  */
14574   if (bpt->type == bp_watchpoint_scope)
14575     return;
14576
14577   /* You can't disable permanent breakpoints.  */
14578   if (bpt->enable_state == bp_permanent)
14579     return;
14580
14581   bpt->enable_state = bp_disabled;
14582
14583   /* Mark breakpoint locations modified.  */
14584   mark_breakpoint_modified (bpt);
14585
14586   if (target_supports_enable_disable_tracepoint ()
14587       && current_trace_status ()->running && is_tracepoint (bpt))
14588     {
14589       struct bp_location *location;
14590      
14591       for (location = bpt->loc; location; location = location->next)
14592         target_disable_tracepoint (location);
14593     }
14594
14595   update_global_location_list (0);
14596
14597   observer_notify_breakpoint_modified (bpt);
14598 }
14599
14600 /* A callback for iterate_over_related_breakpoints.  */
14601
14602 static void
14603 do_disable_breakpoint (struct breakpoint *b, void *ignore)
14604 {
14605   disable_breakpoint (b);
14606 }
14607
14608 /* A callback for map_breakpoint_numbers that calls
14609    disable_breakpoint.  */
14610
14611 static void
14612 do_map_disable_breakpoint (struct breakpoint *b, void *ignore)
14613 {
14614   iterate_over_related_breakpoints (b, do_disable_breakpoint, NULL);
14615 }
14616
14617 static void
14618 disable_command (char *args, int from_tty)
14619 {
14620   if (args == 0)
14621     {
14622       struct breakpoint *bpt;
14623
14624       ALL_BREAKPOINTS (bpt)
14625         if (user_breakpoint_p (bpt))
14626           disable_breakpoint (bpt);
14627     }
14628   else if (strchr (args, '.'))
14629     {
14630       struct bp_location *loc = find_location_by_number (args);
14631       if (loc)
14632         {
14633           if (loc->enabled)
14634             {
14635               loc->enabled = 0;
14636               mark_breakpoint_location_modified (loc);
14637             }
14638           if (target_supports_enable_disable_tracepoint ()
14639               && current_trace_status ()->running && loc->owner
14640               && is_tracepoint (loc->owner))
14641             target_disable_tracepoint (loc);
14642         }
14643       update_global_location_list (0);
14644     }
14645   else
14646     map_breakpoint_numbers (args, do_map_disable_breakpoint, NULL);
14647 }
14648
14649 static void
14650 enable_breakpoint_disp (struct breakpoint *bpt, enum bpdisp disposition,
14651                         int count)
14652 {
14653   int target_resources_ok;
14654
14655   if (bpt->type == bp_hardware_breakpoint)
14656     {
14657       int i;
14658       i = hw_breakpoint_used_count ();
14659       target_resources_ok = 
14660         target_can_use_hardware_watchpoint (bp_hardware_breakpoint, 
14661                                             i + 1, 0);
14662       if (target_resources_ok == 0)
14663         error (_("No hardware breakpoint support in the target."));
14664       else if (target_resources_ok < 0)
14665         error (_("Hardware breakpoints used exceeds limit."));
14666     }
14667
14668   if (is_watchpoint (bpt))
14669     {
14670       /* Initialize it just to avoid a GCC false warning.  */
14671       enum enable_state orig_enable_state = 0;
14672       volatile struct gdb_exception e;
14673
14674       TRY_CATCH (e, RETURN_MASK_ALL)
14675         {
14676           struct watchpoint *w = (struct watchpoint *) bpt;
14677
14678           orig_enable_state = bpt->enable_state;
14679           bpt->enable_state = bp_enabled;
14680           update_watchpoint (w, 1 /* reparse */);
14681         }
14682       if (e.reason < 0)
14683         {
14684           bpt->enable_state = orig_enable_state;
14685           exception_fprintf (gdb_stderr, e, _("Cannot enable watchpoint %d: "),
14686                              bpt->number);
14687           return;
14688         }
14689     }
14690
14691   if (bpt->enable_state != bp_permanent)
14692     bpt->enable_state = bp_enabled;
14693
14694   bpt->enable_state = bp_enabled;
14695
14696   /* Mark breakpoint locations modified.  */
14697   mark_breakpoint_modified (bpt);
14698
14699   if (target_supports_enable_disable_tracepoint ()
14700       && current_trace_status ()->running && is_tracepoint (bpt))
14701     {
14702       struct bp_location *location;
14703
14704       for (location = bpt->loc; location; location = location->next)
14705         target_enable_tracepoint (location);
14706     }
14707
14708   bpt->disposition = disposition;
14709   bpt->enable_count = count;
14710   update_global_location_list (1);
14711
14712   observer_notify_breakpoint_modified (bpt);
14713 }
14714
14715
14716 void
14717 enable_breakpoint (struct breakpoint *bpt)
14718 {
14719   enable_breakpoint_disp (bpt, bpt->disposition, 0);
14720 }
14721
14722 static void
14723 do_enable_breakpoint (struct breakpoint *bpt, void *arg)
14724 {
14725   enable_breakpoint (bpt);
14726 }
14727
14728 /* A callback for map_breakpoint_numbers that calls
14729    enable_breakpoint.  */
14730
14731 static void
14732 do_map_enable_breakpoint (struct breakpoint *b, void *ignore)
14733 {
14734   iterate_over_related_breakpoints (b, do_enable_breakpoint, NULL);
14735 }
14736
14737 /* The enable command enables the specified breakpoints (or all defined
14738    breakpoints) so they once again become (or continue to be) effective
14739    in stopping the inferior.  */
14740
14741 static void
14742 enable_command (char *args, int from_tty)
14743 {
14744   if (args == 0)
14745     {
14746       struct breakpoint *bpt;
14747
14748       ALL_BREAKPOINTS (bpt)
14749         if (user_breakpoint_p (bpt))
14750           enable_breakpoint (bpt);
14751     }
14752   else if (strchr (args, '.'))
14753     {
14754       struct bp_location *loc = find_location_by_number (args);
14755       if (loc)
14756         {
14757           if (!loc->enabled)
14758             {
14759               loc->enabled = 1;
14760               mark_breakpoint_location_modified (loc);
14761             }
14762           if (target_supports_enable_disable_tracepoint ()
14763               && current_trace_status ()->running && loc->owner
14764               && is_tracepoint (loc->owner))
14765             target_enable_tracepoint (loc);
14766         }
14767       update_global_location_list (1);
14768     }
14769   else
14770     map_breakpoint_numbers (args, do_map_enable_breakpoint, NULL);
14771 }
14772
14773 /* This struct packages up disposition data for application to multiple
14774    breakpoints.  */
14775
14776 struct disp_data
14777 {
14778   enum bpdisp disp;
14779   int count;
14780 };
14781
14782 static void
14783 do_enable_breakpoint_disp (struct breakpoint *bpt, void *arg)
14784 {
14785   struct disp_data disp_data = *(struct disp_data *) arg;
14786
14787   enable_breakpoint_disp (bpt, disp_data.disp, disp_data.count);
14788 }
14789
14790 static void
14791 do_map_enable_once_breakpoint (struct breakpoint *bpt, void *ignore)
14792 {
14793   struct disp_data disp = { disp_disable, 1 };
14794
14795   iterate_over_related_breakpoints (bpt, do_enable_breakpoint_disp, &disp);
14796 }
14797
14798 static void
14799 enable_once_command (char *args, int from_tty)
14800 {
14801   map_breakpoint_numbers (args, do_map_enable_once_breakpoint, NULL);
14802 }
14803
14804 static void
14805 do_map_enable_count_breakpoint (struct breakpoint *bpt, void *countptr)
14806 {
14807   struct disp_data disp = { disp_disable, *(int *) countptr };
14808
14809   iterate_over_related_breakpoints (bpt, do_enable_breakpoint_disp, &disp);
14810 }
14811
14812 static void
14813 enable_count_command (char *args, int from_tty)
14814 {
14815   int count = get_number (&args);
14816
14817   map_breakpoint_numbers (args, do_map_enable_count_breakpoint, &count);
14818 }
14819
14820 static void
14821 do_map_enable_delete_breakpoint (struct breakpoint *bpt, void *ignore)
14822 {
14823   struct disp_data disp = { disp_del, 1 };
14824
14825   iterate_over_related_breakpoints (bpt, do_enable_breakpoint_disp, &disp);
14826 }
14827
14828 static void
14829 enable_delete_command (char *args, int from_tty)
14830 {
14831   map_breakpoint_numbers (args, do_map_enable_delete_breakpoint, NULL);
14832 }
14833 \f
14834 static void
14835 set_breakpoint_cmd (char *args, int from_tty)
14836 {
14837 }
14838
14839 static void
14840 show_breakpoint_cmd (char *args, int from_tty)
14841 {
14842 }
14843
14844 /* Invalidate last known value of any hardware watchpoint if
14845    the memory which that value represents has been written to by
14846    GDB itself.  */
14847
14848 static void
14849 invalidate_bp_value_on_memory_change (struct inferior *inferior,
14850                                       CORE_ADDR addr, ssize_t len,
14851                                       const bfd_byte *data)
14852 {
14853   struct breakpoint *bp;
14854
14855   ALL_BREAKPOINTS (bp)
14856     if (bp->enable_state == bp_enabled
14857         && bp->type == bp_hardware_watchpoint)
14858       {
14859         struct watchpoint *wp = (struct watchpoint *) bp;
14860
14861         if (wp->val_valid && wp->val)
14862           {
14863             struct bp_location *loc;
14864
14865             for (loc = bp->loc; loc != NULL; loc = loc->next)
14866               if (loc->loc_type == bp_loc_hardware_watchpoint
14867                   && loc->address + loc->length > addr
14868                   && addr + len > loc->address)
14869                 {
14870                   value_free (wp->val);
14871                   wp->val = NULL;
14872                   wp->val_valid = 0;
14873                 }
14874           }
14875       }
14876 }
14877
14878 /* Create and insert a raw software breakpoint at PC.  Return an
14879    identifier, which should be used to remove the breakpoint later.
14880    In general, places which call this should be using something on the
14881    breakpoint chain instead; this function should be eliminated
14882    someday.  */
14883
14884 void *
14885 deprecated_insert_raw_breakpoint (struct gdbarch *gdbarch,
14886                                   struct address_space *aspace, CORE_ADDR pc)
14887 {
14888   struct bp_target_info *bp_tgt;
14889
14890   bp_tgt = XZALLOC (struct bp_target_info);
14891
14892   bp_tgt->placed_address_space = aspace;
14893   bp_tgt->placed_address = pc;
14894
14895   if (target_insert_breakpoint (gdbarch, bp_tgt) != 0)
14896     {
14897       /* Could not insert the breakpoint.  */
14898       xfree (bp_tgt);
14899       return NULL;
14900     }
14901
14902   return bp_tgt;
14903 }
14904
14905 /* Remove a breakpoint BP inserted by
14906    deprecated_insert_raw_breakpoint.  */
14907
14908 int
14909 deprecated_remove_raw_breakpoint (struct gdbarch *gdbarch, void *bp)
14910 {
14911   struct bp_target_info *bp_tgt = bp;
14912   int ret;
14913
14914   ret = target_remove_breakpoint (gdbarch, bp_tgt);
14915   xfree (bp_tgt);
14916
14917   return ret;
14918 }
14919
14920 /* One (or perhaps two) breakpoints used for software single
14921    stepping.  */
14922
14923 static void *single_step_breakpoints[2];
14924 static struct gdbarch *single_step_gdbarch[2];
14925
14926 /* Create and insert a breakpoint for software single step.  */
14927
14928 void
14929 insert_single_step_breakpoint (struct gdbarch *gdbarch,
14930                                struct address_space *aspace, 
14931                                CORE_ADDR next_pc)
14932 {
14933   void **bpt_p;
14934
14935   if (single_step_breakpoints[0] == NULL)
14936     {
14937       bpt_p = &single_step_breakpoints[0];
14938       single_step_gdbarch[0] = gdbarch;
14939     }
14940   else
14941     {
14942       gdb_assert (single_step_breakpoints[1] == NULL);
14943       bpt_p = &single_step_breakpoints[1];
14944       single_step_gdbarch[1] = gdbarch;
14945     }
14946
14947   /* NOTE drow/2006-04-11: A future improvement to this function would
14948      be to only create the breakpoints once, and actually put them on
14949      the breakpoint chain.  That would let us use set_raw_breakpoint.
14950      We could adjust the addresses each time they were needed.  Doing
14951      this requires corresponding changes elsewhere where single step
14952      breakpoints are handled, however.  So, for now, we use this.  */
14953
14954   *bpt_p = deprecated_insert_raw_breakpoint (gdbarch, aspace, next_pc);
14955   if (*bpt_p == NULL)
14956     error (_("Could not insert single-step breakpoint at %s"),
14957              paddress (gdbarch, next_pc));
14958 }
14959
14960 /* Check if the breakpoints used for software single stepping
14961    were inserted or not.  */
14962
14963 int
14964 single_step_breakpoints_inserted (void)
14965 {
14966   return (single_step_breakpoints[0] != NULL
14967           || single_step_breakpoints[1] != NULL);
14968 }
14969
14970 /* Remove and delete any breakpoints used for software single step.  */
14971
14972 void
14973 remove_single_step_breakpoints (void)
14974 {
14975   gdb_assert (single_step_breakpoints[0] != NULL);
14976
14977   /* See insert_single_step_breakpoint for more about this deprecated
14978      call.  */
14979   deprecated_remove_raw_breakpoint (single_step_gdbarch[0],
14980                                     single_step_breakpoints[0]);
14981   single_step_gdbarch[0] = NULL;
14982   single_step_breakpoints[0] = NULL;
14983
14984   if (single_step_breakpoints[1] != NULL)
14985     {
14986       deprecated_remove_raw_breakpoint (single_step_gdbarch[1],
14987                                         single_step_breakpoints[1]);
14988       single_step_gdbarch[1] = NULL;
14989       single_step_breakpoints[1] = NULL;
14990     }
14991 }
14992
14993 /* Delete software single step breakpoints without removing them from
14994    the inferior.  This is intended to be used if the inferior's address
14995    space where they were inserted is already gone, e.g. after exit or
14996    exec.  */
14997
14998 void
14999 cancel_single_step_breakpoints (void)
15000 {
15001   int i;
15002
15003   for (i = 0; i < 2; i++)
15004     if (single_step_breakpoints[i])
15005       {
15006         xfree (single_step_breakpoints[i]);
15007         single_step_breakpoints[i] = NULL;
15008         single_step_gdbarch[i] = NULL;
15009       }
15010 }
15011
15012 /* Detach software single-step breakpoints from INFERIOR_PTID without
15013    removing them.  */
15014
15015 static void
15016 detach_single_step_breakpoints (void)
15017 {
15018   int i;
15019
15020   for (i = 0; i < 2; i++)
15021     if (single_step_breakpoints[i])
15022       target_remove_breakpoint (single_step_gdbarch[i],
15023                                 single_step_breakpoints[i]);
15024 }
15025
15026 /* Check whether a software single-step breakpoint is inserted at
15027    PC.  */
15028
15029 static int
15030 single_step_breakpoint_inserted_here_p (struct address_space *aspace, 
15031                                         CORE_ADDR pc)
15032 {
15033   int i;
15034
15035   for (i = 0; i < 2; i++)
15036     {
15037       struct bp_target_info *bp_tgt = single_step_breakpoints[i];
15038       if (bp_tgt
15039           && breakpoint_address_match (bp_tgt->placed_address_space,
15040                                        bp_tgt->placed_address,
15041                                        aspace, pc))
15042         return 1;
15043     }
15044
15045   return 0;
15046 }
15047
15048 /* Returns 0 if 'bp' is NOT a syscall catchpoint,
15049    non-zero otherwise.  */
15050 static int
15051 is_syscall_catchpoint_enabled (struct breakpoint *bp)
15052 {
15053   if (syscall_catchpoint_p (bp)
15054       && bp->enable_state != bp_disabled
15055       && bp->enable_state != bp_call_disabled)
15056     return 1;
15057   else
15058     return 0;
15059 }
15060
15061 int
15062 catch_syscall_enabled (void)
15063 {
15064   struct catch_syscall_inferior_data *inf_data
15065     = get_catch_syscall_inferior_data (current_inferior ());
15066
15067   return inf_data->total_syscalls_count != 0;
15068 }
15069
15070 int
15071 catching_syscall_number (int syscall_number)
15072 {
15073   struct breakpoint *bp;
15074
15075   ALL_BREAKPOINTS (bp)
15076     if (is_syscall_catchpoint_enabled (bp))
15077       {
15078         struct syscall_catchpoint *c = (struct syscall_catchpoint *) bp;
15079
15080         if (c->syscalls_to_be_caught)
15081           {
15082             int i, iter;
15083             for (i = 0;
15084                  VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
15085                  i++)
15086               if (syscall_number == iter)
15087                 return 1;
15088           }
15089         else
15090           return 1;
15091       }
15092
15093   return 0;
15094 }
15095
15096 /* Complete syscall names.  Used by "catch syscall".  */
15097 static VEC (char_ptr) *
15098 catch_syscall_completer (struct cmd_list_element *cmd,
15099                          const char *text, const char *word)
15100 {
15101   const char **list = get_syscall_names ();
15102   VEC (char_ptr) *retlist
15103     = (list == NULL) ? NULL : complete_on_enum (list, word, word);
15104
15105   xfree (list);
15106   return retlist;
15107 }
15108
15109 /* Tracepoint-specific operations.  */
15110
15111 /* Set tracepoint count to NUM.  */
15112 static void
15113 set_tracepoint_count (int num)
15114 {
15115   tracepoint_count = num;
15116   set_internalvar_integer (lookup_internalvar ("tpnum"), num);
15117 }
15118
15119 static void
15120 trace_command (char *arg, int from_tty)
15121 {
15122   struct breakpoint_ops *ops;
15123   const char *arg_cp = arg;
15124
15125   if (arg && probe_linespec_to_ops (&arg_cp))
15126     ops = &tracepoint_probe_breakpoint_ops;
15127   else
15128     ops = &tracepoint_breakpoint_ops;
15129
15130   create_breakpoint (get_current_arch (),
15131                      arg,
15132                      NULL, 0, NULL, 1 /* parse arg */,
15133                      0 /* tempflag */,
15134                      bp_tracepoint /* type_wanted */,
15135                      0 /* Ignore count */,
15136                      pending_break_support,
15137                      ops,
15138                      from_tty,
15139                      1 /* enabled */,
15140                      0 /* internal */, 0);
15141 }
15142
15143 static void
15144 ftrace_command (char *arg, int from_tty)
15145 {
15146   create_breakpoint (get_current_arch (),
15147                      arg,
15148                      NULL, 0, NULL, 1 /* parse arg */,
15149                      0 /* tempflag */,
15150                      bp_fast_tracepoint /* type_wanted */,
15151                      0 /* Ignore count */,
15152                      pending_break_support,
15153                      &tracepoint_breakpoint_ops,
15154                      from_tty,
15155                      1 /* enabled */,
15156                      0 /* internal */, 0);
15157 }
15158
15159 /* strace command implementation.  Creates a static tracepoint.  */
15160
15161 static void
15162 strace_command (char *arg, int from_tty)
15163 {
15164   struct breakpoint_ops *ops;
15165
15166   /* Decide if we are dealing with a static tracepoint marker (`-m'),
15167      or with a normal static tracepoint.  */
15168   if (arg && strncmp (arg, "-m", 2) == 0 && isspace (arg[2]))
15169     ops = &strace_marker_breakpoint_ops;
15170   else
15171     ops = &tracepoint_breakpoint_ops;
15172
15173   create_breakpoint (get_current_arch (),
15174                      arg,
15175                      NULL, 0, NULL, 1 /* parse arg */,
15176                      0 /* tempflag */,
15177                      bp_static_tracepoint /* type_wanted */,
15178                      0 /* Ignore count */,
15179                      pending_break_support,
15180                      ops,
15181                      from_tty,
15182                      1 /* enabled */,
15183                      0 /* internal */, 0);
15184 }
15185
15186 /* Set up a fake reader function that gets command lines from a linked
15187    list that was acquired during tracepoint uploading.  */
15188
15189 static struct uploaded_tp *this_utp;
15190 static int next_cmd;
15191
15192 static char *
15193 read_uploaded_action (void)
15194 {
15195   char *rslt;
15196
15197   VEC_iterate (char_ptr, this_utp->cmd_strings, next_cmd, rslt);
15198
15199   next_cmd++;
15200
15201   return rslt;
15202 }
15203
15204 /* Given information about a tracepoint as recorded on a target (which
15205    can be either a live system or a trace file), attempt to create an
15206    equivalent GDB tracepoint.  This is not a reliable process, since
15207    the target does not necessarily have all the information used when
15208    the tracepoint was originally defined.  */
15209   
15210 struct tracepoint *
15211 create_tracepoint_from_upload (struct uploaded_tp *utp)
15212 {
15213   char *addr_str, small_buf[100];
15214   struct tracepoint *tp;
15215
15216   if (utp->at_string)
15217     addr_str = utp->at_string;
15218   else
15219     {
15220       /* In the absence of a source location, fall back to raw
15221          address.  Since there is no way to confirm that the address
15222          means the same thing as when the trace was started, warn the
15223          user.  */
15224       warning (_("Uploaded tracepoint %d has no "
15225                  "source location, using raw address"),
15226                utp->number);
15227       xsnprintf (small_buf, sizeof (small_buf), "*%s", hex_string (utp->addr));
15228       addr_str = small_buf;
15229     }
15230
15231   /* There's not much we can do with a sequence of bytecodes.  */
15232   if (utp->cond && !utp->cond_string)
15233     warning (_("Uploaded tracepoint %d condition "
15234                "has no source form, ignoring it"),
15235              utp->number);
15236
15237   if (!create_breakpoint (get_current_arch (),
15238                           addr_str,
15239                           utp->cond_string, -1, NULL,
15240                           0 /* parse cond/thread */,
15241                           0 /* tempflag */,
15242                           utp->type /* type_wanted */,
15243                           0 /* Ignore count */,
15244                           pending_break_support,
15245                           &tracepoint_breakpoint_ops,
15246                           0 /* from_tty */,
15247                           utp->enabled /* enabled */,
15248                           0 /* internal */,
15249                           CREATE_BREAKPOINT_FLAGS_INSERTED))
15250     return NULL;
15251
15252   /* Get the tracepoint we just created.  */
15253   tp = get_tracepoint (tracepoint_count);
15254   gdb_assert (tp != NULL);
15255
15256   if (utp->pass > 0)
15257     {
15258       xsnprintf (small_buf, sizeof (small_buf), "%d %d", utp->pass,
15259                  tp->base.number);
15260
15261       trace_pass_command (small_buf, 0);
15262     }
15263
15264   /* If we have uploaded versions of the original commands, set up a
15265      special-purpose "reader" function and call the usual command line
15266      reader, then pass the result to the breakpoint command-setting
15267      function.  */
15268   if (!VEC_empty (char_ptr, utp->cmd_strings))
15269     {
15270       struct command_line *cmd_list;
15271
15272       this_utp = utp;
15273       next_cmd = 0;
15274
15275       cmd_list = read_command_lines_1 (read_uploaded_action, 1, NULL, NULL);
15276
15277       breakpoint_set_commands (&tp->base, cmd_list);
15278     }
15279   else if (!VEC_empty (char_ptr, utp->actions)
15280            || !VEC_empty (char_ptr, utp->step_actions))
15281     warning (_("Uploaded tracepoint %d actions "
15282                "have no source form, ignoring them"),
15283              utp->number);
15284
15285   /* Copy any status information that might be available.  */
15286   tp->base.hit_count = utp->hit_count;
15287   tp->traceframe_usage = utp->traceframe_usage;
15288
15289   return tp;
15290 }
15291   
15292 /* Print information on tracepoint number TPNUM_EXP, or all if
15293    omitted.  */
15294
15295 static void
15296 tracepoints_info (char *args, int from_tty)
15297 {
15298   struct ui_out *uiout = current_uiout;
15299   int num_printed;
15300
15301   num_printed = breakpoint_1 (args, 0, is_tracepoint);
15302
15303   if (num_printed == 0)
15304     {
15305       if (args == NULL || *args == '\0')
15306         ui_out_message (uiout, 0, "No tracepoints.\n");
15307       else
15308         ui_out_message (uiout, 0, "No tracepoint matching '%s'.\n", args);
15309     }
15310
15311   default_collect_info ();
15312 }
15313
15314 /* The 'enable trace' command enables tracepoints.
15315    Not supported by all targets.  */
15316 static void
15317 enable_trace_command (char *args, int from_tty)
15318 {
15319   enable_command (args, from_tty);
15320 }
15321
15322 /* The 'disable trace' command disables tracepoints.
15323    Not supported by all targets.  */
15324 static void
15325 disable_trace_command (char *args, int from_tty)
15326 {
15327   disable_command (args, from_tty);
15328 }
15329
15330 /* Remove a tracepoint (or all if no argument).  */
15331 static void
15332 delete_trace_command (char *arg, int from_tty)
15333 {
15334   struct breakpoint *b, *b_tmp;
15335
15336   dont_repeat ();
15337
15338   if (arg == 0)
15339     {
15340       int breaks_to_delete = 0;
15341
15342       /* Delete all breakpoints if no argument.
15343          Do not delete internal or call-dummy breakpoints, these
15344          have to be deleted with an explicit breakpoint number 
15345          argument.  */
15346       ALL_TRACEPOINTS (b)
15347         if (is_tracepoint (b) && user_breakpoint_p (b))
15348           {
15349             breaks_to_delete = 1;
15350             break;
15351           }
15352
15353       /* Ask user only if there are some breakpoints to delete.  */
15354       if (!from_tty
15355           || (breaks_to_delete && query (_("Delete all tracepoints? "))))
15356         {
15357           ALL_BREAKPOINTS_SAFE (b, b_tmp)
15358             if (is_tracepoint (b) && user_breakpoint_p (b))
15359               delete_breakpoint (b);
15360         }
15361     }
15362   else
15363     map_breakpoint_numbers (arg, do_map_delete_breakpoint, NULL);
15364 }
15365
15366 /* Helper function for trace_pass_command.  */
15367
15368 static void
15369 trace_pass_set_count (struct tracepoint *tp, int count, int from_tty)
15370 {
15371   tp->pass_count = count;
15372   observer_notify_breakpoint_modified (&tp->base);
15373   if (from_tty)
15374     printf_filtered (_("Setting tracepoint %d's passcount to %d\n"),
15375                      tp->base.number, count);
15376 }
15377
15378 /* Set passcount for tracepoint.
15379
15380    First command argument is passcount, second is tracepoint number.
15381    If tracepoint number omitted, apply to most recently defined.
15382    Also accepts special argument "all".  */
15383
15384 static void
15385 trace_pass_command (char *args, int from_tty)
15386 {
15387   struct tracepoint *t1;
15388   unsigned int count;
15389
15390   if (args == 0 || *args == 0)
15391     error (_("passcount command requires an "
15392              "argument (count + optional TP num)"));
15393
15394   count = strtoul (args, &args, 10);    /* Count comes first, then TP num.  */
15395
15396   args = skip_spaces (args);
15397   if (*args && strncasecmp (args, "all", 3) == 0)
15398     {
15399       struct breakpoint *b;
15400
15401       args += 3;                        /* Skip special argument "all".  */
15402       if (*args)
15403         error (_("Junk at end of arguments."));
15404
15405       ALL_TRACEPOINTS (b)
15406       {
15407         t1 = (struct tracepoint *) b;
15408         trace_pass_set_count (t1, count, from_tty);
15409       }
15410     }
15411   else if (*args == '\0')
15412     {
15413       t1 = get_tracepoint_by_number (&args, NULL, 1);
15414       if (t1)
15415         trace_pass_set_count (t1, count, from_tty);
15416     }
15417   else
15418     {
15419       struct get_number_or_range_state state;
15420
15421       init_number_or_range (&state, args);
15422       while (!state.finished)
15423         {
15424           t1 = get_tracepoint_by_number (&args, &state, 1);
15425           if (t1)
15426             trace_pass_set_count (t1, count, from_tty);
15427         }
15428     }
15429 }
15430
15431 struct tracepoint *
15432 get_tracepoint (int num)
15433 {
15434   struct breakpoint *t;
15435
15436   ALL_TRACEPOINTS (t)
15437     if (t->number == num)
15438       return (struct tracepoint *) t;
15439
15440   return NULL;
15441 }
15442
15443 /* Find the tracepoint with the given target-side number (which may be
15444    different from the tracepoint number after disconnecting and
15445    reconnecting).  */
15446
15447 struct tracepoint *
15448 get_tracepoint_by_number_on_target (int num)
15449 {
15450   struct breakpoint *b;
15451
15452   ALL_TRACEPOINTS (b)
15453     {
15454       struct tracepoint *t = (struct tracepoint *) b;
15455
15456       if (t->number_on_target == num)
15457         return t;
15458     }
15459
15460   return NULL;
15461 }
15462
15463 /* Utility: parse a tracepoint number and look it up in the list.
15464    If STATE is not NULL, use, get_number_or_range_state and ignore ARG.
15465    If OPTIONAL_P is true, then if the argument is missing, the most
15466    recent tracepoint (tracepoint_count) is returned.  */
15467 struct tracepoint *
15468 get_tracepoint_by_number (char **arg,
15469                           struct get_number_or_range_state *state,
15470                           int optional_p)
15471 {
15472   struct breakpoint *t;
15473   int tpnum;
15474   char *instring = arg == NULL ? NULL : *arg;
15475
15476   if (state)
15477     {
15478       gdb_assert (!state->finished);
15479       tpnum = get_number_or_range (state);
15480     }
15481   else if (arg == NULL || *arg == NULL || ! **arg)
15482     {
15483       if (optional_p)
15484         tpnum = tracepoint_count;
15485       else
15486         error_no_arg (_("tracepoint number"));
15487     }
15488   else
15489     tpnum = get_number (arg);
15490
15491   if (tpnum <= 0)
15492     {
15493       if (instring && *instring)
15494         printf_filtered (_("bad tracepoint number at or near '%s'\n"), 
15495                          instring);
15496       else
15497         printf_filtered (_("Tracepoint argument missing "
15498                            "and no previous tracepoint\n"));
15499       return NULL;
15500     }
15501
15502   ALL_TRACEPOINTS (t)
15503     if (t->number == tpnum)
15504     {
15505       return (struct tracepoint *) t;
15506     }
15507
15508   printf_unfiltered ("No tracepoint number %d.\n", tpnum);
15509   return NULL;
15510 }
15511
15512 void
15513 print_recreate_thread (struct breakpoint *b, struct ui_file *fp)
15514 {
15515   if (b->thread != -1)
15516     fprintf_unfiltered (fp, " thread %d", b->thread);
15517
15518   if (b->task != 0)
15519     fprintf_unfiltered (fp, " task %d", b->task);
15520
15521   fprintf_unfiltered (fp, "\n");
15522 }
15523
15524 /* Save information on user settable breakpoints (watchpoints, etc) to
15525    a new script file named FILENAME.  If FILTER is non-NULL, call it
15526    on each breakpoint and only include the ones for which it returns
15527    non-zero.  */
15528
15529 static void
15530 save_breakpoints (char *filename, int from_tty,
15531                   int (*filter) (const struct breakpoint *))
15532 {
15533   struct breakpoint *tp;
15534   int any = 0;
15535   char *pathname;
15536   struct cleanup *cleanup;
15537   struct ui_file *fp;
15538   int extra_trace_bits = 0;
15539
15540   if (filename == 0 || *filename == 0)
15541     error (_("Argument required (file name in which to save)"));
15542
15543   /* See if we have anything to save.  */
15544   ALL_BREAKPOINTS (tp)
15545   {
15546     /* Skip internal and momentary breakpoints.  */
15547     if (!user_breakpoint_p (tp))
15548       continue;
15549
15550     /* If we have a filter, only save the breakpoints it accepts.  */
15551     if (filter && !filter (tp))
15552       continue;
15553
15554     any = 1;
15555
15556     if (is_tracepoint (tp))
15557       {
15558         extra_trace_bits = 1;
15559
15560         /* We can stop searching.  */
15561         break;
15562       }
15563   }
15564
15565   if (!any)
15566     {
15567       warning (_("Nothing to save."));
15568       return;
15569     }
15570
15571   pathname = tilde_expand (filename);
15572   cleanup = make_cleanup (xfree, pathname);
15573   fp = gdb_fopen (pathname, "w");
15574   if (!fp)
15575     error (_("Unable to open file '%s' for saving (%s)"),
15576            filename, safe_strerror (errno));
15577   make_cleanup_ui_file_delete (fp);
15578
15579   if (extra_trace_bits)
15580     save_trace_state_variables (fp);
15581
15582   ALL_BREAKPOINTS (tp)
15583   {
15584     /* Skip internal and momentary breakpoints.  */
15585     if (!user_breakpoint_p (tp))
15586       continue;
15587
15588     /* If we have a filter, only save the breakpoints it accepts.  */
15589     if (filter && !filter (tp))
15590       continue;
15591
15592     tp->ops->print_recreate (tp, fp);
15593
15594     /* Note, we can't rely on tp->number for anything, as we can't
15595        assume the recreated breakpoint numbers will match.  Use $bpnum
15596        instead.  */
15597
15598     if (tp->cond_string)
15599       fprintf_unfiltered (fp, "  condition $bpnum %s\n", tp->cond_string);
15600
15601     if (tp->ignore_count)
15602       fprintf_unfiltered (fp, "  ignore $bpnum %d\n", tp->ignore_count);
15603
15604     if (tp->commands)
15605       {
15606         volatile struct gdb_exception ex;       
15607
15608         fprintf_unfiltered (fp, "  commands\n");
15609         
15610         ui_out_redirect (current_uiout, fp);
15611         TRY_CATCH (ex, RETURN_MASK_ALL)
15612           {
15613             print_command_lines (current_uiout, tp->commands->commands, 2);
15614           }
15615         ui_out_redirect (current_uiout, NULL);
15616
15617         if (ex.reason < 0)
15618           throw_exception (ex);
15619
15620         fprintf_unfiltered (fp, "  end\n");
15621       }
15622
15623     if (tp->enable_state == bp_disabled)
15624       fprintf_unfiltered (fp, "disable\n");
15625
15626     /* If this is a multi-location breakpoint, check if the locations
15627        should be individually disabled.  Watchpoint locations are
15628        special, and not user visible.  */
15629     if (!is_watchpoint (tp) && tp->loc && tp->loc->next)
15630       {
15631         struct bp_location *loc;
15632         int n = 1;
15633
15634         for (loc = tp->loc; loc != NULL; loc = loc->next, n++)
15635           if (!loc->enabled)
15636             fprintf_unfiltered (fp, "disable $bpnum.%d\n", n);
15637       }
15638   }
15639
15640   if (extra_trace_bits && *default_collect)
15641     fprintf_unfiltered (fp, "set default-collect %s\n", default_collect);
15642
15643   do_cleanups (cleanup);
15644   if (from_tty)
15645     printf_filtered (_("Saved to file '%s'.\n"), filename);
15646 }
15647
15648 /* The `save breakpoints' command.  */
15649
15650 static void
15651 save_breakpoints_command (char *args, int from_tty)
15652 {
15653   save_breakpoints (args, from_tty, NULL);
15654 }
15655
15656 /* The `save tracepoints' command.  */
15657
15658 static void
15659 save_tracepoints_command (char *args, int from_tty)
15660 {
15661   save_breakpoints (args, from_tty, is_tracepoint);
15662 }
15663
15664 /* Create a vector of all tracepoints.  */
15665
15666 VEC(breakpoint_p) *
15667 all_tracepoints (void)
15668 {
15669   VEC(breakpoint_p) *tp_vec = 0;
15670   struct breakpoint *tp;
15671
15672   ALL_TRACEPOINTS (tp)
15673   {
15674     VEC_safe_push (breakpoint_p, tp_vec, tp);
15675   }
15676
15677   return tp_vec;
15678 }
15679
15680 \f
15681 /* This help string is used for the break, hbreak, tbreak and thbreak
15682    commands.  It is defined as a macro to prevent duplication.
15683    COMMAND should be a string constant containing the name of the
15684    command.  */
15685 #define BREAK_ARGS_HELP(command) \
15686 command" [PROBE_MODIFIER] [LOCATION] [thread THREADNUM] [if CONDITION]\n\
15687 PROBE_MODIFIER shall be present if the command is to be placed in a\n\
15688 probe point.  Accepted values are `-probe' (for a generic, automatically\n\
15689 guessed probe type) or `-probe-stap' (for a SystemTap probe).\n\
15690 LOCATION may be a line number, function name, or \"*\" and an address.\n\
15691 If a line number is specified, break at start of code for that line.\n\
15692 If a function is specified, break at start of code for that function.\n\
15693 If an address is specified, break at that exact address.\n\
15694 With no LOCATION, uses current execution address of the selected\n\
15695 stack frame.  This is useful for breaking on return to a stack frame.\n\
15696 \n\
15697 THREADNUM is the number from \"info threads\".\n\
15698 CONDITION is a boolean expression.\n\
15699 \n\
15700 Multiple breakpoints at one place are permitted, and useful if their\n\
15701 conditions are different.\n\
15702 \n\
15703 Do \"help breakpoints\" for info on other commands dealing with breakpoints."
15704
15705 /* List of subcommands for "catch".  */
15706 static struct cmd_list_element *catch_cmdlist;
15707
15708 /* List of subcommands for "tcatch".  */
15709 static struct cmd_list_element *tcatch_cmdlist;
15710
15711 void
15712 add_catch_command (char *name, char *docstring,
15713                    void (*sfunc) (char *args, int from_tty,
15714                                   struct cmd_list_element *command),
15715                    completer_ftype *completer,
15716                    void *user_data_catch,
15717                    void *user_data_tcatch)
15718 {
15719   struct cmd_list_element *command;
15720
15721   command = add_cmd (name, class_breakpoint, NULL, docstring,
15722                      &catch_cmdlist);
15723   set_cmd_sfunc (command, sfunc);
15724   set_cmd_context (command, user_data_catch);
15725   set_cmd_completer (command, completer);
15726
15727   command = add_cmd (name, class_breakpoint, NULL, docstring,
15728                      &tcatch_cmdlist);
15729   set_cmd_sfunc (command, sfunc);
15730   set_cmd_context (command, user_data_tcatch);
15731   set_cmd_completer (command, completer);
15732 }
15733
15734 static void
15735 clear_syscall_counts (struct inferior *inf)
15736 {
15737   struct catch_syscall_inferior_data *inf_data
15738     = get_catch_syscall_inferior_data (inf);
15739
15740   inf_data->total_syscalls_count = 0;
15741   inf_data->any_syscall_count = 0;
15742   VEC_free (int, inf_data->syscalls_counts);
15743 }
15744
15745 static void
15746 save_command (char *arg, int from_tty)
15747 {
15748   printf_unfiltered (_("\"save\" must be followed by "
15749                        "the name of a save subcommand.\n"));
15750   help_list (save_cmdlist, "save ", -1, gdb_stdout);
15751 }
15752
15753 struct breakpoint *
15754 iterate_over_breakpoints (int (*callback) (struct breakpoint *, void *),
15755                           void *data)
15756 {
15757   struct breakpoint *b, *b_tmp;
15758
15759   ALL_BREAKPOINTS_SAFE (b, b_tmp)
15760     {
15761       if ((*callback) (b, data))
15762         return b;
15763     }
15764
15765   return NULL;
15766 }
15767
15768 /* Zero if any of the breakpoint's locations could be a location where
15769    functions have been inlined, nonzero otherwise.  */
15770
15771 static int
15772 is_non_inline_function (struct breakpoint *b)
15773 {
15774   /* The shared library event breakpoint is set on the address of a
15775      non-inline function.  */
15776   if (b->type == bp_shlib_event)
15777     return 1;
15778
15779   return 0;
15780 }
15781
15782 /* Nonzero if the specified PC cannot be a location where functions
15783    have been inlined.  */
15784
15785 int
15786 pc_at_non_inline_function (struct address_space *aspace, CORE_ADDR pc,
15787                            const struct target_waitstatus *ws)
15788 {
15789   struct breakpoint *b;
15790   struct bp_location *bl;
15791
15792   ALL_BREAKPOINTS (b)
15793     {
15794       if (!is_non_inline_function (b))
15795         continue;
15796
15797       for (bl = b->loc; bl != NULL; bl = bl->next)
15798         {
15799           if (!bl->shlib_disabled
15800               && bpstat_check_location (bl, aspace, pc, ws))
15801             return 1;
15802         }
15803     }
15804
15805   return 0;
15806 }
15807
15808 /* Remove any references to OBJFILE which is going to be freed.  */
15809
15810 void
15811 breakpoint_free_objfile (struct objfile *objfile)
15812 {
15813   struct bp_location **locp, *loc;
15814
15815   ALL_BP_LOCATIONS (loc, locp)
15816     if (loc->symtab != NULL && loc->symtab->objfile == objfile)
15817       loc->symtab = NULL;
15818 }
15819
15820 void
15821 initialize_breakpoint_ops (void)
15822 {
15823   static int initialized = 0;
15824
15825   struct breakpoint_ops *ops;
15826
15827   if (initialized)
15828     return;
15829   initialized = 1;
15830
15831   /* The breakpoint_ops structure to be inherit by all kinds of
15832      breakpoints (real breakpoints, i.e., user "break" breakpoints,
15833      internal and momentary breakpoints, etc.).  */
15834   ops = &bkpt_base_breakpoint_ops;
15835   *ops = base_breakpoint_ops;
15836   ops->re_set = bkpt_re_set;
15837   ops->insert_location = bkpt_insert_location;
15838   ops->remove_location = bkpt_remove_location;
15839   ops->breakpoint_hit = bkpt_breakpoint_hit;
15840   ops->create_sals_from_address = bkpt_create_sals_from_address;
15841   ops->create_breakpoints_sal = bkpt_create_breakpoints_sal;
15842   ops->decode_linespec = bkpt_decode_linespec;
15843
15844   /* The breakpoint_ops structure to be used in regular breakpoints.  */
15845   ops = &bkpt_breakpoint_ops;
15846   *ops = bkpt_base_breakpoint_ops;
15847   ops->re_set = bkpt_re_set;
15848   ops->resources_needed = bkpt_resources_needed;
15849   ops->print_it = bkpt_print_it;
15850   ops->print_mention = bkpt_print_mention;
15851   ops->print_recreate = bkpt_print_recreate;
15852
15853   /* Ranged breakpoints.  */
15854   ops = &ranged_breakpoint_ops;
15855   *ops = bkpt_breakpoint_ops;
15856   ops->breakpoint_hit = breakpoint_hit_ranged_breakpoint;
15857   ops->resources_needed = resources_needed_ranged_breakpoint;
15858   ops->print_it = print_it_ranged_breakpoint;
15859   ops->print_one = print_one_ranged_breakpoint;
15860   ops->print_one_detail = print_one_detail_ranged_breakpoint;
15861   ops->print_mention = print_mention_ranged_breakpoint;
15862   ops->print_recreate = print_recreate_ranged_breakpoint;
15863
15864   /* Internal breakpoints.  */
15865   ops = &internal_breakpoint_ops;
15866   *ops = bkpt_base_breakpoint_ops;
15867   ops->re_set = internal_bkpt_re_set;
15868   ops->check_status = internal_bkpt_check_status;
15869   ops->print_it = internal_bkpt_print_it;
15870   ops->print_mention = internal_bkpt_print_mention;
15871
15872   /* Momentary breakpoints.  */
15873   ops = &momentary_breakpoint_ops;
15874   *ops = bkpt_base_breakpoint_ops;
15875   ops->re_set = momentary_bkpt_re_set;
15876   ops->check_status = momentary_bkpt_check_status;
15877   ops->print_it = momentary_bkpt_print_it;
15878   ops->print_mention = momentary_bkpt_print_mention;
15879
15880   /* Momentary breakpoints for bp_longjmp and bp_exception.  */
15881   ops = &longjmp_breakpoint_ops;
15882   *ops = momentary_breakpoint_ops;
15883   ops->dtor = longjmp_bkpt_dtor;
15884
15885   /* Probe breakpoints.  */
15886   ops = &bkpt_probe_breakpoint_ops;
15887   *ops = bkpt_breakpoint_ops;
15888   ops->insert_location = bkpt_probe_insert_location;
15889   ops->remove_location = bkpt_probe_remove_location;
15890   ops->create_sals_from_address = bkpt_probe_create_sals_from_address;
15891   ops->decode_linespec = bkpt_probe_decode_linespec;
15892
15893   /* GNU v3 exception catchpoints.  */
15894   ops = &gnu_v3_exception_catchpoint_ops;
15895   *ops = bkpt_breakpoint_ops;
15896   ops->print_it = print_it_exception_catchpoint;
15897   ops->print_one = print_one_exception_catchpoint;
15898   ops->print_mention = print_mention_exception_catchpoint;
15899   ops->print_recreate = print_recreate_exception_catchpoint;
15900
15901   /* Watchpoints.  */
15902   ops = &watchpoint_breakpoint_ops;
15903   *ops = base_breakpoint_ops;
15904   ops->dtor = dtor_watchpoint;
15905   ops->re_set = re_set_watchpoint;
15906   ops->insert_location = insert_watchpoint;
15907   ops->remove_location = remove_watchpoint;
15908   ops->breakpoint_hit = breakpoint_hit_watchpoint;
15909   ops->check_status = check_status_watchpoint;
15910   ops->resources_needed = resources_needed_watchpoint;
15911   ops->works_in_software_mode = works_in_software_mode_watchpoint;
15912   ops->print_it = print_it_watchpoint;
15913   ops->print_mention = print_mention_watchpoint;
15914   ops->print_recreate = print_recreate_watchpoint;
15915
15916   /* Masked watchpoints.  */
15917   ops = &masked_watchpoint_breakpoint_ops;
15918   *ops = watchpoint_breakpoint_ops;
15919   ops->insert_location = insert_masked_watchpoint;
15920   ops->remove_location = remove_masked_watchpoint;
15921   ops->resources_needed = resources_needed_masked_watchpoint;
15922   ops->works_in_software_mode = works_in_software_mode_masked_watchpoint;
15923   ops->print_it = print_it_masked_watchpoint;
15924   ops->print_one_detail = print_one_detail_masked_watchpoint;
15925   ops->print_mention = print_mention_masked_watchpoint;
15926   ops->print_recreate = print_recreate_masked_watchpoint;
15927
15928   /* Tracepoints.  */
15929   ops = &tracepoint_breakpoint_ops;
15930   *ops = base_breakpoint_ops;
15931   ops->re_set = tracepoint_re_set;
15932   ops->breakpoint_hit = tracepoint_breakpoint_hit;
15933   ops->print_one_detail = tracepoint_print_one_detail;
15934   ops->print_mention = tracepoint_print_mention;
15935   ops->print_recreate = tracepoint_print_recreate;
15936   ops->create_sals_from_address = tracepoint_create_sals_from_address;
15937   ops->create_breakpoints_sal = tracepoint_create_breakpoints_sal;
15938   ops->decode_linespec = tracepoint_decode_linespec;
15939
15940   /* Probe tracepoints.  */
15941   ops = &tracepoint_probe_breakpoint_ops;
15942   *ops = tracepoint_breakpoint_ops;
15943   ops->create_sals_from_address = tracepoint_probe_create_sals_from_address;
15944   ops->decode_linespec = tracepoint_probe_decode_linespec;
15945
15946   /* Static tracepoints with marker (`-m').  */
15947   ops = &strace_marker_breakpoint_ops;
15948   *ops = tracepoint_breakpoint_ops;
15949   ops->create_sals_from_address = strace_marker_create_sals_from_address;
15950   ops->create_breakpoints_sal = strace_marker_create_breakpoints_sal;
15951   ops->decode_linespec = strace_marker_decode_linespec;
15952
15953   /* Fork catchpoints.  */
15954   ops = &catch_fork_breakpoint_ops;
15955   *ops = base_breakpoint_ops;
15956   ops->insert_location = insert_catch_fork;
15957   ops->remove_location = remove_catch_fork;
15958   ops->breakpoint_hit = breakpoint_hit_catch_fork;
15959   ops->print_it = print_it_catch_fork;
15960   ops->print_one = print_one_catch_fork;
15961   ops->print_mention = print_mention_catch_fork;
15962   ops->print_recreate = print_recreate_catch_fork;
15963
15964   /* Vfork catchpoints.  */
15965   ops = &catch_vfork_breakpoint_ops;
15966   *ops = base_breakpoint_ops;
15967   ops->insert_location = insert_catch_vfork;
15968   ops->remove_location = remove_catch_vfork;
15969   ops->breakpoint_hit = breakpoint_hit_catch_vfork;
15970   ops->print_it = print_it_catch_vfork;
15971   ops->print_one = print_one_catch_vfork;
15972   ops->print_mention = print_mention_catch_vfork;
15973   ops->print_recreate = print_recreate_catch_vfork;
15974
15975   /* Exec catchpoints.  */
15976   ops = &catch_exec_breakpoint_ops;
15977   *ops = base_breakpoint_ops;
15978   ops->dtor = dtor_catch_exec;
15979   ops->insert_location = insert_catch_exec;
15980   ops->remove_location = remove_catch_exec;
15981   ops->breakpoint_hit = breakpoint_hit_catch_exec;
15982   ops->print_it = print_it_catch_exec;
15983   ops->print_one = print_one_catch_exec;
15984   ops->print_mention = print_mention_catch_exec;
15985   ops->print_recreate = print_recreate_catch_exec;
15986
15987   /* Syscall catchpoints.  */
15988   ops = &catch_syscall_breakpoint_ops;
15989   *ops = base_breakpoint_ops;
15990   ops->dtor = dtor_catch_syscall;
15991   ops->insert_location = insert_catch_syscall;
15992   ops->remove_location = remove_catch_syscall;
15993   ops->breakpoint_hit = breakpoint_hit_catch_syscall;
15994   ops->print_it = print_it_catch_syscall;
15995   ops->print_one = print_one_catch_syscall;
15996   ops->print_mention = print_mention_catch_syscall;
15997   ops->print_recreate = print_recreate_catch_syscall;
15998
15999   /* Solib-related catchpoints.  */
16000   ops = &catch_solib_breakpoint_ops;
16001   *ops = base_breakpoint_ops;
16002   ops->dtor = dtor_catch_solib;
16003   ops->insert_location = insert_catch_solib;
16004   ops->remove_location = remove_catch_solib;
16005   ops->breakpoint_hit = breakpoint_hit_catch_solib;
16006   ops->check_status = check_status_catch_solib;
16007   ops->print_it = print_it_catch_solib;
16008   ops->print_one = print_one_catch_solib;
16009   ops->print_mention = print_mention_catch_solib;
16010   ops->print_recreate = print_recreate_catch_solib;
16011
16012   ops = &dprintf_breakpoint_ops;
16013   *ops = bkpt_base_breakpoint_ops;
16014   ops->re_set = bkpt_re_set;
16015   ops->resources_needed = bkpt_resources_needed;
16016   ops->print_it = bkpt_print_it;
16017   ops->print_mention = bkpt_print_mention;
16018   ops->print_recreate = bkpt_print_recreate;
16019 }
16020
16021 /* Chain containing all defined "enable breakpoint" subcommands.  */
16022
16023 static struct cmd_list_element *enablebreaklist = NULL;
16024
16025 void
16026 _initialize_breakpoint (void)
16027 {
16028   struct cmd_list_element *c;
16029
16030   initialize_breakpoint_ops ();
16031
16032   observer_attach_solib_unloaded (disable_breakpoints_in_unloaded_shlib);
16033   observer_attach_inferior_exit (clear_syscall_counts);
16034   observer_attach_memory_changed (invalidate_bp_value_on_memory_change);
16035
16036   breakpoint_objfile_key
16037     = register_objfile_data_with_cleanup (NULL, free_breakpoint_probes);
16038
16039   catch_syscall_inferior_data
16040     = register_inferior_data_with_cleanup (NULL,
16041                                            catch_syscall_inferior_data_cleanup);
16042
16043   breakpoint_chain = 0;
16044   /* Don't bother to call set_breakpoint_count.  $bpnum isn't useful
16045      before a breakpoint is set.  */
16046   breakpoint_count = 0;
16047
16048   tracepoint_count = 0;
16049
16050   add_com ("ignore", class_breakpoint, ignore_command, _("\
16051 Set ignore-count of breakpoint number N to COUNT.\n\
16052 Usage is `ignore N COUNT'."));
16053   if (xdb_commands)
16054     add_com_alias ("bc", "ignore", class_breakpoint, 1);
16055
16056   add_com ("commands", class_breakpoint, commands_command, _("\
16057 Set commands to be executed when a breakpoint is hit.\n\
16058 Give breakpoint number as argument after \"commands\".\n\
16059 With no argument, the targeted breakpoint is the last one set.\n\
16060 The commands themselves follow starting on the next line.\n\
16061 Type a line containing \"end\" to indicate the end of them.\n\
16062 Give \"silent\" as the first line to make the breakpoint silent;\n\
16063 then no output is printed when it is hit, except what the commands print."));
16064
16065   c = add_com ("condition", class_breakpoint, condition_command, _("\
16066 Specify breakpoint number N to break only if COND is true.\n\
16067 Usage is `condition N COND', where N is an integer and COND is an\n\
16068 expression to be evaluated whenever breakpoint N is reached."));
16069   set_cmd_completer (c, condition_completer);
16070
16071   c = add_com ("tbreak", class_breakpoint, tbreak_command, _("\
16072 Set a temporary breakpoint.\n\
16073 Like \"break\" except the breakpoint is only temporary,\n\
16074 so it will be deleted when hit.  Equivalent to \"break\" followed\n\
16075 by using \"enable delete\" on the breakpoint number.\n\
16076 \n"
16077 BREAK_ARGS_HELP ("tbreak")));
16078   set_cmd_completer (c, location_completer);
16079
16080   c = add_com ("hbreak", class_breakpoint, hbreak_command, _("\
16081 Set a hardware assisted breakpoint.\n\
16082 Like \"break\" except the breakpoint requires hardware support,\n\
16083 some target hardware may not have this support.\n\
16084 \n"
16085 BREAK_ARGS_HELP ("hbreak")));
16086   set_cmd_completer (c, location_completer);
16087
16088   c = add_com ("thbreak", class_breakpoint, thbreak_command, _("\
16089 Set a temporary hardware assisted breakpoint.\n\
16090 Like \"hbreak\" except the breakpoint is only temporary,\n\
16091 so it will be deleted when hit.\n\
16092 \n"
16093 BREAK_ARGS_HELP ("thbreak")));
16094   set_cmd_completer (c, location_completer);
16095
16096   add_prefix_cmd ("enable", class_breakpoint, enable_command, _("\
16097 Enable some breakpoints.\n\
16098 Give breakpoint numbers (separated by spaces) as arguments.\n\
16099 With no subcommand, breakpoints are enabled until you command otherwise.\n\
16100 This is used to cancel the effect of the \"disable\" command.\n\
16101 With a subcommand you can enable temporarily."),
16102                   &enablelist, "enable ", 1, &cmdlist);
16103   if (xdb_commands)
16104     add_com ("ab", class_breakpoint, enable_command, _("\
16105 Enable some breakpoints.\n\
16106 Give breakpoint numbers (separated by spaces) as arguments.\n\
16107 With no subcommand, breakpoints are enabled until you command otherwise.\n\
16108 This is used to cancel the effect of the \"disable\" command.\n\
16109 With a subcommand you can enable temporarily."));
16110
16111   add_com_alias ("en", "enable", class_breakpoint, 1);
16112
16113   add_prefix_cmd ("breakpoints", class_breakpoint, enable_command, _("\
16114 Enable some breakpoints.\n\
16115 Give breakpoint numbers (separated by spaces) as arguments.\n\
16116 This is used to cancel the effect of the \"disable\" command.\n\
16117 May be abbreviated to simply \"enable\".\n"),
16118                    &enablebreaklist, "enable breakpoints ", 1, &enablelist);
16119
16120   add_cmd ("once", no_class, enable_once_command, _("\
16121 Enable breakpoints for one hit.  Give breakpoint numbers.\n\
16122 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
16123            &enablebreaklist);
16124
16125   add_cmd ("delete", no_class, enable_delete_command, _("\
16126 Enable breakpoints and delete when hit.  Give breakpoint numbers.\n\
16127 If a breakpoint is hit while enabled in this fashion, it is deleted."),
16128            &enablebreaklist);
16129
16130   add_cmd ("count", no_class, enable_count_command, _("\
16131 Enable breakpoints for COUNT hits.  Give count and then breakpoint numbers.\n\
16132 If a breakpoint is hit while enabled in this fashion,\n\
16133 the count is decremented; when it reaches zero, the breakpoint is disabled."),
16134            &enablebreaklist);
16135
16136   add_cmd ("delete", no_class, enable_delete_command, _("\
16137 Enable breakpoints and delete when hit.  Give breakpoint numbers.\n\
16138 If a breakpoint is hit while enabled in this fashion, it is deleted."),
16139            &enablelist);
16140
16141   add_cmd ("once", no_class, enable_once_command, _("\
16142 Enable breakpoints for one hit.  Give breakpoint numbers.\n\
16143 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
16144            &enablelist);
16145
16146   add_cmd ("count", no_class, enable_count_command, _("\
16147 Enable breakpoints for COUNT hits.  Give count and then breakpoint numbers.\n\
16148 If a breakpoint is hit while enabled in this fashion,\n\
16149 the count is decremented; when it reaches zero, the breakpoint is disabled."),
16150            &enablelist);
16151
16152   add_prefix_cmd ("disable", class_breakpoint, disable_command, _("\
16153 Disable some breakpoints.\n\
16154 Arguments are breakpoint numbers with spaces in between.\n\
16155 To disable all breakpoints, give no argument.\n\
16156 A disabled breakpoint is not forgotten, but has no effect until re-enabled."),
16157                   &disablelist, "disable ", 1, &cmdlist);
16158   add_com_alias ("dis", "disable", class_breakpoint, 1);
16159   add_com_alias ("disa", "disable", class_breakpoint, 1);
16160   if (xdb_commands)
16161     add_com ("sb", class_breakpoint, disable_command, _("\
16162 Disable some breakpoints.\n\
16163 Arguments are breakpoint numbers with spaces in between.\n\
16164 To disable all breakpoints, give no argument.\n\
16165 A disabled breakpoint is not forgotten, but has no effect until re-enabled."));
16166
16167   add_cmd ("breakpoints", class_alias, disable_command, _("\
16168 Disable some breakpoints.\n\
16169 Arguments are breakpoint numbers with spaces in between.\n\
16170 To disable all breakpoints, give no argument.\n\
16171 A disabled breakpoint is not forgotten, but has no effect until re-enabled.\n\
16172 This command may be abbreviated \"disable\"."),
16173            &disablelist);
16174
16175   add_prefix_cmd ("delete", class_breakpoint, delete_command, _("\
16176 Delete some breakpoints or auto-display expressions.\n\
16177 Arguments are breakpoint numbers with spaces in between.\n\
16178 To delete all breakpoints, give no argument.\n\
16179 \n\
16180 Also a prefix command for deletion of other GDB objects.\n\
16181 The \"unset\" command is also an alias for \"delete\"."),
16182                   &deletelist, "delete ", 1, &cmdlist);
16183   add_com_alias ("d", "delete", class_breakpoint, 1);
16184   add_com_alias ("del", "delete", class_breakpoint, 1);
16185   if (xdb_commands)
16186     add_com ("db", class_breakpoint, delete_command, _("\
16187 Delete some breakpoints.\n\
16188 Arguments are breakpoint numbers with spaces in between.\n\
16189 To delete all breakpoints, give no argument.\n"));
16190
16191   add_cmd ("breakpoints", class_alias, delete_command, _("\
16192 Delete some breakpoints or auto-display expressions.\n\
16193 Arguments are breakpoint numbers with spaces in between.\n\
16194 To delete all breakpoints, give no argument.\n\
16195 This command may be abbreviated \"delete\"."),
16196            &deletelist);
16197
16198   add_com ("clear", class_breakpoint, clear_command, _("\
16199 Clear breakpoint at specified line or function.\n\
16200 Argument may be line number, function name, or \"*\" and an address.\n\
16201 If line number is specified, all breakpoints in that line are cleared.\n\
16202 If function is specified, breakpoints at beginning of function are cleared.\n\
16203 If an address is specified, breakpoints at that address are cleared.\n\
16204 \n\
16205 With no argument, clears all breakpoints in the line that the selected frame\n\
16206 is executing in.\n\
16207 \n\
16208 See also the \"delete\" command which clears breakpoints by number."));
16209   add_com_alias ("cl", "clear", class_breakpoint, 1);
16210
16211   c = add_com ("break", class_breakpoint, break_command, _("\
16212 Set breakpoint at specified line or function.\n"
16213 BREAK_ARGS_HELP ("break")));
16214   set_cmd_completer (c, location_completer);
16215
16216   add_com_alias ("b", "break", class_run, 1);
16217   add_com_alias ("br", "break", class_run, 1);
16218   add_com_alias ("bre", "break", class_run, 1);
16219   add_com_alias ("brea", "break", class_run, 1);
16220
16221   if (xdb_commands)
16222    add_com_alias ("ba", "break", class_breakpoint, 1);
16223
16224   if (dbx_commands)
16225     {
16226       add_abbrev_prefix_cmd ("stop", class_breakpoint, stop_command, _("\
16227 Break in function/address or break at a line in the current file."),
16228                              &stoplist, "stop ", 1, &cmdlist);
16229       add_cmd ("in", class_breakpoint, stopin_command,
16230                _("Break in function or address."), &stoplist);
16231       add_cmd ("at", class_breakpoint, stopat_command,
16232                _("Break at a line in the current file."), &stoplist);
16233       add_com ("status", class_info, breakpoints_info, _("\
16234 Status of user-settable breakpoints, or breakpoint number NUMBER.\n\
16235 The \"Type\" column indicates one of:\n\
16236 \tbreakpoint     - normal breakpoint\n\
16237 \twatchpoint     - watchpoint\n\
16238 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
16239 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
16240 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
16241 address and file/line number respectively.\n\
16242 \n\
16243 Convenience variable \"$_\" and default examine address for \"x\"\n\
16244 are set to the address of the last breakpoint listed unless the command\n\
16245 is prefixed with \"server \".\n\n\
16246 Convenience variable \"$bpnum\" contains the number of the last\n\
16247 breakpoint set."));
16248     }
16249
16250   add_info ("breakpoints", breakpoints_info, _("\
16251 Status of specified breakpoints (all user-settable breakpoints if no argument).\n\
16252 The \"Type\" column indicates one of:\n\
16253 \tbreakpoint     - normal breakpoint\n\
16254 \twatchpoint     - watchpoint\n\
16255 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
16256 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
16257 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
16258 address and file/line number respectively.\n\
16259 \n\
16260 Convenience variable \"$_\" and default examine address for \"x\"\n\
16261 are set to the address of the last breakpoint listed unless the command\n\
16262 is prefixed with \"server \".\n\n\
16263 Convenience variable \"$bpnum\" contains the number of the last\n\
16264 breakpoint set."));
16265
16266   add_info_alias ("b", "breakpoints", 1);
16267
16268   if (xdb_commands)
16269     add_com ("lb", class_breakpoint, breakpoints_info, _("\
16270 Status of user-settable breakpoints, or breakpoint number NUMBER.\n\
16271 The \"Type\" column indicates one of:\n\
16272 \tbreakpoint     - normal breakpoint\n\
16273 \twatchpoint     - watchpoint\n\
16274 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
16275 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
16276 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
16277 address and file/line number respectively.\n\
16278 \n\
16279 Convenience variable \"$_\" and default examine address for \"x\"\n\
16280 are set to the address of the last breakpoint listed unless the command\n\
16281 is prefixed with \"server \".\n\n\
16282 Convenience variable \"$bpnum\" contains the number of the last\n\
16283 breakpoint set."));
16284
16285   add_cmd ("breakpoints", class_maintenance, maintenance_info_breakpoints, _("\
16286 Status of all breakpoints, or breakpoint number NUMBER.\n\
16287 The \"Type\" column indicates one of:\n\
16288 \tbreakpoint     - normal breakpoint\n\
16289 \twatchpoint     - watchpoint\n\
16290 \tlongjmp        - internal breakpoint used to step through longjmp()\n\
16291 \tlongjmp resume - internal breakpoint at the target of longjmp()\n\
16292 \tuntil          - internal breakpoint used by the \"until\" command\n\
16293 \tfinish         - internal breakpoint used by the \"finish\" command\n\
16294 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
16295 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
16296 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
16297 address and file/line number respectively.\n\
16298 \n\
16299 Convenience variable \"$_\" and default examine address for \"x\"\n\
16300 are set to the address of the last breakpoint listed unless the command\n\
16301 is prefixed with \"server \".\n\n\
16302 Convenience variable \"$bpnum\" contains the number of the last\n\
16303 breakpoint set."),
16304            &maintenanceinfolist);
16305
16306   add_prefix_cmd ("catch", class_breakpoint, catch_command, _("\
16307 Set catchpoints to catch events."),
16308                   &catch_cmdlist, "catch ",
16309                   0/*allow-unknown*/, &cmdlist);
16310
16311   add_prefix_cmd ("tcatch", class_breakpoint, tcatch_command, _("\
16312 Set temporary catchpoints to catch events."),
16313                   &tcatch_cmdlist, "tcatch ",
16314                   0/*allow-unknown*/, &cmdlist);
16315
16316   /* Add catch and tcatch sub-commands.  */
16317   add_catch_command ("catch", _("\
16318 Catch an exception, when caught."),
16319                      catch_catch_command,
16320                      NULL,
16321                      CATCH_PERMANENT,
16322                      CATCH_TEMPORARY);
16323   add_catch_command ("throw", _("\
16324 Catch an exception, when thrown."),
16325                      catch_throw_command,
16326                      NULL,
16327                      CATCH_PERMANENT,
16328                      CATCH_TEMPORARY);
16329   add_catch_command ("fork", _("Catch calls to fork."),
16330                      catch_fork_command_1,
16331                      NULL,
16332                      (void *) (uintptr_t) catch_fork_permanent,
16333                      (void *) (uintptr_t) catch_fork_temporary);
16334   add_catch_command ("vfork", _("Catch calls to vfork."),
16335                      catch_fork_command_1,
16336                      NULL,
16337                      (void *) (uintptr_t) catch_vfork_permanent,
16338                      (void *) (uintptr_t) catch_vfork_temporary);
16339   add_catch_command ("exec", _("Catch calls to exec."),
16340                      catch_exec_command_1,
16341                      NULL,
16342                      CATCH_PERMANENT,
16343                      CATCH_TEMPORARY);
16344   add_catch_command ("load", _("Catch loads of shared libraries.\n\
16345 Usage: catch load [REGEX]\n\
16346 If REGEX is given, only stop for libraries matching the regular expression."),
16347                      catch_load_command_1,
16348                      NULL,
16349                      CATCH_PERMANENT,
16350                      CATCH_TEMPORARY);
16351   add_catch_command ("unload", _("Catch unloads of shared libraries.\n\
16352 Usage: catch unload [REGEX]\n\
16353 If REGEX is given, only stop for libraries matching the regular expression."),
16354                      catch_unload_command_1,
16355                      NULL,
16356                      CATCH_PERMANENT,
16357                      CATCH_TEMPORARY);
16358   add_catch_command ("syscall", _("\
16359 Catch system calls by their names and/or numbers.\n\
16360 Arguments say which system calls to catch.  If no arguments\n\
16361 are given, every system call will be caught.\n\
16362 Arguments, if given, should be one or more system call names\n\
16363 (if your system supports that), or system call numbers."),
16364                      catch_syscall_command_1,
16365                      catch_syscall_completer,
16366                      CATCH_PERMANENT,
16367                      CATCH_TEMPORARY);
16368
16369   c = add_com ("watch", class_breakpoint, watch_command, _("\
16370 Set a watchpoint for an expression.\n\
16371 Usage: watch [-l|-location] EXPRESSION\n\
16372 A watchpoint stops execution of your program whenever the value of\n\
16373 an expression changes.\n\
16374 If -l or -location is given, this evaluates EXPRESSION and watches\n\
16375 the memory to which it refers."));
16376   set_cmd_completer (c, expression_completer);
16377
16378   c = add_com ("rwatch", class_breakpoint, rwatch_command, _("\
16379 Set a read watchpoint for an expression.\n\
16380 Usage: rwatch [-l|-location] EXPRESSION\n\
16381 A watchpoint stops execution of your program whenever the value of\n\
16382 an expression is read.\n\
16383 If -l or -location is given, this evaluates EXPRESSION and watches\n\
16384 the memory to which it refers."));
16385   set_cmd_completer (c, expression_completer);
16386
16387   c = add_com ("awatch", class_breakpoint, awatch_command, _("\
16388 Set a watchpoint for an expression.\n\
16389 Usage: awatch [-l|-location] EXPRESSION\n\
16390 A watchpoint stops execution of your program whenever the value of\n\
16391 an expression is either read or written.\n\
16392 If -l or -location is given, this evaluates EXPRESSION and watches\n\
16393 the memory to which it refers."));
16394   set_cmd_completer (c, expression_completer);
16395
16396   add_info ("watchpoints", watchpoints_info, _("\
16397 Status of specified watchpoints (all watchpoints if no argument)."));
16398
16399   /* XXX: cagney/2005-02-23: This should be a boolean, and should
16400      respond to changes - contrary to the description.  */
16401   add_setshow_zinteger_cmd ("can-use-hw-watchpoints", class_support,
16402                             &can_use_hw_watchpoints, _("\
16403 Set debugger's willingness to use watchpoint hardware."), _("\
16404 Show debugger's willingness to use watchpoint hardware."), _("\
16405 If zero, gdb will not use hardware for new watchpoints, even if\n\
16406 such is available.  (However, any hardware watchpoints that were\n\
16407 created before setting this to nonzero, will continue to use watchpoint\n\
16408 hardware.)"),
16409                             NULL,
16410                             show_can_use_hw_watchpoints,
16411                             &setlist, &showlist);
16412
16413   can_use_hw_watchpoints = 1;
16414
16415   /* Tracepoint manipulation commands.  */
16416
16417   c = add_com ("trace", class_breakpoint, trace_command, _("\
16418 Set a tracepoint at specified line or function.\n\
16419 \n"
16420 BREAK_ARGS_HELP ("trace") "\n\
16421 Do \"help tracepoints\" for info on other tracepoint commands."));
16422   set_cmd_completer (c, location_completer);
16423
16424   add_com_alias ("tp", "trace", class_alias, 0);
16425   add_com_alias ("tr", "trace", class_alias, 1);
16426   add_com_alias ("tra", "trace", class_alias, 1);
16427   add_com_alias ("trac", "trace", class_alias, 1);
16428
16429   c = add_com ("ftrace", class_breakpoint, ftrace_command, _("\
16430 Set a fast tracepoint at specified line or function.\n\
16431 \n"
16432 BREAK_ARGS_HELP ("ftrace") "\n\
16433 Do \"help tracepoints\" for info on other tracepoint commands."));
16434   set_cmd_completer (c, location_completer);
16435
16436   c = add_com ("strace", class_breakpoint, strace_command, _("\
16437 Set a static tracepoint at specified line, function or marker.\n\
16438 \n\
16439 strace [LOCATION] [if CONDITION]\n\
16440 LOCATION may be a line number, function name, \"*\" and an address,\n\
16441 or -m MARKER_ID.\n\
16442 If a line number is specified, probe the marker at start of code\n\
16443 for that line.  If a function is specified, probe the marker at start\n\
16444 of code for that function.  If an address is specified, probe the marker\n\
16445 at that exact address.  If a marker id is specified, probe the marker\n\
16446 with that name.  With no LOCATION, uses current execution address of\n\
16447 the selected stack frame.\n\
16448 Static tracepoints accept an extra collect action -- ``collect $_sdata''.\n\
16449 This collects arbitrary user data passed in the probe point call to the\n\
16450 tracing library.  You can inspect it when analyzing the trace buffer,\n\
16451 by printing the $_sdata variable like any other convenience variable.\n\
16452 \n\
16453 CONDITION is a boolean expression.\n\
16454 \n\
16455 Multiple tracepoints at one place are permitted, and useful if their\n\
16456 conditions are different.\n\
16457 \n\
16458 Do \"help breakpoints\" for info on other commands dealing with breakpoints.\n\
16459 Do \"help tracepoints\" for info on other tracepoint commands."));
16460   set_cmd_completer (c, location_completer);
16461
16462   add_info ("tracepoints", tracepoints_info, _("\
16463 Status of specified tracepoints (all tracepoints if no argument).\n\
16464 Convenience variable \"$tpnum\" contains the number of the\n\
16465 last tracepoint set."));
16466
16467   add_info_alias ("tp", "tracepoints", 1);
16468
16469   add_cmd ("tracepoints", class_trace, delete_trace_command, _("\
16470 Delete specified tracepoints.\n\
16471 Arguments are tracepoint numbers, separated by spaces.\n\
16472 No argument means delete all tracepoints."),
16473            &deletelist);
16474   add_alias_cmd ("tr", "tracepoints", class_trace, 1, &deletelist);
16475
16476   c = add_cmd ("tracepoints", class_trace, disable_trace_command, _("\
16477 Disable specified tracepoints.\n\
16478 Arguments are tracepoint numbers, separated by spaces.\n\
16479 No argument means disable all tracepoints."),
16480            &disablelist);
16481   deprecate_cmd (c, "disable");
16482
16483   c = add_cmd ("tracepoints", class_trace, enable_trace_command, _("\
16484 Enable specified tracepoints.\n\
16485 Arguments are tracepoint numbers, separated by spaces.\n\
16486 No argument means enable all tracepoints."),
16487            &enablelist);
16488   deprecate_cmd (c, "enable");
16489
16490   add_com ("passcount", class_trace, trace_pass_command, _("\
16491 Set the passcount for a tracepoint.\n\
16492 The trace will end when the tracepoint has been passed 'count' times.\n\
16493 Usage: passcount COUNT TPNUM, where TPNUM may also be \"all\";\n\
16494 if TPNUM is omitted, passcount refers to the last tracepoint defined."));
16495
16496   add_prefix_cmd ("save", class_breakpoint, save_command,
16497                   _("Save breakpoint definitions as a script."),
16498                   &save_cmdlist, "save ",
16499                   0/*allow-unknown*/, &cmdlist);
16500
16501   c = add_cmd ("breakpoints", class_breakpoint, save_breakpoints_command, _("\
16502 Save current breakpoint definitions as a script.\n\
16503 This includes all types of breakpoints (breakpoints, watchpoints,\n\
16504 catchpoints, tracepoints).  Use the 'source' command in another debug\n\
16505 session to restore them."),
16506                &save_cmdlist);
16507   set_cmd_completer (c, filename_completer);
16508
16509   c = add_cmd ("tracepoints", class_trace, save_tracepoints_command, _("\
16510 Save current tracepoint definitions as a script.\n\
16511 Use the 'source' command in another debug session to restore them."),
16512                &save_cmdlist);
16513   set_cmd_completer (c, filename_completer);
16514
16515   c = add_com_alias ("save-tracepoints", "save tracepoints", class_trace, 0);
16516   deprecate_cmd (c, "save tracepoints");
16517
16518   add_prefix_cmd ("breakpoint", class_maintenance, set_breakpoint_cmd, _("\
16519 Breakpoint specific settings\n\
16520 Configure various breakpoint-specific variables such as\n\
16521 pending breakpoint behavior"),
16522                   &breakpoint_set_cmdlist, "set breakpoint ",
16523                   0/*allow-unknown*/, &setlist);
16524   add_prefix_cmd ("breakpoint", class_maintenance, show_breakpoint_cmd, _("\
16525 Breakpoint specific settings\n\
16526 Configure various breakpoint-specific variables such as\n\
16527 pending breakpoint behavior"),
16528                   &breakpoint_show_cmdlist, "show breakpoint ",
16529                   0/*allow-unknown*/, &showlist);
16530
16531   add_setshow_auto_boolean_cmd ("pending", no_class,
16532                                 &pending_break_support, _("\
16533 Set debugger's behavior regarding pending breakpoints."), _("\
16534 Show debugger's behavior regarding pending breakpoints."), _("\
16535 If on, an unrecognized breakpoint location will cause gdb to create a\n\
16536 pending breakpoint.  If off, an unrecognized breakpoint location results in\n\
16537 an error.  If auto, an unrecognized breakpoint location results in a\n\
16538 user-query to see if a pending breakpoint should be created."),
16539                                 NULL,
16540                                 show_pending_break_support,
16541                                 &breakpoint_set_cmdlist,
16542                                 &breakpoint_show_cmdlist);
16543
16544   pending_break_support = AUTO_BOOLEAN_AUTO;
16545
16546   add_setshow_boolean_cmd ("auto-hw", no_class,
16547                            &automatic_hardware_breakpoints, _("\
16548 Set automatic usage of hardware breakpoints."), _("\
16549 Show automatic usage of hardware breakpoints."), _("\
16550 If set, the debugger will automatically use hardware breakpoints for\n\
16551 breakpoints set with \"break\" but falling in read-only memory.  If not set,\n\
16552 a warning will be emitted for such breakpoints."),
16553                            NULL,
16554                            show_automatic_hardware_breakpoints,
16555                            &breakpoint_set_cmdlist,
16556                            &breakpoint_show_cmdlist);
16557
16558   add_setshow_auto_boolean_cmd ("always-inserted", class_support,
16559                                 &always_inserted_mode, _("\
16560 Set mode for inserting breakpoints."), _("\
16561 Show mode for inserting breakpoints."), _("\
16562 When this mode is off, breakpoints are inserted in inferior when it is\n\
16563 resumed, and removed when execution stops.  When this mode is on,\n\
16564 breakpoints are inserted immediately and removed only when the user\n\
16565 deletes the breakpoint.  When this mode is auto (which is the default),\n\
16566 the behaviour depends on the non-stop setting (see help set non-stop).\n\
16567 In this case, if gdb is controlling the inferior in non-stop mode, gdb\n\
16568 behaves as if always-inserted mode is on; if gdb is controlling the\n\
16569 inferior in all-stop mode, gdb behaves as if always-inserted mode is off."),
16570                                 NULL,
16571                                 &show_always_inserted_mode,
16572                                 &breakpoint_set_cmdlist,
16573                                 &breakpoint_show_cmdlist);
16574
16575   add_setshow_enum_cmd ("condition-evaluation", class_breakpoint,
16576                         condition_evaluation_enums,
16577                         &condition_evaluation_mode_1, _("\
16578 Set mode of breakpoint condition evaluation."), _("\
16579 Show mode of breakpoint condition evaluation."), _("\
16580 When this is set to \"host\", breakpoint conditions will be\n\
16581 evaluated on the host's side by GDB.  When it is set to \"target\",\n\
16582 breakpoint conditions will be downloaded to the target (if the target\n\
16583 supports such feature) and conditions will be evaluated on the target's side.\n\
16584 If this is set to \"auto\" (default), this will be automatically set to\n\
16585 \"target\" if it supports condition evaluation, otherwise it will\n\
16586 be set to \"gdb\""),
16587                            &set_condition_evaluation_mode,
16588                            &show_condition_evaluation_mode,
16589                            &breakpoint_set_cmdlist,
16590                            &breakpoint_show_cmdlist);
16591
16592   add_com ("break-range", class_breakpoint, break_range_command, _("\
16593 Set a breakpoint for an address range.\n\
16594 break-range START-LOCATION, END-LOCATION\n\
16595 where START-LOCATION and END-LOCATION can be one of the following:\n\
16596   LINENUM, for that line in the current file,\n\
16597   FILE:LINENUM, for that line in that file,\n\
16598   +OFFSET, for that number of lines after the current line\n\
16599            or the start of the range\n\
16600   FUNCTION, for the first line in that function,\n\
16601   FILE:FUNCTION, to distinguish among like-named static functions.\n\
16602   *ADDRESS, for the instruction at that address.\n\
16603 \n\
16604 The breakpoint will stop execution of the inferior whenever it executes\n\
16605 an instruction at any address within the [START-LOCATION, END-LOCATION]\n\
16606 range (including START-LOCATION and END-LOCATION)."));
16607
16608   c = add_com ("dprintf", class_breakpoint, dprintf_command, _("\
16609 Set a dynamic printf at specified line or function.\n\
16610 dprintf location,format string,arg1,arg2,...\n\
16611 location may be a line number, function name, or \"*\" and an address.\n\
16612 If a line number is specified, break at start of code for that line.\n\
16613 If a function is specified, break at start of code for that function.\n\
16614 "));
16615   set_cmd_completer (c, location_completer);
16616
16617   add_setshow_enum_cmd ("dprintf-style", class_support,
16618                         dprintf_style_enums, &dprintf_style, _("\
16619 Set the style of usage for dynamic printf."), _("\
16620 Show the style of usage for dynamic printf."), _("\
16621 This setting chooses how GDB will do a dynamic printf.\n\
16622 If the value is \"gdb\", then the printing is done by GDB to its own\n\
16623 console, as with the \"printf\" command.\n\
16624 If the value is \"call\", the print is done by calling a function in your\n\
16625 program; by default printf(), but you can choose a different function or\n\
16626 output stream by setting dprintf-function and dprintf-channel."),
16627                         update_dprintf_commands, NULL,
16628                         &setlist, &showlist);
16629
16630   dprintf_function = xstrdup ("printf");
16631   add_setshow_string_cmd ("dprintf-function", class_support,
16632                           &dprintf_function, _("\
16633 Set the function to use for dynamic printf"), _("\
16634 Show the function to use for dynamic printf"), NULL,
16635                           update_dprintf_commands, NULL,
16636                           &setlist, &showlist);
16637
16638   dprintf_channel = xstrdup ("");
16639   add_setshow_string_cmd ("dprintf-channel", class_support,
16640                           &dprintf_channel, _("\
16641 Set the channel to use for dynamic printf"), _("\
16642 Show the channel to use for dynamic printf"), NULL,
16643                           update_dprintf_commands, NULL,
16644                           &setlist, &showlist);
16645
16646   add_setshow_boolean_cmd ("disconnected-dprintf", no_class,
16647                            &disconnected_dprintf, _("\
16648 Set whether dprintf continues after GDB disconnects."), _("\
16649 Show whether dprintf continues after GDB disconnects."), _("\
16650 Use this to let dprintf commands continue to hit and produce output\n\
16651 even if GDB disconnects or detaches from the target."),
16652                            NULL,
16653                            NULL,
16654                            &setlist, &showlist);
16655
16656   add_com ("agent-printf", class_vars, agent_printf_command, _("\
16657 agent-printf \"printf format string\", arg1, arg2, arg3, ..., argn\n\
16658 (target agent only) This is useful for formatted output in user-defined commands."));
16659
16660   automatic_hardware_breakpoints = 1;
16661
16662   observer_attach_about_to_proceed (breakpoint_about_to_proceed);
16663 }