Add "volatile" keyword to "struct gdb_exception" declaration
[platform/upstream/binutils.git] / gdb / breakpoint.c
1 /* Everything about breakpoints, for GDB.
2
3    Copyright (C) 1986-2014 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 <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 "ax-gdb.h"
70 #include "dummy-frame.h"
71
72 #include "format.h"
73
74 /* readline include files */
75 #include "readline/readline.h"
76 #include "readline/history.h"
77
78 /* readline defines this.  */
79 #undef savestring
80
81 #include "mi/mi-common.h"
82 #include "python/python.h"
83
84 /* Enums for exception-handling support.  */
85 enum exception_event_kind
86 {
87   EX_EVENT_THROW,
88   EX_EVENT_RETHROW,
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                                             char *, char *, enum bptype,
122                                             enum bpdisp, int, int,
123                                             int,
124                                             const struct breakpoint_ops *,
125                                             int, int, int, unsigned);
126
127 static void decode_linespec_default (struct breakpoint *, char **,
128                                      struct symtabs_and_lines *);
129
130 static void clear_command (char *, int);
131
132 static void catch_command (char *, int);
133
134 static int can_use_hardware_watchpoint (struct value *);
135
136 static void break_command_1 (char *, int, int);
137
138 static void mention (struct breakpoint *);
139
140 static struct breakpoint *set_raw_breakpoint_without_location (struct gdbarch *,
141                                                                enum bptype,
142                                                                const struct breakpoint_ops *);
143 static struct bp_location *add_location_to_breakpoint (struct breakpoint *,
144                                                        const struct symtab_and_line *);
145
146 /* This function is used in gdbtk sources and thus can not be made
147    static.  */
148 struct breakpoint *set_raw_breakpoint (struct gdbarch *gdbarch,
149                                        struct symtab_and_line,
150                                        enum bptype,
151                                        const struct breakpoint_ops *);
152
153 static struct breakpoint *
154   momentary_breakpoint_from_master (struct breakpoint *orig,
155                                     enum bptype type,
156                                     const struct breakpoint_ops *ops);
157
158 static void breakpoint_adjustment_warning (CORE_ADDR, CORE_ADDR, int, int);
159
160 static CORE_ADDR adjust_breakpoint_address (struct gdbarch *gdbarch,
161                                             CORE_ADDR bpaddr,
162                                             enum bptype bptype);
163
164 static void describe_other_breakpoints (struct gdbarch *,
165                                         struct program_space *, CORE_ADDR,
166                                         struct obj_section *, int);
167
168 static int breakpoint_address_match (struct address_space *aspace1,
169                                      CORE_ADDR addr1,
170                                      struct address_space *aspace2,
171                                      CORE_ADDR addr2);
172
173 static int watchpoint_locations_match (struct bp_location *loc1,
174                                        struct bp_location *loc2);
175
176 static int breakpoint_location_address_match (struct bp_location *bl,
177                                               struct address_space *aspace,
178                                               CORE_ADDR addr);
179
180 static void breakpoints_info (char *, int);
181
182 static void watchpoints_info (char *, int);
183
184 static int breakpoint_1 (char *, int, 
185                          int (*) (const struct breakpoint *));
186
187 static int breakpoint_cond_eval (void *);
188
189 static void cleanup_executing_breakpoints (void *);
190
191 static void commands_command (char *, int);
192
193 static void condition_command (char *, int);
194
195 typedef enum
196   {
197     mark_inserted,
198     mark_uninserted
199   }
200 insertion_state_t;
201
202 static int remove_breakpoint (struct bp_location *, insertion_state_t);
203 static int remove_breakpoint_1 (struct bp_location *, insertion_state_t);
204
205 static enum print_stop_action print_bp_stop_message (bpstat bs);
206
207 static int watchpoint_check (void *);
208
209 static void maintenance_info_breakpoints (char *, int);
210
211 static int hw_breakpoint_used_count (void);
212
213 static int hw_watchpoint_use_count (struct breakpoint *);
214
215 static int hw_watchpoint_used_count_others (struct breakpoint *except,
216                                             enum bptype type,
217                                             int *other_type_used);
218
219 static void hbreak_command (char *, int);
220
221 static void thbreak_command (char *, int);
222
223 static void enable_breakpoint_disp (struct breakpoint *, enum bpdisp,
224                                     int count);
225
226 static void stop_command (char *arg, int from_tty);
227
228 static void stopin_command (char *arg, int from_tty);
229
230 static void stopat_command (char *arg, int from_tty);
231
232 static void tcatch_command (char *arg, int from_tty);
233
234 static void detach_single_step_breakpoints (void);
235
236 static int single_step_breakpoint_inserted_here_p (struct address_space *,
237                                                    CORE_ADDR pc);
238
239 static void free_bp_location (struct bp_location *loc);
240 static void incref_bp_location (struct bp_location *loc);
241 static void decref_bp_location (struct bp_location **loc);
242
243 static struct bp_location *allocate_bp_location (struct breakpoint *bpt);
244
245 static void update_global_location_list (int);
246
247 static void update_global_location_list_nothrow (int);
248
249 static int is_hardware_watchpoint (const struct breakpoint *bpt);
250
251 static void insert_breakpoint_locations (void);
252
253 static int syscall_catchpoint_p (struct breakpoint *b);
254
255 static void tracepoints_info (char *, int);
256
257 static void delete_trace_command (char *, int);
258
259 static void enable_trace_command (char *, int);
260
261 static void disable_trace_command (char *, int);
262
263 static void trace_pass_command (char *, int);
264
265 static void set_tracepoint_count (int num);
266
267 static int is_masked_watchpoint (const struct breakpoint *b);
268
269 static struct bp_location **get_first_locp_gte_addr (CORE_ADDR address);
270
271 /* Return 1 if B refers to a static tracepoint set by marker ("-m"), zero
272    otherwise.  */
273
274 static int strace_marker_p (struct breakpoint *b);
275
276 /* The abstract base class all breakpoint_ops structures inherit
277    from.  */
278 struct breakpoint_ops base_breakpoint_ops;
279
280 /* The breakpoint_ops structure to be inherited by all breakpoint_ops
281    that are implemented on top of software or hardware breakpoints
282    (user breakpoints, internal and momentary breakpoints, etc.).  */
283 static struct breakpoint_ops bkpt_base_breakpoint_ops;
284
285 /* Internal breakpoints class type.  */
286 static struct breakpoint_ops internal_breakpoint_ops;
287
288 /* Momentary breakpoints class type.  */
289 static struct breakpoint_ops momentary_breakpoint_ops;
290
291 /* Momentary breakpoints for bp_longjmp and bp_exception class type.  */
292 static struct breakpoint_ops longjmp_breakpoint_ops;
293
294 /* The breakpoint_ops structure to be used in regular user created
295    breakpoints.  */
296 struct breakpoint_ops bkpt_breakpoint_ops;
297
298 /* Breakpoints set on probes.  */
299 static struct breakpoint_ops bkpt_probe_breakpoint_ops;
300
301 /* Dynamic printf class type.  */
302 struct breakpoint_ops dprintf_breakpoint_ops;
303
304 /* The style in which to perform a dynamic printf.  This is a user
305    option because different output options have different tradeoffs;
306    if GDB does the printing, there is better error handling if there
307    is a problem with any of the arguments, but using an inferior
308    function lets you have special-purpose printers and sending of
309    output to the same place as compiled-in print functions.  */
310
311 static const char dprintf_style_gdb[] = "gdb";
312 static const char dprintf_style_call[] = "call";
313 static const char dprintf_style_agent[] = "agent";
314 static const char *const dprintf_style_enums[] = {
315   dprintf_style_gdb,
316   dprintf_style_call,
317   dprintf_style_agent,
318   NULL
319 };
320 static const char *dprintf_style = dprintf_style_gdb;
321
322 /* The function to use for dynamic printf if the preferred style is to
323    call into the inferior.  The value is simply a string that is
324    copied into the command, so it can be anything that GDB can
325    evaluate to a callable address, not necessarily a function name.  */
326
327 static char *dprintf_function = "";
328
329 /* The channel to use for dynamic printf if the preferred style is to
330    call into the inferior; if a nonempty string, it will be passed to
331    the call as the first argument, with the format string as the
332    second.  As with the dprintf function, this can be anything that
333    GDB knows how to evaluate, so in addition to common choices like
334    "stderr", this could be an app-specific expression like
335    "mystreams[curlogger]".  */
336
337 static char *dprintf_channel = "";
338
339 /* True if dprintf commands should continue to operate even if GDB
340    has disconnected.  */
341 static int disconnected_dprintf = 1;
342
343 /* A reference-counted struct command_line.  This lets multiple
344    breakpoints share a single command list.  */
345 struct counted_command_line
346 {
347   /* The reference count.  */
348   int refc;
349
350   /* The command list.  */
351   struct command_line *commands;
352 };
353
354 struct command_line *
355 breakpoint_commands (struct breakpoint *b)
356 {
357   return b->commands ? b->commands->commands : NULL;
358 }
359
360 /* Flag indicating that a command has proceeded the inferior past the
361    current breakpoint.  */
362
363 static int breakpoint_proceeded;
364
365 const char *
366 bpdisp_text (enum bpdisp disp)
367 {
368   /* NOTE: the following values are a part of MI protocol and
369      represent values of 'disp' field returned when inferior stops at
370      a breakpoint.  */
371   static const char * const bpdisps[] = {"del", "dstp", "dis", "keep"};
372
373   return bpdisps[(int) disp];
374 }
375
376 /* Prototypes for exported functions.  */
377 /* If FALSE, gdb will not use hardware support for watchpoints, even
378    if such is available.  */
379 static int can_use_hw_watchpoints;
380
381 static void
382 show_can_use_hw_watchpoints (struct ui_file *file, int from_tty,
383                              struct cmd_list_element *c,
384                              const char *value)
385 {
386   fprintf_filtered (file,
387                     _("Debugger's willingness to use "
388                       "watchpoint hardware is %s.\n"),
389                     value);
390 }
391
392 /* If AUTO_BOOLEAN_FALSE, gdb will not attempt to create pending breakpoints.
393    If AUTO_BOOLEAN_TRUE, gdb will automatically create pending breakpoints
394    for unrecognized breakpoint locations.
395    If AUTO_BOOLEAN_AUTO, gdb will query when breakpoints are unrecognized.  */
396 static enum auto_boolean pending_break_support;
397 static void
398 show_pending_break_support (struct ui_file *file, int from_tty,
399                             struct cmd_list_element *c,
400                             const char *value)
401 {
402   fprintf_filtered (file,
403                     _("Debugger's behavior regarding "
404                       "pending breakpoints is %s.\n"),
405                     value);
406 }
407
408 /* If 1, gdb will automatically use hardware breakpoints for breakpoints
409    set with "break" but falling in read-only memory.
410    If 0, gdb will warn about such breakpoints, but won't automatically
411    use hardware breakpoints.  */
412 static int automatic_hardware_breakpoints;
413 static void
414 show_automatic_hardware_breakpoints (struct ui_file *file, int from_tty,
415                                      struct cmd_list_element *c,
416                                      const char *value)
417 {
418   fprintf_filtered (file,
419                     _("Automatic usage of hardware breakpoints is %s.\n"),
420                     value);
421 }
422
423 /* If on, gdb will keep breakpoints inserted even as inferior is
424    stopped, and immediately insert any new breakpoints.  If off, gdb
425    will insert breakpoints into inferior only when resuming it, and
426    will remove breakpoints upon stop.  If auto, GDB will behave as ON
427    if in non-stop mode, and as OFF if all-stop mode.*/
428
429 static enum auto_boolean always_inserted_mode = AUTO_BOOLEAN_AUTO;
430
431 static void
432 show_always_inserted_mode (struct ui_file *file, int from_tty,
433                      struct cmd_list_element *c, const char *value)
434 {
435   if (always_inserted_mode == AUTO_BOOLEAN_AUTO)
436     fprintf_filtered (file,
437                       _("Always inserted breakpoint "
438                         "mode is %s (currently %s).\n"),
439                       value,
440                       breakpoints_always_inserted_mode () ? "on" : "off");
441   else
442     fprintf_filtered (file, _("Always inserted breakpoint mode is %s.\n"),
443                       value);
444 }
445
446 int
447 breakpoints_always_inserted_mode (void)
448 {
449   return (always_inserted_mode == AUTO_BOOLEAN_TRUE
450           || (always_inserted_mode == AUTO_BOOLEAN_AUTO && non_stop));
451 }
452
453 static const char condition_evaluation_both[] = "host or target";
454
455 /* Modes for breakpoint condition evaluation.  */
456 static const char condition_evaluation_auto[] = "auto";
457 static const char condition_evaluation_host[] = "host";
458 static const char condition_evaluation_target[] = "target";
459 static const char *const condition_evaluation_enums[] = {
460   condition_evaluation_auto,
461   condition_evaluation_host,
462   condition_evaluation_target,
463   NULL
464 };
465
466 /* Global that holds the current mode for breakpoint condition evaluation.  */
467 static const char *condition_evaluation_mode_1 = condition_evaluation_auto;
468
469 /* Global that we use to display information to the user (gets its value from
470    condition_evaluation_mode_1.  */
471 static const char *condition_evaluation_mode = condition_evaluation_auto;
472
473 /* Translate a condition evaluation mode MODE into either "host"
474    or "target".  This is used mostly to translate from "auto" to the
475    real setting that is being used.  It returns the translated
476    evaluation mode.  */
477
478 static const char *
479 translate_condition_evaluation_mode (const char *mode)
480 {
481   if (mode == condition_evaluation_auto)
482     {
483       if (target_supports_evaluation_of_breakpoint_conditions ())
484         return condition_evaluation_target;
485       else
486         return condition_evaluation_host;
487     }
488   else
489     return mode;
490 }
491
492 /* Discovers what condition_evaluation_auto translates to.  */
493
494 static const char *
495 breakpoint_condition_evaluation_mode (void)
496 {
497   return translate_condition_evaluation_mode (condition_evaluation_mode);
498 }
499
500 /* Return true if GDB should evaluate breakpoint conditions or false
501    otherwise.  */
502
503 static int
504 gdb_evaluates_breakpoint_condition_p (void)
505 {
506   const char *mode = breakpoint_condition_evaluation_mode ();
507
508   return (mode == condition_evaluation_host);
509 }
510
511 void _initialize_breakpoint (void);
512
513 /* Are we executing breakpoint commands?  */
514 static int executing_breakpoint_commands;
515
516 /* Are overlay event breakpoints enabled? */
517 static int overlay_events_enabled;
518
519 /* See description in breakpoint.h. */
520 int target_exact_watchpoints = 0;
521
522 /* Walk the following statement or block through all breakpoints.
523    ALL_BREAKPOINTS_SAFE does so even if the statement deletes the
524    current breakpoint.  */
525
526 #define ALL_BREAKPOINTS(B)  for (B = breakpoint_chain; B; B = B->next)
527
528 #define ALL_BREAKPOINTS_SAFE(B,TMP)     \
529         for (B = breakpoint_chain;      \
530              B ? (TMP=B->next, 1): 0;   \
531              B = TMP)
532
533 /* Similar iterator for the low-level breakpoints.  SAFE variant is
534    not provided so update_global_location_list must not be called
535    while executing the block of ALL_BP_LOCATIONS.  */
536
537 #define ALL_BP_LOCATIONS(B,BP_TMP)                                      \
538         for (BP_TMP = bp_location;                                      \
539              BP_TMP < bp_location + bp_location_count && (B = *BP_TMP); \
540              BP_TMP++)
541
542 /* Iterates through locations with address ADDRESS for the currently selected
543    program space.  BP_LOCP_TMP points to each object.  BP_LOCP_START points
544    to where the loop should start from.
545    If BP_LOCP_START is a NULL pointer, the macro automatically seeks the
546    appropriate location to start with.  */
547
548 #define ALL_BP_LOCATIONS_AT_ADDR(BP_LOCP_TMP, BP_LOCP_START, ADDRESS)   \
549         for (BP_LOCP_START = BP_LOCP_START == NULL ? get_first_locp_gte_addr (ADDRESS) : BP_LOCP_START, \
550              BP_LOCP_TMP = BP_LOCP_START;                               \
551              BP_LOCP_START                                              \
552              && (BP_LOCP_TMP < bp_location + bp_location_count          \
553              && (*BP_LOCP_TMP)->address == ADDRESS);                    \
554              BP_LOCP_TMP++)
555
556 /* Iterator for tracepoints only.  */
557
558 #define ALL_TRACEPOINTS(B)  \
559   for (B = breakpoint_chain; B; B = B->next)  \
560     if (is_tracepoint (B))
561
562 /* Chains of all breakpoints defined.  */
563
564 struct breakpoint *breakpoint_chain;
565
566 /* Array is sorted by bp_location_compare - primarily by the ADDRESS.  */
567
568 static struct bp_location **bp_location;
569
570 /* Number of elements of BP_LOCATION.  */
571
572 static unsigned bp_location_count;
573
574 /* Maximum alignment offset between bp_target_info.PLACED_ADDRESS and
575    ADDRESS for the current elements of BP_LOCATION which get a valid
576    result from bp_location_has_shadow.  You can use it for roughly
577    limiting the subrange of BP_LOCATION to scan for shadow bytes for
578    an address you need to read.  */
579
580 static CORE_ADDR bp_location_placed_address_before_address_max;
581
582 /* Maximum offset plus alignment between bp_target_info.PLACED_ADDRESS
583    + bp_target_info.SHADOW_LEN and ADDRESS for the current elements of
584    BP_LOCATION which get a valid result from bp_location_has_shadow.
585    You can use it for roughly limiting the subrange of BP_LOCATION to
586    scan for shadow bytes for an address you need to read.  */
587
588 static CORE_ADDR bp_location_shadow_len_after_address_max;
589
590 /* The locations that no longer correspond to any breakpoint, unlinked
591    from bp_location array, but for which a hit may still be reported
592    by a target.  */
593 VEC(bp_location_p) *moribund_locations = NULL;
594
595 /* Number of last breakpoint made.  */
596
597 static int breakpoint_count;
598
599 /* The value of `breakpoint_count' before the last command that
600    created breakpoints.  If the last (break-like) command created more
601    than one breakpoint, then the difference between BREAKPOINT_COUNT
602    and PREV_BREAKPOINT_COUNT is more than one.  */
603 static int prev_breakpoint_count;
604
605 /* Number of last tracepoint made.  */
606
607 static int tracepoint_count;
608
609 static struct cmd_list_element *breakpoint_set_cmdlist;
610 static struct cmd_list_element *breakpoint_show_cmdlist;
611 struct cmd_list_element *save_cmdlist;
612
613 /* Return whether a breakpoint is an active enabled breakpoint.  */
614 static int
615 breakpoint_enabled (struct breakpoint *b)
616 {
617   return (b->enable_state == bp_enabled);
618 }
619
620 /* Set breakpoint count to NUM.  */
621
622 static void
623 set_breakpoint_count (int num)
624 {
625   prev_breakpoint_count = breakpoint_count;
626   breakpoint_count = num;
627   set_internalvar_integer (lookup_internalvar ("bpnum"), num);
628 }
629
630 /* Used by `start_rbreak_breakpoints' below, to record the current
631    breakpoint count before "rbreak" creates any breakpoint.  */
632 static int rbreak_start_breakpoint_count;
633
634 /* Called at the start an "rbreak" command to record the first
635    breakpoint made.  */
636
637 void
638 start_rbreak_breakpoints (void)
639 {
640   rbreak_start_breakpoint_count = breakpoint_count;
641 }
642
643 /* Called at the end of an "rbreak" command to record the last
644    breakpoint made.  */
645
646 void
647 end_rbreak_breakpoints (void)
648 {
649   prev_breakpoint_count = rbreak_start_breakpoint_count;
650 }
651
652 /* Used in run_command to zero the hit count when a new run starts.  */
653
654 void
655 clear_breakpoint_hit_counts (void)
656 {
657   struct breakpoint *b;
658
659   ALL_BREAKPOINTS (b)
660     b->hit_count = 0;
661 }
662
663 /* Allocate a new counted_command_line with reference count of 1.
664    The new structure owns COMMANDS.  */
665
666 static struct counted_command_line *
667 alloc_counted_command_line (struct command_line *commands)
668 {
669   struct counted_command_line *result
670     = xmalloc (sizeof (struct counted_command_line));
671
672   result->refc = 1;
673   result->commands = commands;
674   return result;
675 }
676
677 /* Increment reference count.  This does nothing if CMD is NULL.  */
678
679 static void
680 incref_counted_command_line (struct counted_command_line *cmd)
681 {
682   if (cmd)
683     ++cmd->refc;
684 }
685
686 /* Decrement reference count.  If the reference count reaches 0,
687    destroy the counted_command_line.  Sets *CMDP to NULL.  This does
688    nothing if *CMDP is NULL.  */
689
690 static void
691 decref_counted_command_line (struct counted_command_line **cmdp)
692 {
693   if (*cmdp)
694     {
695       if (--(*cmdp)->refc == 0)
696         {
697           free_command_lines (&(*cmdp)->commands);
698           xfree (*cmdp);
699         }
700       *cmdp = NULL;
701     }
702 }
703
704 /* A cleanup function that calls decref_counted_command_line.  */
705
706 static void
707 do_cleanup_counted_command_line (void *arg)
708 {
709   decref_counted_command_line (arg);
710 }
711
712 /* Create a cleanup that calls decref_counted_command_line on the
713    argument.  */
714
715 static struct cleanup *
716 make_cleanup_decref_counted_command_line (struct counted_command_line **cmdp)
717 {
718   return make_cleanup (do_cleanup_counted_command_line, cmdp);
719 }
720
721 \f
722 /* Return the breakpoint with the specified number, or NULL
723    if the number does not refer to an existing breakpoint.  */
724
725 struct breakpoint *
726 get_breakpoint (int num)
727 {
728   struct breakpoint *b;
729
730   ALL_BREAKPOINTS (b)
731     if (b->number == num)
732       return b;
733   
734   return NULL;
735 }
736
737 \f
738
739 /* Mark locations as "conditions have changed" in case the target supports
740    evaluating conditions on its side.  */
741
742 static void
743 mark_breakpoint_modified (struct breakpoint *b)
744 {
745   struct bp_location *loc;
746
747   /* This is only meaningful if the target is
748      evaluating conditions and if the user has
749      opted for condition evaluation on the target's
750      side.  */
751   if (gdb_evaluates_breakpoint_condition_p ()
752       || !target_supports_evaluation_of_breakpoint_conditions ())
753     return;
754
755   if (!is_breakpoint (b))
756     return;
757
758   for (loc = b->loc; loc; loc = loc->next)
759     loc->condition_changed = condition_modified;
760 }
761
762 /* Mark location as "conditions have changed" in case the target supports
763    evaluating conditions on its side.  */
764
765 static void
766 mark_breakpoint_location_modified (struct bp_location *loc)
767 {
768   /* This is only meaningful if the target is
769      evaluating conditions and if the user has
770      opted for condition evaluation on the target's
771      side.  */
772   if (gdb_evaluates_breakpoint_condition_p ()
773       || !target_supports_evaluation_of_breakpoint_conditions ())
774
775     return;
776
777   if (!is_breakpoint (loc->owner))
778     return;
779
780   loc->condition_changed = condition_modified;
781 }
782
783 /* Sets the condition-evaluation mode using the static global
784    condition_evaluation_mode.  */
785
786 static void
787 set_condition_evaluation_mode (char *args, int from_tty,
788                                struct cmd_list_element *c)
789 {
790   const char *old_mode, *new_mode;
791
792   if ((condition_evaluation_mode_1 == condition_evaluation_target)
793       && !target_supports_evaluation_of_breakpoint_conditions ())
794     {
795       condition_evaluation_mode_1 = condition_evaluation_mode;
796       warning (_("Target does not support breakpoint condition evaluation.\n"
797                  "Using host evaluation mode instead."));
798       return;
799     }
800
801   new_mode = translate_condition_evaluation_mode (condition_evaluation_mode_1);
802   old_mode = translate_condition_evaluation_mode (condition_evaluation_mode);
803
804   /* Flip the switch.  Flip it even if OLD_MODE == NEW_MODE as one of the
805      settings was "auto".  */
806   condition_evaluation_mode = condition_evaluation_mode_1;
807
808   /* Only update the mode if the user picked a different one.  */
809   if (new_mode != old_mode)
810     {
811       struct bp_location *loc, **loc_tmp;
812       /* If the user switched to a different evaluation mode, we
813          need to synch the changes with the target as follows:
814
815          "host" -> "target": Send all (valid) conditions to the target.
816          "target" -> "host": Remove all the conditions from the target.
817       */
818
819       if (new_mode == condition_evaluation_target)
820         {
821           /* Mark everything modified and synch conditions with the
822              target.  */
823           ALL_BP_LOCATIONS (loc, loc_tmp)
824             mark_breakpoint_location_modified (loc);
825         }
826       else
827         {
828           /* Manually mark non-duplicate locations to synch conditions
829              with the target.  We do this to remove all the conditions the
830              target knows about.  */
831           ALL_BP_LOCATIONS (loc, loc_tmp)
832             if (is_breakpoint (loc->owner) && loc->inserted)
833               loc->needs_update = 1;
834         }
835
836       /* Do the update.  */
837       update_global_location_list (1);
838     }
839
840   return;
841 }
842
843 /* Shows the current mode of breakpoint condition evaluation.  Explicitly shows
844    what "auto" is translating to.  */
845
846 static void
847 show_condition_evaluation_mode (struct ui_file *file, int from_tty,
848                                 struct cmd_list_element *c, const char *value)
849 {
850   if (condition_evaluation_mode == condition_evaluation_auto)
851     fprintf_filtered (file,
852                       _("Breakpoint condition evaluation "
853                         "mode is %s (currently %s).\n"),
854                       value,
855                       breakpoint_condition_evaluation_mode ());
856   else
857     fprintf_filtered (file, _("Breakpoint condition evaluation mode is %s.\n"),
858                       value);
859 }
860
861 /* A comparison function for bp_location AP and BP that is used by
862    bsearch.  This comparison function only cares about addresses, unlike
863    the more general bp_location_compare function.  */
864
865 static int
866 bp_location_compare_addrs (const void *ap, const void *bp)
867 {
868   struct bp_location *a = *(void **) ap;
869   struct bp_location *b = *(void **) bp;
870
871   if (a->address == b->address)
872     return 0;
873   else
874     return ((a->address > b->address) - (a->address < b->address));
875 }
876
877 /* Helper function to skip all bp_locations with addresses
878    less than ADDRESS.  It returns the first bp_location that
879    is greater than or equal to ADDRESS.  If none is found, just
880    return NULL.  */
881
882 static struct bp_location **
883 get_first_locp_gte_addr (CORE_ADDR address)
884 {
885   struct bp_location dummy_loc;
886   struct bp_location *dummy_locp = &dummy_loc;
887   struct bp_location **locp_found = NULL;
888
889   /* Initialize the dummy location's address field.  */
890   memset (&dummy_loc, 0, sizeof (struct bp_location));
891   dummy_loc.address = address;
892
893   /* Find a close match to the first location at ADDRESS.  */
894   locp_found = bsearch (&dummy_locp, bp_location, bp_location_count,
895                         sizeof (struct bp_location **),
896                         bp_location_compare_addrs);
897
898   /* Nothing was found, nothing left to do.  */
899   if (locp_found == NULL)
900     return NULL;
901
902   /* We may have found a location that is at ADDRESS but is not the first in the
903      location's list.  Go backwards (if possible) and locate the first one.  */
904   while ((locp_found - 1) >= bp_location
905          && (*(locp_found - 1))->address == address)
906     locp_found--;
907
908   return locp_found;
909 }
910
911 void
912 set_breakpoint_condition (struct breakpoint *b, char *exp,
913                           int from_tty)
914 {
915   xfree (b->cond_string);
916   b->cond_string = NULL;
917
918   if (is_watchpoint (b))
919     {
920       struct watchpoint *w = (struct watchpoint *) b;
921
922       xfree (w->cond_exp);
923       w->cond_exp = NULL;
924     }
925   else
926     {
927       struct bp_location *loc;
928
929       for (loc = b->loc; loc; loc = loc->next)
930         {
931           xfree (loc->cond);
932           loc->cond = NULL;
933
934           /* No need to free the condition agent expression
935              bytecode (if we have one).  We will handle this
936              when we go through update_global_location_list.  */
937         }
938     }
939
940   if (*exp == 0)
941     {
942       if (from_tty)
943         printf_filtered (_("Breakpoint %d now unconditional.\n"), b->number);
944     }
945   else
946     {
947       const char *arg = exp;
948
949       /* I don't know if it matters whether this is the string the user
950          typed in or the decompiled expression.  */
951       b->cond_string = xstrdup (arg);
952       b->condition_not_parsed = 0;
953
954       if (is_watchpoint (b))
955         {
956           struct watchpoint *w = (struct watchpoint *) b;
957
958           innermost_block = NULL;
959           arg = exp;
960           w->cond_exp = parse_exp_1 (&arg, 0, 0, 0);
961           if (*arg)
962             error (_("Junk at end of expression"));
963           w->cond_exp_valid_block = innermost_block;
964         }
965       else
966         {
967           struct bp_location *loc;
968
969           for (loc = b->loc; loc; loc = loc->next)
970             {
971               arg = exp;
972               loc->cond =
973                 parse_exp_1 (&arg, loc->address,
974                              block_for_pc (loc->address), 0);
975               if (*arg)
976                 error (_("Junk at end of expression"));
977             }
978         }
979     }
980   mark_breakpoint_modified (b);
981
982   observer_notify_breakpoint_modified (b);
983 }
984
985 /* Completion for the "condition" command.  */
986
987 static VEC (char_ptr) *
988 condition_completer (struct cmd_list_element *cmd,
989                      const char *text, const char *word)
990 {
991   const char *space;
992
993   text = skip_spaces_const (text);
994   space = skip_to_space_const (text);
995   if (*space == '\0')
996     {
997       int len;
998       struct breakpoint *b;
999       VEC (char_ptr) *result = NULL;
1000
1001       if (text[0] == '$')
1002         {
1003           /* We don't support completion of history indices.  */
1004           if (isdigit (text[1]))
1005             return NULL;
1006           return complete_internalvar (&text[1]);
1007         }
1008
1009       /* We're completing the breakpoint number.  */
1010       len = strlen (text);
1011
1012       ALL_BREAKPOINTS (b)
1013         {
1014           char number[50];
1015
1016           xsnprintf (number, sizeof (number), "%d", b->number);
1017
1018           if (strncmp (number, text, len) == 0)
1019             VEC_safe_push (char_ptr, result, xstrdup (number));
1020         }
1021
1022       return result;
1023     }
1024
1025   /* We're completing the expression part.  */
1026   text = skip_spaces_const (space);
1027   return expression_completer (cmd, text, word);
1028 }
1029
1030 /* condition N EXP -- set break condition of breakpoint N to EXP.  */
1031
1032 static void
1033 condition_command (char *arg, int from_tty)
1034 {
1035   struct breakpoint *b;
1036   char *p;
1037   int bnum;
1038
1039   if (arg == 0)
1040     error_no_arg (_("breakpoint number"));
1041
1042   p = arg;
1043   bnum = get_number (&p);
1044   if (bnum == 0)
1045     error (_("Bad breakpoint argument: '%s'"), arg);
1046
1047   ALL_BREAKPOINTS (b)
1048     if (b->number == bnum)
1049       {
1050         /* Check if this breakpoint has a Python object assigned to
1051            it, and if it has a definition of the "stop"
1052            method.  This method and conditions entered into GDB from
1053            the CLI are mutually exclusive.  */
1054         if (b->py_bp_object
1055             && gdbpy_breakpoint_has_py_cond (b->py_bp_object))
1056           error (_("Cannot set a condition where a Python 'stop' "
1057                    "method has been defined in the breakpoint."));
1058         set_breakpoint_condition (b, p, from_tty);
1059
1060         if (is_breakpoint (b))
1061           update_global_location_list (1);
1062
1063         return;
1064       }
1065
1066   error (_("No breakpoint number %d."), bnum);
1067 }
1068
1069 /* Check that COMMAND do not contain commands that are suitable
1070    only for tracepoints and not suitable for ordinary breakpoints.
1071    Throw if any such commands is found.  */
1072
1073 static void
1074 check_no_tracepoint_commands (struct command_line *commands)
1075 {
1076   struct command_line *c;
1077
1078   for (c = commands; c; c = c->next)
1079     {
1080       int i;
1081
1082       if (c->control_type == while_stepping_control)
1083         error (_("The 'while-stepping' command can "
1084                  "only be used for tracepoints"));
1085
1086       for (i = 0; i < c->body_count; ++i)
1087         check_no_tracepoint_commands ((c->body_list)[i]);
1088
1089       /* Not that command parsing removes leading whitespace and comment
1090          lines and also empty lines.  So, we only need to check for
1091          command directly.  */
1092       if (strstr (c->line, "collect ") == c->line)
1093         error (_("The 'collect' command can only be used for tracepoints"));
1094
1095       if (strstr (c->line, "teval ") == c->line)
1096         error (_("The 'teval' command can only be used for tracepoints"));
1097     }
1098 }
1099
1100 /* Encapsulate tests for different types of tracepoints.  */
1101
1102 static int
1103 is_tracepoint_type (enum bptype type)
1104 {
1105   return (type == bp_tracepoint
1106           || type == bp_fast_tracepoint
1107           || type == bp_static_tracepoint);
1108 }
1109
1110 int
1111 is_tracepoint (const struct breakpoint *b)
1112 {
1113   return is_tracepoint_type (b->type);
1114 }
1115
1116 /* A helper function that validates that COMMANDS are valid for a
1117    breakpoint.  This function will throw an exception if a problem is
1118    found.  */
1119
1120 static void
1121 validate_commands_for_breakpoint (struct breakpoint *b,
1122                                   struct command_line *commands)
1123 {
1124   if (is_tracepoint (b))
1125     {
1126       struct tracepoint *t = (struct tracepoint *) b;
1127       struct command_line *c;
1128       struct command_line *while_stepping = 0;
1129
1130       /* Reset the while-stepping step count.  The previous commands
1131          might have included a while-stepping action, while the new
1132          ones might not.  */
1133       t->step_count = 0;
1134
1135       /* We need to verify that each top-level element of commands is
1136          valid for tracepoints, that there's at most one
1137          while-stepping element, and that the while-stepping's body
1138          has valid tracing commands excluding nested while-stepping.
1139          We also need to validate the tracepoint action line in the
1140          context of the tracepoint --- validate_actionline actually
1141          has side effects, like setting the tracepoint's
1142          while-stepping STEP_COUNT, in addition to checking if the
1143          collect/teval actions parse and make sense in the
1144          tracepoint's context.  */
1145       for (c = commands; c; c = c->next)
1146         {
1147           if (c->control_type == while_stepping_control)
1148             {
1149               if (b->type == bp_fast_tracepoint)
1150                 error (_("The 'while-stepping' command "
1151                          "cannot be used for fast tracepoint"));
1152               else if (b->type == bp_static_tracepoint)
1153                 error (_("The 'while-stepping' command "
1154                          "cannot be used for static tracepoint"));
1155
1156               if (while_stepping)
1157                 error (_("The 'while-stepping' command "
1158                          "can be used only once"));
1159               else
1160                 while_stepping = c;
1161             }
1162
1163           validate_actionline (c->line, b);
1164         }
1165       if (while_stepping)
1166         {
1167           struct command_line *c2;
1168
1169           gdb_assert (while_stepping->body_count == 1);
1170           c2 = while_stepping->body_list[0];
1171           for (; c2; c2 = c2->next)
1172             {
1173               if (c2->control_type == while_stepping_control)
1174                 error (_("The 'while-stepping' command cannot be nested"));
1175             }
1176         }
1177     }
1178   else
1179     {
1180       check_no_tracepoint_commands (commands);
1181     }
1182 }
1183
1184 /* Return a vector of all the static tracepoints set at ADDR.  The
1185    caller is responsible for releasing the vector.  */
1186
1187 VEC(breakpoint_p) *
1188 static_tracepoints_here (CORE_ADDR addr)
1189 {
1190   struct breakpoint *b;
1191   VEC(breakpoint_p) *found = 0;
1192   struct bp_location *loc;
1193
1194   ALL_BREAKPOINTS (b)
1195     if (b->type == bp_static_tracepoint)
1196       {
1197         for (loc = b->loc; loc; loc = loc->next)
1198           if (loc->address == addr)
1199             VEC_safe_push(breakpoint_p, found, b);
1200       }
1201
1202   return found;
1203 }
1204
1205 /* Set the command list of B to COMMANDS.  If breakpoint is tracepoint,
1206    validate that only allowed commands are included.  */
1207
1208 void
1209 breakpoint_set_commands (struct breakpoint *b, 
1210                          struct command_line *commands)
1211 {
1212   validate_commands_for_breakpoint (b, commands);
1213
1214   decref_counted_command_line (&b->commands);
1215   b->commands = alloc_counted_command_line (commands);
1216   observer_notify_breakpoint_modified (b);
1217 }
1218
1219 /* Set the internal `silent' flag on the breakpoint.  Note that this
1220    is not the same as the "silent" that may appear in the breakpoint's
1221    commands.  */
1222
1223 void
1224 breakpoint_set_silent (struct breakpoint *b, int silent)
1225 {
1226   int old_silent = b->silent;
1227
1228   b->silent = silent;
1229   if (old_silent != silent)
1230     observer_notify_breakpoint_modified (b);
1231 }
1232
1233 /* Set the thread for this breakpoint.  If THREAD is -1, make the
1234    breakpoint work for any thread.  */
1235
1236 void
1237 breakpoint_set_thread (struct breakpoint *b, int thread)
1238 {
1239   int old_thread = b->thread;
1240
1241   b->thread = thread;
1242   if (old_thread != thread)
1243     observer_notify_breakpoint_modified (b);
1244 }
1245
1246 /* Set the task for this breakpoint.  If TASK is 0, make the
1247    breakpoint work for any task.  */
1248
1249 void
1250 breakpoint_set_task (struct breakpoint *b, int task)
1251 {
1252   int old_task = b->task;
1253
1254   b->task = task;
1255   if (old_task != task)
1256     observer_notify_breakpoint_modified (b);
1257 }
1258
1259 void
1260 check_tracepoint_command (char *line, void *closure)
1261 {
1262   struct breakpoint *b = closure;
1263
1264   validate_actionline (line, b);
1265 }
1266
1267 /* A structure used to pass information through
1268    map_breakpoint_numbers.  */
1269
1270 struct commands_info
1271 {
1272   /* True if the command was typed at a tty.  */
1273   int from_tty;
1274
1275   /* The breakpoint range spec.  */
1276   char *arg;
1277
1278   /* Non-NULL if the body of the commands are being read from this
1279      already-parsed command.  */
1280   struct command_line *control;
1281
1282   /* The command lines read from the user, or NULL if they have not
1283      yet been read.  */
1284   struct counted_command_line *cmd;
1285 };
1286
1287 /* A callback for map_breakpoint_numbers that sets the commands for
1288    commands_command.  */
1289
1290 static void
1291 do_map_commands_command (struct breakpoint *b, void *data)
1292 {
1293   struct commands_info *info = data;
1294
1295   if (info->cmd == NULL)
1296     {
1297       struct command_line *l;
1298
1299       if (info->control != NULL)
1300         l = copy_command_lines (info->control->body_list[0]);
1301       else
1302         {
1303           struct cleanup *old_chain;
1304           char *str;
1305
1306           str = xstrprintf (_("Type commands for breakpoint(s) "
1307                               "%s, one per line."),
1308                             info->arg);
1309
1310           old_chain = make_cleanup (xfree, str);
1311
1312           l = read_command_lines (str,
1313                                   info->from_tty, 1,
1314                                   (is_tracepoint (b)
1315                                    ? check_tracepoint_command : 0),
1316                                   b);
1317
1318           do_cleanups (old_chain);
1319         }
1320
1321       info->cmd = alloc_counted_command_line (l);
1322     }
1323
1324   /* If a breakpoint was on the list more than once, we don't need to
1325      do anything.  */
1326   if (b->commands != info->cmd)
1327     {
1328       validate_commands_for_breakpoint (b, info->cmd->commands);
1329       incref_counted_command_line (info->cmd);
1330       decref_counted_command_line (&b->commands);
1331       b->commands = info->cmd;
1332       observer_notify_breakpoint_modified (b);
1333     }
1334 }
1335
1336 static void
1337 commands_command_1 (char *arg, int from_tty, 
1338                     struct command_line *control)
1339 {
1340   struct cleanup *cleanups;
1341   struct commands_info info;
1342
1343   info.from_tty = from_tty;
1344   info.control = control;
1345   info.cmd = NULL;
1346   /* If we read command lines from the user, then `info' will hold an
1347      extra reference to the commands that we must clean up.  */
1348   cleanups = make_cleanup_decref_counted_command_line (&info.cmd);
1349
1350   if (arg == NULL || !*arg)
1351     {
1352       if (breakpoint_count - prev_breakpoint_count > 1)
1353         arg = xstrprintf ("%d-%d", prev_breakpoint_count + 1, 
1354                           breakpoint_count);
1355       else if (breakpoint_count > 0)
1356         arg = xstrprintf ("%d", breakpoint_count);
1357       else
1358         {
1359           /* So that we don't try to free the incoming non-NULL
1360              argument in the cleanup below.  Mapping breakpoint
1361              numbers will fail in this case.  */
1362           arg = NULL;
1363         }
1364     }
1365   else
1366     /* The command loop has some static state, so we need to preserve
1367        our argument.  */
1368     arg = xstrdup (arg);
1369
1370   if (arg != NULL)
1371     make_cleanup (xfree, arg);
1372
1373   info.arg = arg;
1374
1375   map_breakpoint_numbers (arg, do_map_commands_command, &info);
1376
1377   if (info.cmd == NULL)
1378     error (_("No breakpoints specified."));
1379
1380   do_cleanups (cleanups);
1381 }
1382
1383 static void
1384 commands_command (char *arg, int from_tty)
1385 {
1386   commands_command_1 (arg, from_tty, NULL);
1387 }
1388
1389 /* Like commands_command, but instead of reading the commands from
1390    input stream, takes them from an already parsed command structure.
1391
1392    This is used by cli-script.c to DTRT with breakpoint commands
1393    that are part of if and while bodies.  */
1394 enum command_control_type
1395 commands_from_control_command (char *arg, struct command_line *cmd)
1396 {
1397   commands_command_1 (arg, 0, cmd);
1398   return simple_control;
1399 }
1400
1401 /* Return non-zero if BL->TARGET_INFO contains valid information.  */
1402
1403 static int
1404 bp_location_has_shadow (struct bp_location *bl)
1405 {
1406   if (bl->loc_type != bp_loc_software_breakpoint)
1407     return 0;
1408   if (!bl->inserted)
1409     return 0;
1410   if (bl->target_info.shadow_len == 0)
1411     /* BL isn't valid, or doesn't shadow memory.  */
1412     return 0;
1413   return 1;
1414 }
1415
1416 /* Update BUF, which is LEN bytes read from the target address MEMADDR,
1417    by replacing any memory breakpoints with their shadowed contents.
1418
1419    If READBUF is not NULL, this buffer must not overlap with any of
1420    the breakpoint location's shadow_contents buffers.  Otherwise,
1421    a failed assertion internal error will be raised.
1422
1423    The range of shadowed area by each bp_location is:
1424      bl->address - bp_location_placed_address_before_address_max
1425      up to bl->address + bp_location_shadow_len_after_address_max
1426    The range we were requested to resolve shadows for is:
1427      memaddr ... memaddr + len
1428    Thus the safe cutoff boundaries for performance optimization are
1429      memaddr + len <= (bl->address
1430                        - bp_location_placed_address_before_address_max)
1431    and:
1432      bl->address + bp_location_shadow_len_after_address_max <= memaddr  */
1433
1434 void
1435 breakpoint_xfer_memory (gdb_byte *readbuf, gdb_byte *writebuf,
1436                         const gdb_byte *writebuf_org,
1437                         ULONGEST memaddr, LONGEST len)
1438 {
1439   /* Left boundary, right boundary and median element of our binary
1440      search.  */
1441   unsigned bc_l, bc_r, bc;
1442
1443   /* Find BC_L which is a leftmost element which may affect BUF
1444      content.  It is safe to report lower value but a failure to
1445      report higher one.  */
1446
1447   bc_l = 0;
1448   bc_r = bp_location_count;
1449   while (bc_l + 1 < bc_r)
1450     {
1451       struct bp_location *bl;
1452
1453       bc = (bc_l + bc_r) / 2;
1454       bl = bp_location[bc];
1455
1456       /* Check first BL->ADDRESS will not overflow due to the added
1457          constant.  Then advance the left boundary only if we are sure
1458          the BC element can in no way affect the BUF content (MEMADDR
1459          to MEMADDR + LEN range).
1460
1461          Use the BP_LOCATION_SHADOW_LEN_AFTER_ADDRESS_MAX safety
1462          offset so that we cannot miss a breakpoint with its shadow
1463          range tail still reaching MEMADDR.  */
1464
1465       if ((bl->address + bp_location_shadow_len_after_address_max
1466            >= bl->address)
1467           && (bl->address + bp_location_shadow_len_after_address_max
1468               <= memaddr))
1469         bc_l = bc;
1470       else
1471         bc_r = bc;
1472     }
1473
1474   /* Due to the binary search above, we need to make sure we pick the
1475      first location that's at BC_L's address.  E.g., if there are
1476      multiple locations at the same address, BC_L may end up pointing
1477      at a duplicate location, and miss the "master"/"inserted"
1478      location.  Say, given locations L1, L2 and L3 at addresses A and
1479      B:
1480
1481       L1@A, L2@A, L3@B, ...
1482
1483      BC_L could end up pointing at location L2, while the "master"
1484      location could be L1.  Since the `loc->inserted' flag is only set
1485      on "master" locations, we'd forget to restore the shadow of L1
1486      and L2.  */
1487   while (bc_l > 0
1488          && bp_location[bc_l]->address == bp_location[bc_l - 1]->address)
1489     bc_l--;
1490
1491   /* Now do full processing of the found relevant range of elements.  */
1492
1493   for (bc = bc_l; bc < bp_location_count; bc++)
1494   {
1495     struct bp_location *bl = bp_location[bc];
1496     CORE_ADDR bp_addr = 0;
1497     int bp_size = 0;
1498     int bptoffset = 0;
1499
1500     /* bp_location array has BL->OWNER always non-NULL.  */
1501     if (bl->owner->type == bp_none)
1502       warning (_("reading through apparently deleted breakpoint #%d?"),
1503                bl->owner->number);
1504
1505     /* Performance optimization: any further element can no longer affect BUF
1506        content.  */
1507
1508     if (bl->address >= bp_location_placed_address_before_address_max
1509         && memaddr + len <= (bl->address
1510                              - bp_location_placed_address_before_address_max))
1511       break;
1512
1513     if (!bp_location_has_shadow (bl))
1514       continue;
1515     if (!breakpoint_address_match (bl->target_info.placed_address_space, 0,
1516                                    current_program_space->aspace, 0))
1517       continue;
1518
1519     /* Addresses and length of the part of the breakpoint that
1520        we need to copy.  */
1521     bp_addr = bl->target_info.placed_address;
1522     bp_size = bl->target_info.shadow_len;
1523
1524     if (bp_addr + bp_size <= memaddr)
1525       /* The breakpoint is entirely before the chunk of memory we
1526          are reading.  */
1527       continue;
1528
1529     if (bp_addr >= memaddr + len)
1530       /* The breakpoint is entirely after the chunk of memory we are
1531          reading.  */
1532       continue;
1533
1534     /* Offset within shadow_contents.  */
1535     if (bp_addr < memaddr)
1536       {
1537         /* Only copy the second part of the breakpoint.  */
1538         bp_size -= memaddr - bp_addr;
1539         bptoffset = memaddr - bp_addr;
1540         bp_addr = memaddr;
1541       }
1542
1543     if (bp_addr + bp_size > memaddr + len)
1544       {
1545         /* Only copy the first part of the breakpoint.  */
1546         bp_size -= (bp_addr + bp_size) - (memaddr + len);
1547       }
1548
1549     if (readbuf != NULL)
1550       {
1551         /* Verify that the readbuf buffer does not overlap with
1552            the shadow_contents buffer.  */
1553         gdb_assert (bl->target_info.shadow_contents >= readbuf + len
1554                     || readbuf >= (bl->target_info.shadow_contents
1555                                    + bl->target_info.shadow_len));
1556
1557         /* Update the read buffer with this inserted breakpoint's
1558            shadow.  */
1559         memcpy (readbuf + bp_addr - memaddr,
1560                 bl->target_info.shadow_contents + bptoffset, bp_size);
1561       }
1562     else
1563       {
1564         struct gdbarch *gdbarch = bl->gdbarch;
1565         const unsigned char *bp;
1566         CORE_ADDR placed_address = bl->target_info.placed_address;
1567         int placed_size = bl->target_info.placed_size;
1568
1569         /* Update the shadow with what we want to write to memory.  */
1570         memcpy (bl->target_info.shadow_contents + bptoffset,
1571                 writebuf_org + bp_addr - memaddr, bp_size);
1572
1573         /* Determine appropriate breakpoint contents and size for this
1574            address.  */
1575         bp = gdbarch_breakpoint_from_pc (gdbarch, &placed_address, &placed_size);
1576
1577         /* Update the final write buffer with this inserted
1578            breakpoint's INSN.  */
1579         memcpy (writebuf + bp_addr - memaddr, bp + bptoffset, bp_size);
1580       }
1581   }
1582 }
1583 \f
1584
1585 /* Return true if BPT is either a software breakpoint or a hardware
1586    breakpoint.  */
1587
1588 int
1589 is_breakpoint (const struct breakpoint *bpt)
1590 {
1591   return (bpt->type == bp_breakpoint
1592           || bpt->type == bp_hardware_breakpoint
1593           || bpt->type == bp_dprintf);
1594 }
1595
1596 /* Return true if BPT is of any hardware watchpoint kind.  */
1597
1598 static int
1599 is_hardware_watchpoint (const struct breakpoint *bpt)
1600 {
1601   return (bpt->type == bp_hardware_watchpoint
1602           || bpt->type == bp_read_watchpoint
1603           || bpt->type == bp_access_watchpoint);
1604 }
1605
1606 /* Return true if BPT is of any watchpoint kind, hardware or
1607    software.  */
1608
1609 int
1610 is_watchpoint (const struct breakpoint *bpt)
1611 {
1612   return (is_hardware_watchpoint (bpt)
1613           || bpt->type == bp_watchpoint);
1614 }
1615
1616 /* Returns true if the current thread and its running state are safe
1617    to evaluate or update watchpoint B.  Watchpoints on local
1618    expressions need to be evaluated in the context of the thread that
1619    was current when the watchpoint was created, and, that thread needs
1620    to be stopped to be able to select the correct frame context.
1621    Watchpoints on global expressions can be evaluated on any thread,
1622    and in any state.  It is presently left to the target allowing
1623    memory accesses when threads are running.  */
1624
1625 static int
1626 watchpoint_in_thread_scope (struct watchpoint *b)
1627 {
1628   return (b->base.pspace == current_program_space
1629           && (ptid_equal (b->watchpoint_thread, null_ptid)
1630               || (ptid_equal (inferior_ptid, b->watchpoint_thread)
1631                   && !is_executing (inferior_ptid))));
1632 }
1633
1634 /* Set watchpoint B to disp_del_at_next_stop, even including its possible
1635    associated bp_watchpoint_scope breakpoint.  */
1636
1637 static void
1638 watchpoint_del_at_next_stop (struct watchpoint *w)
1639 {
1640   struct breakpoint *b = &w->base;
1641
1642   if (b->related_breakpoint != b)
1643     {
1644       gdb_assert (b->related_breakpoint->type == bp_watchpoint_scope);
1645       gdb_assert (b->related_breakpoint->related_breakpoint == b);
1646       b->related_breakpoint->disposition = disp_del_at_next_stop;
1647       b->related_breakpoint->related_breakpoint = b->related_breakpoint;
1648       b->related_breakpoint = b;
1649     }
1650   b->disposition = disp_del_at_next_stop;
1651 }
1652
1653 /* Assuming that B is a watchpoint:
1654    - Reparse watchpoint expression, if REPARSE is non-zero
1655    - Evaluate expression and store the result in B->val
1656    - Evaluate the condition if there is one, and store the result
1657      in b->loc->cond.
1658    - Update the list of values that must be watched in B->loc.
1659
1660    If the watchpoint disposition is disp_del_at_next_stop, then do
1661    nothing.  If this is local watchpoint that is out of scope, delete
1662    it.
1663
1664    Even with `set breakpoint always-inserted on' the watchpoints are
1665    removed + inserted on each stop here.  Normal breakpoints must
1666    never be removed because they might be missed by a running thread
1667    when debugging in non-stop mode.  On the other hand, hardware
1668    watchpoints (is_hardware_watchpoint; processed here) are specific
1669    to each LWP since they are stored in each LWP's hardware debug
1670    registers.  Therefore, such LWP must be stopped first in order to
1671    be able to modify its hardware watchpoints.
1672
1673    Hardware watchpoints must be reset exactly once after being
1674    presented to the user.  It cannot be done sooner, because it would
1675    reset the data used to present the watchpoint hit to the user.  And
1676    it must not be done later because it could display the same single
1677    watchpoint hit during multiple GDB stops.  Note that the latter is
1678    relevant only to the hardware watchpoint types bp_read_watchpoint
1679    and bp_access_watchpoint.  False hit by bp_hardware_watchpoint is
1680    not user-visible - its hit is suppressed if the memory content has
1681    not changed.
1682
1683    The following constraints influence the location where we can reset
1684    hardware watchpoints:
1685
1686    * target_stopped_by_watchpoint and target_stopped_data_address are
1687      called several times when GDB stops.
1688
1689    [linux] 
1690    * Multiple hardware watchpoints can be hit at the same time,
1691      causing GDB to stop.  GDB only presents one hardware watchpoint
1692      hit at a time as the reason for stopping, and all the other hits
1693      are presented later, one after the other, each time the user
1694      requests the execution to be resumed.  Execution is not resumed
1695      for the threads still having pending hit event stored in
1696      LWP_INFO->STATUS.  While the watchpoint is already removed from
1697      the inferior on the first stop the thread hit event is kept being
1698      reported from its cached value by linux_nat_stopped_data_address
1699      until the real thread resume happens after the watchpoint gets
1700      presented and thus its LWP_INFO->STATUS gets reset.
1701
1702    Therefore the hardware watchpoint hit can get safely reset on the
1703    watchpoint removal from inferior.  */
1704
1705 static void
1706 update_watchpoint (struct watchpoint *b, int reparse)
1707 {
1708   int within_current_scope;
1709   struct frame_id saved_frame_id;
1710   int frame_saved;
1711
1712   /* If this is a local watchpoint, we only want to check if the
1713      watchpoint frame is in scope if the current thread is the thread
1714      that was used to create the watchpoint.  */
1715   if (!watchpoint_in_thread_scope (b))
1716     return;
1717
1718   if (b->base.disposition == disp_del_at_next_stop)
1719     return;
1720  
1721   frame_saved = 0;
1722
1723   /* Determine if the watchpoint is within scope.  */
1724   if (b->exp_valid_block == NULL)
1725     within_current_scope = 1;
1726   else
1727     {
1728       struct frame_info *fi = get_current_frame ();
1729       struct gdbarch *frame_arch = get_frame_arch (fi);
1730       CORE_ADDR frame_pc = get_frame_pc (fi);
1731
1732       /* If we're in a function epilogue, unwinding may not work
1733          properly, so do not attempt to recreate locations at this
1734          point.  See similar comments in watchpoint_check.  */
1735       if (gdbarch_in_function_epilogue_p (frame_arch, frame_pc))
1736         return;
1737
1738       /* Save the current frame's ID so we can restore it after
1739          evaluating the watchpoint expression on its own frame.  */
1740       /* FIXME drow/2003-09-09: It would be nice if evaluate_expression
1741          took a frame parameter, so that we didn't have to change the
1742          selected frame.  */
1743       frame_saved = 1;
1744       saved_frame_id = get_frame_id (get_selected_frame (NULL));
1745
1746       fi = frame_find_by_id (b->watchpoint_frame);
1747       within_current_scope = (fi != NULL);
1748       if (within_current_scope)
1749         select_frame (fi);
1750     }
1751
1752   /* We don't free locations.  They are stored in the bp_location array
1753      and update_global_location_list will eventually delete them and
1754      remove breakpoints if needed.  */
1755   b->base.loc = NULL;
1756
1757   if (within_current_scope && reparse)
1758     {
1759       const char *s;
1760
1761       if (b->exp)
1762         {
1763           xfree (b->exp);
1764           b->exp = NULL;
1765         }
1766       s = b->exp_string_reparse ? b->exp_string_reparse : b->exp_string;
1767       b->exp = parse_exp_1 (&s, 0, b->exp_valid_block, 0);
1768       /* If the meaning of expression itself changed, the old value is
1769          no longer relevant.  We don't want to report a watchpoint hit
1770          to the user when the old value and the new value may actually
1771          be completely different objects.  */
1772       value_free (b->val);
1773       b->val = NULL;
1774       b->val_valid = 0;
1775
1776       /* Note that unlike with breakpoints, the watchpoint's condition
1777          expression is stored in the breakpoint object, not in the
1778          locations (re)created below.  */
1779       if (b->base.cond_string != NULL)
1780         {
1781           if (b->cond_exp != NULL)
1782             {
1783               xfree (b->cond_exp);
1784               b->cond_exp = NULL;
1785             }
1786
1787           s = b->base.cond_string;
1788           b->cond_exp = parse_exp_1 (&s, 0, b->cond_exp_valid_block, 0);
1789         }
1790     }
1791
1792   /* If we failed to parse the expression, for example because
1793      it refers to a global variable in a not-yet-loaded shared library,
1794      don't try to insert watchpoint.  We don't automatically delete
1795      such watchpoint, though, since failure to parse expression
1796      is different from out-of-scope watchpoint.  */
1797   if (!target_has_execution)
1798     {
1799       /* Without execution, memory can't change.  No use to try and
1800          set watchpoint locations.  The watchpoint will be reset when
1801          the target gains execution, through breakpoint_re_set.  */
1802       if (!can_use_hw_watchpoints)
1803         {
1804           if (b->base.ops->works_in_software_mode (&b->base))
1805             b->base.type = bp_watchpoint;
1806           else
1807             error (_("Can't set read/access watchpoint when "
1808                      "hardware watchpoints are disabled."));
1809         }
1810     }
1811   else if (within_current_scope && b->exp)
1812     {
1813       int pc = 0;
1814       struct value *val_chain, *v, *result, *next;
1815       struct program_space *frame_pspace;
1816
1817       fetch_subexp_value (b->exp, &pc, &v, &result, &val_chain, 0);
1818
1819       /* Avoid setting b->val if it's already set.  The meaning of
1820          b->val is 'the last value' user saw, and we should update
1821          it only if we reported that last value to user.  As it
1822          happens, the code that reports it updates b->val directly.
1823          We don't keep track of the memory value for masked
1824          watchpoints.  */
1825       if (!b->val_valid && !is_masked_watchpoint (&b->base))
1826         {
1827           b->val = v;
1828           b->val_valid = 1;
1829         }
1830
1831       frame_pspace = get_frame_program_space (get_selected_frame (NULL));
1832
1833       /* Look at each value on the value chain.  */
1834       for (v = val_chain; v; v = value_next (v))
1835         {
1836           /* If it's a memory location, and GDB actually needed
1837              its contents to evaluate the expression, then we
1838              must watch it.  If the first value returned is
1839              still lazy, that means an error occurred reading it;
1840              watch it anyway in case it becomes readable.  */
1841           if (VALUE_LVAL (v) == lval_memory
1842               && (v == val_chain || ! value_lazy (v)))
1843             {
1844               struct type *vtype = check_typedef (value_type (v));
1845
1846               /* We only watch structs and arrays if user asked
1847                  for it explicitly, never if they just happen to
1848                  appear in the middle of some value chain.  */
1849               if (v == result
1850                   || (TYPE_CODE (vtype) != TYPE_CODE_STRUCT
1851                       && TYPE_CODE (vtype) != TYPE_CODE_ARRAY))
1852                 {
1853                   CORE_ADDR addr;
1854                   int type;
1855                   struct bp_location *loc, **tmp;
1856
1857                   addr = value_address (v);
1858                   type = hw_write;
1859                   if (b->base.type == bp_read_watchpoint)
1860                     type = hw_read;
1861                   else if (b->base.type == bp_access_watchpoint)
1862                     type = hw_access;
1863
1864                   loc = allocate_bp_location (&b->base);
1865                   for (tmp = &(b->base.loc); *tmp != NULL; tmp = &((*tmp)->next))
1866                     ;
1867                   *tmp = loc;
1868                   loc->gdbarch = get_type_arch (value_type (v));
1869
1870                   loc->pspace = frame_pspace;
1871                   loc->address = addr;
1872                   loc->length = TYPE_LENGTH (value_type (v));
1873                   loc->watchpoint_type = type;
1874                 }
1875             }
1876         }
1877
1878       /* Change the type of breakpoint between hardware assisted or
1879          an ordinary watchpoint depending on the hardware support
1880          and free hardware slots.  REPARSE is set when the inferior
1881          is started.  */
1882       if (reparse)
1883         {
1884           int reg_cnt;
1885           enum bp_loc_type loc_type;
1886           struct bp_location *bl;
1887
1888           reg_cnt = can_use_hardware_watchpoint (val_chain);
1889
1890           if (reg_cnt)
1891             {
1892               int i, target_resources_ok, other_type_used;
1893               enum bptype type;
1894
1895               /* Use an exact watchpoint when there's only one memory region to be
1896                  watched, and only one debug register is needed to watch it.  */
1897               b->exact = target_exact_watchpoints && reg_cnt == 1;
1898
1899               /* We need to determine how many resources are already
1900                  used for all other hardware watchpoints plus this one
1901                  to see if we still have enough resources to also fit
1902                  this watchpoint in as well.  */
1903
1904               /* If this is a software watchpoint, we try to turn it
1905                  to a hardware one -- count resources as if B was of
1906                  hardware watchpoint type.  */
1907               type = b->base.type;
1908               if (type == bp_watchpoint)
1909                 type = bp_hardware_watchpoint;
1910
1911               /* This watchpoint may or may not have been placed on
1912                  the list yet at this point (it won't be in the list
1913                  if we're trying to create it for the first time,
1914                  through watch_command), so always account for it
1915                  manually.  */
1916
1917               /* Count resources used by all watchpoints except B.  */
1918               i = hw_watchpoint_used_count_others (&b->base, type, &other_type_used);
1919
1920               /* Add in the resources needed for B.  */
1921               i += hw_watchpoint_use_count (&b->base);
1922
1923               target_resources_ok
1924                 = target_can_use_hardware_watchpoint (type, i, other_type_used);
1925               if (target_resources_ok <= 0)
1926                 {
1927                   int sw_mode = b->base.ops->works_in_software_mode (&b->base);
1928
1929                   if (target_resources_ok == 0 && !sw_mode)
1930                     error (_("Target does not support this type of "
1931                              "hardware watchpoint."));
1932                   else if (target_resources_ok < 0 && !sw_mode)
1933                     error (_("There are not enough available hardware "
1934                              "resources for this watchpoint."));
1935
1936                   /* Downgrade to software watchpoint.  */
1937                   b->base.type = bp_watchpoint;
1938                 }
1939               else
1940                 {
1941                   /* If this was a software watchpoint, we've just
1942                      found we have enough resources to turn it to a
1943                      hardware watchpoint.  Otherwise, this is a
1944                      nop.  */
1945                   b->base.type = type;
1946                 }
1947             }
1948           else if (!b->base.ops->works_in_software_mode (&b->base))
1949             {
1950               if (!can_use_hw_watchpoints)
1951                 error (_("Can't set read/access watchpoint when "
1952                          "hardware watchpoints are disabled."));
1953               else
1954                 error (_("Expression cannot be implemented with "
1955                          "read/access watchpoint."));
1956             }
1957           else
1958             b->base.type = bp_watchpoint;
1959
1960           loc_type = (b->base.type == bp_watchpoint? bp_loc_other
1961                       : bp_loc_hardware_watchpoint);
1962           for (bl = b->base.loc; bl; bl = bl->next)
1963             bl->loc_type = loc_type;
1964         }
1965
1966       for (v = val_chain; v; v = next)
1967         {
1968           next = value_next (v);
1969           if (v != b->val)
1970             value_free (v);
1971         }
1972
1973       /* If a software watchpoint is not watching any memory, then the
1974          above left it without any location set up.  But,
1975          bpstat_stop_status requires a location to be able to report
1976          stops, so make sure there's at least a dummy one.  */
1977       if (b->base.type == bp_watchpoint && b->base.loc == NULL)
1978         {
1979           struct breakpoint *base = &b->base;
1980           base->loc = allocate_bp_location (base);
1981           base->loc->pspace = frame_pspace;
1982           base->loc->address = -1;
1983           base->loc->length = -1;
1984           base->loc->watchpoint_type = -1;
1985         }
1986     }
1987   else if (!within_current_scope)
1988     {
1989       printf_filtered (_("\
1990 Watchpoint %d deleted because the program has left the block\n\
1991 in which its expression is valid.\n"),
1992                        b->base.number);
1993       watchpoint_del_at_next_stop (b);
1994     }
1995
1996   /* Restore the selected frame.  */
1997   if (frame_saved)
1998     select_frame (frame_find_by_id (saved_frame_id));
1999 }
2000
2001
2002 /* Returns 1 iff breakpoint location should be
2003    inserted in the inferior.  We don't differentiate the type of BL's owner
2004    (breakpoint vs. tracepoint), although insert_location in tracepoint's
2005    breakpoint_ops is not defined, because in insert_bp_location,
2006    tracepoint's insert_location will not be called.  */
2007 static int
2008 should_be_inserted (struct bp_location *bl)
2009 {
2010   if (bl->owner == NULL || !breakpoint_enabled (bl->owner))
2011     return 0;
2012
2013   if (bl->owner->disposition == disp_del_at_next_stop)
2014     return 0;
2015
2016   if (!bl->enabled || bl->shlib_disabled || bl->duplicate)
2017     return 0;
2018
2019   if (user_breakpoint_p (bl->owner) && bl->pspace->executing_startup)
2020     return 0;
2021
2022   /* This is set for example, when we're attached to the parent of a
2023      vfork, and have detached from the child.  The child is running
2024      free, and we expect it to do an exec or exit, at which point the
2025      OS makes the parent schedulable again (and the target reports
2026      that the vfork is done).  Until the child is done with the shared
2027      memory region, do not insert breakpoints in the parent, otherwise
2028      the child could still trip on the parent's breakpoints.  Since
2029      the parent is blocked anyway, it won't miss any breakpoint.  */
2030   if (bl->pspace->breakpoints_not_allowed)
2031     return 0;
2032
2033   return 1;
2034 }
2035
2036 /* Same as should_be_inserted but does the check assuming
2037    that the location is not duplicated.  */
2038
2039 static int
2040 unduplicated_should_be_inserted (struct bp_location *bl)
2041 {
2042   int result;
2043   const int save_duplicate = bl->duplicate;
2044
2045   bl->duplicate = 0;
2046   result = should_be_inserted (bl);
2047   bl->duplicate = save_duplicate;
2048   return result;
2049 }
2050
2051 /* Parses a conditional described by an expression COND into an
2052    agent expression bytecode suitable for evaluation
2053    by the bytecode interpreter.  Return NULL if there was
2054    any error during parsing.  */
2055
2056 static struct agent_expr *
2057 parse_cond_to_aexpr (CORE_ADDR scope, struct expression *cond)
2058 {
2059   struct agent_expr *aexpr = NULL;
2060   volatile struct gdb_exception ex;
2061
2062   if (!cond)
2063     return NULL;
2064
2065   /* We don't want to stop processing, so catch any errors
2066      that may show up.  */
2067   TRY_CATCH (ex, RETURN_MASK_ERROR)
2068     {
2069       aexpr = gen_eval_for_expr (scope, cond);
2070     }
2071
2072   if (ex.reason < 0)
2073     {
2074       /* If we got here, it means the condition could not be parsed to a valid
2075          bytecode expression and thus can't be evaluated on the target's side.
2076          It's no use iterating through the conditions.  */
2077       return NULL;
2078     }
2079
2080   /* We have a valid agent expression.  */
2081   return aexpr;
2082 }
2083
2084 /* Based on location BL, create a list of breakpoint conditions to be
2085    passed on to the target.  If we have duplicated locations with different
2086    conditions, we will add such conditions to the list.  The idea is that the
2087    target will evaluate the list of conditions and will only notify GDB when
2088    one of them is true.  */
2089
2090 static void
2091 build_target_condition_list (struct bp_location *bl)
2092 {
2093   struct bp_location **locp = NULL, **loc2p;
2094   int null_condition_or_parse_error = 0;
2095   int modified = bl->needs_update;
2096   struct bp_location *loc;
2097
2098   /* Release conditions left over from a previous insert.  */
2099   VEC_free (agent_expr_p, bl->target_info.conditions);
2100
2101   /* This is only meaningful if the target is
2102      evaluating conditions and if the user has
2103      opted for condition evaluation on the target's
2104      side.  */
2105   if (gdb_evaluates_breakpoint_condition_p ()
2106       || !target_supports_evaluation_of_breakpoint_conditions ())
2107     return;
2108
2109   /* Do a first pass to check for locations with no assigned
2110      conditions or conditions that fail to parse to a valid agent expression
2111      bytecode.  If any of these happen, then it's no use to send conditions
2112      to the target since this location will always trigger and generate a
2113      response back to GDB.  */
2114   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2115     {
2116       loc = (*loc2p);
2117       if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2118         {
2119           if (modified)
2120             {
2121               struct agent_expr *aexpr;
2122
2123               /* Re-parse the conditions since something changed.  In that
2124                  case we already freed the condition bytecodes (see
2125                  force_breakpoint_reinsertion).  We just
2126                  need to parse the condition to bytecodes again.  */
2127               aexpr = parse_cond_to_aexpr (bl->address, loc->cond);
2128               loc->cond_bytecode = aexpr;
2129
2130               /* Check if we managed to parse the conditional expression
2131                  correctly.  If not, we will not send this condition
2132                  to the target.  */
2133               if (aexpr)
2134                 continue;
2135             }
2136
2137           /* If we have a NULL bytecode expression, it means something
2138              went wrong or we have a null condition expression.  */
2139           if (!loc->cond_bytecode)
2140             {
2141               null_condition_or_parse_error = 1;
2142               break;
2143             }
2144         }
2145     }
2146
2147   /* If any of these happened, it means we will have to evaluate the conditions
2148      for the location's address on gdb's side.  It is no use keeping bytecodes
2149      for all the other duplicate locations, thus we free all of them here.
2150
2151      This is so we have a finer control over which locations' conditions are
2152      being evaluated by GDB or the remote stub.  */
2153   if (null_condition_or_parse_error)
2154     {
2155       ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2156         {
2157           loc = (*loc2p);
2158           if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2159             {
2160               /* Only go as far as the first NULL bytecode is
2161                  located.  */
2162               if (!loc->cond_bytecode)
2163                 return;
2164
2165               free_agent_expr (loc->cond_bytecode);
2166               loc->cond_bytecode = NULL;
2167             }
2168         }
2169     }
2170
2171   /* No NULL conditions or failed bytecode generation.  Build a condition list
2172      for this location's address.  */
2173   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2174     {
2175       loc = (*loc2p);
2176       if (loc->cond
2177           && is_breakpoint (loc->owner)
2178           && loc->pspace->num == bl->pspace->num
2179           && loc->owner->enable_state == bp_enabled
2180           && loc->enabled)
2181         /* Add the condition to the vector.  This will be used later to send the
2182            conditions to the target.  */
2183         VEC_safe_push (agent_expr_p, bl->target_info.conditions,
2184                        loc->cond_bytecode);
2185     }
2186
2187   return;
2188 }
2189
2190 /* Parses a command described by string CMD into an agent expression
2191    bytecode suitable for evaluation by the bytecode interpreter.
2192    Return NULL if there was any error during parsing.  */
2193
2194 static struct agent_expr *
2195 parse_cmd_to_aexpr (CORE_ADDR scope, char *cmd)
2196 {
2197   struct cleanup *old_cleanups = 0;
2198   struct expression *expr, **argvec;
2199   struct agent_expr *aexpr = NULL;
2200   volatile struct gdb_exception ex;
2201   const char *cmdrest;
2202   const char *format_start, *format_end;
2203   struct format_piece *fpieces;
2204   int nargs;
2205   struct gdbarch *gdbarch = get_current_arch ();
2206
2207   if (!cmd)
2208     return NULL;
2209
2210   cmdrest = cmd;
2211
2212   if (*cmdrest == ',')
2213     ++cmdrest;
2214   cmdrest = skip_spaces_const (cmdrest);
2215
2216   if (*cmdrest++ != '"')
2217     error (_("No format string following the location"));
2218
2219   format_start = cmdrest;
2220
2221   fpieces = parse_format_string (&cmdrest);
2222
2223   old_cleanups = make_cleanup (free_format_pieces_cleanup, &fpieces);
2224
2225   format_end = cmdrest;
2226
2227   if (*cmdrest++ != '"')
2228     error (_("Bad format string, non-terminated '\"'."));
2229   
2230   cmdrest = skip_spaces_const (cmdrest);
2231
2232   if (!(*cmdrest == ',' || *cmdrest == '\0'))
2233     error (_("Invalid argument syntax"));
2234
2235   if (*cmdrest == ',')
2236     cmdrest++;
2237   cmdrest = skip_spaces_const (cmdrest);
2238
2239   /* For each argument, make an expression.  */
2240
2241   argvec = (struct expression **) alloca (strlen (cmd)
2242                                          * sizeof (struct expression *));
2243
2244   nargs = 0;
2245   while (*cmdrest != '\0')
2246     {
2247       const char *cmd1;
2248
2249       cmd1 = cmdrest;
2250       expr = parse_exp_1 (&cmd1, scope, block_for_pc (scope), 1);
2251       argvec[nargs++] = expr;
2252       cmdrest = cmd1;
2253       if (*cmdrest == ',')
2254         ++cmdrest;
2255     }
2256
2257   /* We don't want to stop processing, so catch any errors
2258      that may show up.  */
2259   TRY_CATCH (ex, RETURN_MASK_ERROR)
2260     {
2261       aexpr = gen_printf (scope, gdbarch, 0, 0,
2262                           format_start, format_end - format_start,
2263                           fpieces, nargs, argvec);
2264     }
2265
2266   do_cleanups (old_cleanups);
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   /* We have a valid agent expression, return it.  */
2277   return aexpr;
2278 }
2279
2280 /* Based on location BL, create a list of breakpoint commands to be
2281    passed on to the target.  If we have duplicated locations with
2282    different commands, we will add any such to the list.  */
2283
2284 static void
2285 build_target_command_list (struct bp_location *bl)
2286 {
2287   struct bp_location **locp = NULL, **loc2p;
2288   int null_command_or_parse_error = 0;
2289   int modified = bl->needs_update;
2290   struct bp_location *loc;
2291
2292   /* Release commands left over from a previous insert.  */
2293   VEC_free (agent_expr_p, bl->target_info.tcommands);
2294
2295   /* For now, limit to agent-style dprintf breakpoints.  */
2296   if (bl->owner->type != bp_dprintf
2297       || strcmp (dprintf_style, dprintf_style_agent) != 0)
2298     return;
2299
2300   if (!target_can_run_breakpoint_commands ())
2301     return;
2302
2303   /* Do a first pass to check for locations with no assigned
2304      conditions or conditions that fail to parse to a valid agent expression
2305      bytecode.  If any of these happen, then it's no use to send conditions
2306      to the target since this location will always trigger and generate a
2307      response back to GDB.  */
2308   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2309     {
2310       loc = (*loc2p);
2311       if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2312         {
2313           if (modified)
2314             {
2315               struct agent_expr *aexpr;
2316
2317               /* Re-parse the commands since something changed.  In that
2318                  case we already freed the command bytecodes (see
2319                  force_breakpoint_reinsertion).  We just
2320                  need to parse the command to bytecodes again.  */
2321               aexpr = parse_cmd_to_aexpr (bl->address,
2322                                           loc->owner->extra_string);
2323               loc->cmd_bytecode = aexpr;
2324
2325               if (!aexpr)
2326                 continue;
2327             }
2328
2329           /* If we have a NULL bytecode expression, it means something
2330              went wrong or we have a null command expression.  */
2331           if (!loc->cmd_bytecode)
2332             {
2333               null_command_or_parse_error = 1;
2334               break;
2335             }
2336         }
2337     }
2338
2339   /* If anything failed, then we're not doing target-side commands,
2340      and so clean up.  */
2341   if (null_command_or_parse_error)
2342     {
2343       ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2344         {
2345           loc = (*loc2p);
2346           if (is_breakpoint (loc->owner)
2347               && loc->pspace->num == bl->pspace->num)
2348             {
2349               /* Only go as far as the first NULL bytecode is
2350                  located.  */
2351               if (loc->cmd_bytecode == NULL)
2352                 return;
2353
2354               free_agent_expr (loc->cmd_bytecode);
2355               loc->cmd_bytecode = NULL;
2356             }
2357         }
2358     }
2359
2360   /* No NULL commands or failed bytecode generation.  Build a command list
2361      for this location's address.  */
2362   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2363     {
2364       loc = (*loc2p);
2365       if (loc->owner->extra_string
2366           && is_breakpoint (loc->owner)
2367           && loc->pspace->num == bl->pspace->num
2368           && loc->owner->enable_state == bp_enabled
2369           && loc->enabled)
2370         /* Add the command to the vector.  This will be used later
2371            to send the commands to the target.  */
2372         VEC_safe_push (agent_expr_p, bl->target_info.tcommands,
2373                        loc->cmd_bytecode);
2374     }
2375
2376   bl->target_info.persist = 0;
2377   /* Maybe flag this location as persistent.  */
2378   if (bl->owner->type == bp_dprintf && disconnected_dprintf)
2379     bl->target_info.persist = 1;
2380 }
2381
2382 /* Insert a low-level "breakpoint" of some type.  BL is the breakpoint
2383    location.  Any error messages are printed to TMP_ERROR_STREAM; and
2384    DISABLED_BREAKS, and HW_BREAKPOINT_ERROR are used to report problems.
2385    Returns 0 for success, 1 if the bp_location type is not supported or
2386    -1 for failure.
2387
2388    NOTE drow/2003-09-09: This routine could be broken down to an
2389    object-style method for each breakpoint or catchpoint type.  */
2390 static int
2391 insert_bp_location (struct bp_location *bl,
2392                     struct ui_file *tmp_error_stream,
2393                     int *disabled_breaks,
2394                     int *hw_breakpoint_error,
2395                     int *hw_bp_error_explained_already)
2396 {
2397   enum errors bp_err = GDB_NO_ERROR;
2398   const char *bp_err_message = NULL;
2399   volatile struct gdb_exception e;
2400
2401   if (!should_be_inserted (bl) || (bl->inserted && !bl->needs_update))
2402     return 0;
2403
2404   /* Note we don't initialize bl->target_info, as that wipes out
2405      the breakpoint location's shadow_contents if the breakpoint
2406      is still inserted at that location.  This in turn breaks
2407      target_read_memory which depends on these buffers when
2408      a memory read is requested at the breakpoint location:
2409      Once the target_info has been wiped, we fail to see that
2410      we have a breakpoint inserted at that address and thus
2411      read the breakpoint instead of returning the data saved in
2412      the breakpoint location's shadow contents.  */
2413   bl->target_info.placed_address = bl->address;
2414   bl->target_info.placed_address_space = bl->pspace->aspace;
2415   bl->target_info.length = bl->length;
2416
2417   /* When working with target-side conditions, we must pass all the conditions
2418      for the same breakpoint address down to the target since GDB will not
2419      insert those locations.  With a list of breakpoint conditions, the target
2420      can decide when to stop and notify GDB.  */
2421
2422   if (is_breakpoint (bl->owner))
2423     {
2424       build_target_condition_list (bl);
2425       build_target_command_list (bl);
2426       /* Reset the modification marker.  */
2427       bl->needs_update = 0;
2428     }
2429
2430   if (bl->loc_type == bp_loc_software_breakpoint
2431       || bl->loc_type == bp_loc_hardware_breakpoint)
2432     {
2433       if (bl->owner->type != bp_hardware_breakpoint)
2434         {
2435           /* If the explicitly specified breakpoint type
2436              is not hardware breakpoint, check the memory map to see
2437              if the breakpoint address is in read only memory or not.
2438
2439              Two important cases are:
2440              - location type is not hardware breakpoint, memory
2441              is readonly.  We change the type of the location to
2442              hardware breakpoint.
2443              - location type is hardware breakpoint, memory is
2444              read-write.  This means we've previously made the
2445              location hardware one, but then the memory map changed,
2446              so we undo.
2447              
2448              When breakpoints are removed, remove_breakpoints will use
2449              location types we've just set here, the only possible
2450              problem is that memory map has changed during running
2451              program, but it's not going to work anyway with current
2452              gdb.  */
2453           struct mem_region *mr 
2454             = lookup_mem_region (bl->target_info.placed_address);
2455           
2456           if (mr)
2457             {
2458               if (automatic_hardware_breakpoints)
2459                 {
2460                   enum bp_loc_type new_type;
2461                   
2462                   if (mr->attrib.mode != MEM_RW)
2463                     new_type = bp_loc_hardware_breakpoint;
2464                   else 
2465                     new_type = bp_loc_software_breakpoint;
2466                   
2467                   if (new_type != bl->loc_type)
2468                     {
2469                       static int said = 0;
2470
2471                       bl->loc_type = new_type;
2472                       if (!said)
2473                         {
2474                           fprintf_filtered (gdb_stdout,
2475                                             _("Note: automatically using "
2476                                               "hardware breakpoints for "
2477                                               "read-only addresses.\n"));
2478                           said = 1;
2479                         }
2480                     }
2481                 }
2482               else if (bl->loc_type == bp_loc_software_breakpoint
2483                        && mr->attrib.mode != MEM_RW)        
2484                 warning (_("cannot set software breakpoint "
2485                            "at readonly address %s"),
2486                          paddress (bl->gdbarch, bl->address));
2487             }
2488         }
2489         
2490       /* First check to see if we have to handle an overlay.  */
2491       if (overlay_debugging == ovly_off
2492           || bl->section == NULL
2493           || !(section_is_overlay (bl->section)))
2494         {
2495           /* No overlay handling: just set the breakpoint.  */
2496           TRY_CATCH (e, RETURN_MASK_ALL)
2497             {
2498               int val;
2499
2500               val = bl->owner->ops->insert_location (bl);
2501               if (val)
2502                 bp_err = GENERIC_ERROR;
2503             }
2504           if (e.reason < 0)
2505             {
2506               bp_err = e.error;
2507               bp_err_message = e.message;
2508             }
2509         }
2510       else
2511         {
2512           /* This breakpoint is in an overlay section.
2513              Shall we set a breakpoint at the LMA?  */
2514           if (!overlay_events_enabled)
2515             {
2516               /* Yes -- overlay event support is not active, 
2517                  so we must try to set a breakpoint at the LMA.
2518                  This will not work for a hardware breakpoint.  */
2519               if (bl->loc_type == bp_loc_hardware_breakpoint)
2520                 warning (_("hardware breakpoint %d not supported in overlay!"),
2521                          bl->owner->number);
2522               else
2523                 {
2524                   CORE_ADDR addr = overlay_unmapped_address (bl->address,
2525                                                              bl->section);
2526                   /* Set a software (trap) breakpoint at the LMA.  */
2527                   bl->overlay_target_info = bl->target_info;
2528                   bl->overlay_target_info.placed_address = addr;
2529
2530                   /* No overlay handling: just set the breakpoint.  */
2531                   TRY_CATCH (e, RETURN_MASK_ALL)
2532                     {
2533                       int val;
2534
2535                       val = target_insert_breakpoint (bl->gdbarch,
2536                                                       &bl->overlay_target_info);
2537                       if (val)
2538                         bp_err = GENERIC_ERROR;
2539                     }
2540                   if (e.reason < 0)
2541                     {
2542                       bp_err = e.error;
2543                       bp_err_message = e.message;
2544                     }
2545
2546                   if (bp_err != GDB_NO_ERROR)
2547                     fprintf_unfiltered (tmp_error_stream,
2548                                         "Overlay breakpoint %d "
2549                                         "failed: in ROM?\n",
2550                                         bl->owner->number);
2551                 }
2552             }
2553           /* Shall we set a breakpoint at the VMA? */
2554           if (section_is_mapped (bl->section))
2555             {
2556               /* Yes.  This overlay section is mapped into memory.  */
2557               TRY_CATCH (e, RETURN_MASK_ALL)
2558                 {
2559                   int val;
2560
2561                   val = bl->owner->ops->insert_location (bl);
2562                   if (val)
2563                     bp_err = GENERIC_ERROR;
2564                 }
2565               if (e.reason < 0)
2566                 {
2567                   bp_err = e.error;
2568                   bp_err_message = e.message;
2569                 }
2570             }
2571           else
2572             {
2573               /* No.  This breakpoint will not be inserted.  
2574                  No error, but do not mark the bp as 'inserted'.  */
2575               return 0;
2576             }
2577         }
2578
2579       if (bp_err != GDB_NO_ERROR)
2580         {
2581           /* Can't set the breakpoint.  */
2582
2583           /* In some cases, we might not be able to insert a
2584              breakpoint in a shared library that has already been
2585              removed, but we have not yet processed the shlib unload
2586              event.  Unfortunately, some targets that implement
2587              breakpoint insertion themselves (necessary if this is a
2588              HW breakpoint, but SW breakpoints likewise) can't tell
2589              why the breakpoint insertion failed (e.g., the remote
2590              target doesn't define error codes), so we must treat
2591              generic errors as memory errors.  */
2592           if ((bp_err == GENERIC_ERROR || bp_err == MEMORY_ERROR)
2593               && solib_name_from_address (bl->pspace, bl->address))
2594             {
2595               /* See also: disable_breakpoints_in_shlibs.  */
2596               bl->shlib_disabled = 1;
2597               observer_notify_breakpoint_modified (bl->owner);
2598               if (!*disabled_breaks)
2599                 {
2600                   fprintf_unfiltered (tmp_error_stream, 
2601                                       "Cannot insert breakpoint %d.\n", 
2602                                       bl->owner->number);
2603                   fprintf_unfiltered (tmp_error_stream, 
2604                                       "Temporarily disabling shared "
2605                                       "library breakpoints:\n");
2606                 }
2607               *disabled_breaks = 1;
2608               fprintf_unfiltered (tmp_error_stream,
2609                                   "breakpoint #%d\n", bl->owner->number);
2610               return 0;
2611             }
2612           else
2613             {
2614               if (bl->loc_type == bp_loc_hardware_breakpoint)
2615                 {
2616                   *hw_breakpoint_error = 1;
2617                   *hw_bp_error_explained_already = bp_err_message != NULL;
2618                   fprintf_unfiltered (tmp_error_stream,
2619                                       "Cannot insert hardware breakpoint %d%s",
2620                                       bl->owner->number, bp_err_message ? ":" : ".\n");
2621                   if (bp_err_message != NULL)
2622                     fprintf_unfiltered (tmp_error_stream, "%s.\n", bp_err_message);
2623                 }
2624               else
2625                 {
2626                   if (bp_err_message == NULL)
2627                     {
2628                       char *message
2629                         = memory_error_message (TARGET_XFER_E_IO,
2630                                                 bl->gdbarch, bl->address);
2631                       struct cleanup *old_chain = make_cleanup (xfree, message);
2632
2633                       fprintf_unfiltered (tmp_error_stream,
2634                                           "Cannot insert breakpoint %d.\n"
2635                                           "%s\n",
2636                                           bl->owner->number, message);
2637                       do_cleanups (old_chain);
2638                     }
2639                   else
2640                     {
2641                       fprintf_unfiltered (tmp_error_stream,
2642                                           "Cannot insert breakpoint %d: %s\n",
2643                                           bl->owner->number,
2644                                           bp_err_message);
2645                     }
2646                 }
2647               return 1;
2648
2649             }
2650         }
2651       else
2652         bl->inserted = 1;
2653
2654       return 0;
2655     }
2656
2657   else if (bl->loc_type == bp_loc_hardware_watchpoint
2658            /* NOTE drow/2003-09-08: This state only exists for removing
2659               watchpoints.  It's not clear that it's necessary...  */
2660            && bl->owner->disposition != disp_del_at_next_stop)
2661     {
2662       int val;
2663
2664       gdb_assert (bl->owner->ops != NULL
2665                   && bl->owner->ops->insert_location != NULL);
2666
2667       val = bl->owner->ops->insert_location (bl);
2668
2669       /* If trying to set a read-watchpoint, and it turns out it's not
2670          supported, try emulating one with an access watchpoint.  */
2671       if (val == 1 && bl->watchpoint_type == hw_read)
2672         {
2673           struct bp_location *loc, **loc_temp;
2674
2675           /* But don't try to insert it, if there's already another
2676              hw_access location that would be considered a duplicate
2677              of this one.  */
2678           ALL_BP_LOCATIONS (loc, loc_temp)
2679             if (loc != bl
2680                 && loc->watchpoint_type == hw_access
2681                 && watchpoint_locations_match (bl, loc))
2682               {
2683                 bl->duplicate = 1;
2684                 bl->inserted = 1;
2685                 bl->target_info = loc->target_info;
2686                 bl->watchpoint_type = hw_access;
2687                 val = 0;
2688                 break;
2689               }
2690
2691           if (val == 1)
2692             {
2693               bl->watchpoint_type = hw_access;
2694               val = bl->owner->ops->insert_location (bl);
2695
2696               if (val)
2697                 /* Back to the original value.  */
2698                 bl->watchpoint_type = hw_read;
2699             }
2700         }
2701
2702       bl->inserted = (val == 0);
2703     }
2704
2705   else if (bl->owner->type == bp_catchpoint)
2706     {
2707       int val;
2708
2709       gdb_assert (bl->owner->ops != NULL
2710                   && bl->owner->ops->insert_location != NULL);
2711
2712       val = bl->owner->ops->insert_location (bl);
2713       if (val)
2714         {
2715           bl->owner->enable_state = bp_disabled;
2716
2717           if (val == 1)
2718             warning (_("\
2719 Error inserting catchpoint %d: Your system does not support this type\n\
2720 of catchpoint."), bl->owner->number);
2721           else
2722             warning (_("Error inserting catchpoint %d."), bl->owner->number);
2723         }
2724
2725       bl->inserted = (val == 0);
2726
2727       /* We've already printed an error message if there was a problem
2728          inserting this catchpoint, and we've disabled the catchpoint,
2729          so just return success.  */
2730       return 0;
2731     }
2732
2733   return 0;
2734 }
2735
2736 /* This function is called when program space PSPACE is about to be
2737    deleted.  It takes care of updating breakpoints to not reference
2738    PSPACE anymore.  */
2739
2740 void
2741 breakpoint_program_space_exit (struct program_space *pspace)
2742 {
2743   struct breakpoint *b, *b_temp;
2744   struct bp_location *loc, **loc_temp;
2745
2746   /* Remove any breakpoint that was set through this program space.  */
2747   ALL_BREAKPOINTS_SAFE (b, b_temp)
2748     {
2749       if (b->pspace == pspace)
2750         delete_breakpoint (b);
2751     }
2752
2753   /* Breakpoints set through other program spaces could have locations
2754      bound to PSPACE as well.  Remove those.  */
2755   ALL_BP_LOCATIONS (loc, loc_temp)
2756     {
2757       struct bp_location *tmp;
2758
2759       if (loc->pspace == pspace)
2760         {
2761           /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
2762           if (loc->owner->loc == loc)
2763             loc->owner->loc = loc->next;
2764           else
2765             for (tmp = loc->owner->loc; tmp->next != NULL; tmp = tmp->next)
2766               if (tmp->next == loc)
2767                 {
2768                   tmp->next = loc->next;
2769                   break;
2770                 }
2771         }
2772     }
2773
2774   /* Now update the global location list to permanently delete the
2775      removed locations above.  */
2776   update_global_location_list (0);
2777 }
2778
2779 /* Make sure all breakpoints are inserted in inferior.
2780    Throws exception on any error.
2781    A breakpoint that is already inserted won't be inserted
2782    again, so calling this function twice is safe.  */
2783 void
2784 insert_breakpoints (void)
2785 {
2786   struct breakpoint *bpt;
2787
2788   ALL_BREAKPOINTS (bpt)
2789     if (is_hardware_watchpoint (bpt))
2790       {
2791         struct watchpoint *w = (struct watchpoint *) bpt;
2792
2793         update_watchpoint (w, 0 /* don't reparse.  */);
2794       }
2795
2796   update_global_location_list (1);
2797
2798   /* update_global_location_list does not insert breakpoints when
2799      always_inserted_mode is not enabled.  Explicitly insert them
2800      now.  */
2801   if (!breakpoints_always_inserted_mode ())
2802     insert_breakpoint_locations ();
2803 }
2804
2805 /* Invoke CALLBACK for each of bp_location.  */
2806
2807 void
2808 iterate_over_bp_locations (walk_bp_location_callback callback)
2809 {
2810   struct bp_location *loc, **loc_tmp;
2811
2812   ALL_BP_LOCATIONS (loc, loc_tmp)
2813     {
2814       callback (loc, NULL);
2815     }
2816 }
2817
2818 /* This is used when we need to synch breakpoint conditions between GDB and the
2819    target.  It is the case with deleting and disabling of breakpoints when using
2820    always-inserted mode.  */
2821
2822 static void
2823 update_inserted_breakpoint_locations (void)
2824 {
2825   struct bp_location *bl, **blp_tmp;
2826   int error_flag = 0;
2827   int val = 0;
2828   int disabled_breaks = 0;
2829   int hw_breakpoint_error = 0;
2830   int hw_bp_details_reported = 0;
2831
2832   struct ui_file *tmp_error_stream = mem_fileopen ();
2833   struct cleanup *cleanups = make_cleanup_ui_file_delete (tmp_error_stream);
2834
2835   /* Explicitly mark the warning -- this will only be printed if
2836      there was an error.  */
2837   fprintf_unfiltered (tmp_error_stream, "Warning:\n");
2838
2839   save_current_space_and_thread ();
2840
2841   ALL_BP_LOCATIONS (bl, blp_tmp)
2842     {
2843       /* We only want to update software breakpoints and hardware
2844          breakpoints.  */
2845       if (!is_breakpoint (bl->owner))
2846         continue;
2847
2848       /* We only want to update locations that are already inserted
2849          and need updating.  This is to avoid unwanted insertion during
2850          deletion of breakpoints.  */
2851       if (!bl->inserted || (bl->inserted && !bl->needs_update))
2852         continue;
2853
2854       switch_to_program_space_and_thread (bl->pspace);
2855
2856       /* For targets that support global breakpoints, there's no need
2857          to select an inferior to insert breakpoint to.  In fact, even
2858          if we aren't attached to any process yet, we should still
2859          insert breakpoints.  */
2860       if (!gdbarch_has_global_breakpoints (target_gdbarch ())
2861           && ptid_equal (inferior_ptid, null_ptid))
2862         continue;
2863
2864       val = insert_bp_location (bl, tmp_error_stream, &disabled_breaks,
2865                                     &hw_breakpoint_error, &hw_bp_details_reported);
2866       if (val)
2867         error_flag = val;
2868     }
2869
2870   if (error_flag)
2871     {
2872       target_terminal_ours_for_output ();
2873       error_stream (tmp_error_stream);
2874     }
2875
2876   do_cleanups (cleanups);
2877 }
2878
2879 /* Used when starting or continuing the program.  */
2880
2881 static void
2882 insert_breakpoint_locations (void)
2883 {
2884   struct breakpoint *bpt;
2885   struct bp_location *bl, **blp_tmp;
2886   int error_flag = 0;
2887   int val = 0;
2888   int disabled_breaks = 0;
2889   int hw_breakpoint_error = 0;
2890   int hw_bp_error_explained_already = 0;
2891
2892   struct ui_file *tmp_error_stream = mem_fileopen ();
2893   struct cleanup *cleanups = make_cleanup_ui_file_delete (tmp_error_stream);
2894   
2895   /* Explicitly mark the warning -- this will only be printed if
2896      there was an error.  */
2897   fprintf_unfiltered (tmp_error_stream, "Warning:\n");
2898
2899   save_current_space_and_thread ();
2900
2901   ALL_BP_LOCATIONS (bl, blp_tmp)
2902     {
2903       if (!should_be_inserted (bl) || (bl->inserted && !bl->needs_update))
2904         continue;
2905
2906       /* There is no point inserting thread-specific breakpoints if
2907          the thread no longer exists.  ALL_BP_LOCATIONS bp_location
2908          has BL->OWNER always non-NULL.  */
2909       if (bl->owner->thread != -1
2910           && !valid_thread_id (bl->owner->thread))
2911         continue;
2912
2913       switch_to_program_space_and_thread (bl->pspace);
2914
2915       /* For targets that support global breakpoints, there's no need
2916          to select an inferior to insert breakpoint to.  In fact, even
2917          if we aren't attached to any process yet, we should still
2918          insert breakpoints.  */
2919       if (!gdbarch_has_global_breakpoints (target_gdbarch ())
2920           && ptid_equal (inferior_ptid, null_ptid))
2921         continue;
2922
2923       val = insert_bp_location (bl, tmp_error_stream, &disabled_breaks,
2924                                     &hw_breakpoint_error, &hw_bp_error_explained_already);
2925       if (val)
2926         error_flag = val;
2927     }
2928
2929   /* If we failed to insert all locations of a watchpoint, remove
2930      them, as half-inserted watchpoint is of limited use.  */
2931   ALL_BREAKPOINTS (bpt)  
2932     {
2933       int some_failed = 0;
2934       struct bp_location *loc;
2935
2936       if (!is_hardware_watchpoint (bpt))
2937         continue;
2938
2939       if (!breakpoint_enabled (bpt))
2940         continue;
2941
2942       if (bpt->disposition == disp_del_at_next_stop)
2943         continue;
2944       
2945       for (loc = bpt->loc; loc; loc = loc->next)
2946         if (!loc->inserted && should_be_inserted (loc))
2947           {
2948             some_failed = 1;
2949             break;
2950           }
2951       if (some_failed)
2952         {
2953           for (loc = bpt->loc; loc; loc = loc->next)
2954             if (loc->inserted)
2955               remove_breakpoint (loc, mark_uninserted);
2956
2957           hw_breakpoint_error = 1;
2958           fprintf_unfiltered (tmp_error_stream,
2959                               "Could not insert hardware watchpoint %d.\n", 
2960                               bpt->number);
2961           error_flag = -1;
2962         }
2963     }
2964
2965   if (error_flag)
2966     {
2967       /* If a hardware breakpoint or watchpoint was inserted, add a
2968          message about possibly exhausted resources.  */
2969       if (hw_breakpoint_error && !hw_bp_error_explained_already)
2970         {
2971           fprintf_unfiltered (tmp_error_stream, 
2972                               "Could not insert hardware breakpoints:\n\
2973 You may have requested too many hardware breakpoints/watchpoints.\n");
2974         }
2975       target_terminal_ours_for_output ();
2976       error_stream (tmp_error_stream);
2977     }
2978
2979   do_cleanups (cleanups);
2980 }
2981
2982 /* Used when the program stops.
2983    Returns zero if successful, or non-zero if there was a problem
2984    removing a breakpoint location.  */
2985
2986 int
2987 remove_breakpoints (void)
2988 {
2989   struct bp_location *bl, **blp_tmp;
2990   int val = 0;
2991
2992   ALL_BP_LOCATIONS (bl, blp_tmp)
2993   {
2994     if (bl->inserted && !is_tracepoint (bl->owner))
2995       val |= remove_breakpoint (bl, mark_uninserted);
2996   }
2997   return val;
2998 }
2999
3000 /* When a thread exits, remove breakpoints that are related to
3001    that thread.  */
3002
3003 static void
3004 remove_threaded_breakpoints (struct thread_info *tp, int silent)
3005 {
3006   struct breakpoint *b, *b_tmp;
3007
3008   ALL_BREAKPOINTS_SAFE (b, b_tmp)
3009     {
3010       if (b->thread == tp->num && user_breakpoint_p (b))
3011         {
3012           b->disposition = disp_del_at_next_stop;
3013
3014           printf_filtered (_("\
3015 Thread-specific breakpoint %d deleted - thread %d no longer in the thread list.\n"),
3016                           b->number, tp->num);
3017
3018           /* Hide it from the user.  */
3019           b->number = 0;
3020        }
3021     }
3022 }
3023
3024 /* Remove breakpoints of process PID.  */
3025
3026 int
3027 remove_breakpoints_pid (int pid)
3028 {
3029   struct bp_location *bl, **blp_tmp;
3030   int val;
3031   struct inferior *inf = find_inferior_pid (pid);
3032
3033   ALL_BP_LOCATIONS (bl, blp_tmp)
3034   {
3035     if (bl->pspace != inf->pspace)
3036       continue;
3037
3038     if (bl->owner->type == bp_dprintf)
3039       continue;
3040
3041     if (bl->inserted)
3042       {
3043         val = remove_breakpoint (bl, mark_uninserted);
3044         if (val != 0)
3045           return val;
3046       }
3047   }
3048   return 0;
3049 }
3050
3051 int
3052 reattach_breakpoints (int pid)
3053 {
3054   struct cleanup *old_chain;
3055   struct bp_location *bl, **blp_tmp;
3056   int val;
3057   struct ui_file *tmp_error_stream;
3058   int dummy1 = 0, dummy2 = 0, dummy3 = 0;
3059   struct inferior *inf;
3060   struct thread_info *tp;
3061
3062   tp = any_live_thread_of_process (pid);
3063   if (tp == NULL)
3064     return 1;
3065
3066   inf = find_inferior_pid (pid);
3067   old_chain = save_inferior_ptid ();
3068
3069   inferior_ptid = tp->ptid;
3070
3071   tmp_error_stream = mem_fileopen ();
3072   make_cleanup_ui_file_delete (tmp_error_stream);
3073
3074   ALL_BP_LOCATIONS (bl, blp_tmp)
3075   {
3076     if (bl->pspace != inf->pspace)
3077       continue;
3078
3079     if (bl->inserted)
3080       {
3081         bl->inserted = 0;
3082         val = insert_bp_location (bl, tmp_error_stream, &dummy1, &dummy2, &dummy3);
3083         if (val != 0)
3084           {
3085             do_cleanups (old_chain);
3086             return val;
3087           }
3088       }
3089   }
3090   do_cleanups (old_chain);
3091   return 0;
3092 }
3093
3094 static int internal_breakpoint_number = -1;
3095
3096 /* Set the breakpoint number of B, depending on the value of INTERNAL.
3097    If INTERNAL is non-zero, the breakpoint number will be populated
3098    from internal_breakpoint_number and that variable decremented.
3099    Otherwise the breakpoint number will be populated from
3100    breakpoint_count and that value incremented.  Internal breakpoints
3101    do not set the internal var bpnum.  */
3102 static void
3103 set_breakpoint_number (int internal, struct breakpoint *b)
3104 {
3105   if (internal)
3106     b->number = internal_breakpoint_number--;
3107   else
3108     {
3109       set_breakpoint_count (breakpoint_count + 1);
3110       b->number = breakpoint_count;
3111     }
3112 }
3113
3114 static struct breakpoint *
3115 create_internal_breakpoint (struct gdbarch *gdbarch,
3116                             CORE_ADDR address, enum bptype type,
3117                             const struct breakpoint_ops *ops)
3118 {
3119   struct symtab_and_line sal;
3120   struct breakpoint *b;
3121
3122   init_sal (&sal);              /* Initialize to zeroes.  */
3123
3124   sal.pc = address;
3125   sal.section = find_pc_overlay (sal.pc);
3126   sal.pspace = current_program_space;
3127
3128   b = set_raw_breakpoint (gdbarch, sal, type, ops);
3129   b->number = internal_breakpoint_number--;
3130   b->disposition = disp_donttouch;
3131
3132   return b;
3133 }
3134
3135 static const char *const longjmp_names[] =
3136   {
3137     "longjmp", "_longjmp", "siglongjmp", "_siglongjmp"
3138   };
3139 #define NUM_LONGJMP_NAMES ARRAY_SIZE(longjmp_names)
3140
3141 /* Per-objfile data private to breakpoint.c.  */
3142 struct breakpoint_objfile_data
3143 {
3144   /* Minimal symbol for "_ovly_debug_event" (if any).  */
3145   struct minimal_symbol *overlay_msym;
3146
3147   /* Minimal symbol(s) for "longjmp", "siglongjmp", etc. (if any).  */
3148   struct minimal_symbol *longjmp_msym[NUM_LONGJMP_NAMES];
3149
3150   /* True if we have looked for longjmp probes.  */
3151   int longjmp_searched;
3152
3153   /* SystemTap probe points for longjmp (if any).  */
3154   VEC (probe_p) *longjmp_probes;
3155
3156   /* Minimal symbol for "std::terminate()" (if any).  */
3157   struct minimal_symbol *terminate_msym;
3158
3159   /* Minimal symbol for "_Unwind_DebugHook" (if any).  */
3160   struct minimal_symbol *exception_msym;
3161
3162   /* True if we have looked for exception probes.  */
3163   int exception_searched;
3164
3165   /* SystemTap probe points for unwinding (if any).  */
3166   VEC (probe_p) *exception_probes;
3167 };
3168
3169 static const struct objfile_data *breakpoint_objfile_key;
3170
3171 /* Minimal symbol not found sentinel.  */
3172 static struct minimal_symbol msym_not_found;
3173
3174 /* Returns TRUE if MSYM point to the "not found" sentinel.  */
3175
3176 static int
3177 msym_not_found_p (const struct minimal_symbol *msym)
3178 {
3179   return msym == &msym_not_found;
3180 }
3181
3182 /* Return per-objfile data needed by breakpoint.c.
3183    Allocate the data if necessary.  */
3184
3185 static struct breakpoint_objfile_data *
3186 get_breakpoint_objfile_data (struct objfile *objfile)
3187 {
3188   struct breakpoint_objfile_data *bp_objfile_data;
3189
3190   bp_objfile_data = objfile_data (objfile, breakpoint_objfile_key);
3191   if (bp_objfile_data == NULL)
3192     {
3193       bp_objfile_data = obstack_alloc (&objfile->objfile_obstack,
3194                                        sizeof (*bp_objfile_data));
3195
3196       memset (bp_objfile_data, 0, sizeof (*bp_objfile_data));
3197       set_objfile_data (objfile, breakpoint_objfile_key, bp_objfile_data);
3198     }
3199   return bp_objfile_data;
3200 }
3201
3202 static void
3203 free_breakpoint_probes (struct objfile *obj, void *data)
3204 {
3205   struct breakpoint_objfile_data *bp_objfile_data = data;
3206
3207   VEC_free (probe_p, bp_objfile_data->longjmp_probes);
3208   VEC_free (probe_p, bp_objfile_data->exception_probes);
3209 }
3210
3211 static void
3212 create_overlay_event_breakpoint (void)
3213 {
3214   struct objfile *objfile;
3215   const char *const func_name = "_ovly_debug_event";
3216
3217   ALL_OBJFILES (objfile)
3218     {
3219       struct breakpoint *b;
3220       struct breakpoint_objfile_data *bp_objfile_data;
3221       CORE_ADDR addr;
3222
3223       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3224
3225       if (msym_not_found_p (bp_objfile_data->overlay_msym))
3226         continue;
3227
3228       if (bp_objfile_data->overlay_msym == NULL)
3229         {
3230           struct minimal_symbol *m;
3231
3232           m = lookup_minimal_symbol_text (func_name, objfile);
3233           if (m == NULL)
3234             {
3235               /* Avoid future lookups in this objfile.  */
3236               bp_objfile_data->overlay_msym = &msym_not_found;
3237               continue;
3238             }
3239           bp_objfile_data->overlay_msym = m;
3240         }
3241
3242       addr = SYMBOL_VALUE_ADDRESS (bp_objfile_data->overlay_msym);
3243       b = create_internal_breakpoint (get_objfile_arch (objfile), addr,
3244                                       bp_overlay_event,
3245                                       &internal_breakpoint_ops);
3246       b->addr_string = xstrdup (func_name);
3247
3248       if (overlay_debugging == ovly_auto)
3249         {
3250           b->enable_state = bp_enabled;
3251           overlay_events_enabled = 1;
3252         }
3253       else
3254        {
3255          b->enable_state = bp_disabled;
3256          overlay_events_enabled = 0;
3257        }
3258     }
3259   update_global_location_list (1);
3260 }
3261
3262 static void
3263 create_longjmp_master_breakpoint (void)
3264 {
3265   struct program_space *pspace;
3266   struct cleanup *old_chain;
3267
3268   old_chain = save_current_program_space ();
3269
3270   ALL_PSPACES (pspace)
3271   {
3272     struct objfile *objfile;
3273
3274     set_current_program_space (pspace);
3275
3276     ALL_OBJFILES (objfile)
3277     {
3278       int i;
3279       struct gdbarch *gdbarch;
3280       struct breakpoint_objfile_data *bp_objfile_data;
3281
3282       gdbarch = get_objfile_arch (objfile);
3283
3284       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3285
3286       if (!bp_objfile_data->longjmp_searched)
3287         {
3288           VEC (probe_p) *ret;
3289
3290           ret = find_probes_in_objfile (objfile, "libc", "longjmp");
3291           if (ret != NULL)
3292             {
3293               /* We are only interested in checking one element.  */
3294               struct probe *p = VEC_index (probe_p, ret, 0);
3295
3296               if (!can_evaluate_probe_arguments (p))
3297                 {
3298                   /* We cannot use the probe interface here, because it does
3299                      not know how to evaluate arguments.  */
3300                   VEC_free (probe_p, ret);
3301                   ret = NULL;
3302                 }
3303             }
3304           bp_objfile_data->longjmp_probes = ret;
3305           bp_objfile_data->longjmp_searched = 1;
3306         }
3307
3308       if (bp_objfile_data->longjmp_probes != NULL)
3309         {
3310           int i;
3311           struct probe *probe;
3312           struct gdbarch *gdbarch = get_objfile_arch (objfile);
3313
3314           for (i = 0;
3315                VEC_iterate (probe_p,
3316                             bp_objfile_data->longjmp_probes,
3317                             i, probe);
3318                ++i)
3319             {
3320               struct breakpoint *b;
3321
3322               b = create_internal_breakpoint (gdbarch, probe->address,
3323                                               bp_longjmp_master,
3324                                               &internal_breakpoint_ops);
3325               b->addr_string = xstrdup ("-probe-stap libc:longjmp");
3326               b->enable_state = bp_disabled;
3327             }
3328
3329           continue;
3330         }
3331
3332       if (!gdbarch_get_longjmp_target_p (gdbarch))
3333         continue;
3334
3335       for (i = 0; i < NUM_LONGJMP_NAMES; i++)
3336         {
3337           struct breakpoint *b;
3338           const char *func_name;
3339           CORE_ADDR addr;
3340
3341           if (msym_not_found_p (bp_objfile_data->longjmp_msym[i]))
3342             continue;
3343
3344           func_name = longjmp_names[i];
3345           if (bp_objfile_data->longjmp_msym[i] == NULL)
3346             {
3347               struct minimal_symbol *m;
3348
3349               m = lookup_minimal_symbol_text (func_name, objfile);
3350               if (m == NULL)
3351                 {
3352                   /* Prevent future lookups in this objfile.  */
3353                   bp_objfile_data->longjmp_msym[i] = &msym_not_found;
3354                   continue;
3355                 }
3356               bp_objfile_data->longjmp_msym[i] = m;
3357             }
3358
3359           addr = SYMBOL_VALUE_ADDRESS (bp_objfile_data->longjmp_msym[i]);
3360           b = create_internal_breakpoint (gdbarch, addr, bp_longjmp_master,
3361                                           &internal_breakpoint_ops);
3362           b->addr_string = xstrdup (func_name);
3363           b->enable_state = bp_disabled;
3364         }
3365     }
3366   }
3367   update_global_location_list (1);
3368
3369   do_cleanups (old_chain);
3370 }
3371
3372 /* Create a master std::terminate breakpoint.  */
3373 static void
3374 create_std_terminate_master_breakpoint (void)
3375 {
3376   struct program_space *pspace;
3377   struct cleanup *old_chain;
3378   const char *const func_name = "std::terminate()";
3379
3380   old_chain = save_current_program_space ();
3381
3382   ALL_PSPACES (pspace)
3383   {
3384     struct objfile *objfile;
3385     CORE_ADDR addr;
3386
3387     set_current_program_space (pspace);
3388
3389     ALL_OBJFILES (objfile)
3390     {
3391       struct breakpoint *b;
3392       struct breakpoint_objfile_data *bp_objfile_data;
3393
3394       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3395
3396       if (msym_not_found_p (bp_objfile_data->terminate_msym))
3397         continue;
3398
3399       if (bp_objfile_data->terminate_msym == NULL)
3400         {
3401           struct minimal_symbol *m;
3402
3403           m = lookup_minimal_symbol (func_name, NULL, objfile);
3404           if (m == NULL || (MSYMBOL_TYPE (m) != mst_text
3405                             && MSYMBOL_TYPE (m) != mst_file_text))
3406             {
3407               /* Prevent future lookups in this objfile.  */
3408               bp_objfile_data->terminate_msym = &msym_not_found;
3409               continue;
3410             }
3411           bp_objfile_data->terminate_msym = m;
3412         }
3413
3414       addr = SYMBOL_VALUE_ADDRESS (bp_objfile_data->terminate_msym);
3415       b = create_internal_breakpoint (get_objfile_arch (objfile), addr,
3416                                       bp_std_terminate_master,
3417                                       &internal_breakpoint_ops);
3418       b->addr_string = xstrdup (func_name);
3419       b->enable_state = bp_disabled;
3420     }
3421   }
3422
3423   update_global_location_list (1);
3424
3425   do_cleanups (old_chain);
3426 }
3427
3428 /* Install a master breakpoint on the unwinder's debug hook.  */
3429
3430 static void
3431 create_exception_master_breakpoint (void)
3432 {
3433   struct objfile *objfile;
3434   const char *const func_name = "_Unwind_DebugHook";
3435
3436   ALL_OBJFILES (objfile)
3437     {
3438       struct breakpoint *b;
3439       struct gdbarch *gdbarch;
3440       struct breakpoint_objfile_data *bp_objfile_data;
3441       CORE_ADDR addr;
3442
3443       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3444
3445       /* We prefer the SystemTap probe point if it exists.  */
3446       if (!bp_objfile_data->exception_searched)
3447         {
3448           VEC (probe_p) *ret;
3449
3450           ret = find_probes_in_objfile (objfile, "libgcc", "unwind");
3451
3452           if (ret != NULL)
3453             {
3454               /* We are only interested in checking one element.  */
3455               struct probe *p = VEC_index (probe_p, ret, 0);
3456
3457               if (!can_evaluate_probe_arguments (p))
3458                 {
3459                   /* We cannot use the probe interface here, because it does
3460                      not know how to evaluate arguments.  */
3461                   VEC_free (probe_p, ret);
3462                   ret = NULL;
3463                 }
3464             }
3465           bp_objfile_data->exception_probes = ret;
3466           bp_objfile_data->exception_searched = 1;
3467         }
3468
3469       if (bp_objfile_data->exception_probes != NULL)
3470         {
3471           struct gdbarch *gdbarch = get_objfile_arch (objfile);
3472           int i;
3473           struct probe *probe;
3474
3475           for (i = 0;
3476                VEC_iterate (probe_p,
3477                             bp_objfile_data->exception_probes,
3478                             i, probe);
3479                ++i)
3480             {
3481               struct breakpoint *b;
3482
3483               b = create_internal_breakpoint (gdbarch, probe->address,
3484                                               bp_exception_master,
3485                                               &internal_breakpoint_ops);
3486               b->addr_string = xstrdup ("-probe-stap libgcc:unwind");
3487               b->enable_state = bp_disabled;
3488             }
3489
3490           continue;
3491         }
3492
3493       /* Otherwise, try the hook function.  */
3494
3495       if (msym_not_found_p (bp_objfile_data->exception_msym))
3496         continue;
3497
3498       gdbarch = get_objfile_arch (objfile);
3499
3500       if (bp_objfile_data->exception_msym == NULL)
3501         {
3502           struct minimal_symbol *debug_hook;
3503
3504           debug_hook = lookup_minimal_symbol (func_name, NULL, objfile);
3505           if (debug_hook == NULL)
3506             {
3507               bp_objfile_data->exception_msym = &msym_not_found;
3508               continue;
3509             }
3510
3511           bp_objfile_data->exception_msym = debug_hook;
3512         }
3513
3514       addr = SYMBOL_VALUE_ADDRESS (bp_objfile_data->exception_msym);
3515       addr = gdbarch_convert_from_func_ptr_addr (gdbarch, addr,
3516                                                  &current_target);
3517       b = create_internal_breakpoint (gdbarch, addr, bp_exception_master,
3518                                       &internal_breakpoint_ops);
3519       b->addr_string = xstrdup (func_name);
3520       b->enable_state = bp_disabled;
3521     }
3522
3523   update_global_location_list (1);
3524 }
3525
3526 void
3527 update_breakpoints_after_exec (void)
3528 {
3529   struct breakpoint *b, *b_tmp;
3530   struct bp_location *bploc, **bplocp_tmp;
3531
3532   /* We're about to delete breakpoints from GDB's lists.  If the
3533      INSERTED flag is true, GDB will try to lift the breakpoints by
3534      writing the breakpoints' "shadow contents" back into memory.  The
3535      "shadow contents" are NOT valid after an exec, so GDB should not
3536      do that.  Instead, the target is responsible from marking
3537      breakpoints out as soon as it detects an exec.  We don't do that
3538      here instead, because there may be other attempts to delete
3539      breakpoints after detecting an exec and before reaching here.  */
3540   ALL_BP_LOCATIONS (bploc, bplocp_tmp)
3541     if (bploc->pspace == current_program_space)
3542       gdb_assert (!bploc->inserted);
3543
3544   ALL_BREAKPOINTS_SAFE (b, b_tmp)
3545   {
3546     if (b->pspace != current_program_space)
3547       continue;
3548
3549     /* Solib breakpoints must be explicitly reset after an exec().  */
3550     if (b->type == bp_shlib_event)
3551       {
3552         delete_breakpoint (b);
3553         continue;
3554       }
3555
3556     /* JIT breakpoints must be explicitly reset after an exec().  */
3557     if (b->type == bp_jit_event)
3558       {
3559         delete_breakpoint (b);
3560         continue;
3561       }
3562
3563     /* Thread event breakpoints must be set anew after an exec(),
3564        as must overlay event and longjmp master breakpoints.  */
3565     if (b->type == bp_thread_event || b->type == bp_overlay_event
3566         || b->type == bp_longjmp_master || b->type == bp_std_terminate_master
3567         || b->type == bp_exception_master)
3568       {
3569         delete_breakpoint (b);
3570         continue;
3571       }
3572
3573     /* Step-resume breakpoints are meaningless after an exec().  */
3574     if (b->type == bp_step_resume || b->type == bp_hp_step_resume)
3575       {
3576         delete_breakpoint (b);
3577         continue;
3578       }
3579
3580     /* Longjmp and longjmp-resume breakpoints are also meaningless
3581        after an exec.  */
3582     if (b->type == bp_longjmp || b->type == bp_longjmp_resume
3583         || b->type == bp_longjmp_call_dummy
3584         || b->type == bp_exception || b->type == bp_exception_resume)
3585       {
3586         delete_breakpoint (b);
3587         continue;
3588       }
3589
3590     if (b->type == bp_catchpoint)
3591       {
3592         /* For now, none of the bp_catchpoint breakpoints need to
3593            do anything at this point.  In the future, if some of
3594            the catchpoints need to something, we will need to add
3595            a new method, and call this method from here.  */
3596         continue;
3597       }
3598
3599     /* bp_finish is a special case.  The only way we ought to be able
3600        to see one of these when an exec() has happened, is if the user
3601        caught a vfork, and then said "finish".  Ordinarily a finish just
3602        carries them to the call-site of the current callee, by setting
3603        a temporary bp there and resuming.  But in this case, the finish
3604        will carry them entirely through the vfork & exec.
3605
3606        We don't want to allow a bp_finish to remain inserted now.  But
3607        we can't safely delete it, 'cause finish_command has a handle to
3608        the bp on a bpstat, and will later want to delete it.  There's a
3609        chance (and I've seen it happen) that if we delete the bp_finish
3610        here, that its storage will get reused by the time finish_command
3611        gets 'round to deleting the "use to be a bp_finish" breakpoint.
3612        We really must allow finish_command to delete a bp_finish.
3613
3614        In the absence of a general solution for the "how do we know
3615        it's safe to delete something others may have handles to?"
3616        problem, what we'll do here is just uninsert the bp_finish, and
3617        let finish_command delete it.
3618
3619        (We know the bp_finish is "doomed" in the sense that it's
3620        momentary, and will be deleted as soon as finish_command sees
3621        the inferior stopped.  So it doesn't matter that the bp's
3622        address is probably bogus in the new a.out, unlike e.g., the
3623        solib breakpoints.)  */
3624
3625     if (b->type == bp_finish)
3626       {
3627         continue;
3628       }
3629
3630     /* Without a symbolic address, we have little hope of the
3631        pre-exec() address meaning the same thing in the post-exec()
3632        a.out.  */
3633     if (b->addr_string == NULL)
3634       {
3635         delete_breakpoint (b);
3636         continue;
3637       }
3638   }
3639   /* FIXME what about longjmp breakpoints?  Re-create them here?  */
3640   create_overlay_event_breakpoint ();
3641   create_longjmp_master_breakpoint ();
3642   create_std_terminate_master_breakpoint ();
3643   create_exception_master_breakpoint ();
3644 }
3645
3646 int
3647 detach_breakpoints (ptid_t ptid)
3648 {
3649   struct bp_location *bl, **blp_tmp;
3650   int val = 0;
3651   struct cleanup *old_chain = save_inferior_ptid ();
3652   struct inferior *inf = current_inferior ();
3653
3654   if (ptid_get_pid (ptid) == ptid_get_pid (inferior_ptid))
3655     error (_("Cannot detach breakpoints of inferior_ptid"));
3656
3657   /* Set inferior_ptid; remove_breakpoint_1 uses this global.  */
3658   inferior_ptid = ptid;
3659   ALL_BP_LOCATIONS (bl, blp_tmp)
3660   {
3661     if (bl->pspace != inf->pspace)
3662       continue;
3663
3664     /* This function must physically remove breakpoints locations
3665        from the specified ptid, without modifying the breakpoint
3666        package's state.  Locations of type bp_loc_other are only
3667        maintained at GDB side.  So, there is no need to remove
3668        these bp_loc_other locations.  Moreover, removing these
3669        would modify the breakpoint package's state.  */
3670     if (bl->loc_type == bp_loc_other)
3671       continue;
3672
3673     if (bl->inserted)
3674       val |= remove_breakpoint_1 (bl, mark_inserted);
3675   }
3676
3677   /* Detach single-step breakpoints as well.  */
3678   detach_single_step_breakpoints ();
3679
3680   do_cleanups (old_chain);
3681   return val;
3682 }
3683
3684 /* Remove the breakpoint location BL from the current address space.
3685    Note that this is used to detach breakpoints from a child fork.
3686    When we get here, the child isn't in the inferior list, and neither
3687    do we have objects to represent its address space --- we should
3688    *not* look at bl->pspace->aspace here.  */
3689
3690 static int
3691 remove_breakpoint_1 (struct bp_location *bl, insertion_state_t is)
3692 {
3693   int val;
3694
3695   /* BL is never in moribund_locations by our callers.  */
3696   gdb_assert (bl->owner != NULL);
3697
3698   if (bl->owner->enable_state == bp_permanent)
3699     /* Permanent breakpoints cannot be inserted or removed.  */
3700     return 0;
3701
3702   /* The type of none suggests that owner is actually deleted.
3703      This should not ever happen.  */
3704   gdb_assert (bl->owner->type != bp_none);
3705
3706   if (bl->loc_type == bp_loc_software_breakpoint
3707       || bl->loc_type == bp_loc_hardware_breakpoint)
3708     {
3709       /* "Normal" instruction breakpoint: either the standard
3710          trap-instruction bp (bp_breakpoint), or a
3711          bp_hardware_breakpoint.  */
3712
3713       /* First check to see if we have to handle an overlay.  */
3714       if (overlay_debugging == ovly_off
3715           || bl->section == NULL
3716           || !(section_is_overlay (bl->section)))
3717         {
3718           /* No overlay handling: just remove the breakpoint.  */
3719           val = bl->owner->ops->remove_location (bl);
3720         }
3721       else
3722         {
3723           /* This breakpoint is in an overlay section.
3724              Did we set a breakpoint at the LMA?  */
3725           if (!overlay_events_enabled)
3726               {
3727                 /* Yes -- overlay event support is not active, so we
3728                    should have set a breakpoint at the LMA.  Remove it.  
3729                 */
3730                 /* Ignore any failures: if the LMA is in ROM, we will
3731                    have already warned when we failed to insert it.  */
3732                 if (bl->loc_type == bp_loc_hardware_breakpoint)
3733                   target_remove_hw_breakpoint (bl->gdbarch,
3734                                                &bl->overlay_target_info);
3735                 else
3736                   target_remove_breakpoint (bl->gdbarch,
3737                                             &bl->overlay_target_info);
3738               }
3739           /* Did we set a breakpoint at the VMA? 
3740              If so, we will have marked the breakpoint 'inserted'.  */
3741           if (bl->inserted)
3742             {
3743               /* Yes -- remove it.  Previously we did not bother to
3744                  remove the breakpoint if the section had been
3745                  unmapped, but let's not rely on that being safe.  We
3746                  don't know what the overlay manager might do.  */
3747
3748               /* However, we should remove *software* breakpoints only
3749                  if the section is still mapped, or else we overwrite
3750                  wrong code with the saved shadow contents.  */
3751               if (bl->loc_type == bp_loc_hardware_breakpoint
3752                   || section_is_mapped (bl->section))
3753                 val = bl->owner->ops->remove_location (bl);
3754               else
3755                 val = 0;
3756             }
3757           else
3758             {
3759               /* No -- not inserted, so no need to remove.  No error.  */
3760               val = 0;
3761             }
3762         }
3763
3764       /* In some cases, we might not be able to remove a breakpoint
3765          in a shared library that has already been removed, but we
3766          have not yet processed the shlib unload event.  */
3767       if (val && solib_name_from_address (bl->pspace, bl->address))
3768         val = 0;
3769
3770       if (val)
3771         return val;
3772       bl->inserted = (is == mark_inserted);
3773     }
3774   else if (bl->loc_type == bp_loc_hardware_watchpoint)
3775     {
3776       gdb_assert (bl->owner->ops != NULL
3777                   && bl->owner->ops->remove_location != NULL);
3778
3779       bl->inserted = (is == mark_inserted);
3780       bl->owner->ops->remove_location (bl);
3781
3782       /* Failure to remove any of the hardware watchpoints comes here.  */
3783       if ((is == mark_uninserted) && (bl->inserted))
3784         warning (_("Could not remove hardware watchpoint %d."),
3785                  bl->owner->number);
3786     }
3787   else if (bl->owner->type == bp_catchpoint
3788            && breakpoint_enabled (bl->owner)
3789            && !bl->duplicate)
3790     {
3791       gdb_assert (bl->owner->ops != NULL
3792                   && bl->owner->ops->remove_location != NULL);
3793
3794       val = bl->owner->ops->remove_location (bl);
3795       if (val)
3796         return val;
3797
3798       bl->inserted = (is == mark_inserted);
3799     }
3800
3801   return 0;
3802 }
3803
3804 static int
3805 remove_breakpoint (struct bp_location *bl, insertion_state_t is)
3806 {
3807   int ret;
3808   struct cleanup *old_chain;
3809
3810   /* BL is never in moribund_locations by our callers.  */
3811   gdb_assert (bl->owner != NULL);
3812
3813   if (bl->owner->enable_state == bp_permanent)
3814     /* Permanent breakpoints cannot be inserted or removed.  */
3815     return 0;
3816
3817   /* The type of none suggests that owner is actually deleted.
3818      This should not ever happen.  */
3819   gdb_assert (bl->owner->type != bp_none);
3820
3821   old_chain = save_current_space_and_thread ();
3822
3823   switch_to_program_space_and_thread (bl->pspace);
3824
3825   ret = remove_breakpoint_1 (bl, is);
3826
3827   do_cleanups (old_chain);
3828   return ret;
3829 }
3830
3831 /* Clear the "inserted" flag in all breakpoints.  */
3832
3833 void
3834 mark_breakpoints_out (void)
3835 {
3836   struct bp_location *bl, **blp_tmp;
3837
3838   ALL_BP_LOCATIONS (bl, blp_tmp)
3839     if (bl->pspace == current_program_space)
3840       bl->inserted = 0;
3841 }
3842
3843 /* Clear the "inserted" flag in all breakpoints and delete any
3844    breakpoints which should go away between runs of the program.
3845
3846    Plus other such housekeeping that has to be done for breakpoints
3847    between runs.
3848
3849    Note: this function gets called at the end of a run (by
3850    generic_mourn_inferior) and when a run begins (by
3851    init_wait_for_inferior).  */
3852
3853
3854
3855 void
3856 breakpoint_init_inferior (enum inf_context context)
3857 {
3858   struct breakpoint *b, *b_tmp;
3859   struct bp_location *bl, **blp_tmp;
3860   int ix;
3861   struct program_space *pspace = current_program_space;
3862
3863   /* If breakpoint locations are shared across processes, then there's
3864      nothing to do.  */
3865   if (gdbarch_has_global_breakpoints (target_gdbarch ()))
3866     return;
3867
3868   ALL_BP_LOCATIONS (bl, blp_tmp)
3869   {
3870     /* ALL_BP_LOCATIONS bp_location has BL->OWNER always non-NULL.  */
3871     if (bl->pspace == pspace
3872         && bl->owner->enable_state != bp_permanent)
3873       bl->inserted = 0;
3874   }
3875
3876   ALL_BREAKPOINTS_SAFE (b, b_tmp)
3877   {
3878     if (b->loc && b->loc->pspace != pspace)
3879       continue;
3880
3881     switch (b->type)
3882       {
3883       case bp_call_dummy:
3884       case bp_longjmp_call_dummy:
3885
3886         /* If the call dummy breakpoint is at the entry point it will
3887            cause problems when the inferior is rerun, so we better get
3888            rid of it.  */
3889
3890       case bp_watchpoint_scope:
3891
3892         /* Also get rid of scope breakpoints.  */
3893
3894       case bp_shlib_event:
3895
3896         /* Also remove solib event breakpoints.  Their addresses may
3897            have changed since the last time we ran the program.
3898            Actually we may now be debugging against different target;
3899            and so the solib backend that installed this breakpoint may
3900            not be used in by the target.  E.g.,
3901
3902            (gdb) file prog-linux
3903            (gdb) run               # native linux target
3904            ...
3905            (gdb) kill
3906            (gdb) file prog-win.exe
3907            (gdb) tar rem :9999     # remote Windows gdbserver.
3908         */
3909
3910       case bp_step_resume:
3911
3912         /* Also remove step-resume breakpoints.  */
3913
3914         delete_breakpoint (b);
3915         break;
3916
3917       case bp_watchpoint:
3918       case bp_hardware_watchpoint:
3919       case bp_read_watchpoint:
3920       case bp_access_watchpoint:
3921         {
3922           struct watchpoint *w = (struct watchpoint *) b;
3923
3924           /* Likewise for watchpoints on local expressions.  */
3925           if (w->exp_valid_block != NULL)
3926             delete_breakpoint (b);
3927           else if (context == inf_starting)
3928             {
3929               /* Reset val field to force reread of starting value in
3930                  insert_breakpoints.  */
3931               if (w->val)
3932                 value_free (w->val);
3933               w->val = NULL;
3934               w->val_valid = 0;
3935           }
3936         }
3937         break;
3938       default:
3939         break;
3940       }
3941   }
3942
3943   /* Get rid of the moribund locations.  */
3944   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, bl); ++ix)
3945     decref_bp_location (&bl);
3946   VEC_free (bp_location_p, moribund_locations);
3947 }
3948
3949 /* These functions concern about actual breakpoints inserted in the
3950    target --- to e.g. check if we need to do decr_pc adjustment or if
3951    we need to hop over the bkpt --- so we check for address space
3952    match, not program space.  */
3953
3954 /* breakpoint_here_p (PC) returns non-zero if an enabled breakpoint
3955    exists at PC.  It returns ordinary_breakpoint_here if it's an
3956    ordinary breakpoint, or permanent_breakpoint_here if it's a
3957    permanent breakpoint.
3958    - When continuing from a location with an ordinary breakpoint, we
3959      actually single step once before calling insert_breakpoints.
3960    - When continuing from a location with a permanent breakpoint, we
3961      need to use the `SKIP_PERMANENT_BREAKPOINT' macro, provided by
3962      the target, to advance the PC past the breakpoint.  */
3963
3964 enum breakpoint_here
3965 breakpoint_here_p (struct address_space *aspace, CORE_ADDR pc)
3966 {
3967   struct bp_location *bl, **blp_tmp;
3968   int any_breakpoint_here = 0;
3969
3970   ALL_BP_LOCATIONS (bl, blp_tmp)
3971     {
3972       if (bl->loc_type != bp_loc_software_breakpoint
3973           && bl->loc_type != bp_loc_hardware_breakpoint)
3974         continue;
3975
3976       /* ALL_BP_LOCATIONS bp_location has BL->OWNER always non-NULL.  */
3977       if ((breakpoint_enabled (bl->owner)
3978            || bl->owner->enable_state == bp_permanent)
3979           && breakpoint_location_address_match (bl, aspace, pc))
3980         {
3981           if (overlay_debugging 
3982               && section_is_overlay (bl->section)
3983               && !section_is_mapped (bl->section))
3984             continue;           /* unmapped overlay -- can't be a match */
3985           else if (bl->owner->enable_state == bp_permanent)
3986             return permanent_breakpoint_here;
3987           else
3988             any_breakpoint_here = 1;
3989         }
3990     }
3991
3992   return any_breakpoint_here ? ordinary_breakpoint_here : 0;
3993 }
3994
3995 /* Return true if there's a moribund breakpoint at PC.  */
3996
3997 int
3998 moribund_breakpoint_here_p (struct address_space *aspace, CORE_ADDR pc)
3999 {
4000   struct bp_location *loc;
4001   int ix;
4002
4003   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
4004     if (breakpoint_location_address_match (loc, aspace, pc))
4005       return 1;
4006
4007   return 0;
4008 }
4009
4010 /* Returns non-zero if there's a breakpoint inserted at PC, which is
4011    inserted using regular breakpoint_chain / bp_location array
4012    mechanism.  This does not check for single-step breakpoints, which
4013    are inserted and removed using direct target manipulation.  */
4014
4015 int
4016 regular_breakpoint_inserted_here_p (struct address_space *aspace, 
4017                                     CORE_ADDR pc)
4018 {
4019   struct bp_location *bl, **blp_tmp;
4020
4021   ALL_BP_LOCATIONS (bl, blp_tmp)
4022     {
4023       if (bl->loc_type != bp_loc_software_breakpoint
4024           && bl->loc_type != bp_loc_hardware_breakpoint)
4025         continue;
4026
4027       if (bl->inserted
4028           && breakpoint_location_address_match (bl, aspace, pc))
4029         {
4030           if (overlay_debugging 
4031               && section_is_overlay (bl->section)
4032               && !section_is_mapped (bl->section))
4033             continue;           /* unmapped overlay -- can't be a match */
4034           else
4035             return 1;
4036         }
4037     }
4038   return 0;
4039 }
4040
4041 /* Returns non-zero iff there's either regular breakpoint
4042    or a single step breakpoint inserted at PC.  */
4043
4044 int
4045 breakpoint_inserted_here_p (struct address_space *aspace, CORE_ADDR pc)
4046 {
4047   if (regular_breakpoint_inserted_here_p (aspace, pc))
4048     return 1;
4049
4050   if (single_step_breakpoint_inserted_here_p (aspace, pc))
4051     return 1;
4052
4053   return 0;
4054 }
4055
4056 /* This function returns non-zero iff there is a software breakpoint
4057    inserted at PC.  */
4058
4059 int
4060 software_breakpoint_inserted_here_p (struct address_space *aspace,
4061                                      CORE_ADDR pc)
4062 {
4063   struct bp_location *bl, **blp_tmp;
4064
4065   ALL_BP_LOCATIONS (bl, blp_tmp)
4066     {
4067       if (bl->loc_type != bp_loc_software_breakpoint)
4068         continue;
4069
4070       if (bl->inserted
4071           && breakpoint_address_match (bl->pspace->aspace, bl->address,
4072                                        aspace, pc))
4073         {
4074           if (overlay_debugging 
4075               && section_is_overlay (bl->section)
4076               && !section_is_mapped (bl->section))
4077             continue;           /* unmapped overlay -- can't be a match */
4078           else
4079             return 1;
4080         }
4081     }
4082
4083   /* Also check for software single-step breakpoints.  */
4084   if (single_step_breakpoint_inserted_here_p (aspace, pc))
4085     return 1;
4086
4087   return 0;
4088 }
4089
4090 int
4091 hardware_watchpoint_inserted_in_range (struct address_space *aspace,
4092                                        CORE_ADDR addr, ULONGEST len)
4093 {
4094   struct breakpoint *bpt;
4095
4096   ALL_BREAKPOINTS (bpt)
4097     {
4098       struct bp_location *loc;
4099
4100       if (bpt->type != bp_hardware_watchpoint
4101           && bpt->type != bp_access_watchpoint)
4102         continue;
4103
4104       if (!breakpoint_enabled (bpt))
4105         continue;
4106
4107       for (loc = bpt->loc; loc; loc = loc->next)
4108         if (loc->pspace->aspace == aspace && loc->inserted)
4109           {
4110             CORE_ADDR l, h;
4111
4112             /* Check for intersection.  */
4113             l = max (loc->address, addr);
4114             h = min (loc->address + loc->length, addr + len);
4115             if (l < h)
4116               return 1;
4117           }
4118     }
4119   return 0;
4120 }
4121
4122 /* breakpoint_thread_match (PC, PTID) returns true if the breakpoint at
4123    PC is valid for process/thread PTID.  */
4124
4125 int
4126 breakpoint_thread_match (struct address_space *aspace, CORE_ADDR pc,
4127                          ptid_t ptid)
4128 {
4129   struct bp_location *bl, **blp_tmp;
4130   /* The thread and task IDs associated to PTID, computed lazily.  */
4131   int thread = -1;
4132   int task = 0;
4133   
4134   ALL_BP_LOCATIONS (bl, blp_tmp)
4135     {
4136       if (bl->loc_type != bp_loc_software_breakpoint
4137           && bl->loc_type != bp_loc_hardware_breakpoint)
4138         continue;
4139
4140       /* ALL_BP_LOCATIONS bp_location has bl->OWNER always non-NULL.  */
4141       if (!breakpoint_enabled (bl->owner)
4142           && bl->owner->enable_state != bp_permanent)
4143         continue;
4144
4145       if (!breakpoint_location_address_match (bl, aspace, pc))
4146         continue;
4147
4148       if (bl->owner->thread != -1)
4149         {
4150           /* This is a thread-specific breakpoint.  Check that ptid
4151              matches that thread.  If thread hasn't been computed yet,
4152              it is now time to do so.  */
4153           if (thread == -1)
4154             thread = pid_to_thread_id (ptid);
4155           if (bl->owner->thread != thread)
4156             continue;
4157         }
4158
4159       if (bl->owner->task != 0)
4160         {
4161           /* This is a task-specific breakpoint.  Check that ptid
4162              matches that task.  If task hasn't been computed yet,
4163              it is now time to do so.  */
4164           if (task == 0)
4165             task = ada_get_task_number (ptid);
4166           if (bl->owner->task != task)
4167             continue;
4168         }
4169
4170       if (overlay_debugging 
4171           && section_is_overlay (bl->section)
4172           && !section_is_mapped (bl->section))
4173         continue;           /* unmapped overlay -- can't be a match */
4174
4175       return 1;
4176     }
4177
4178   return 0;
4179 }
4180 \f
4181
4182 /* bpstat stuff.  External routines' interfaces are documented
4183    in breakpoint.h.  */
4184
4185 int
4186 is_catchpoint (struct breakpoint *ep)
4187 {
4188   return (ep->type == bp_catchpoint);
4189 }
4190
4191 /* Frees any storage that is part of a bpstat.  Does not walk the
4192    'next' chain.  */
4193
4194 static void
4195 bpstat_free (bpstat bs)
4196 {
4197   if (bs->old_val != NULL)
4198     value_free (bs->old_val);
4199   decref_counted_command_line (&bs->commands);
4200   decref_bp_location (&bs->bp_location_at);
4201   xfree (bs);
4202 }
4203
4204 /* Clear a bpstat so that it says we are not at any breakpoint.
4205    Also free any storage that is part of a bpstat.  */
4206
4207 void
4208 bpstat_clear (bpstat *bsp)
4209 {
4210   bpstat p;
4211   bpstat q;
4212
4213   if (bsp == 0)
4214     return;
4215   p = *bsp;
4216   while (p != NULL)
4217     {
4218       q = p->next;
4219       bpstat_free (p);
4220       p = q;
4221     }
4222   *bsp = NULL;
4223 }
4224
4225 /* Return a copy of a bpstat.  Like "bs1 = bs2" but all storage that
4226    is part of the bpstat is copied as well.  */
4227
4228 bpstat
4229 bpstat_copy (bpstat bs)
4230 {
4231   bpstat p = NULL;
4232   bpstat tmp;
4233   bpstat retval = NULL;
4234
4235   if (bs == NULL)
4236     return bs;
4237
4238   for (; bs != NULL; bs = bs->next)
4239     {
4240       tmp = (bpstat) xmalloc (sizeof (*tmp));
4241       memcpy (tmp, bs, sizeof (*tmp));
4242       incref_counted_command_line (tmp->commands);
4243       incref_bp_location (tmp->bp_location_at);
4244       if (bs->old_val != NULL)
4245         {
4246           tmp->old_val = value_copy (bs->old_val);
4247           release_value (tmp->old_val);
4248         }
4249
4250       if (p == NULL)
4251         /* This is the first thing in the chain.  */
4252         retval = tmp;
4253       else
4254         p->next = tmp;
4255       p = tmp;
4256     }
4257   p->next = NULL;
4258   return retval;
4259 }
4260
4261 /* Find the bpstat associated with this breakpoint.  */
4262
4263 bpstat
4264 bpstat_find_breakpoint (bpstat bsp, struct breakpoint *breakpoint)
4265 {
4266   if (bsp == NULL)
4267     return NULL;
4268
4269   for (; bsp != NULL; bsp = bsp->next)
4270     {
4271       if (bsp->breakpoint_at == breakpoint)
4272         return bsp;
4273     }
4274   return NULL;
4275 }
4276
4277 /* See breakpoint.h.  */
4278
4279 int
4280 bpstat_explains_signal (bpstat bsp, enum gdb_signal sig)
4281 {
4282   for (; bsp != NULL; bsp = bsp->next)
4283     {
4284       if (bsp->breakpoint_at == NULL)
4285         {
4286           /* A moribund location can never explain a signal other than
4287              GDB_SIGNAL_TRAP.  */
4288           if (sig == GDB_SIGNAL_TRAP)
4289             return 1;
4290         }
4291       else
4292         {
4293           if (bsp->breakpoint_at->ops->explains_signal (bsp->breakpoint_at,
4294                                                         sig))
4295             return 1;
4296         }
4297     }
4298
4299   return 0;
4300 }
4301
4302 /* Put in *NUM the breakpoint number of the first breakpoint we are
4303    stopped at.  *BSP upon return is a bpstat which points to the
4304    remaining breakpoints stopped at (but which is not guaranteed to be
4305    good for anything but further calls to bpstat_num).
4306
4307    Return 0 if passed a bpstat which does not indicate any breakpoints.
4308    Return -1 if stopped at a breakpoint that has been deleted since
4309    we set it.
4310    Return 1 otherwise.  */
4311
4312 int
4313 bpstat_num (bpstat *bsp, int *num)
4314 {
4315   struct breakpoint *b;
4316
4317   if ((*bsp) == NULL)
4318     return 0;                   /* No more breakpoint values */
4319
4320   /* We assume we'll never have several bpstats that correspond to a
4321      single breakpoint -- otherwise, this function might return the
4322      same number more than once and this will look ugly.  */
4323   b = (*bsp)->breakpoint_at;
4324   *bsp = (*bsp)->next;
4325   if (b == NULL)
4326     return -1;                  /* breakpoint that's been deleted since */
4327
4328   *num = b->number;             /* We have its number */
4329   return 1;
4330 }
4331
4332 /* See breakpoint.h.  */
4333
4334 void
4335 bpstat_clear_actions (void)
4336 {
4337   struct thread_info *tp;
4338   bpstat bs;
4339
4340   if (ptid_equal (inferior_ptid, null_ptid))
4341     return;
4342
4343   tp = find_thread_ptid (inferior_ptid);
4344   if (tp == NULL)
4345     return;
4346
4347   for (bs = tp->control.stop_bpstat; bs != NULL; bs = bs->next)
4348     {
4349       decref_counted_command_line (&bs->commands);
4350
4351       if (bs->old_val != NULL)
4352         {
4353           value_free (bs->old_val);
4354           bs->old_val = NULL;
4355         }
4356     }
4357 }
4358
4359 /* Called when a command is about to proceed the inferior.  */
4360
4361 static void
4362 breakpoint_about_to_proceed (void)
4363 {
4364   if (!ptid_equal (inferior_ptid, null_ptid))
4365     {
4366       struct thread_info *tp = inferior_thread ();
4367
4368       /* Allow inferior function calls in breakpoint commands to not
4369          interrupt the command list.  When the call finishes
4370          successfully, the inferior will be standing at the same
4371          breakpoint as if nothing happened.  */
4372       if (tp->control.in_infcall)
4373         return;
4374     }
4375
4376   breakpoint_proceeded = 1;
4377 }
4378
4379 /* Stub for cleaning up our state if we error-out of a breakpoint
4380    command.  */
4381 static void
4382 cleanup_executing_breakpoints (void *ignore)
4383 {
4384   executing_breakpoint_commands = 0;
4385 }
4386
4387 /* Return non-zero iff CMD as the first line of a command sequence is `silent'
4388    or its equivalent.  */
4389
4390 static int
4391 command_line_is_silent (struct command_line *cmd)
4392 {
4393   return cmd && (strcmp ("silent", cmd->line) == 0
4394                  || (xdb_commands && strcmp ("Q", cmd->line) == 0));
4395 }
4396
4397 /* Execute all the commands associated with all the breakpoints at
4398    this location.  Any of these commands could cause the process to
4399    proceed beyond this point, etc.  We look out for such changes by
4400    checking the global "breakpoint_proceeded" after each command.
4401
4402    Returns true if a breakpoint command resumed the inferior.  In that
4403    case, it is the caller's responsibility to recall it again with the
4404    bpstat of the current thread.  */
4405
4406 static int
4407 bpstat_do_actions_1 (bpstat *bsp)
4408 {
4409   bpstat bs;
4410   struct cleanup *old_chain;
4411   int again = 0;
4412
4413   /* Avoid endless recursion if a `source' command is contained
4414      in bs->commands.  */
4415   if (executing_breakpoint_commands)
4416     return 0;
4417
4418   executing_breakpoint_commands = 1;
4419   old_chain = make_cleanup (cleanup_executing_breakpoints, 0);
4420
4421   prevent_dont_repeat ();
4422
4423   /* This pointer will iterate over the list of bpstat's.  */
4424   bs = *bsp;
4425
4426   breakpoint_proceeded = 0;
4427   for (; bs != NULL; bs = bs->next)
4428     {
4429       struct counted_command_line *ccmd;
4430       struct command_line *cmd;
4431       struct cleanup *this_cmd_tree_chain;
4432
4433       /* Take ownership of the BSP's command tree, if it has one.
4434
4435          The command tree could legitimately contain commands like
4436          'step' and 'next', which call clear_proceed_status, which
4437          frees stop_bpstat's command tree.  To make sure this doesn't
4438          free the tree we're executing out from under us, we need to
4439          take ownership of the tree ourselves.  Since a given bpstat's
4440          commands are only executed once, we don't need to copy it; we
4441          can clear the pointer in the bpstat, and make sure we free
4442          the tree when we're done.  */
4443       ccmd = bs->commands;
4444       bs->commands = NULL;
4445       this_cmd_tree_chain = make_cleanup_decref_counted_command_line (&ccmd);
4446       cmd = ccmd ? ccmd->commands : NULL;
4447       if (command_line_is_silent (cmd))
4448         {
4449           /* The action has been already done by bpstat_stop_status.  */
4450           cmd = cmd->next;
4451         }
4452
4453       while (cmd != NULL)
4454         {
4455           execute_control_command (cmd);
4456
4457           if (breakpoint_proceeded)
4458             break;
4459           else
4460             cmd = cmd->next;
4461         }
4462
4463       /* We can free this command tree now.  */
4464       do_cleanups (this_cmd_tree_chain);
4465
4466       if (breakpoint_proceeded)
4467         {
4468           if (target_can_async_p ())
4469             /* If we are in async mode, then the target might be still
4470                running, not stopped at any breakpoint, so nothing for
4471                us to do here -- just return to the event loop.  */
4472             ;
4473           else
4474             /* In sync mode, when execute_control_command returns
4475                we're already standing on the next breakpoint.
4476                Breakpoint commands for that stop were not run, since
4477                execute_command does not run breakpoint commands --
4478                only command_line_handler does, but that one is not
4479                involved in execution of breakpoint commands.  So, we
4480                can now execute breakpoint commands.  It should be
4481                noted that making execute_command do bpstat actions is
4482                not an option -- in this case we'll have recursive
4483                invocation of bpstat for each breakpoint with a
4484                command, and can easily blow up GDB stack.  Instead, we
4485                return true, which will trigger the caller to recall us
4486                with the new stop_bpstat.  */
4487             again = 1;
4488           break;
4489         }
4490     }
4491   do_cleanups (old_chain);
4492   return again;
4493 }
4494
4495 void
4496 bpstat_do_actions (void)
4497 {
4498   struct cleanup *cleanup_if_error = make_bpstat_clear_actions_cleanup ();
4499
4500   /* Do any commands attached to breakpoint we are stopped at.  */
4501   while (!ptid_equal (inferior_ptid, null_ptid)
4502          && target_has_execution
4503          && !is_exited (inferior_ptid)
4504          && !is_executing (inferior_ptid))
4505     /* Since in sync mode, bpstat_do_actions may resume the inferior,
4506        and only return when it is stopped at the next breakpoint, we
4507        keep doing breakpoint actions until it returns false to
4508        indicate the inferior was not resumed.  */
4509     if (!bpstat_do_actions_1 (&inferior_thread ()->control.stop_bpstat))
4510       break;
4511
4512   discard_cleanups (cleanup_if_error);
4513 }
4514
4515 /* Print out the (old or new) value associated with a watchpoint.  */
4516
4517 static void
4518 watchpoint_value_print (struct value *val, struct ui_file *stream)
4519 {
4520   if (val == NULL)
4521     fprintf_unfiltered (stream, _("<unreadable>"));
4522   else
4523     {
4524       struct value_print_options opts;
4525       get_user_print_options (&opts);
4526       value_print (val, stream, &opts);
4527     }
4528 }
4529
4530 /* Generic routine for printing messages indicating why we
4531    stopped.  The behavior of this function depends on the value
4532    'print_it' in the bpstat structure.  Under some circumstances we
4533    may decide not to print anything here and delegate the task to
4534    normal_stop().  */
4535
4536 static enum print_stop_action
4537 print_bp_stop_message (bpstat bs)
4538 {
4539   switch (bs->print_it)
4540     {
4541     case print_it_noop:
4542       /* Nothing should be printed for this bpstat entry.  */
4543       return PRINT_UNKNOWN;
4544       break;
4545
4546     case print_it_done:
4547       /* We still want to print the frame, but we already printed the
4548          relevant messages.  */
4549       return PRINT_SRC_AND_LOC;
4550       break;
4551
4552     case print_it_normal:
4553       {
4554         struct breakpoint *b = bs->breakpoint_at;
4555
4556         /* bs->breakpoint_at can be NULL if it was a momentary breakpoint
4557            which has since been deleted.  */
4558         if (b == NULL)
4559           return PRINT_UNKNOWN;
4560
4561         /* Normal case.  Call the breakpoint's print_it method.  */
4562         return b->ops->print_it (bs);
4563       }
4564       break;
4565
4566     default:
4567       internal_error (__FILE__, __LINE__,
4568                       _("print_bp_stop_message: unrecognized enum value"));
4569       break;
4570     }
4571 }
4572
4573 /* A helper function that prints a shared library stopped event.  */
4574
4575 static void
4576 print_solib_event (int is_catchpoint)
4577 {
4578   int any_deleted
4579     = !VEC_empty (char_ptr, current_program_space->deleted_solibs);
4580   int any_added
4581     = !VEC_empty (so_list_ptr, current_program_space->added_solibs);
4582
4583   if (!is_catchpoint)
4584     {
4585       if (any_added || any_deleted)
4586         ui_out_text (current_uiout,
4587                      _("Stopped due to shared library event:\n"));
4588       else
4589         ui_out_text (current_uiout,
4590                      _("Stopped due to shared library event (no "
4591                        "libraries added or removed)\n"));
4592     }
4593
4594   if (ui_out_is_mi_like_p (current_uiout))
4595     ui_out_field_string (current_uiout, "reason",
4596                          async_reason_lookup (EXEC_ASYNC_SOLIB_EVENT));
4597
4598   if (any_deleted)
4599     {
4600       struct cleanup *cleanup;
4601       char *name;
4602       int ix;
4603
4604       ui_out_text (current_uiout, _("  Inferior unloaded "));
4605       cleanup = make_cleanup_ui_out_list_begin_end (current_uiout,
4606                                                     "removed");
4607       for (ix = 0;
4608            VEC_iterate (char_ptr, current_program_space->deleted_solibs,
4609                         ix, name);
4610            ++ix)
4611         {
4612           if (ix > 0)
4613             ui_out_text (current_uiout, "    ");
4614           ui_out_field_string (current_uiout, "library", name);
4615           ui_out_text (current_uiout, "\n");
4616         }
4617
4618       do_cleanups (cleanup);
4619     }
4620
4621   if (any_added)
4622     {
4623       struct so_list *iter;
4624       int ix;
4625       struct cleanup *cleanup;
4626
4627       ui_out_text (current_uiout, _("  Inferior loaded "));
4628       cleanup = make_cleanup_ui_out_list_begin_end (current_uiout,
4629                                                     "added");
4630       for (ix = 0;
4631            VEC_iterate (so_list_ptr, current_program_space->added_solibs,
4632                         ix, iter);
4633            ++ix)
4634         {
4635           if (ix > 0)
4636             ui_out_text (current_uiout, "    ");
4637           ui_out_field_string (current_uiout, "library", iter->so_name);
4638           ui_out_text (current_uiout, "\n");
4639         }
4640
4641       do_cleanups (cleanup);
4642     }
4643 }
4644
4645 /* Print a message indicating what happened.  This is called from
4646    normal_stop().  The input to this routine is the head of the bpstat
4647    list - a list of the eventpoints that caused this stop.  KIND is
4648    the target_waitkind for the stopping event.  This
4649    routine calls the generic print routine for printing a message
4650    about reasons for stopping.  This will print (for example) the
4651    "Breakpoint n," part of the output.  The return value of this
4652    routine is one of:
4653
4654    PRINT_UNKNOWN: Means we printed nothing.
4655    PRINT_SRC_AND_LOC: Means we printed something, and expect subsequent
4656    code to print the location.  An example is 
4657    "Breakpoint 1, " which should be followed by
4658    the location.
4659    PRINT_SRC_ONLY: Means we printed something, but there is no need
4660    to also print the location part of the message.
4661    An example is the catch/throw messages, which
4662    don't require a location appended to the end.
4663    PRINT_NOTHING: We have done some printing and we don't need any 
4664    further info to be printed.  */
4665
4666 enum print_stop_action
4667 bpstat_print (bpstat bs, int kind)
4668 {
4669   int val;
4670
4671   /* Maybe another breakpoint in the chain caused us to stop.
4672      (Currently all watchpoints go on the bpstat whether hit or not.
4673      That probably could (should) be changed, provided care is taken
4674      with respect to bpstat_explains_signal).  */
4675   for (; bs; bs = bs->next)
4676     {
4677       val = print_bp_stop_message (bs);
4678       if (val == PRINT_SRC_ONLY 
4679           || val == PRINT_SRC_AND_LOC 
4680           || val == PRINT_NOTHING)
4681         return val;
4682     }
4683
4684   /* If we had hit a shared library event breakpoint,
4685      print_bp_stop_message would print out this message.  If we hit an
4686      OS-level shared library event, do the same thing.  */
4687   if (kind == TARGET_WAITKIND_LOADED)
4688     {
4689       print_solib_event (0);
4690       return PRINT_NOTHING;
4691     }
4692
4693   /* We reached the end of the chain, or we got a null BS to start
4694      with and nothing was printed.  */
4695   return PRINT_UNKNOWN;
4696 }
4697
4698 /* Evaluate the expression EXP and return 1 if value is zero.
4699    This returns the inverse of the condition because it is called
4700    from catch_errors which returns 0 if an exception happened, and if an
4701    exception happens we want execution to stop.
4702    The argument is a "struct expression *" that has been cast to a
4703    "void *" to make it pass through catch_errors.  */
4704
4705 static int
4706 breakpoint_cond_eval (void *exp)
4707 {
4708   struct value *mark = value_mark ();
4709   int i = !value_true (evaluate_expression ((struct expression *) exp));
4710
4711   value_free_to_mark (mark);
4712   return i;
4713 }
4714
4715 /* Allocate a new bpstat.  Link it to the FIFO list by BS_LINK_POINTER.  */
4716
4717 static bpstat
4718 bpstat_alloc (struct bp_location *bl, bpstat **bs_link_pointer)
4719 {
4720   bpstat bs;
4721
4722   bs = (bpstat) xmalloc (sizeof (*bs));
4723   bs->next = NULL;
4724   **bs_link_pointer = bs;
4725   *bs_link_pointer = &bs->next;
4726   bs->breakpoint_at = bl->owner;
4727   bs->bp_location_at = bl;
4728   incref_bp_location (bl);
4729   /* If the condition is false, etc., don't do the commands.  */
4730   bs->commands = NULL;
4731   bs->old_val = NULL;
4732   bs->print_it = print_it_normal;
4733   return bs;
4734 }
4735 \f
4736 /* The target has stopped with waitstatus WS.  Check if any hardware
4737    watchpoints have triggered, according to the target.  */
4738
4739 int
4740 watchpoints_triggered (struct target_waitstatus *ws)
4741 {
4742   int stopped_by_watchpoint = target_stopped_by_watchpoint ();
4743   CORE_ADDR addr;
4744   struct breakpoint *b;
4745
4746   if (!stopped_by_watchpoint)
4747     {
4748       /* We were not stopped by a watchpoint.  Mark all watchpoints
4749          as not triggered.  */
4750       ALL_BREAKPOINTS (b)
4751         if (is_hardware_watchpoint (b))
4752           {
4753             struct watchpoint *w = (struct watchpoint *) b;
4754
4755             w->watchpoint_triggered = watch_triggered_no;
4756           }
4757
4758       return 0;
4759     }
4760
4761   if (!target_stopped_data_address (&current_target, &addr))
4762     {
4763       /* We were stopped by a watchpoint, but we don't know where.
4764          Mark all watchpoints as unknown.  */
4765       ALL_BREAKPOINTS (b)
4766         if (is_hardware_watchpoint (b))
4767           {
4768             struct watchpoint *w = (struct watchpoint *) b;
4769
4770             w->watchpoint_triggered = watch_triggered_unknown;
4771           }
4772
4773       return 1;
4774     }
4775
4776   /* The target could report the data address.  Mark watchpoints
4777      affected by this data address as triggered, and all others as not
4778      triggered.  */
4779
4780   ALL_BREAKPOINTS (b)
4781     if (is_hardware_watchpoint (b))
4782       {
4783         struct watchpoint *w = (struct watchpoint *) b;
4784         struct bp_location *loc;
4785
4786         w->watchpoint_triggered = watch_triggered_no;
4787         for (loc = b->loc; loc; loc = loc->next)
4788           {
4789             if (is_masked_watchpoint (b))
4790               {
4791                 CORE_ADDR newaddr = addr & w->hw_wp_mask;
4792                 CORE_ADDR start = loc->address & w->hw_wp_mask;
4793
4794                 if (newaddr == start)
4795                   {
4796                     w->watchpoint_triggered = watch_triggered_yes;
4797                     break;
4798                   }
4799               }
4800             /* Exact match not required.  Within range is sufficient.  */
4801             else if (target_watchpoint_addr_within_range (&current_target,
4802                                                          addr, loc->address,
4803                                                          loc->length))
4804               {
4805                 w->watchpoint_triggered = watch_triggered_yes;
4806                 break;
4807               }
4808           }
4809       }
4810
4811   return 1;
4812 }
4813
4814 /* Possible return values for watchpoint_check (this can't be an enum
4815    because of check_errors).  */
4816 /* The watchpoint has been deleted.  */
4817 #define WP_DELETED 1
4818 /* The value has changed.  */
4819 #define WP_VALUE_CHANGED 2
4820 /* The value has not changed.  */
4821 #define WP_VALUE_NOT_CHANGED 3
4822 /* Ignore this watchpoint, no matter if the value changed or not.  */
4823 #define WP_IGNORE 4
4824
4825 #define BP_TEMPFLAG 1
4826 #define BP_HARDWAREFLAG 2
4827
4828 /* Evaluate watchpoint condition expression and check if its value
4829    changed.
4830
4831    P should be a pointer to struct bpstat, but is defined as a void *
4832    in order for this function to be usable with catch_errors.  */
4833
4834 static int
4835 watchpoint_check (void *p)
4836 {
4837   bpstat bs = (bpstat) p;
4838   struct watchpoint *b;
4839   struct frame_info *fr;
4840   int within_current_scope;
4841
4842   /* BS is built from an existing struct breakpoint.  */
4843   gdb_assert (bs->breakpoint_at != NULL);
4844   b = (struct watchpoint *) bs->breakpoint_at;
4845
4846   /* If this is a local watchpoint, we only want to check if the
4847      watchpoint frame is in scope if the current thread is the thread
4848      that was used to create the watchpoint.  */
4849   if (!watchpoint_in_thread_scope (b))
4850     return WP_IGNORE;
4851
4852   if (b->exp_valid_block == NULL)
4853     within_current_scope = 1;
4854   else
4855     {
4856       struct frame_info *frame = get_current_frame ();
4857       struct gdbarch *frame_arch = get_frame_arch (frame);
4858       CORE_ADDR frame_pc = get_frame_pc (frame);
4859
4860       /* in_function_epilogue_p() returns a non-zero value if we're
4861          still in the function but the stack frame has already been
4862          invalidated.  Since we can't rely on the values of local
4863          variables after the stack has been destroyed, we are treating
4864          the watchpoint in that state as `not changed' without further
4865          checking.  Don't mark watchpoints as changed if the current
4866          frame is in an epilogue - even if they are in some other
4867          frame, our view of the stack is likely to be wrong and
4868          frame_find_by_id could error out.  */
4869       if (gdbarch_in_function_epilogue_p (frame_arch, frame_pc))
4870         return WP_IGNORE;
4871
4872       fr = frame_find_by_id (b->watchpoint_frame);
4873       within_current_scope = (fr != NULL);
4874
4875       /* If we've gotten confused in the unwinder, we might have
4876          returned a frame that can't describe this variable.  */
4877       if (within_current_scope)
4878         {
4879           struct symbol *function;
4880
4881           function = get_frame_function (fr);
4882           if (function == NULL
4883               || !contained_in (b->exp_valid_block,
4884                                 SYMBOL_BLOCK_VALUE (function)))
4885             within_current_scope = 0;
4886         }
4887
4888       if (within_current_scope)
4889         /* If we end up stopping, the current frame will get selected
4890            in normal_stop.  So this call to select_frame won't affect
4891            the user.  */
4892         select_frame (fr);
4893     }
4894
4895   if (within_current_scope)
4896     {
4897       /* We use value_{,free_to_}mark because it could be a *long*
4898          time before we return to the command level and call
4899          free_all_values.  We can't call free_all_values because we
4900          might be in the middle of evaluating a function call.  */
4901
4902       int pc = 0;
4903       struct value *mark;
4904       struct value *new_val;
4905
4906       if (is_masked_watchpoint (&b->base))
4907         /* Since we don't know the exact trigger address (from
4908            stopped_data_address), just tell the user we've triggered
4909            a mask watchpoint.  */
4910         return WP_VALUE_CHANGED;
4911
4912       mark = value_mark ();
4913       fetch_subexp_value (b->exp, &pc, &new_val, NULL, NULL, 0);
4914
4915       /* We use value_equal_contents instead of value_equal because
4916          the latter coerces an array to a pointer, thus comparing just
4917          the address of the array instead of its contents.  This is
4918          not what we want.  */
4919       if ((b->val != NULL) != (new_val != NULL)
4920           || (b->val != NULL && !value_equal_contents (b->val, new_val)))
4921         {
4922           if (new_val != NULL)
4923             {
4924               release_value (new_val);
4925               value_free_to_mark (mark);
4926             }
4927           bs->old_val = b->val;
4928           b->val = new_val;
4929           b->val_valid = 1;
4930           return WP_VALUE_CHANGED;
4931         }
4932       else
4933         {
4934           /* Nothing changed.  */
4935           value_free_to_mark (mark);
4936           return WP_VALUE_NOT_CHANGED;
4937         }
4938     }
4939   else
4940     {
4941       struct ui_out *uiout = current_uiout;
4942
4943       /* This seems like the only logical thing to do because
4944          if we temporarily ignored the watchpoint, then when
4945          we reenter the block in which it is valid it contains
4946          garbage (in the case of a function, it may have two
4947          garbage values, one before and one after the prologue).
4948          So we can't even detect the first assignment to it and
4949          watch after that (since the garbage may or may not equal
4950          the first value assigned).  */
4951       /* We print all the stop information in
4952          breakpoint_ops->print_it, but in this case, by the time we
4953          call breakpoint_ops->print_it this bp will be deleted
4954          already.  So we have no choice but print the information
4955          here.  */
4956       if (ui_out_is_mi_like_p (uiout))
4957         ui_out_field_string
4958           (uiout, "reason", async_reason_lookup (EXEC_ASYNC_WATCHPOINT_SCOPE));
4959       ui_out_text (uiout, "\nWatchpoint ");
4960       ui_out_field_int (uiout, "wpnum", b->base.number);
4961       ui_out_text (uiout,
4962                    " deleted because the program has left the block in\n\
4963 which its expression is valid.\n");     
4964
4965       /* Make sure the watchpoint's commands aren't executed.  */
4966       decref_counted_command_line (&b->base.commands);
4967       watchpoint_del_at_next_stop (b);
4968
4969       return WP_DELETED;
4970     }
4971 }
4972
4973 /* Return true if it looks like target has stopped due to hitting
4974    breakpoint location BL.  This function does not check if we should
4975    stop, only if BL explains the stop.  */
4976
4977 static int
4978 bpstat_check_location (const struct bp_location *bl,
4979                        struct address_space *aspace, CORE_ADDR bp_addr,
4980                        const struct target_waitstatus *ws)
4981 {
4982   struct breakpoint *b = bl->owner;
4983
4984   /* BL is from an existing breakpoint.  */
4985   gdb_assert (b != NULL);
4986
4987   return b->ops->breakpoint_hit (bl, aspace, bp_addr, ws);
4988 }
4989
4990 /* Determine if the watched values have actually changed, and we
4991    should stop.  If not, set BS->stop to 0.  */
4992
4993 static void
4994 bpstat_check_watchpoint (bpstat bs)
4995 {
4996   const struct bp_location *bl;
4997   struct watchpoint *b;
4998
4999   /* BS is built for existing struct breakpoint.  */
5000   bl = bs->bp_location_at;
5001   gdb_assert (bl != NULL);
5002   b = (struct watchpoint *) bs->breakpoint_at;
5003   gdb_assert (b != NULL);
5004
5005     {
5006       int must_check_value = 0;
5007       
5008       if (b->base.type == bp_watchpoint)
5009         /* For a software watchpoint, we must always check the
5010            watched value.  */
5011         must_check_value = 1;
5012       else if (b->watchpoint_triggered == watch_triggered_yes)
5013         /* We have a hardware watchpoint (read, write, or access)
5014            and the target earlier reported an address watched by
5015            this watchpoint.  */
5016         must_check_value = 1;
5017       else if (b->watchpoint_triggered == watch_triggered_unknown
5018                && b->base.type == bp_hardware_watchpoint)
5019         /* We were stopped by a hardware watchpoint, but the target could
5020            not report the data address.  We must check the watchpoint's
5021            value.  Access and read watchpoints are out of luck; without
5022            a data address, we can't figure it out.  */
5023         must_check_value = 1;
5024
5025       if (must_check_value)
5026         {
5027           char *message
5028             = xstrprintf ("Error evaluating expression for watchpoint %d\n",
5029                           b->base.number);
5030           struct cleanup *cleanups = make_cleanup (xfree, message);
5031           int e = catch_errors (watchpoint_check, bs, message,
5032                                 RETURN_MASK_ALL);
5033           do_cleanups (cleanups);
5034           switch (e)
5035             {
5036             case WP_DELETED:
5037               /* We've already printed what needs to be printed.  */
5038               bs->print_it = print_it_done;
5039               /* Stop.  */
5040               break;
5041             case WP_IGNORE:
5042               bs->print_it = print_it_noop;
5043               bs->stop = 0;
5044               break;
5045             case WP_VALUE_CHANGED:
5046               if (b->base.type == bp_read_watchpoint)
5047                 {
5048                   /* There are two cases to consider here:
5049
5050                      1. We're watching the triggered memory for reads.
5051                      In that case, trust the target, and always report
5052                      the watchpoint hit to the user.  Even though
5053                      reads don't cause value changes, the value may
5054                      have changed since the last time it was read, and
5055                      since we're not trapping writes, we will not see
5056                      those, and as such we should ignore our notion of
5057                      old value.
5058
5059                      2. We're watching the triggered memory for both
5060                      reads and writes.  There are two ways this may
5061                      happen:
5062
5063                      2.1. This is a target that can't break on data
5064                      reads only, but can break on accesses (reads or
5065                      writes), such as e.g., x86.  We detect this case
5066                      at the time we try to insert read watchpoints.
5067
5068                      2.2. Otherwise, the target supports read
5069                      watchpoints, but, the user set an access or write
5070                      watchpoint watching the same memory as this read
5071                      watchpoint.
5072
5073                      If we're watching memory writes as well as reads,
5074                      ignore watchpoint hits when we find that the
5075                      value hasn't changed, as reads don't cause
5076                      changes.  This still gives false positives when
5077                      the program writes the same value to memory as
5078                      what there was already in memory (we will confuse
5079                      it for a read), but it's much better than
5080                      nothing.  */
5081
5082                   int other_write_watchpoint = 0;
5083
5084                   if (bl->watchpoint_type == hw_read)
5085                     {
5086                       struct breakpoint *other_b;
5087
5088                       ALL_BREAKPOINTS (other_b)
5089                         if (other_b->type == bp_hardware_watchpoint
5090                             || other_b->type == bp_access_watchpoint)
5091                           {
5092                             struct watchpoint *other_w =
5093                               (struct watchpoint *) other_b;
5094
5095                             if (other_w->watchpoint_triggered
5096                                 == watch_triggered_yes)
5097                               {
5098                                 other_write_watchpoint = 1;
5099                                 break;
5100                               }
5101                           }
5102                     }
5103
5104                   if (other_write_watchpoint
5105                       || bl->watchpoint_type == hw_access)
5106                     {
5107                       /* We're watching the same memory for writes,
5108                          and the value changed since the last time we
5109                          updated it, so this trap must be for a write.
5110                          Ignore it.  */
5111                       bs->print_it = print_it_noop;
5112                       bs->stop = 0;
5113                     }
5114                 }
5115               break;
5116             case WP_VALUE_NOT_CHANGED:
5117               if (b->base.type == bp_hardware_watchpoint
5118                   || b->base.type == bp_watchpoint)
5119                 {
5120                   /* Don't stop: write watchpoints shouldn't fire if
5121                      the value hasn't changed.  */
5122                   bs->print_it = print_it_noop;
5123                   bs->stop = 0;
5124                 }
5125               /* Stop.  */
5126               break;
5127             default:
5128               /* Can't happen.  */
5129             case 0:
5130               /* Error from catch_errors.  */
5131               printf_filtered (_("Watchpoint %d deleted.\n"), b->base.number);
5132               watchpoint_del_at_next_stop (b);
5133               /* We've already printed what needs to be printed.  */
5134               bs->print_it = print_it_done;
5135               break;
5136             }
5137         }
5138       else      /* must_check_value == 0 */
5139         {
5140           /* This is a case where some watchpoint(s) triggered, but
5141              not at the address of this watchpoint, or else no
5142              watchpoint triggered after all.  So don't print
5143              anything for this watchpoint.  */
5144           bs->print_it = print_it_noop;
5145           bs->stop = 0;
5146         }
5147     }
5148 }
5149
5150 /* For breakpoints that are currently marked as telling gdb to stop,
5151    check conditions (condition proper, frame, thread and ignore count)
5152    of breakpoint referred to by BS.  If we should not stop for this
5153    breakpoint, set BS->stop to 0.  */
5154
5155 static void
5156 bpstat_check_breakpoint_conditions (bpstat bs, ptid_t ptid)
5157 {
5158   int thread_id = pid_to_thread_id (ptid);
5159   const struct bp_location *bl;
5160   struct breakpoint *b;
5161   int value_is_zero = 0;
5162   struct expression *cond;
5163
5164   gdb_assert (bs->stop);
5165
5166   /* BS is built for existing struct breakpoint.  */
5167   bl = bs->bp_location_at;
5168   gdb_assert (bl != NULL);
5169   b = bs->breakpoint_at;
5170   gdb_assert (b != NULL);
5171
5172   /* Even if the target evaluated the condition on its end and notified GDB, we
5173      need to do so again since GDB does not know if we stopped due to a
5174      breakpoint or a single step breakpoint.  */
5175
5176   if (frame_id_p (b->frame_id)
5177       && !frame_id_eq (b->frame_id, get_stack_frame_id (get_current_frame ())))
5178     {
5179       bs->stop = 0;
5180       return;
5181     }
5182
5183   /* If this is a thread-specific breakpoint, don't waste cpu evaluating the
5184      condition if this isn't the specified thread.  */
5185   if (b->thread != -1 && b->thread != thread_id)
5186     {
5187       bs->stop = 0;
5188       return;
5189     }
5190
5191   /* Evaluate Python breakpoints that have a "stop" method implemented.  */
5192   if (b->py_bp_object)
5193     bs->stop = gdbpy_should_stop (b->py_bp_object);
5194
5195   if (is_watchpoint (b))
5196     {
5197       struct watchpoint *w = (struct watchpoint *) b;
5198
5199       cond = w->cond_exp;
5200     }
5201   else
5202     cond = bl->cond;
5203
5204   if (cond && b->disposition != disp_del_at_next_stop)
5205     {
5206       int within_current_scope = 1;
5207       struct watchpoint * w;
5208
5209       /* We use value_mark and value_free_to_mark because it could
5210          be a long time before we return to the command level and
5211          call free_all_values.  We can't call free_all_values
5212          because we might be in the middle of evaluating a
5213          function call.  */
5214       struct value *mark = value_mark ();
5215
5216       if (is_watchpoint (b))
5217         w = (struct watchpoint *) b;
5218       else
5219         w = NULL;
5220
5221       /* Need to select the frame, with all that implies so that
5222          the conditions will have the right context.  Because we
5223          use the frame, we will not see an inlined function's
5224          variables when we arrive at a breakpoint at the start
5225          of the inlined function; the current frame will be the
5226          call site.  */
5227       if (w == NULL || w->cond_exp_valid_block == NULL)
5228         select_frame (get_current_frame ());
5229       else
5230         {
5231           struct frame_info *frame;
5232
5233           /* For local watchpoint expressions, which particular
5234              instance of a local is being watched matters, so we
5235              keep track of the frame to evaluate the expression
5236              in.  To evaluate the condition however, it doesn't
5237              really matter which instantiation of the function
5238              where the condition makes sense triggers the
5239              watchpoint.  This allows an expression like "watch
5240              global if q > 10" set in `func', catch writes to
5241              global on all threads that call `func', or catch
5242              writes on all recursive calls of `func' by a single
5243              thread.  We simply always evaluate the condition in
5244              the innermost frame that's executing where it makes
5245              sense to evaluate the condition.  It seems
5246              intuitive.  */
5247           frame = block_innermost_frame (w->cond_exp_valid_block);
5248           if (frame != NULL)
5249             select_frame (frame);
5250           else
5251             within_current_scope = 0;
5252         }
5253       if (within_current_scope)
5254         value_is_zero
5255           = catch_errors (breakpoint_cond_eval, cond,
5256                           "Error in testing breakpoint condition:\n",
5257                           RETURN_MASK_ALL);
5258       else
5259         {
5260           warning (_("Watchpoint condition cannot be tested "
5261                      "in the current scope"));
5262           /* If we failed to set the right context for this
5263              watchpoint, unconditionally report it.  */
5264           value_is_zero = 0;
5265         }
5266       /* FIXME-someday, should give breakpoint #.  */
5267       value_free_to_mark (mark);
5268     }
5269
5270   if (cond && value_is_zero)
5271     {
5272       bs->stop = 0;
5273     }
5274   else if (b->ignore_count > 0)
5275     {
5276       b->ignore_count--;
5277       bs->stop = 0;
5278       /* Increase the hit count even though we don't stop.  */
5279       ++(b->hit_count);
5280       observer_notify_breakpoint_modified (b);
5281     }   
5282 }
5283
5284
5285 /* Get a bpstat associated with having just stopped at address
5286    BP_ADDR in thread PTID.
5287
5288    Determine whether we stopped at a breakpoint, etc, or whether we
5289    don't understand this stop.  Result is a chain of bpstat's such
5290    that:
5291
5292    if we don't understand the stop, the result is a null pointer.
5293
5294    if we understand why we stopped, the result is not null.
5295
5296    Each element of the chain refers to a particular breakpoint or
5297    watchpoint at which we have stopped.  (We may have stopped for
5298    several reasons concurrently.)
5299
5300    Each element of the chain has valid next, breakpoint_at,
5301    commands, FIXME??? fields.  */
5302
5303 bpstat
5304 bpstat_stop_status (struct address_space *aspace,
5305                     CORE_ADDR bp_addr, ptid_t ptid,
5306                     const struct target_waitstatus *ws)
5307 {
5308   struct breakpoint *b = NULL;
5309   struct bp_location *bl;
5310   struct bp_location *loc;
5311   /* First item of allocated bpstat's.  */
5312   bpstat bs_head = NULL, *bs_link = &bs_head;
5313   /* Pointer to the last thing in the chain currently.  */
5314   bpstat bs;
5315   int ix;
5316   int need_remove_insert;
5317   int removed_any;
5318
5319   /* First, build the bpstat chain with locations that explain a
5320      target stop, while being careful to not set the target running,
5321      as that may invalidate locations (in particular watchpoint
5322      locations are recreated).  Resuming will happen here with
5323      breakpoint conditions or watchpoint expressions that include
5324      inferior function calls.  */
5325
5326   ALL_BREAKPOINTS (b)
5327     {
5328       if (!breakpoint_enabled (b) && b->enable_state != bp_permanent)
5329         continue;
5330
5331       for (bl = b->loc; bl != NULL; bl = bl->next)
5332         {
5333           /* For hardware watchpoints, we look only at the first
5334              location.  The watchpoint_check function will work on the
5335              entire expression, not the individual locations.  For
5336              read watchpoints, the watchpoints_triggered function has
5337              checked all locations already.  */
5338           if (b->type == bp_hardware_watchpoint && bl != b->loc)
5339             break;
5340
5341           if (!bl->enabled || bl->shlib_disabled)
5342             continue;
5343
5344           if (!bpstat_check_location (bl, aspace, bp_addr, ws))
5345             continue;
5346
5347           /* Come here if it's a watchpoint, or if the break address
5348              matches.  */
5349
5350           bs = bpstat_alloc (bl, &bs_link);     /* Alloc a bpstat to
5351                                                    explain stop.  */
5352
5353           /* Assume we stop.  Should we find a watchpoint that is not
5354              actually triggered, or if the condition of the breakpoint
5355              evaluates as false, we'll reset 'stop' to 0.  */
5356           bs->stop = 1;
5357           bs->print = 1;
5358
5359           /* If this is a scope breakpoint, mark the associated
5360              watchpoint as triggered so that we will handle the
5361              out-of-scope event.  We'll get to the watchpoint next
5362              iteration.  */
5363           if (b->type == bp_watchpoint_scope && b->related_breakpoint != b)
5364             {
5365               struct watchpoint *w = (struct watchpoint *) b->related_breakpoint;
5366
5367               w->watchpoint_triggered = watch_triggered_yes;
5368             }
5369         }
5370     }
5371
5372   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
5373     {
5374       if (breakpoint_location_address_match (loc, aspace, bp_addr))
5375         {
5376           bs = bpstat_alloc (loc, &bs_link);
5377           /* For hits of moribund locations, we should just proceed.  */
5378           bs->stop = 0;
5379           bs->print = 0;
5380           bs->print_it = print_it_noop;
5381         }
5382     }
5383
5384   /* A bit of special processing for shlib breakpoints.  We need to
5385      process solib loading here, so that the lists of loaded and
5386      unloaded libraries are correct before we handle "catch load" and
5387      "catch unload".  */
5388   for (bs = bs_head; bs != NULL; bs = bs->next)
5389     {
5390       if (bs->breakpoint_at && bs->breakpoint_at->type == bp_shlib_event)
5391         {
5392           handle_solib_event ();
5393           break;
5394         }
5395     }
5396
5397   /* Now go through the locations that caused the target to stop, and
5398      check whether we're interested in reporting this stop to higher
5399      layers, or whether we should resume the target transparently.  */
5400
5401   removed_any = 0;
5402
5403   for (bs = bs_head; bs != NULL; bs = bs->next)
5404     {
5405       if (!bs->stop)
5406         continue;
5407
5408       b = bs->breakpoint_at;
5409       b->ops->check_status (bs);
5410       if (bs->stop)
5411         {
5412           bpstat_check_breakpoint_conditions (bs, ptid);
5413
5414           if (bs->stop)
5415             {
5416               ++(b->hit_count);
5417               observer_notify_breakpoint_modified (b);
5418
5419               /* We will stop here.  */
5420               if (b->disposition == disp_disable)
5421                 {
5422                   --(b->enable_count);
5423                   if (b->enable_count <= 0
5424                       && b->enable_state != bp_permanent)
5425                     b->enable_state = bp_disabled;
5426                   removed_any = 1;
5427                 }
5428               if (b->silent)
5429                 bs->print = 0;
5430               bs->commands = b->commands;
5431               incref_counted_command_line (bs->commands);
5432               if (command_line_is_silent (bs->commands
5433                                           ? bs->commands->commands : NULL))
5434                 bs->print = 0;
5435
5436               b->ops->after_condition_true (bs);
5437             }
5438
5439         }
5440
5441       /* Print nothing for this entry if we don't stop or don't
5442          print.  */
5443       if (!bs->stop || !bs->print)
5444         bs->print_it = print_it_noop;
5445     }
5446
5447   /* If we aren't stopping, the value of some hardware watchpoint may
5448      not have changed, but the intermediate memory locations we are
5449      watching may have.  Don't bother if we're stopping; this will get
5450      done later.  */
5451   need_remove_insert = 0;
5452   if (! bpstat_causes_stop (bs_head))
5453     for (bs = bs_head; bs != NULL; bs = bs->next)
5454       if (!bs->stop
5455           && bs->breakpoint_at
5456           && is_hardware_watchpoint (bs->breakpoint_at))
5457         {
5458           struct watchpoint *w = (struct watchpoint *) bs->breakpoint_at;
5459
5460           update_watchpoint (w, 0 /* don't reparse.  */);
5461           need_remove_insert = 1;
5462         }
5463
5464   if (need_remove_insert)
5465     update_global_location_list (1);
5466   else if (removed_any)
5467     update_global_location_list (0);
5468
5469   return bs_head;
5470 }
5471
5472 static void
5473 handle_jit_event (void)
5474 {
5475   struct frame_info *frame;
5476   struct gdbarch *gdbarch;
5477
5478   /* Switch terminal for any messages produced by
5479      breakpoint_re_set.  */
5480   target_terminal_ours_for_output ();
5481
5482   frame = get_current_frame ();
5483   gdbarch = get_frame_arch (frame);
5484
5485   jit_event_handler (gdbarch);
5486
5487   target_terminal_inferior ();
5488 }
5489
5490 /* Prepare WHAT final decision for infrun.  */
5491
5492 /* Decide what infrun needs to do with this bpstat.  */
5493
5494 struct bpstat_what
5495 bpstat_what (bpstat bs_head)
5496 {
5497   struct bpstat_what retval;
5498   int jit_event = 0;
5499   bpstat bs;
5500
5501   retval.main_action = BPSTAT_WHAT_KEEP_CHECKING;
5502   retval.call_dummy = STOP_NONE;
5503   retval.is_longjmp = 0;
5504
5505   for (bs = bs_head; bs != NULL; bs = bs->next)
5506     {
5507       /* Extract this BS's action.  After processing each BS, we check
5508          if its action overrides all we've seem so far.  */
5509       enum bpstat_what_main_action this_action = BPSTAT_WHAT_KEEP_CHECKING;
5510       enum bptype bptype;
5511
5512       if (bs->breakpoint_at == NULL)
5513         {
5514           /* I suspect this can happen if it was a momentary
5515              breakpoint which has since been deleted.  */
5516           bptype = bp_none;
5517         }
5518       else
5519         bptype = bs->breakpoint_at->type;
5520
5521       switch (bptype)
5522         {
5523         case bp_none:
5524           break;
5525         case bp_breakpoint:
5526         case bp_hardware_breakpoint:
5527         case bp_until:
5528         case bp_finish:
5529         case bp_shlib_event:
5530           if (bs->stop)
5531             {
5532               if (bs->print)
5533                 this_action = BPSTAT_WHAT_STOP_NOISY;
5534               else
5535                 this_action = BPSTAT_WHAT_STOP_SILENT;
5536             }
5537           else
5538             this_action = BPSTAT_WHAT_SINGLE;
5539           break;
5540         case bp_watchpoint:
5541         case bp_hardware_watchpoint:
5542         case bp_read_watchpoint:
5543         case bp_access_watchpoint:
5544           if (bs->stop)
5545             {
5546               if (bs->print)
5547                 this_action = BPSTAT_WHAT_STOP_NOISY;
5548               else
5549                 this_action = BPSTAT_WHAT_STOP_SILENT;
5550             }
5551           else
5552             {
5553               /* There was a watchpoint, but we're not stopping.
5554                  This requires no further action.  */
5555             }
5556           break;
5557         case bp_longjmp:
5558         case bp_longjmp_call_dummy:
5559         case bp_exception:
5560           this_action = BPSTAT_WHAT_SET_LONGJMP_RESUME;
5561           retval.is_longjmp = bptype != bp_exception;
5562           break;
5563         case bp_longjmp_resume:
5564         case bp_exception_resume:
5565           this_action = BPSTAT_WHAT_CLEAR_LONGJMP_RESUME;
5566           retval.is_longjmp = bptype == bp_longjmp_resume;
5567           break;
5568         case bp_step_resume:
5569           if (bs->stop)
5570             this_action = BPSTAT_WHAT_STEP_RESUME;
5571           else
5572             {
5573               /* It is for the wrong frame.  */
5574               this_action = BPSTAT_WHAT_SINGLE;
5575             }
5576           break;
5577         case bp_hp_step_resume:
5578           if (bs->stop)
5579             this_action = BPSTAT_WHAT_HP_STEP_RESUME;
5580           else
5581             {
5582               /* It is for the wrong frame.  */
5583               this_action = BPSTAT_WHAT_SINGLE;
5584             }
5585           break;
5586         case bp_watchpoint_scope:
5587         case bp_thread_event:
5588         case bp_overlay_event:
5589         case bp_longjmp_master:
5590         case bp_std_terminate_master:
5591         case bp_exception_master:
5592           this_action = BPSTAT_WHAT_SINGLE;
5593           break;
5594         case bp_catchpoint:
5595           if (bs->stop)
5596             {
5597               if (bs->print)
5598                 this_action = BPSTAT_WHAT_STOP_NOISY;
5599               else
5600                 this_action = BPSTAT_WHAT_STOP_SILENT;
5601             }
5602           else
5603             {
5604               /* There was a catchpoint, but we're not stopping.
5605                  This requires no further action.  */
5606             }
5607           break;
5608         case bp_jit_event:
5609           jit_event = 1;
5610           this_action = BPSTAT_WHAT_SINGLE;
5611           break;
5612         case bp_call_dummy:
5613           /* Make sure the action is stop (silent or noisy),
5614              so infrun.c pops the dummy frame.  */
5615           retval.call_dummy = STOP_STACK_DUMMY;
5616           this_action = BPSTAT_WHAT_STOP_SILENT;
5617           break;
5618         case bp_std_terminate:
5619           /* Make sure the action is stop (silent or noisy),
5620              so infrun.c pops the dummy frame.  */
5621           retval.call_dummy = STOP_STD_TERMINATE;
5622           this_action = BPSTAT_WHAT_STOP_SILENT;
5623           break;
5624         case bp_tracepoint:
5625         case bp_fast_tracepoint:
5626         case bp_static_tracepoint:
5627           /* Tracepoint hits should not be reported back to GDB, and
5628              if one got through somehow, it should have been filtered
5629              out already.  */
5630           internal_error (__FILE__, __LINE__,
5631                           _("bpstat_what: tracepoint encountered"));
5632           break;
5633         case bp_gnu_ifunc_resolver:
5634           /* Step over it (and insert bp_gnu_ifunc_resolver_return).  */
5635           this_action = BPSTAT_WHAT_SINGLE;
5636           break;
5637         case bp_gnu_ifunc_resolver_return:
5638           /* The breakpoint will be removed, execution will restart from the
5639              PC of the former breakpoint.  */
5640           this_action = BPSTAT_WHAT_KEEP_CHECKING;
5641           break;
5642
5643         case bp_dprintf:
5644           if (bs->stop)
5645             this_action = BPSTAT_WHAT_STOP_SILENT;
5646           else
5647             this_action = BPSTAT_WHAT_SINGLE;
5648           break;
5649
5650         default:
5651           internal_error (__FILE__, __LINE__,
5652                           _("bpstat_what: unhandled bptype %d"), (int) bptype);
5653         }
5654
5655       retval.main_action = max (retval.main_action, this_action);
5656     }
5657
5658   /* These operations may affect the bs->breakpoint_at state so they are
5659      delayed after MAIN_ACTION is decided above.  */
5660
5661   if (jit_event)
5662     {
5663       if (debug_infrun)
5664         fprintf_unfiltered (gdb_stdlog, "bpstat_what: bp_jit_event\n");
5665
5666       handle_jit_event ();
5667     }
5668
5669   for (bs = bs_head; bs != NULL; bs = bs->next)
5670     {
5671       struct breakpoint *b = bs->breakpoint_at;
5672
5673       if (b == NULL)
5674         continue;
5675       switch (b->type)
5676         {
5677         case bp_gnu_ifunc_resolver:
5678           gnu_ifunc_resolver_stop (b);
5679           break;
5680         case bp_gnu_ifunc_resolver_return:
5681           gnu_ifunc_resolver_return_stop (b);
5682           break;
5683         }
5684     }
5685
5686   return retval;
5687 }
5688
5689 /* Nonzero if we should step constantly (e.g. watchpoints on machines
5690    without hardware support).  This isn't related to a specific bpstat,
5691    just to things like whether watchpoints are set.  */
5692
5693 int
5694 bpstat_should_step (void)
5695 {
5696   struct breakpoint *b;
5697
5698   ALL_BREAKPOINTS (b)
5699     if (breakpoint_enabled (b) && b->type == bp_watchpoint && b->loc != NULL)
5700       return 1;
5701   return 0;
5702 }
5703
5704 int
5705 bpstat_causes_stop (bpstat bs)
5706 {
5707   for (; bs != NULL; bs = bs->next)
5708     if (bs->stop)
5709       return 1;
5710
5711   return 0;
5712 }
5713
5714 \f
5715
5716 /* Compute a string of spaces suitable to indent the next line
5717    so it starts at the position corresponding to the table column
5718    named COL_NAME in the currently active table of UIOUT.  */
5719
5720 static char *
5721 wrap_indent_at_field (struct ui_out *uiout, const char *col_name)
5722 {
5723   static char wrap_indent[80];
5724   int i, total_width, width, align;
5725   char *text;
5726
5727   total_width = 0;
5728   for (i = 1; ui_out_query_field (uiout, i, &width, &align, &text); i++)
5729     {
5730       if (strcmp (text, col_name) == 0)
5731         {
5732           gdb_assert (total_width < sizeof wrap_indent);
5733           memset (wrap_indent, ' ', total_width);
5734           wrap_indent[total_width] = 0;
5735
5736           return wrap_indent;
5737         }
5738
5739       total_width += width + 1;
5740     }
5741
5742   return NULL;
5743 }
5744
5745 /* Determine if the locations of this breakpoint will have their conditions
5746    evaluated by the target, host or a mix of both.  Returns the following:
5747
5748     "host": Host evals condition.
5749     "host or target": Host or Target evals condition.
5750     "target": Target evals condition.
5751 */
5752
5753 static const char *
5754 bp_condition_evaluator (struct breakpoint *b)
5755 {
5756   struct bp_location *bl;
5757   char host_evals = 0;
5758   char target_evals = 0;
5759
5760   if (!b)
5761     return NULL;
5762
5763   if (!is_breakpoint (b))
5764     return NULL;
5765
5766   if (gdb_evaluates_breakpoint_condition_p ()
5767       || !target_supports_evaluation_of_breakpoint_conditions ())
5768     return condition_evaluation_host;
5769
5770   for (bl = b->loc; bl; bl = bl->next)
5771     {
5772       if (bl->cond_bytecode)
5773         target_evals++;
5774       else
5775         host_evals++;
5776     }
5777
5778   if (host_evals && target_evals)
5779     return condition_evaluation_both;
5780   else if (target_evals)
5781     return condition_evaluation_target;
5782   else
5783     return condition_evaluation_host;
5784 }
5785
5786 /* Determine the breakpoint location's condition evaluator.  This is
5787    similar to bp_condition_evaluator, but for locations.  */
5788
5789 static const char *
5790 bp_location_condition_evaluator (struct bp_location *bl)
5791 {
5792   if (bl && !is_breakpoint (bl->owner))
5793     return NULL;
5794
5795   if (gdb_evaluates_breakpoint_condition_p ()
5796       || !target_supports_evaluation_of_breakpoint_conditions ())
5797     return condition_evaluation_host;
5798
5799   if (bl && bl->cond_bytecode)
5800     return condition_evaluation_target;
5801   else
5802     return condition_evaluation_host;
5803 }
5804
5805 /* Print the LOC location out of the list of B->LOC locations.  */
5806
5807 static void
5808 print_breakpoint_location (struct breakpoint *b,
5809                            struct bp_location *loc)
5810 {
5811   struct ui_out *uiout = current_uiout;
5812   struct cleanup *old_chain = save_current_program_space ();
5813
5814   if (loc != NULL && loc->shlib_disabled)
5815     loc = NULL;
5816
5817   if (loc != NULL)
5818     set_current_program_space (loc->pspace);
5819
5820   if (b->display_canonical)
5821     ui_out_field_string (uiout, "what", b->addr_string);
5822   else if (loc && loc->symtab)
5823     {
5824       struct symbol *sym 
5825         = find_pc_sect_function (loc->address, loc->section);
5826       if (sym)
5827         {
5828           ui_out_text (uiout, "in ");
5829           ui_out_field_string (uiout, "func",
5830                                SYMBOL_PRINT_NAME (sym));
5831           ui_out_text (uiout, " ");
5832           ui_out_wrap_hint (uiout, wrap_indent_at_field (uiout, "what"));
5833           ui_out_text (uiout, "at ");
5834         }
5835       ui_out_field_string (uiout, "file",
5836                            symtab_to_filename_for_display (loc->symtab));
5837       ui_out_text (uiout, ":");
5838
5839       if (ui_out_is_mi_like_p (uiout))
5840         ui_out_field_string (uiout, "fullname",
5841                              symtab_to_fullname (loc->symtab));
5842       
5843       ui_out_field_int (uiout, "line", loc->line_number);
5844     }
5845   else if (loc)
5846     {
5847       struct ui_file *stb = mem_fileopen ();
5848       struct cleanup *stb_chain = make_cleanup_ui_file_delete (stb);
5849
5850       print_address_symbolic (loc->gdbarch, loc->address, stb,
5851                               demangle, "");
5852       ui_out_field_stream (uiout, "at", stb);
5853
5854       do_cleanups (stb_chain);
5855     }
5856   else
5857     ui_out_field_string (uiout, "pending", b->addr_string);
5858
5859   if (loc && is_breakpoint (b)
5860       && breakpoint_condition_evaluation_mode () == condition_evaluation_target
5861       && bp_condition_evaluator (b) == condition_evaluation_both)
5862     {
5863       ui_out_text (uiout, " (");
5864       ui_out_field_string (uiout, "evaluated-by",
5865                            bp_location_condition_evaluator (loc));
5866       ui_out_text (uiout, ")");
5867     }
5868
5869   do_cleanups (old_chain);
5870 }
5871
5872 static const char *
5873 bptype_string (enum bptype type)
5874 {
5875   struct ep_type_description
5876     {
5877       enum bptype type;
5878       char *description;
5879     };
5880   static struct ep_type_description bptypes[] =
5881   {
5882     {bp_none, "?deleted?"},
5883     {bp_breakpoint, "breakpoint"},
5884     {bp_hardware_breakpoint, "hw breakpoint"},
5885     {bp_until, "until"},
5886     {bp_finish, "finish"},
5887     {bp_watchpoint, "watchpoint"},
5888     {bp_hardware_watchpoint, "hw watchpoint"},
5889     {bp_read_watchpoint, "read watchpoint"},
5890     {bp_access_watchpoint, "acc watchpoint"},
5891     {bp_longjmp, "longjmp"},
5892     {bp_longjmp_resume, "longjmp resume"},
5893     {bp_longjmp_call_dummy, "longjmp for call dummy"},
5894     {bp_exception, "exception"},
5895     {bp_exception_resume, "exception resume"},
5896     {bp_step_resume, "step resume"},
5897     {bp_hp_step_resume, "high-priority step resume"},
5898     {bp_watchpoint_scope, "watchpoint scope"},
5899     {bp_call_dummy, "call dummy"},
5900     {bp_std_terminate, "std::terminate"},
5901     {bp_shlib_event, "shlib events"},
5902     {bp_thread_event, "thread events"},
5903     {bp_overlay_event, "overlay events"},
5904     {bp_longjmp_master, "longjmp master"},
5905     {bp_std_terminate_master, "std::terminate master"},
5906     {bp_exception_master, "exception master"},
5907     {bp_catchpoint, "catchpoint"},
5908     {bp_tracepoint, "tracepoint"},
5909     {bp_fast_tracepoint, "fast tracepoint"},
5910     {bp_static_tracepoint, "static tracepoint"},
5911     {bp_dprintf, "dprintf"},
5912     {bp_jit_event, "jit events"},
5913     {bp_gnu_ifunc_resolver, "STT_GNU_IFUNC resolver"},
5914     {bp_gnu_ifunc_resolver_return, "STT_GNU_IFUNC resolver return"},
5915   };
5916
5917   if (((int) type >= (sizeof (bptypes) / sizeof (bptypes[0])))
5918       || ((int) type != bptypes[(int) type].type))
5919     internal_error (__FILE__, __LINE__,
5920                     _("bptypes table does not describe type #%d."),
5921                     (int) type);
5922
5923   return bptypes[(int) type].description;
5924 }
5925
5926 /* For MI, output a field named 'thread-groups' with a list as the value.
5927    For CLI, prefix the list with the string 'inf'. */
5928
5929 static void
5930 output_thread_groups (struct ui_out *uiout,
5931                       const char *field_name,
5932                       VEC(int) *inf_num,
5933                       int mi_only)
5934 {
5935   struct cleanup *back_to;
5936   int is_mi = ui_out_is_mi_like_p (uiout);
5937   int inf;
5938   int i;
5939
5940   /* For backward compatibility, don't display inferiors in CLI unless
5941      there are several.  Always display them for MI. */
5942   if (!is_mi && mi_only)
5943     return;
5944
5945   back_to = make_cleanup_ui_out_list_begin_end (uiout, field_name);
5946
5947   for (i = 0; VEC_iterate (int, inf_num, i, inf); ++i)
5948     {
5949       if (is_mi)
5950         {
5951           char mi_group[10];
5952
5953           xsnprintf (mi_group, sizeof (mi_group), "i%d", inf);
5954           ui_out_field_string (uiout, NULL, mi_group);
5955         }
5956       else
5957         {
5958           if (i == 0)
5959             ui_out_text (uiout, " inf ");
5960           else
5961             ui_out_text (uiout, ", ");
5962         
5963           ui_out_text (uiout, plongest (inf));
5964         }
5965     }
5966
5967   do_cleanups (back_to);
5968 }
5969
5970 /* Print B to gdb_stdout.  */
5971
5972 static void
5973 print_one_breakpoint_location (struct breakpoint *b,
5974                                struct bp_location *loc,
5975                                int loc_number,
5976                                struct bp_location **last_loc,
5977                                int allflag)
5978 {
5979   struct command_line *l;
5980   static char bpenables[] = "nynny";
5981
5982   struct ui_out *uiout = current_uiout;
5983   int header_of_multiple = 0;
5984   int part_of_multiple = (loc != NULL);
5985   struct value_print_options opts;
5986
5987   get_user_print_options (&opts);
5988
5989   gdb_assert (!loc || loc_number != 0);
5990   /* See comment in print_one_breakpoint concerning treatment of
5991      breakpoints with single disabled location.  */
5992   if (loc == NULL 
5993       && (b->loc != NULL 
5994           && (b->loc->next != NULL || !b->loc->enabled)))
5995     header_of_multiple = 1;
5996   if (loc == NULL)
5997     loc = b->loc;
5998
5999   annotate_record ();
6000
6001   /* 1 */
6002   annotate_field (0);
6003   if (part_of_multiple)
6004     {
6005       char *formatted;
6006       formatted = xstrprintf ("%d.%d", b->number, loc_number);
6007       ui_out_field_string (uiout, "number", formatted);
6008       xfree (formatted);
6009     }
6010   else
6011     {
6012       ui_out_field_int (uiout, "number", b->number);
6013     }
6014
6015   /* 2 */
6016   annotate_field (1);
6017   if (part_of_multiple)
6018     ui_out_field_skip (uiout, "type");
6019   else
6020     ui_out_field_string (uiout, "type", bptype_string (b->type));
6021
6022   /* 3 */
6023   annotate_field (2);
6024   if (part_of_multiple)
6025     ui_out_field_skip (uiout, "disp");
6026   else
6027     ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
6028
6029
6030   /* 4 */
6031   annotate_field (3);
6032   if (part_of_multiple)
6033     ui_out_field_string (uiout, "enabled", loc->enabled ? "y" : "n");
6034   else
6035     ui_out_field_fmt (uiout, "enabled", "%c", 
6036                       bpenables[(int) b->enable_state]);
6037   ui_out_spaces (uiout, 2);
6038
6039   
6040   /* 5 and 6 */
6041   if (b->ops != NULL && b->ops->print_one != NULL)
6042     {
6043       /* Although the print_one can possibly print all locations,
6044          calling it here is not likely to get any nice result.  So,
6045          make sure there's just one location.  */
6046       gdb_assert (b->loc == NULL || b->loc->next == NULL);
6047       b->ops->print_one (b, last_loc);
6048     }
6049   else
6050     switch (b->type)
6051       {
6052       case bp_none:
6053         internal_error (__FILE__, __LINE__,
6054                         _("print_one_breakpoint: bp_none encountered\n"));
6055         break;
6056
6057       case bp_watchpoint:
6058       case bp_hardware_watchpoint:
6059       case bp_read_watchpoint:
6060       case bp_access_watchpoint:
6061         {
6062           struct watchpoint *w = (struct watchpoint *) b;
6063
6064           /* Field 4, the address, is omitted (which makes the columns
6065              not line up too nicely with the headers, but the effect
6066              is relatively readable).  */
6067           if (opts.addressprint)
6068             ui_out_field_skip (uiout, "addr");
6069           annotate_field (5);
6070           ui_out_field_string (uiout, "what", w->exp_string);
6071         }
6072         break;
6073
6074       case bp_breakpoint:
6075       case bp_hardware_breakpoint:
6076       case bp_until:
6077       case bp_finish:
6078       case bp_longjmp:
6079       case bp_longjmp_resume:
6080       case bp_longjmp_call_dummy:
6081       case bp_exception:
6082       case bp_exception_resume:
6083       case bp_step_resume:
6084       case bp_hp_step_resume:
6085       case bp_watchpoint_scope:
6086       case bp_call_dummy:
6087       case bp_std_terminate:
6088       case bp_shlib_event:
6089       case bp_thread_event:
6090       case bp_overlay_event:
6091       case bp_longjmp_master:
6092       case bp_std_terminate_master:
6093       case bp_exception_master:
6094       case bp_tracepoint:
6095       case bp_fast_tracepoint:
6096       case bp_static_tracepoint:
6097       case bp_dprintf:
6098       case bp_jit_event:
6099       case bp_gnu_ifunc_resolver:
6100       case bp_gnu_ifunc_resolver_return:
6101         if (opts.addressprint)
6102           {
6103             annotate_field (4);
6104             if (header_of_multiple)
6105               ui_out_field_string (uiout, "addr", "<MULTIPLE>");
6106             else if (b->loc == NULL || loc->shlib_disabled)
6107               ui_out_field_string (uiout, "addr", "<PENDING>");
6108             else
6109               ui_out_field_core_addr (uiout, "addr",
6110                                       loc->gdbarch, loc->address);
6111           }
6112         annotate_field (5);
6113         if (!header_of_multiple)
6114           print_breakpoint_location (b, loc);
6115         if (b->loc)
6116           *last_loc = b->loc;
6117         break;
6118       }
6119
6120
6121   if (loc != NULL && !header_of_multiple)
6122     {
6123       struct inferior *inf;
6124       VEC(int) *inf_num = NULL;
6125       int mi_only = 1;
6126
6127       ALL_INFERIORS (inf)
6128         {
6129           if (inf->pspace == loc->pspace)
6130             VEC_safe_push (int, inf_num, inf->num);
6131         }
6132
6133         /* For backward compatibility, don't display inferiors in CLI unless
6134            there are several.  Always display for MI. */
6135         if (allflag
6136             || (!gdbarch_has_global_breakpoints (target_gdbarch ())
6137                 && (number_of_program_spaces () > 1
6138                     || number_of_inferiors () > 1)
6139                 /* LOC is for existing B, it cannot be in
6140                    moribund_locations and thus having NULL OWNER.  */
6141                 && loc->owner->type != bp_catchpoint))
6142         mi_only = 0;
6143       output_thread_groups (uiout, "thread-groups", inf_num, mi_only);
6144       VEC_free (int, inf_num);
6145     }
6146
6147   if (!part_of_multiple)
6148     {
6149       if (b->thread != -1)
6150         {
6151           /* FIXME: This seems to be redundant and lost here; see the
6152              "stop only in" line a little further down.  */
6153           ui_out_text (uiout, " thread ");
6154           ui_out_field_int (uiout, "thread", b->thread);
6155         }
6156       else if (b->task != 0)
6157         {
6158           ui_out_text (uiout, " task ");
6159           ui_out_field_int (uiout, "task", b->task);
6160         }
6161     }
6162
6163   ui_out_text (uiout, "\n");
6164
6165   if (!part_of_multiple)
6166     b->ops->print_one_detail (b, uiout);
6167
6168   if (part_of_multiple && frame_id_p (b->frame_id))
6169     {
6170       annotate_field (6);
6171       ui_out_text (uiout, "\tstop only in stack frame at ");
6172       /* FIXME: cagney/2002-12-01: Shouldn't be poking around inside
6173          the frame ID.  */
6174       ui_out_field_core_addr (uiout, "frame",
6175                               b->gdbarch, b->frame_id.stack_addr);
6176       ui_out_text (uiout, "\n");
6177     }
6178   
6179   if (!part_of_multiple && b->cond_string)
6180     {
6181       annotate_field (7);
6182       if (is_tracepoint (b))
6183         ui_out_text (uiout, "\ttrace only if ");
6184       else
6185         ui_out_text (uiout, "\tstop only if ");
6186       ui_out_field_string (uiout, "cond", b->cond_string);
6187
6188       /* Print whether the target is doing the breakpoint's condition
6189          evaluation.  If GDB is doing the evaluation, don't print anything.  */
6190       if (is_breakpoint (b)
6191           && breakpoint_condition_evaluation_mode ()
6192           == condition_evaluation_target)
6193         {
6194           ui_out_text (uiout, " (");
6195           ui_out_field_string (uiout, "evaluated-by",
6196                                bp_condition_evaluator (b));
6197           ui_out_text (uiout, " evals)");
6198         }
6199       ui_out_text (uiout, "\n");
6200     }
6201
6202   if (!part_of_multiple && b->thread != -1)
6203     {
6204       /* FIXME should make an annotation for this.  */
6205       ui_out_text (uiout, "\tstop only in thread ");
6206       ui_out_field_int (uiout, "thread", b->thread);
6207       ui_out_text (uiout, "\n");
6208     }
6209   
6210   if (!part_of_multiple)
6211     {
6212       if (b->hit_count)
6213         {
6214           /* FIXME should make an annotation for this.  */
6215           if (is_catchpoint (b))
6216             ui_out_text (uiout, "\tcatchpoint");
6217           else if (is_tracepoint (b))
6218             ui_out_text (uiout, "\ttracepoint");
6219           else
6220             ui_out_text (uiout, "\tbreakpoint");
6221           ui_out_text (uiout, " already hit ");
6222           ui_out_field_int (uiout, "times", b->hit_count);
6223           if (b->hit_count == 1)
6224             ui_out_text (uiout, " time\n");
6225           else
6226             ui_out_text (uiout, " times\n");
6227         }
6228       else
6229         {
6230           /* Output the count also if it is zero, but only if this is mi.  */
6231           if (ui_out_is_mi_like_p (uiout))
6232             ui_out_field_int (uiout, "times", b->hit_count);
6233         }
6234     }
6235
6236   if (!part_of_multiple && b->ignore_count)
6237     {
6238       annotate_field (8);
6239       ui_out_text (uiout, "\tignore next ");
6240       ui_out_field_int (uiout, "ignore", b->ignore_count);
6241       ui_out_text (uiout, " hits\n");
6242     }
6243
6244   /* Note that an enable count of 1 corresponds to "enable once"
6245      behavior, which is reported by the combination of enablement and
6246      disposition, so we don't need to mention it here.  */
6247   if (!part_of_multiple && b->enable_count > 1)
6248     {
6249       annotate_field (8);
6250       ui_out_text (uiout, "\tdisable after ");
6251       /* Tweak the wording to clarify that ignore and enable counts
6252          are distinct, and have additive effect.  */
6253       if (b->ignore_count)
6254         ui_out_text (uiout, "additional ");
6255       else
6256         ui_out_text (uiout, "next ");
6257       ui_out_field_int (uiout, "enable", b->enable_count);
6258       ui_out_text (uiout, " hits\n");
6259     }
6260
6261   if (!part_of_multiple && is_tracepoint (b))
6262     {
6263       struct tracepoint *tp = (struct tracepoint *) b;
6264
6265       if (tp->traceframe_usage)
6266         {
6267           ui_out_text (uiout, "\ttrace buffer usage ");
6268           ui_out_field_int (uiout, "traceframe-usage", tp->traceframe_usage);
6269           ui_out_text (uiout, " bytes\n");
6270         }
6271     }
6272
6273   l = b->commands ? b->commands->commands : NULL;
6274   if (!part_of_multiple && l)
6275     {
6276       struct cleanup *script_chain;
6277
6278       annotate_field (9);
6279       script_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "script");
6280       print_command_lines (uiout, l, 4);
6281       do_cleanups (script_chain);
6282     }
6283
6284   if (is_tracepoint (b))
6285     {
6286       struct tracepoint *t = (struct tracepoint *) b;
6287
6288       if (!part_of_multiple && t->pass_count)
6289         {
6290           annotate_field (10);
6291           ui_out_text (uiout, "\tpass count ");
6292           ui_out_field_int (uiout, "pass", t->pass_count);
6293           ui_out_text (uiout, " \n");
6294         }
6295
6296       /* Don't display it when tracepoint or tracepoint location is
6297          pending.   */
6298       if (!header_of_multiple && loc != NULL && !loc->shlib_disabled)
6299         {
6300           annotate_field (11);
6301
6302           if (ui_out_is_mi_like_p (uiout))
6303             ui_out_field_string (uiout, "installed",
6304                                  loc->inserted ? "y" : "n");
6305           else
6306             {
6307               if (loc->inserted)
6308                 ui_out_text (uiout, "\t");
6309               else
6310                 ui_out_text (uiout, "\tnot ");
6311               ui_out_text (uiout, "installed on target\n");
6312             }
6313         }
6314     }
6315
6316   if (ui_out_is_mi_like_p (uiout) && !part_of_multiple)
6317     {
6318       if (is_watchpoint (b))
6319         {
6320           struct watchpoint *w = (struct watchpoint *) b;
6321
6322           ui_out_field_string (uiout, "original-location", w->exp_string);
6323         }
6324       else if (b->addr_string)
6325         ui_out_field_string (uiout, "original-location", b->addr_string);
6326     }
6327 }
6328
6329 static void
6330 print_one_breakpoint (struct breakpoint *b,
6331                       struct bp_location **last_loc, 
6332                       int allflag)
6333 {
6334   struct cleanup *bkpt_chain;
6335   struct ui_out *uiout = current_uiout;
6336
6337   bkpt_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "bkpt");
6338
6339   print_one_breakpoint_location (b, NULL, 0, last_loc, allflag);
6340   do_cleanups (bkpt_chain);
6341
6342   /* If this breakpoint has custom print function,
6343      it's already printed.  Otherwise, print individual
6344      locations, if any.  */
6345   if (b->ops == NULL || b->ops->print_one == NULL)
6346     {
6347       /* If breakpoint has a single location that is disabled, we
6348          print it as if it had several locations, since otherwise it's
6349          hard to represent "breakpoint enabled, location disabled"
6350          situation.
6351
6352          Note that while hardware watchpoints have several locations
6353          internally, that's not a property exposed to user.  */
6354       if (b->loc 
6355           && !is_hardware_watchpoint (b)
6356           && (b->loc->next || !b->loc->enabled))
6357         {
6358           struct bp_location *loc;
6359           int n = 1;
6360
6361           for (loc = b->loc; loc; loc = loc->next, ++n)
6362             {
6363               struct cleanup *inner2 =
6364                 make_cleanup_ui_out_tuple_begin_end (uiout, NULL);
6365               print_one_breakpoint_location (b, loc, n, last_loc, allflag);
6366               do_cleanups (inner2);
6367             }
6368         }
6369     }
6370 }
6371
6372 static int
6373 breakpoint_address_bits (struct breakpoint *b)
6374 {
6375   int print_address_bits = 0;
6376   struct bp_location *loc;
6377
6378   for (loc = b->loc; loc; loc = loc->next)
6379     {
6380       int addr_bit;
6381
6382       /* Software watchpoints that aren't watching memory don't have
6383          an address to print.  */
6384       if (b->type == bp_watchpoint && loc->watchpoint_type == -1)
6385         continue;
6386
6387       addr_bit = gdbarch_addr_bit (loc->gdbarch);
6388       if (addr_bit > print_address_bits)
6389         print_address_bits = addr_bit;
6390     }
6391
6392   return print_address_bits;
6393 }
6394
6395 struct captured_breakpoint_query_args
6396   {
6397     int bnum;
6398   };
6399
6400 static int
6401 do_captured_breakpoint_query (struct ui_out *uiout, void *data)
6402 {
6403   struct captured_breakpoint_query_args *args = data;
6404   struct breakpoint *b;
6405   struct bp_location *dummy_loc = NULL;
6406
6407   ALL_BREAKPOINTS (b)
6408     {
6409       if (args->bnum == b->number)
6410         {
6411           print_one_breakpoint (b, &dummy_loc, 0);
6412           return GDB_RC_OK;
6413         }
6414     }
6415   return GDB_RC_NONE;
6416 }
6417
6418 enum gdb_rc
6419 gdb_breakpoint_query (struct ui_out *uiout, int bnum, 
6420                       char **error_message)
6421 {
6422   struct captured_breakpoint_query_args args;
6423
6424   args.bnum = bnum;
6425   /* For the moment we don't trust print_one_breakpoint() to not throw
6426      an error.  */
6427   if (catch_exceptions_with_msg (uiout, do_captured_breakpoint_query, &args,
6428                                  error_message, RETURN_MASK_ALL) < 0)
6429     return GDB_RC_FAIL;
6430   else
6431     return GDB_RC_OK;
6432 }
6433
6434 /* Return true if this breakpoint was set by the user, false if it is
6435    internal or momentary.  */
6436
6437 int
6438 user_breakpoint_p (struct breakpoint *b)
6439 {
6440   return b->number > 0;
6441 }
6442
6443 /* Print information on user settable breakpoint (watchpoint, etc)
6444    number BNUM.  If BNUM is -1 print all user-settable breakpoints.
6445    If ALLFLAG is non-zero, include non-user-settable breakpoints.  If
6446    FILTER is non-NULL, call it on each breakpoint and only include the
6447    ones for which it returns non-zero.  Return the total number of
6448    breakpoints listed.  */
6449
6450 static int
6451 breakpoint_1 (char *args, int allflag, 
6452               int (*filter) (const struct breakpoint *))
6453 {
6454   struct breakpoint *b;
6455   struct bp_location *last_loc = NULL;
6456   int nr_printable_breakpoints;
6457   struct cleanup *bkpttbl_chain;
6458   struct value_print_options opts;
6459   int print_address_bits = 0;
6460   int print_type_col_width = 14;
6461   struct ui_out *uiout = current_uiout;
6462
6463   get_user_print_options (&opts);
6464
6465   /* Compute the number of rows in the table, as well as the size
6466      required for address fields.  */
6467   nr_printable_breakpoints = 0;
6468   ALL_BREAKPOINTS (b)
6469     {
6470       /* If we have a filter, only list the breakpoints it accepts.  */
6471       if (filter && !filter (b))
6472         continue;
6473
6474       /* If we have an "args" string, it is a list of breakpoints to 
6475          accept.  Skip the others.  */
6476       if (args != NULL && *args != '\0')
6477         {
6478           if (allflag && parse_and_eval_long (args) != b->number)
6479             continue;
6480           if (!allflag && !number_is_in_list (args, b->number))
6481             continue;
6482         }
6483
6484       if (allflag || user_breakpoint_p (b))
6485         {
6486           int addr_bit, type_len;
6487
6488           addr_bit = breakpoint_address_bits (b);
6489           if (addr_bit > print_address_bits)
6490             print_address_bits = addr_bit;
6491
6492           type_len = strlen (bptype_string (b->type));
6493           if (type_len > print_type_col_width)
6494             print_type_col_width = type_len;
6495
6496           nr_printable_breakpoints++;
6497         }
6498     }
6499
6500   if (opts.addressprint)
6501     bkpttbl_chain 
6502       = make_cleanup_ui_out_table_begin_end (uiout, 6,
6503                                              nr_printable_breakpoints,
6504                                              "BreakpointTable");
6505   else
6506     bkpttbl_chain 
6507       = make_cleanup_ui_out_table_begin_end (uiout, 5,
6508                                              nr_printable_breakpoints,
6509                                              "BreakpointTable");
6510
6511   if (nr_printable_breakpoints > 0)
6512     annotate_breakpoints_headers ();
6513   if (nr_printable_breakpoints > 0)
6514     annotate_field (0);
6515   ui_out_table_header (uiout, 7, ui_left, "number", "Num");     /* 1 */
6516   if (nr_printable_breakpoints > 0)
6517     annotate_field (1);
6518   ui_out_table_header (uiout, print_type_col_width, ui_left,
6519                        "type", "Type");                         /* 2 */
6520   if (nr_printable_breakpoints > 0)
6521     annotate_field (2);
6522   ui_out_table_header (uiout, 4, ui_left, "disp", "Disp");      /* 3 */
6523   if (nr_printable_breakpoints > 0)
6524     annotate_field (3);
6525   ui_out_table_header (uiout, 3, ui_left, "enabled", "Enb");    /* 4 */
6526   if (opts.addressprint)
6527     {
6528       if (nr_printable_breakpoints > 0)
6529         annotate_field (4);
6530       if (print_address_bits <= 32)
6531         ui_out_table_header (uiout, 10, ui_left, 
6532                              "addr", "Address");                /* 5 */
6533       else
6534         ui_out_table_header (uiout, 18, ui_left, 
6535                              "addr", "Address");                /* 5 */
6536     }
6537   if (nr_printable_breakpoints > 0)
6538     annotate_field (5);
6539   ui_out_table_header (uiout, 40, ui_noalign, "what", "What");  /* 6 */
6540   ui_out_table_body (uiout);
6541   if (nr_printable_breakpoints > 0)
6542     annotate_breakpoints_table ();
6543
6544   ALL_BREAKPOINTS (b)
6545     {
6546       QUIT;
6547       /* If we have a filter, only list the breakpoints it accepts.  */
6548       if (filter && !filter (b))
6549         continue;
6550
6551       /* If we have an "args" string, it is a list of breakpoints to 
6552          accept.  Skip the others.  */
6553
6554       if (args != NULL && *args != '\0')
6555         {
6556           if (allflag)  /* maintenance info breakpoint */
6557             {
6558               if (parse_and_eval_long (args) != b->number)
6559                 continue;
6560             }
6561           else          /* all others */
6562             {
6563               if (!number_is_in_list (args, b->number))
6564                 continue;
6565             }
6566         }
6567       /* We only print out user settable breakpoints unless the
6568          allflag is set.  */
6569       if (allflag || user_breakpoint_p (b))
6570         print_one_breakpoint (b, &last_loc, allflag);
6571     }
6572
6573   do_cleanups (bkpttbl_chain);
6574
6575   if (nr_printable_breakpoints == 0)
6576     {
6577       /* If there's a filter, let the caller decide how to report
6578          empty list.  */
6579       if (!filter)
6580         {
6581           if (args == NULL || *args == '\0')
6582             ui_out_message (uiout, 0, "No breakpoints or watchpoints.\n");
6583           else
6584             ui_out_message (uiout, 0, 
6585                             "No breakpoint or watchpoint matching '%s'.\n",
6586                             args);
6587         }
6588     }
6589   else
6590     {
6591       if (last_loc && !server_command)
6592         set_next_address (last_loc->gdbarch, last_loc->address);
6593     }
6594
6595   /* FIXME?  Should this be moved up so that it is only called when
6596      there have been breakpoints? */
6597   annotate_breakpoints_table_end ();
6598
6599   return nr_printable_breakpoints;
6600 }
6601
6602 /* Display the value of default-collect in a way that is generally
6603    compatible with the breakpoint list.  */
6604
6605 static void
6606 default_collect_info (void)
6607 {
6608   struct ui_out *uiout = current_uiout;
6609
6610   /* If it has no value (which is frequently the case), say nothing; a
6611      message like "No default-collect." gets in user's face when it's
6612      not wanted.  */
6613   if (!*default_collect)
6614     return;
6615
6616   /* The following phrase lines up nicely with per-tracepoint collect
6617      actions.  */
6618   ui_out_text (uiout, "default collect ");
6619   ui_out_field_string (uiout, "default-collect", default_collect);
6620   ui_out_text (uiout, " \n");
6621 }
6622   
6623 static void
6624 breakpoints_info (char *args, int from_tty)
6625 {
6626   breakpoint_1 (args, 0, NULL);
6627
6628   default_collect_info ();
6629 }
6630
6631 static void
6632 watchpoints_info (char *args, int from_tty)
6633 {
6634   int num_printed = breakpoint_1 (args, 0, is_watchpoint);
6635   struct ui_out *uiout = current_uiout;
6636
6637   if (num_printed == 0)
6638     {
6639       if (args == NULL || *args == '\0')
6640         ui_out_message (uiout, 0, "No watchpoints.\n");
6641       else
6642         ui_out_message (uiout, 0, "No watchpoint matching '%s'.\n", args);
6643     }
6644 }
6645
6646 static void
6647 maintenance_info_breakpoints (char *args, int from_tty)
6648 {
6649   breakpoint_1 (args, 1, NULL);
6650
6651   default_collect_info ();
6652 }
6653
6654 static int
6655 breakpoint_has_pc (struct breakpoint *b,
6656                    struct program_space *pspace,
6657                    CORE_ADDR pc, struct obj_section *section)
6658 {
6659   struct bp_location *bl = b->loc;
6660
6661   for (; bl; bl = bl->next)
6662     {
6663       if (bl->pspace == pspace
6664           && bl->address == pc
6665           && (!overlay_debugging || bl->section == section))
6666         return 1;         
6667     }
6668   return 0;
6669 }
6670
6671 /* Print a message describing any user-breakpoints set at PC.  This
6672    concerns with logical breakpoints, so we match program spaces, not
6673    address spaces.  */
6674
6675 static void
6676 describe_other_breakpoints (struct gdbarch *gdbarch,
6677                             struct program_space *pspace, CORE_ADDR pc,
6678                             struct obj_section *section, int thread)
6679 {
6680   int others = 0;
6681   struct breakpoint *b;
6682
6683   ALL_BREAKPOINTS (b)
6684     others += (user_breakpoint_p (b)
6685                && breakpoint_has_pc (b, pspace, pc, section));
6686   if (others > 0)
6687     {
6688       if (others == 1)
6689         printf_filtered (_("Note: breakpoint "));
6690       else /* if (others == ???) */
6691         printf_filtered (_("Note: breakpoints "));
6692       ALL_BREAKPOINTS (b)
6693         if (user_breakpoint_p (b) && breakpoint_has_pc (b, pspace, pc, section))
6694           {
6695             others--;
6696             printf_filtered ("%d", b->number);
6697             if (b->thread == -1 && thread != -1)
6698               printf_filtered (" (all threads)");
6699             else if (b->thread != -1)
6700               printf_filtered (" (thread %d)", b->thread);
6701             printf_filtered ("%s%s ",
6702                              ((b->enable_state == bp_disabled
6703                                || b->enable_state == bp_call_disabled)
6704                               ? " (disabled)"
6705                               : b->enable_state == bp_permanent 
6706                               ? " (permanent)"
6707                               : ""),
6708                              (others > 1) ? "," 
6709                              : ((others == 1) ? " and" : ""));
6710           }
6711       printf_filtered (_("also set at pc "));
6712       fputs_filtered (paddress (gdbarch, pc), gdb_stdout);
6713       printf_filtered (".\n");
6714     }
6715 }
6716 \f
6717
6718 /* Return true iff it is meaningful to use the address member of
6719    BPT.  For some breakpoint types, the address member is irrelevant
6720    and it makes no sense to attempt to compare it to other addresses
6721    (or use it for any other purpose either).
6722
6723    More specifically, each of the following breakpoint types will
6724    always have a zero valued address and we don't want to mark
6725    breakpoints of any of these types to be a duplicate of an actual
6726    breakpoint at address zero:
6727
6728       bp_watchpoint
6729       bp_catchpoint
6730
6731 */
6732
6733 static int
6734 breakpoint_address_is_meaningful (struct breakpoint *bpt)
6735 {
6736   enum bptype type = bpt->type;
6737
6738   return (type != bp_watchpoint && type != bp_catchpoint);
6739 }
6740
6741 /* Assuming LOC1 and LOC2's owners are hardware watchpoints, returns
6742    true if LOC1 and LOC2 represent the same watchpoint location.  */
6743
6744 static int
6745 watchpoint_locations_match (struct bp_location *loc1, 
6746                             struct bp_location *loc2)
6747 {
6748   struct watchpoint *w1 = (struct watchpoint *) loc1->owner;
6749   struct watchpoint *w2 = (struct watchpoint *) loc2->owner;
6750
6751   /* Both of them must exist.  */
6752   gdb_assert (w1 != NULL);
6753   gdb_assert (w2 != NULL);
6754
6755   /* If the target can evaluate the condition expression in hardware,
6756      then we we need to insert both watchpoints even if they are at
6757      the same place.  Otherwise the watchpoint will only trigger when
6758      the condition of whichever watchpoint was inserted evaluates to
6759      true, not giving a chance for GDB to check the condition of the
6760      other watchpoint.  */
6761   if ((w1->cond_exp
6762        && target_can_accel_watchpoint_condition (loc1->address, 
6763                                                  loc1->length,
6764                                                  loc1->watchpoint_type,
6765                                                  w1->cond_exp))
6766       || (w2->cond_exp
6767           && target_can_accel_watchpoint_condition (loc2->address, 
6768                                                     loc2->length,
6769                                                     loc2->watchpoint_type,
6770                                                     w2->cond_exp)))
6771     return 0;
6772
6773   /* Note that this checks the owner's type, not the location's.  In
6774      case the target does not support read watchpoints, but does
6775      support access watchpoints, we'll have bp_read_watchpoint
6776      watchpoints with hw_access locations.  Those should be considered
6777      duplicates of hw_read locations.  The hw_read locations will
6778      become hw_access locations later.  */
6779   return (loc1->owner->type == loc2->owner->type
6780           && loc1->pspace->aspace == loc2->pspace->aspace
6781           && loc1->address == loc2->address
6782           && loc1->length == loc2->length);
6783 }
6784
6785 /* Returns true if {ASPACE1,ADDR1} and {ASPACE2,ADDR2} represent the
6786    same breakpoint location.  In most targets, this can only be true
6787    if ASPACE1 matches ASPACE2.  On targets that have global
6788    breakpoints, the address space doesn't really matter.  */
6789
6790 static int
6791 breakpoint_address_match (struct address_space *aspace1, CORE_ADDR addr1,
6792                           struct address_space *aspace2, CORE_ADDR addr2)
6793 {
6794   return ((gdbarch_has_global_breakpoints (target_gdbarch ())
6795            || aspace1 == aspace2)
6796           && addr1 == addr2);
6797 }
6798
6799 /* Returns true if {ASPACE2,ADDR2} falls within the range determined by
6800    {ASPACE1,ADDR1,LEN1}.  In most targets, this can only be true if ASPACE1
6801    matches ASPACE2.  On targets that have global breakpoints, the address
6802    space doesn't really matter.  */
6803
6804 static int
6805 breakpoint_address_match_range (struct address_space *aspace1, CORE_ADDR addr1,
6806                                 int len1, struct address_space *aspace2,
6807                                 CORE_ADDR addr2)
6808 {
6809   return ((gdbarch_has_global_breakpoints (target_gdbarch ())
6810            || aspace1 == aspace2)
6811           && addr2 >= addr1 && addr2 < addr1 + len1);
6812 }
6813
6814 /* Returns true if {ASPACE,ADDR} matches the breakpoint BL.  BL may be
6815    a ranged breakpoint.  In most targets, a match happens only if ASPACE
6816    matches the breakpoint's address space.  On targets that have global
6817    breakpoints, the address space doesn't really matter.  */
6818
6819 static int
6820 breakpoint_location_address_match (struct bp_location *bl,
6821                                    struct address_space *aspace,
6822                                    CORE_ADDR addr)
6823 {
6824   return (breakpoint_address_match (bl->pspace->aspace, bl->address,
6825                                     aspace, addr)
6826           || (bl->length
6827               && breakpoint_address_match_range (bl->pspace->aspace,
6828                                                  bl->address, bl->length,
6829                                                  aspace, addr)));
6830 }
6831
6832 /* If LOC1 and LOC2's owners are not tracepoints, returns false directly.
6833    Then, if LOC1 and LOC2 represent the same tracepoint location, returns
6834    true, otherwise returns false.  */
6835
6836 static int
6837 tracepoint_locations_match (struct bp_location *loc1,
6838                             struct bp_location *loc2)
6839 {
6840   if (is_tracepoint (loc1->owner) && is_tracepoint (loc2->owner))
6841     /* Since tracepoint locations are never duplicated with others', tracepoint
6842        locations at the same address of different tracepoints are regarded as
6843        different locations.  */
6844     return (loc1->address == loc2->address && loc1->owner == loc2->owner);
6845   else
6846     return 0;
6847 }
6848
6849 /* Assuming LOC1 and LOC2's types' have meaningful target addresses
6850    (breakpoint_address_is_meaningful), returns true if LOC1 and LOC2
6851    represent the same location.  */
6852
6853 static int
6854 breakpoint_locations_match (struct bp_location *loc1, 
6855                             struct bp_location *loc2)
6856 {
6857   int hw_point1, hw_point2;
6858
6859   /* Both of them must not be in moribund_locations.  */
6860   gdb_assert (loc1->owner != NULL);
6861   gdb_assert (loc2->owner != NULL);
6862
6863   hw_point1 = is_hardware_watchpoint (loc1->owner);
6864   hw_point2 = is_hardware_watchpoint (loc2->owner);
6865
6866   if (hw_point1 != hw_point2)
6867     return 0;
6868   else if (hw_point1)
6869     return watchpoint_locations_match (loc1, loc2);
6870   else if (is_tracepoint (loc1->owner) || is_tracepoint (loc2->owner))
6871     return tracepoint_locations_match (loc1, loc2);
6872   else
6873     /* We compare bp_location.length in order to cover ranged breakpoints.  */
6874     return (breakpoint_address_match (loc1->pspace->aspace, loc1->address,
6875                                      loc2->pspace->aspace, loc2->address)
6876             && loc1->length == loc2->length);
6877 }
6878
6879 static void
6880 breakpoint_adjustment_warning (CORE_ADDR from_addr, CORE_ADDR to_addr,
6881                                int bnum, int have_bnum)
6882 {
6883   /* The longest string possibly returned by hex_string_custom
6884      is 50 chars.  These must be at least that big for safety.  */
6885   char astr1[64];
6886   char astr2[64];
6887
6888   strcpy (astr1, hex_string_custom ((unsigned long) from_addr, 8));
6889   strcpy (astr2, hex_string_custom ((unsigned long) to_addr, 8));
6890   if (have_bnum)
6891     warning (_("Breakpoint %d address previously adjusted from %s to %s."),
6892              bnum, astr1, astr2);
6893   else
6894     warning (_("Breakpoint address adjusted from %s to %s."), astr1, astr2);
6895 }
6896
6897 /* Adjust a breakpoint's address to account for architectural
6898    constraints on breakpoint placement.  Return the adjusted address.
6899    Note: Very few targets require this kind of adjustment.  For most
6900    targets, this function is simply the identity function.  */
6901
6902 static CORE_ADDR
6903 adjust_breakpoint_address (struct gdbarch *gdbarch,
6904                            CORE_ADDR bpaddr, enum bptype bptype)
6905 {
6906   if (!gdbarch_adjust_breakpoint_address_p (gdbarch))
6907     {
6908       /* Very few targets need any kind of breakpoint adjustment.  */
6909       return bpaddr;
6910     }
6911   else if (bptype == bp_watchpoint
6912            || bptype == bp_hardware_watchpoint
6913            || bptype == bp_read_watchpoint
6914            || bptype == bp_access_watchpoint
6915            || bptype == bp_catchpoint)
6916     {
6917       /* Watchpoints and the various bp_catch_* eventpoints should not
6918          have their addresses modified.  */
6919       return bpaddr;
6920     }
6921   else
6922     {
6923       CORE_ADDR adjusted_bpaddr;
6924
6925       /* Some targets have architectural constraints on the placement
6926          of breakpoint instructions.  Obtain the adjusted address.  */
6927       adjusted_bpaddr = gdbarch_adjust_breakpoint_address (gdbarch, bpaddr);
6928
6929       /* An adjusted breakpoint address can significantly alter
6930          a user's expectations.  Print a warning if an adjustment
6931          is required.  */
6932       if (adjusted_bpaddr != bpaddr)
6933         breakpoint_adjustment_warning (bpaddr, adjusted_bpaddr, 0, 0);
6934
6935       return adjusted_bpaddr;
6936     }
6937 }
6938
6939 void
6940 init_bp_location (struct bp_location *loc, const struct bp_location_ops *ops,
6941                   struct breakpoint *owner)
6942 {
6943   memset (loc, 0, sizeof (*loc));
6944
6945   gdb_assert (ops != NULL);
6946
6947   loc->ops = ops;
6948   loc->owner = owner;
6949   loc->cond = NULL;
6950   loc->cond_bytecode = NULL;
6951   loc->shlib_disabled = 0;
6952   loc->enabled = 1;
6953
6954   switch (owner->type)
6955     {
6956     case bp_breakpoint:
6957     case bp_until:
6958     case bp_finish:
6959     case bp_longjmp:
6960     case bp_longjmp_resume:
6961     case bp_longjmp_call_dummy:
6962     case bp_exception:
6963     case bp_exception_resume:
6964     case bp_step_resume:
6965     case bp_hp_step_resume:
6966     case bp_watchpoint_scope:
6967     case bp_call_dummy:
6968     case bp_std_terminate:
6969     case bp_shlib_event:
6970     case bp_thread_event:
6971     case bp_overlay_event:
6972     case bp_jit_event:
6973     case bp_longjmp_master:
6974     case bp_std_terminate_master:
6975     case bp_exception_master:
6976     case bp_gnu_ifunc_resolver:
6977     case bp_gnu_ifunc_resolver_return:
6978     case bp_dprintf:
6979       loc->loc_type = bp_loc_software_breakpoint;
6980       mark_breakpoint_location_modified (loc);
6981       break;
6982     case bp_hardware_breakpoint:
6983       loc->loc_type = bp_loc_hardware_breakpoint;
6984       mark_breakpoint_location_modified (loc);
6985       break;
6986     case bp_hardware_watchpoint:
6987     case bp_read_watchpoint:
6988     case bp_access_watchpoint:
6989       loc->loc_type = bp_loc_hardware_watchpoint;
6990       break;
6991     case bp_watchpoint:
6992     case bp_catchpoint:
6993     case bp_tracepoint:
6994     case bp_fast_tracepoint:
6995     case bp_static_tracepoint:
6996       loc->loc_type = bp_loc_other;
6997       break;
6998     default:
6999       internal_error (__FILE__, __LINE__, _("unknown breakpoint type"));
7000     }
7001
7002   loc->refc = 1;
7003 }
7004
7005 /* Allocate a struct bp_location.  */
7006
7007 static struct bp_location *
7008 allocate_bp_location (struct breakpoint *bpt)
7009 {
7010   return bpt->ops->allocate_location (bpt);
7011 }
7012
7013 static void
7014 free_bp_location (struct bp_location *loc)
7015 {
7016   loc->ops->dtor (loc);
7017   xfree (loc);
7018 }
7019
7020 /* Increment reference count.  */
7021
7022 static void
7023 incref_bp_location (struct bp_location *bl)
7024 {
7025   ++bl->refc;
7026 }
7027
7028 /* Decrement reference count.  If the reference count reaches 0,
7029    destroy the bp_location.  Sets *BLP to NULL.  */
7030
7031 static void
7032 decref_bp_location (struct bp_location **blp)
7033 {
7034   gdb_assert ((*blp)->refc > 0);
7035
7036   if (--(*blp)->refc == 0)
7037     free_bp_location (*blp);
7038   *blp = NULL;
7039 }
7040
7041 /* Add breakpoint B at the end of the global breakpoint chain.  */
7042
7043 static void
7044 add_to_breakpoint_chain (struct breakpoint *b)
7045 {
7046   struct breakpoint *b1;
7047
7048   /* Add this breakpoint to the end of the chain so that a list of
7049      breakpoints will come out in order of increasing numbers.  */
7050
7051   b1 = breakpoint_chain;
7052   if (b1 == 0)
7053     breakpoint_chain = b;
7054   else
7055     {
7056       while (b1->next)
7057         b1 = b1->next;
7058       b1->next = b;
7059     }
7060 }
7061
7062 /* Initializes breakpoint B with type BPTYPE and no locations yet.  */
7063
7064 static void
7065 init_raw_breakpoint_without_location (struct breakpoint *b,
7066                                       struct gdbarch *gdbarch,
7067                                       enum bptype bptype,
7068                                       const struct breakpoint_ops *ops)
7069 {
7070   memset (b, 0, sizeof (*b));
7071
7072   gdb_assert (ops != NULL);
7073
7074   b->ops = ops;
7075   b->type = bptype;
7076   b->gdbarch = gdbarch;
7077   b->language = current_language->la_language;
7078   b->input_radix = input_radix;
7079   b->thread = -1;
7080   b->enable_state = bp_enabled;
7081   b->next = 0;
7082   b->silent = 0;
7083   b->ignore_count = 0;
7084   b->commands = NULL;
7085   b->frame_id = null_frame_id;
7086   b->condition_not_parsed = 0;
7087   b->py_bp_object = NULL;
7088   b->related_breakpoint = b;
7089 }
7090
7091 /* Helper to set_raw_breakpoint below.  Creates a breakpoint
7092    that has type BPTYPE and has no locations as yet.  */
7093
7094 static struct breakpoint *
7095 set_raw_breakpoint_without_location (struct gdbarch *gdbarch,
7096                                      enum bptype bptype,
7097                                      const struct breakpoint_ops *ops)
7098 {
7099   struct breakpoint *b = XNEW (struct breakpoint);
7100
7101   init_raw_breakpoint_without_location (b, gdbarch, bptype, ops);
7102   add_to_breakpoint_chain (b);
7103   return b;
7104 }
7105
7106 /* Initialize loc->function_name.  EXPLICIT_LOC says no indirect function
7107    resolutions should be made as the user specified the location explicitly
7108    enough.  */
7109
7110 static void
7111 set_breakpoint_location_function (struct bp_location *loc, int explicit_loc)
7112 {
7113   gdb_assert (loc->owner != NULL);
7114
7115   if (loc->owner->type == bp_breakpoint
7116       || loc->owner->type == bp_hardware_breakpoint
7117       || is_tracepoint (loc->owner))
7118     {
7119       int is_gnu_ifunc;
7120       const char *function_name;
7121       CORE_ADDR func_addr;
7122
7123       find_pc_partial_function_gnu_ifunc (loc->address, &function_name,
7124                                           &func_addr, NULL, &is_gnu_ifunc);
7125
7126       if (is_gnu_ifunc && !explicit_loc)
7127         {
7128           struct breakpoint *b = loc->owner;
7129
7130           gdb_assert (loc->pspace == current_program_space);
7131           if (gnu_ifunc_resolve_name (function_name,
7132                                       &loc->requested_address))
7133             {
7134               /* Recalculate ADDRESS based on new REQUESTED_ADDRESS.  */
7135               loc->address = adjust_breakpoint_address (loc->gdbarch,
7136                                                         loc->requested_address,
7137                                                         b->type);
7138             }
7139           else if (b->type == bp_breakpoint && b->loc == loc
7140                    && loc->next == NULL && b->related_breakpoint == b)
7141             {
7142               /* Create only the whole new breakpoint of this type but do not
7143                  mess more complicated breakpoints with multiple locations.  */
7144               b->type = bp_gnu_ifunc_resolver;
7145               /* Remember the resolver's address for use by the return
7146                  breakpoint.  */
7147               loc->related_address = func_addr;
7148             }
7149         }
7150
7151       if (function_name)
7152         loc->function_name = xstrdup (function_name);
7153     }
7154 }
7155
7156 /* Attempt to determine architecture of location identified by SAL.  */
7157 struct gdbarch *
7158 get_sal_arch (struct symtab_and_line sal)
7159 {
7160   if (sal.section)
7161     return get_objfile_arch (sal.section->objfile);
7162   if (sal.symtab)
7163     return get_objfile_arch (sal.symtab->objfile);
7164
7165   return NULL;
7166 }
7167
7168 /* Low level routine for partially initializing a breakpoint of type
7169    BPTYPE.  The newly created breakpoint's address, section, source
7170    file name, and line number are provided by SAL.
7171
7172    It is expected that the caller will complete the initialization of
7173    the newly created breakpoint struct as well as output any status
7174    information regarding the creation of a new breakpoint.  */
7175
7176 static void
7177 init_raw_breakpoint (struct breakpoint *b, struct gdbarch *gdbarch,
7178                      struct symtab_and_line sal, enum bptype bptype,
7179                      const struct breakpoint_ops *ops)
7180 {
7181   init_raw_breakpoint_without_location (b, gdbarch, bptype, ops);
7182
7183   add_location_to_breakpoint (b, &sal);
7184
7185   if (bptype != bp_catchpoint)
7186     gdb_assert (sal.pspace != NULL);
7187
7188   /* Store the program space that was used to set the breakpoint,
7189      except for ordinary breakpoints, which are independent of the
7190      program space.  */
7191   if (bptype != bp_breakpoint && bptype != bp_hardware_breakpoint)
7192     b->pspace = sal.pspace;
7193 }
7194
7195 /* set_raw_breakpoint is a low level routine for allocating and
7196    partially initializing a breakpoint of type BPTYPE.  The newly
7197    created breakpoint's address, section, source file name, and line
7198    number are provided by SAL.  The newly created and partially
7199    initialized breakpoint is added to the breakpoint chain and
7200    is also returned as the value of this function.
7201
7202    It is expected that the caller will complete the initialization of
7203    the newly created breakpoint struct as well as output any status
7204    information regarding the creation of a new breakpoint.  In
7205    particular, set_raw_breakpoint does NOT set the breakpoint
7206    number!  Care should be taken to not allow an error to occur
7207    prior to completing the initialization of the breakpoint.  If this
7208    should happen, a bogus breakpoint will be left on the chain.  */
7209
7210 struct breakpoint *
7211 set_raw_breakpoint (struct gdbarch *gdbarch,
7212                     struct symtab_and_line sal, enum bptype bptype,
7213                     const struct breakpoint_ops *ops)
7214 {
7215   struct breakpoint *b = XNEW (struct breakpoint);
7216
7217   init_raw_breakpoint (b, gdbarch, sal, bptype, ops);
7218   add_to_breakpoint_chain (b);
7219   return b;
7220 }
7221
7222
7223 /* Note that the breakpoint object B describes a permanent breakpoint
7224    instruction, hard-wired into the inferior's code.  */
7225 void
7226 make_breakpoint_permanent (struct breakpoint *b)
7227 {
7228   struct bp_location *bl;
7229
7230   b->enable_state = bp_permanent;
7231
7232   /* By definition, permanent breakpoints are already present in the
7233      code.  Mark all locations as inserted.  For now,
7234      make_breakpoint_permanent is called in just one place, so it's
7235      hard to say if it's reasonable to have permanent breakpoint with
7236      multiple locations or not, but it's easy to implement.  */
7237   for (bl = b->loc; bl; bl = bl->next)
7238     bl->inserted = 1;
7239 }
7240
7241 /* Call this routine when stepping and nexting to enable a breakpoint
7242    if we do a longjmp() or 'throw' in TP.  FRAME is the frame which
7243    initiated the operation.  */
7244
7245 void
7246 set_longjmp_breakpoint (struct thread_info *tp, struct frame_id frame)
7247 {
7248   struct breakpoint *b, *b_tmp;
7249   int thread = tp->num;
7250
7251   /* To avoid having to rescan all objfile symbols at every step,
7252      we maintain a list of continually-inserted but always disabled
7253      longjmp "master" breakpoints.  Here, we simply create momentary
7254      clones of those and enable them for the requested thread.  */
7255   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7256     if (b->pspace == current_program_space
7257         && (b->type == bp_longjmp_master
7258             || b->type == bp_exception_master))
7259       {
7260         enum bptype type = b->type == bp_longjmp_master ? bp_longjmp : bp_exception;
7261         struct breakpoint *clone;
7262
7263         /* longjmp_breakpoint_ops ensures INITIATING_FRAME is cleared again
7264            after their removal.  */
7265         clone = momentary_breakpoint_from_master (b, type,
7266                                                   &longjmp_breakpoint_ops);
7267         clone->thread = thread;
7268       }
7269
7270   tp->initiating_frame = frame;
7271 }
7272
7273 /* Delete all longjmp breakpoints from THREAD.  */
7274 void
7275 delete_longjmp_breakpoint (int thread)
7276 {
7277   struct breakpoint *b, *b_tmp;
7278
7279   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7280     if (b->type == bp_longjmp || b->type == bp_exception)
7281       {
7282         if (b->thread == thread)
7283           delete_breakpoint (b);
7284       }
7285 }
7286
7287 void
7288 delete_longjmp_breakpoint_at_next_stop (int thread)
7289 {
7290   struct breakpoint *b, *b_tmp;
7291
7292   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7293     if (b->type == bp_longjmp || b->type == bp_exception)
7294       {
7295         if (b->thread == thread)
7296           b->disposition = disp_del_at_next_stop;
7297       }
7298 }
7299
7300 /* Place breakpoints of type bp_longjmp_call_dummy to catch longjmp for
7301    INFERIOR_PTID thread.  Chain them all by RELATED_BREAKPOINT and return
7302    pointer to any of them.  Return NULL if this system cannot place longjmp
7303    breakpoints.  */
7304
7305 struct breakpoint *
7306 set_longjmp_breakpoint_for_call_dummy (void)
7307 {
7308   struct breakpoint *b, *retval = NULL;
7309
7310   ALL_BREAKPOINTS (b)
7311     if (b->pspace == current_program_space && b->type == bp_longjmp_master)
7312       {
7313         struct breakpoint *new_b;
7314
7315         new_b = momentary_breakpoint_from_master (b, bp_longjmp_call_dummy,
7316                                                   &momentary_breakpoint_ops);
7317         new_b->thread = pid_to_thread_id (inferior_ptid);
7318
7319         /* Link NEW_B into the chain of RETVAL breakpoints.  */
7320
7321         gdb_assert (new_b->related_breakpoint == new_b);
7322         if (retval == NULL)
7323           retval = new_b;
7324         new_b->related_breakpoint = retval;
7325         while (retval->related_breakpoint != new_b->related_breakpoint)
7326           retval = retval->related_breakpoint;
7327         retval->related_breakpoint = new_b;
7328       }
7329
7330   return retval;
7331 }
7332
7333 /* Verify all existing dummy frames and their associated breakpoints for
7334    THREAD.  Remove those which can no longer be found in the current frame
7335    stack.
7336
7337    You should call this function only at places where it is safe to currently
7338    unwind the whole stack.  Failed stack unwind would discard live dummy
7339    frames.  */
7340
7341 void
7342 check_longjmp_breakpoint_for_call_dummy (int thread)
7343 {
7344   struct breakpoint *b, *b_tmp;
7345
7346   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7347     if (b->type == bp_longjmp_call_dummy && b->thread == thread)
7348       {
7349         struct breakpoint *dummy_b = b->related_breakpoint;
7350
7351         while (dummy_b != b && dummy_b->type != bp_call_dummy)
7352           dummy_b = dummy_b->related_breakpoint;
7353         if (dummy_b->type != bp_call_dummy
7354             || frame_find_by_id (dummy_b->frame_id) != NULL)
7355           continue;
7356         
7357         dummy_frame_discard (dummy_b->frame_id);
7358
7359         while (b->related_breakpoint != b)
7360           {
7361             if (b_tmp == b->related_breakpoint)
7362               b_tmp = b->related_breakpoint->next;
7363             delete_breakpoint (b->related_breakpoint);
7364           }
7365         delete_breakpoint (b);
7366       }
7367 }
7368
7369 void
7370 enable_overlay_breakpoints (void)
7371 {
7372   struct breakpoint *b;
7373
7374   ALL_BREAKPOINTS (b)
7375     if (b->type == bp_overlay_event)
7376     {
7377       b->enable_state = bp_enabled;
7378       update_global_location_list (1);
7379       overlay_events_enabled = 1;
7380     }
7381 }
7382
7383 void
7384 disable_overlay_breakpoints (void)
7385 {
7386   struct breakpoint *b;
7387
7388   ALL_BREAKPOINTS (b)
7389     if (b->type == bp_overlay_event)
7390     {
7391       b->enable_state = bp_disabled;
7392       update_global_location_list (0);
7393       overlay_events_enabled = 0;
7394     }
7395 }
7396
7397 /* Set an active std::terminate breakpoint for each std::terminate
7398    master breakpoint.  */
7399 void
7400 set_std_terminate_breakpoint (void)
7401 {
7402   struct breakpoint *b, *b_tmp;
7403
7404   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7405     if (b->pspace == current_program_space
7406         && b->type == bp_std_terminate_master)
7407       {
7408         momentary_breakpoint_from_master (b, bp_std_terminate,
7409                                           &momentary_breakpoint_ops);
7410       }
7411 }
7412
7413 /* Delete all the std::terminate breakpoints.  */
7414 void
7415 delete_std_terminate_breakpoint (void)
7416 {
7417   struct breakpoint *b, *b_tmp;
7418
7419   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7420     if (b->type == bp_std_terminate)
7421       delete_breakpoint (b);
7422 }
7423
7424 struct breakpoint *
7425 create_thread_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7426 {
7427   struct breakpoint *b;
7428
7429   b = create_internal_breakpoint (gdbarch, address, bp_thread_event,
7430                                   &internal_breakpoint_ops);
7431
7432   b->enable_state = bp_enabled;
7433   /* addr_string has to be used or breakpoint_re_set will delete me.  */
7434   b->addr_string
7435     = xstrprintf ("*%s", paddress (b->loc->gdbarch, b->loc->address));
7436
7437   update_global_location_list_nothrow (1);
7438
7439   return b;
7440 }
7441
7442 void
7443 remove_thread_event_breakpoints (void)
7444 {
7445   struct breakpoint *b, *b_tmp;
7446
7447   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7448     if (b->type == bp_thread_event
7449         && b->loc->pspace == current_program_space)
7450       delete_breakpoint (b);
7451 }
7452
7453 struct lang_and_radix
7454   {
7455     enum language lang;
7456     int radix;
7457   };
7458
7459 /* Create a breakpoint for JIT code registration and unregistration.  */
7460
7461 struct breakpoint *
7462 create_jit_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7463 {
7464   struct breakpoint *b;
7465
7466   b = create_internal_breakpoint (gdbarch, address, bp_jit_event,
7467                                   &internal_breakpoint_ops);
7468   update_global_location_list_nothrow (1);
7469   return b;
7470 }
7471
7472 /* Remove JIT code registration and unregistration breakpoint(s).  */
7473
7474 void
7475 remove_jit_event_breakpoints (void)
7476 {
7477   struct breakpoint *b, *b_tmp;
7478
7479   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7480     if (b->type == bp_jit_event
7481         && b->loc->pspace == current_program_space)
7482       delete_breakpoint (b);
7483 }
7484
7485 void
7486 remove_solib_event_breakpoints (void)
7487 {
7488   struct breakpoint *b, *b_tmp;
7489
7490   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7491     if (b->type == bp_shlib_event
7492         && b->loc->pspace == current_program_space)
7493       delete_breakpoint (b);
7494 }
7495
7496 struct breakpoint *
7497 create_solib_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7498 {
7499   struct breakpoint *b;
7500
7501   b = create_internal_breakpoint (gdbarch, address, bp_shlib_event,
7502                                   &internal_breakpoint_ops);
7503   update_global_location_list_nothrow (1);
7504   return b;
7505 }
7506
7507 /* Disable any breakpoints that are on code in shared libraries.  Only
7508    apply to enabled breakpoints, disabled ones can just stay disabled.  */
7509
7510 void
7511 disable_breakpoints_in_shlibs (void)
7512 {
7513   struct bp_location *loc, **locp_tmp;
7514
7515   ALL_BP_LOCATIONS (loc, locp_tmp)
7516   {
7517     /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
7518     struct breakpoint *b = loc->owner;
7519
7520     /* We apply the check to all breakpoints, including disabled for
7521        those with loc->duplicate set.  This is so that when breakpoint
7522        becomes enabled, or the duplicate is removed, gdb will try to
7523        insert all breakpoints.  If we don't set shlib_disabled here,
7524        we'll try to insert those breakpoints and fail.  */
7525     if (((b->type == bp_breakpoint)
7526          || (b->type == bp_jit_event)
7527          || (b->type == bp_hardware_breakpoint)
7528          || (is_tracepoint (b)))
7529         && loc->pspace == current_program_space
7530         && !loc->shlib_disabled
7531         && solib_name_from_address (loc->pspace, loc->address)
7532         )
7533       {
7534         loc->shlib_disabled = 1;
7535       }
7536   }
7537 }
7538
7539 /* Disable any breakpoints and tracepoints that are in SOLIB upon
7540    notification of unloaded_shlib.  Only apply to enabled breakpoints,
7541    disabled ones can just stay disabled.  */
7542
7543 static void
7544 disable_breakpoints_in_unloaded_shlib (struct so_list *solib)
7545 {
7546   struct bp_location *loc, **locp_tmp;
7547   int disabled_shlib_breaks = 0;
7548
7549   /* SunOS a.out shared libraries are always mapped, so do not
7550      disable breakpoints; they will only be reported as unloaded
7551      through clear_solib when GDB discards its shared library
7552      list.  See clear_solib for more information.  */
7553   if (exec_bfd != NULL
7554       && bfd_get_flavour (exec_bfd) == bfd_target_aout_flavour)
7555     return;
7556
7557   ALL_BP_LOCATIONS (loc, locp_tmp)
7558   {
7559     /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
7560     struct breakpoint *b = loc->owner;
7561
7562     if (solib->pspace == loc->pspace
7563         && !loc->shlib_disabled
7564         && (((b->type == bp_breakpoint
7565               || b->type == bp_jit_event
7566               || b->type == bp_hardware_breakpoint)
7567              && (loc->loc_type == bp_loc_hardware_breakpoint
7568                  || loc->loc_type == bp_loc_software_breakpoint))
7569             || is_tracepoint (b))
7570         && solib_contains_address_p (solib, loc->address))
7571       {
7572         loc->shlib_disabled = 1;
7573         /* At this point, we cannot rely on remove_breakpoint
7574            succeeding so we must mark the breakpoint as not inserted
7575            to prevent future errors occurring in remove_breakpoints.  */
7576         loc->inserted = 0;
7577
7578         /* This may cause duplicate notifications for the same breakpoint.  */
7579         observer_notify_breakpoint_modified (b);
7580
7581         if (!disabled_shlib_breaks)
7582           {
7583             target_terminal_ours_for_output ();
7584             warning (_("Temporarily disabling breakpoints "
7585                        "for unloaded shared library \"%s\""),
7586                      solib->so_name);
7587           }
7588         disabled_shlib_breaks = 1;
7589       }
7590   }
7591 }
7592
7593 /* Disable any breakpoints and tracepoints in OBJFILE upon
7594    notification of free_objfile.  Only apply to enabled breakpoints,
7595    disabled ones can just stay disabled.  */
7596
7597 static void
7598 disable_breakpoints_in_freed_objfile (struct objfile *objfile)
7599 {
7600   struct breakpoint *b;
7601
7602   if (objfile == NULL)
7603     return;
7604
7605   /* If the file is a shared library not loaded by the user then
7606      solib_unloaded was notified and disable_breakpoints_in_unloaded_shlib
7607      was called.  In that case there is no need to take action again.  */
7608   if ((objfile->flags & OBJF_SHARED) && !(objfile->flags & OBJF_USERLOADED))
7609     return;
7610
7611   ALL_BREAKPOINTS (b)
7612     {
7613       struct bp_location *loc;
7614       int bp_modified = 0;
7615
7616       if (!is_breakpoint (b) && !is_tracepoint (b))
7617         continue;
7618
7619       for (loc = b->loc; loc != NULL; loc = loc->next)
7620         {
7621           CORE_ADDR loc_addr = loc->address;
7622
7623           if (loc->loc_type != bp_loc_hardware_breakpoint
7624               && loc->loc_type != bp_loc_software_breakpoint)
7625             continue;
7626
7627           if (loc->shlib_disabled != 0)
7628             continue;
7629
7630           if (objfile->pspace != loc->pspace)
7631             continue;
7632
7633           if (loc->loc_type != bp_loc_hardware_breakpoint
7634               && loc->loc_type != bp_loc_software_breakpoint)
7635             continue;
7636
7637           if (is_addr_in_objfile (loc_addr, objfile))
7638             {
7639               loc->shlib_disabled = 1;
7640               loc->inserted = 0;
7641
7642               mark_breakpoint_location_modified (loc);
7643
7644               bp_modified = 1;
7645             }
7646         }
7647
7648       if (bp_modified)
7649         observer_notify_breakpoint_modified (b);
7650     }
7651 }
7652
7653 /* FORK & VFORK catchpoints.  */
7654
7655 /* An instance of this type is used to represent a fork or vfork
7656    catchpoint.  It includes a "struct breakpoint" as a kind of base
7657    class; users downcast to "struct breakpoint *" when needed.  A
7658    breakpoint is really of this type iff its ops pointer points to
7659    CATCH_FORK_BREAKPOINT_OPS.  */
7660
7661 struct fork_catchpoint
7662 {
7663   /* The base class.  */
7664   struct breakpoint base;
7665
7666   /* Process id of a child process whose forking triggered this
7667      catchpoint.  This field is only valid immediately after this
7668      catchpoint has triggered.  */
7669   ptid_t forked_inferior_pid;
7670 };
7671
7672 /* Implement the "insert" breakpoint_ops method for fork
7673    catchpoints.  */
7674
7675 static int
7676 insert_catch_fork (struct bp_location *bl)
7677 {
7678   return target_insert_fork_catchpoint (ptid_get_pid (inferior_ptid));
7679 }
7680
7681 /* Implement the "remove" breakpoint_ops method for fork
7682    catchpoints.  */
7683
7684 static int
7685 remove_catch_fork (struct bp_location *bl)
7686 {
7687   return target_remove_fork_catchpoint (ptid_get_pid (inferior_ptid));
7688 }
7689
7690 /* Implement the "breakpoint_hit" breakpoint_ops method for fork
7691    catchpoints.  */
7692
7693 static int
7694 breakpoint_hit_catch_fork (const struct bp_location *bl,
7695                            struct address_space *aspace, CORE_ADDR bp_addr,
7696                            const struct target_waitstatus *ws)
7697 {
7698   struct fork_catchpoint *c = (struct fork_catchpoint *) bl->owner;
7699
7700   if (ws->kind != TARGET_WAITKIND_FORKED)
7701     return 0;
7702
7703   c->forked_inferior_pid = ws->value.related_pid;
7704   return 1;
7705 }
7706
7707 /* Implement the "print_it" breakpoint_ops method for fork
7708    catchpoints.  */
7709
7710 static enum print_stop_action
7711 print_it_catch_fork (bpstat bs)
7712 {
7713   struct ui_out *uiout = current_uiout;
7714   struct breakpoint *b = bs->breakpoint_at;
7715   struct fork_catchpoint *c = (struct fork_catchpoint *) bs->breakpoint_at;
7716
7717   annotate_catchpoint (b->number);
7718   if (b->disposition == disp_del)
7719     ui_out_text (uiout, "\nTemporary catchpoint ");
7720   else
7721     ui_out_text (uiout, "\nCatchpoint ");
7722   if (ui_out_is_mi_like_p (uiout))
7723     {
7724       ui_out_field_string (uiout, "reason",
7725                            async_reason_lookup (EXEC_ASYNC_FORK));
7726       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
7727     }
7728   ui_out_field_int (uiout, "bkptno", b->number);
7729   ui_out_text (uiout, " (forked process ");
7730   ui_out_field_int (uiout, "newpid", ptid_get_pid (c->forked_inferior_pid));
7731   ui_out_text (uiout, "), ");
7732   return PRINT_SRC_AND_LOC;
7733 }
7734
7735 /* Implement the "print_one" breakpoint_ops method for fork
7736    catchpoints.  */
7737
7738 static void
7739 print_one_catch_fork (struct breakpoint *b, struct bp_location **last_loc)
7740 {
7741   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
7742   struct value_print_options opts;
7743   struct ui_out *uiout = current_uiout;
7744
7745   get_user_print_options (&opts);
7746
7747   /* Field 4, the address, is omitted (which makes the columns not
7748      line up too nicely with the headers, but the effect is relatively
7749      readable).  */
7750   if (opts.addressprint)
7751     ui_out_field_skip (uiout, "addr");
7752   annotate_field (5);
7753   ui_out_text (uiout, "fork");
7754   if (!ptid_equal (c->forked_inferior_pid, null_ptid))
7755     {
7756       ui_out_text (uiout, ", process ");
7757       ui_out_field_int (uiout, "what",
7758                         ptid_get_pid (c->forked_inferior_pid));
7759       ui_out_spaces (uiout, 1);
7760     }
7761
7762   if (ui_out_is_mi_like_p (uiout))
7763     ui_out_field_string (uiout, "catch-type", "fork");
7764 }
7765
7766 /* Implement the "print_mention" breakpoint_ops method for fork
7767    catchpoints.  */
7768
7769 static void
7770 print_mention_catch_fork (struct breakpoint *b)
7771 {
7772   printf_filtered (_("Catchpoint %d (fork)"), b->number);
7773 }
7774
7775 /* Implement the "print_recreate" breakpoint_ops method for fork
7776    catchpoints.  */
7777
7778 static void
7779 print_recreate_catch_fork (struct breakpoint *b, struct ui_file *fp)
7780 {
7781   fprintf_unfiltered (fp, "catch fork");
7782   print_recreate_thread (b, fp);
7783 }
7784
7785 /* The breakpoint_ops structure to be used in fork catchpoints.  */
7786
7787 static struct breakpoint_ops catch_fork_breakpoint_ops;
7788
7789 /* Implement the "insert" breakpoint_ops method for vfork
7790    catchpoints.  */
7791
7792 static int
7793 insert_catch_vfork (struct bp_location *bl)
7794 {
7795   return target_insert_vfork_catchpoint (ptid_get_pid (inferior_ptid));
7796 }
7797
7798 /* Implement the "remove" breakpoint_ops method for vfork
7799    catchpoints.  */
7800
7801 static int
7802 remove_catch_vfork (struct bp_location *bl)
7803 {
7804   return target_remove_vfork_catchpoint (ptid_get_pid (inferior_ptid));
7805 }
7806
7807 /* Implement the "breakpoint_hit" breakpoint_ops method for vfork
7808    catchpoints.  */
7809
7810 static int
7811 breakpoint_hit_catch_vfork (const struct bp_location *bl,
7812                             struct address_space *aspace, CORE_ADDR bp_addr,
7813                             const struct target_waitstatus *ws)
7814 {
7815   struct fork_catchpoint *c = (struct fork_catchpoint *) bl->owner;
7816
7817   if (ws->kind != TARGET_WAITKIND_VFORKED)
7818     return 0;
7819
7820   c->forked_inferior_pid = ws->value.related_pid;
7821   return 1;
7822 }
7823
7824 /* Implement the "print_it" breakpoint_ops method for vfork
7825    catchpoints.  */
7826
7827 static enum print_stop_action
7828 print_it_catch_vfork (bpstat bs)
7829 {
7830   struct ui_out *uiout = current_uiout;
7831   struct breakpoint *b = bs->breakpoint_at;
7832   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
7833
7834   annotate_catchpoint (b->number);
7835   if (b->disposition == disp_del)
7836     ui_out_text (uiout, "\nTemporary catchpoint ");
7837   else
7838     ui_out_text (uiout, "\nCatchpoint ");
7839   if (ui_out_is_mi_like_p (uiout))
7840     {
7841       ui_out_field_string (uiout, "reason",
7842                            async_reason_lookup (EXEC_ASYNC_VFORK));
7843       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
7844     }
7845   ui_out_field_int (uiout, "bkptno", b->number);
7846   ui_out_text (uiout, " (vforked process ");
7847   ui_out_field_int (uiout, "newpid", ptid_get_pid (c->forked_inferior_pid));
7848   ui_out_text (uiout, "), ");
7849   return PRINT_SRC_AND_LOC;
7850 }
7851
7852 /* Implement the "print_one" breakpoint_ops method for vfork
7853    catchpoints.  */
7854
7855 static void
7856 print_one_catch_vfork (struct breakpoint *b, struct bp_location **last_loc)
7857 {
7858   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
7859   struct value_print_options opts;
7860   struct ui_out *uiout = current_uiout;
7861
7862   get_user_print_options (&opts);
7863   /* Field 4, the address, is omitted (which makes the columns not
7864      line up too nicely with the headers, but the effect is relatively
7865      readable).  */
7866   if (opts.addressprint)
7867     ui_out_field_skip (uiout, "addr");
7868   annotate_field (5);
7869   ui_out_text (uiout, "vfork");
7870   if (!ptid_equal (c->forked_inferior_pid, null_ptid))
7871     {
7872       ui_out_text (uiout, ", process ");
7873       ui_out_field_int (uiout, "what",
7874                         ptid_get_pid (c->forked_inferior_pid));
7875       ui_out_spaces (uiout, 1);
7876     }
7877
7878   if (ui_out_is_mi_like_p (uiout))
7879     ui_out_field_string (uiout, "catch-type", "vfork");
7880 }
7881
7882 /* Implement the "print_mention" breakpoint_ops method for vfork
7883    catchpoints.  */
7884
7885 static void
7886 print_mention_catch_vfork (struct breakpoint *b)
7887 {
7888   printf_filtered (_("Catchpoint %d (vfork)"), b->number);
7889 }
7890
7891 /* Implement the "print_recreate" breakpoint_ops method for vfork
7892    catchpoints.  */
7893
7894 static void
7895 print_recreate_catch_vfork (struct breakpoint *b, struct ui_file *fp)
7896 {
7897   fprintf_unfiltered (fp, "catch vfork");
7898   print_recreate_thread (b, fp);
7899 }
7900
7901 /* The breakpoint_ops structure to be used in vfork catchpoints.  */
7902
7903 static struct breakpoint_ops catch_vfork_breakpoint_ops;
7904
7905 /* An instance of this type is used to represent an solib catchpoint.
7906    It includes a "struct breakpoint" as a kind of base class; users
7907    downcast to "struct breakpoint *" when needed.  A breakpoint is
7908    really of this type iff its ops pointer points to
7909    CATCH_SOLIB_BREAKPOINT_OPS.  */
7910
7911 struct solib_catchpoint
7912 {
7913   /* The base class.  */
7914   struct breakpoint base;
7915
7916   /* True for "catch load", false for "catch unload".  */
7917   unsigned char is_load;
7918
7919   /* Regular expression to match, if any.  COMPILED is only valid when
7920      REGEX is non-NULL.  */
7921   char *regex;
7922   regex_t compiled;
7923 };
7924
7925 static void
7926 dtor_catch_solib (struct breakpoint *b)
7927 {
7928   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
7929
7930   if (self->regex)
7931     regfree (&self->compiled);
7932   xfree (self->regex);
7933
7934   base_breakpoint_ops.dtor (b);
7935 }
7936
7937 static int
7938 insert_catch_solib (struct bp_location *ignore)
7939 {
7940   return 0;
7941 }
7942
7943 static int
7944 remove_catch_solib (struct bp_location *ignore)
7945 {
7946   return 0;
7947 }
7948
7949 static int
7950 breakpoint_hit_catch_solib (const struct bp_location *bl,
7951                             struct address_space *aspace,
7952                             CORE_ADDR bp_addr,
7953                             const struct target_waitstatus *ws)
7954 {
7955   struct solib_catchpoint *self = (struct solib_catchpoint *) bl->owner;
7956   struct breakpoint *other;
7957
7958   if (ws->kind == TARGET_WAITKIND_LOADED)
7959     return 1;
7960
7961   ALL_BREAKPOINTS (other)
7962   {
7963     struct bp_location *other_bl;
7964
7965     if (other == bl->owner)
7966       continue;
7967
7968     if (other->type != bp_shlib_event)
7969       continue;
7970
7971     if (self->base.pspace != NULL && other->pspace != self->base.pspace)
7972       continue;
7973
7974     for (other_bl = other->loc; other_bl != NULL; other_bl = other_bl->next)
7975       {
7976         if (other->ops->breakpoint_hit (other_bl, aspace, bp_addr, ws))
7977           return 1;
7978       }
7979   }
7980
7981   return 0;
7982 }
7983
7984 static void
7985 check_status_catch_solib (struct bpstats *bs)
7986 {
7987   struct solib_catchpoint *self
7988     = (struct solib_catchpoint *) bs->breakpoint_at;
7989   int ix;
7990
7991   if (self->is_load)
7992     {
7993       struct so_list *iter;
7994
7995       for (ix = 0;
7996            VEC_iterate (so_list_ptr, current_program_space->added_solibs,
7997                         ix, iter);
7998            ++ix)
7999         {
8000           if (!self->regex
8001               || regexec (&self->compiled, iter->so_name, 0, NULL, 0) == 0)
8002             return;
8003         }
8004     }
8005   else
8006     {
8007       char *iter;
8008
8009       for (ix = 0;
8010            VEC_iterate (char_ptr, current_program_space->deleted_solibs,
8011                         ix, iter);
8012            ++ix)
8013         {
8014           if (!self->regex
8015               || regexec (&self->compiled, iter, 0, NULL, 0) == 0)
8016             return;
8017         }
8018     }
8019
8020   bs->stop = 0;
8021   bs->print_it = print_it_noop;
8022 }
8023
8024 static enum print_stop_action
8025 print_it_catch_solib (bpstat bs)
8026 {
8027   struct breakpoint *b = bs->breakpoint_at;
8028   struct ui_out *uiout = current_uiout;
8029
8030   annotate_catchpoint (b->number);
8031   if (b->disposition == disp_del)
8032     ui_out_text (uiout, "\nTemporary catchpoint ");
8033   else
8034     ui_out_text (uiout, "\nCatchpoint ");
8035   ui_out_field_int (uiout, "bkptno", b->number);
8036   ui_out_text (uiout, "\n");
8037   if (ui_out_is_mi_like_p (uiout))
8038     ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
8039   print_solib_event (1);
8040   return PRINT_SRC_AND_LOC;
8041 }
8042
8043 static void
8044 print_one_catch_solib (struct breakpoint *b, struct bp_location **locs)
8045 {
8046   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8047   struct value_print_options opts;
8048   struct ui_out *uiout = current_uiout;
8049   char *msg;
8050
8051   get_user_print_options (&opts);
8052   /* Field 4, the address, is omitted (which makes the columns not
8053      line up too nicely with the headers, but the effect is relatively
8054      readable).  */
8055   if (opts.addressprint)
8056     {
8057       annotate_field (4);
8058       ui_out_field_skip (uiout, "addr");
8059     }
8060
8061   annotate_field (5);
8062   if (self->is_load)
8063     {
8064       if (self->regex)
8065         msg = xstrprintf (_("load of library matching %s"), self->regex);
8066       else
8067         msg = xstrdup (_("load of library"));
8068     }
8069   else
8070     {
8071       if (self->regex)
8072         msg = xstrprintf (_("unload of library matching %s"), self->regex);
8073       else
8074         msg = xstrdup (_("unload of library"));
8075     }
8076   ui_out_field_string (uiout, "what", msg);
8077   xfree (msg);
8078
8079   if (ui_out_is_mi_like_p (uiout))
8080     ui_out_field_string (uiout, "catch-type",
8081                          self->is_load ? "load" : "unload");
8082 }
8083
8084 static void
8085 print_mention_catch_solib (struct breakpoint *b)
8086 {
8087   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8088
8089   printf_filtered (_("Catchpoint %d (%s)"), b->number,
8090                    self->is_load ? "load" : "unload");
8091 }
8092
8093 static void
8094 print_recreate_catch_solib (struct breakpoint *b, struct ui_file *fp)
8095 {
8096   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8097
8098   fprintf_unfiltered (fp, "%s %s",
8099                       b->disposition == disp_del ? "tcatch" : "catch",
8100                       self->is_load ? "load" : "unload");
8101   if (self->regex)
8102     fprintf_unfiltered (fp, " %s", self->regex);
8103   fprintf_unfiltered (fp, "\n");
8104 }
8105
8106 static struct breakpoint_ops catch_solib_breakpoint_ops;
8107
8108 /* Shared helper function (MI and CLI) for creating and installing
8109    a shared object event catchpoint.  If IS_LOAD is non-zero then
8110    the events to be caught are load events, otherwise they are
8111    unload events.  If IS_TEMP is non-zero the catchpoint is a
8112    temporary one.  If ENABLED is non-zero the catchpoint is
8113    created in an enabled state.  */
8114
8115 void
8116 add_solib_catchpoint (char *arg, int is_load, int is_temp, int enabled)
8117 {
8118   struct solib_catchpoint *c;
8119   struct gdbarch *gdbarch = get_current_arch ();
8120   struct cleanup *cleanup;
8121
8122   if (!arg)
8123     arg = "";
8124   arg = skip_spaces (arg);
8125
8126   c = XCNEW (struct solib_catchpoint);
8127   cleanup = make_cleanup (xfree, c);
8128
8129   if (*arg != '\0')
8130     {
8131       int errcode;
8132
8133       errcode = regcomp (&c->compiled, arg, REG_NOSUB);
8134       if (errcode != 0)
8135         {
8136           char *err = get_regcomp_error (errcode, &c->compiled);
8137
8138           make_cleanup (xfree, err);
8139           error (_("Invalid regexp (%s): %s"), err, arg);
8140         }
8141       c->regex = xstrdup (arg);
8142     }
8143
8144   c->is_load = is_load;
8145   init_catchpoint (&c->base, gdbarch, is_temp, NULL,
8146                    &catch_solib_breakpoint_ops);
8147
8148   c->base.enable_state = enabled ? bp_enabled : bp_disabled;
8149
8150   discard_cleanups (cleanup);
8151   install_breakpoint (0, &c->base, 1);
8152 }
8153
8154 /* A helper function that does all the work for "catch load" and
8155    "catch unload".  */
8156
8157 static void
8158 catch_load_or_unload (char *arg, int from_tty, int is_load,
8159                       struct cmd_list_element *command)
8160 {
8161   int tempflag;
8162   const int enabled = 1;
8163
8164   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
8165
8166   add_solib_catchpoint (arg, is_load, tempflag, enabled);
8167 }
8168
8169 static void
8170 catch_load_command_1 (char *arg, int from_tty,
8171                       struct cmd_list_element *command)
8172 {
8173   catch_load_or_unload (arg, from_tty, 1, command);
8174 }
8175
8176 static void
8177 catch_unload_command_1 (char *arg, int from_tty,
8178                         struct cmd_list_element *command)
8179 {
8180   catch_load_or_unload (arg, from_tty, 0, command);
8181 }
8182
8183 /* An instance of this type is used to represent a syscall catchpoint.
8184    It includes a "struct breakpoint" as a kind of base class; users
8185    downcast to "struct breakpoint *" when needed.  A breakpoint is
8186    really of this type iff its ops pointer points to
8187    CATCH_SYSCALL_BREAKPOINT_OPS.  */
8188
8189 struct syscall_catchpoint
8190 {
8191   /* The base class.  */
8192   struct breakpoint base;
8193
8194   /* Syscall numbers used for the 'catch syscall' feature.  If no
8195      syscall has been specified for filtering, its value is NULL.
8196      Otherwise, it holds a list of all syscalls to be caught.  The
8197      list elements are allocated with xmalloc.  */
8198   VEC(int) *syscalls_to_be_caught;
8199 };
8200
8201 /* Implement the "dtor" breakpoint_ops method for syscall
8202    catchpoints.  */
8203
8204 static void
8205 dtor_catch_syscall (struct breakpoint *b)
8206 {
8207   struct syscall_catchpoint *c = (struct syscall_catchpoint *) b;
8208
8209   VEC_free (int, c->syscalls_to_be_caught);
8210
8211   base_breakpoint_ops.dtor (b);
8212 }
8213
8214 static const struct inferior_data *catch_syscall_inferior_data = NULL;
8215
8216 struct catch_syscall_inferior_data
8217 {
8218   /* We keep a count of the number of times the user has requested a
8219      particular syscall to be tracked, and pass this information to the
8220      target.  This lets capable targets implement filtering directly.  */
8221
8222   /* Number of times that "any" syscall is requested.  */
8223   int any_syscall_count;
8224
8225   /* Count of each system call.  */
8226   VEC(int) *syscalls_counts;
8227
8228   /* This counts all syscall catch requests, so we can readily determine
8229      if any catching is necessary.  */
8230   int total_syscalls_count;
8231 };
8232
8233 static struct catch_syscall_inferior_data*
8234 get_catch_syscall_inferior_data (struct inferior *inf)
8235 {
8236   struct catch_syscall_inferior_data *inf_data;
8237
8238   inf_data = inferior_data (inf, catch_syscall_inferior_data);
8239   if (inf_data == NULL)
8240     {
8241       inf_data = XCNEW (struct catch_syscall_inferior_data);
8242       set_inferior_data (inf, catch_syscall_inferior_data, inf_data);
8243     }
8244
8245   return inf_data;
8246 }
8247
8248 static void
8249 catch_syscall_inferior_data_cleanup (struct inferior *inf, void *arg)
8250 {
8251   xfree (arg);
8252 }
8253
8254
8255 /* Implement the "insert" breakpoint_ops method for syscall
8256    catchpoints.  */
8257
8258 static int
8259 insert_catch_syscall (struct bp_location *bl)
8260 {
8261   struct syscall_catchpoint *c = (struct syscall_catchpoint *) bl->owner;
8262   struct inferior *inf = current_inferior ();
8263   struct catch_syscall_inferior_data *inf_data
8264     = get_catch_syscall_inferior_data (inf);
8265
8266   ++inf_data->total_syscalls_count;
8267   if (!c->syscalls_to_be_caught)
8268     ++inf_data->any_syscall_count;
8269   else
8270     {
8271       int i, iter;
8272
8273       for (i = 0;
8274            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
8275            i++)
8276         {
8277           int elem;
8278
8279           if (iter >= VEC_length (int, inf_data->syscalls_counts))
8280             {
8281               int old_size = VEC_length (int, inf_data->syscalls_counts);
8282               uintptr_t vec_addr_offset
8283                 = old_size * ((uintptr_t) sizeof (int));
8284               uintptr_t vec_addr;
8285               VEC_safe_grow (int, inf_data->syscalls_counts, iter + 1);
8286               vec_addr = ((uintptr_t) VEC_address (int,
8287                                                   inf_data->syscalls_counts)
8288                           + vec_addr_offset);
8289               memset ((void *) vec_addr, 0,
8290                       (iter + 1 - old_size) * sizeof (int));
8291             }
8292           elem = VEC_index (int, inf_data->syscalls_counts, iter);
8293           VEC_replace (int, inf_data->syscalls_counts, iter, ++elem);
8294         }
8295     }
8296
8297   return target_set_syscall_catchpoint (ptid_get_pid (inferior_ptid),
8298                                         inf_data->total_syscalls_count != 0,
8299                                         inf_data->any_syscall_count,
8300                                         VEC_length (int,
8301                                                     inf_data->syscalls_counts),
8302                                         VEC_address (int,
8303                                                      inf_data->syscalls_counts));
8304 }
8305
8306 /* Implement the "remove" breakpoint_ops method for syscall
8307    catchpoints.  */
8308
8309 static int
8310 remove_catch_syscall (struct bp_location *bl)
8311 {
8312   struct syscall_catchpoint *c = (struct syscall_catchpoint *) bl->owner;
8313   struct inferior *inf = current_inferior ();
8314   struct catch_syscall_inferior_data *inf_data
8315     = get_catch_syscall_inferior_data (inf);
8316
8317   --inf_data->total_syscalls_count;
8318   if (!c->syscalls_to_be_caught)
8319     --inf_data->any_syscall_count;
8320   else
8321     {
8322       int i, iter;
8323
8324       for (i = 0;
8325            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
8326            i++)
8327         {
8328           int elem;
8329           if (iter >= VEC_length (int, inf_data->syscalls_counts))
8330             /* Shouldn't happen.  */
8331             continue;
8332           elem = VEC_index (int, inf_data->syscalls_counts, iter);
8333           VEC_replace (int, inf_data->syscalls_counts, iter, --elem);
8334         }
8335     }
8336
8337   return target_set_syscall_catchpoint (ptid_get_pid (inferior_ptid),
8338                                         inf_data->total_syscalls_count != 0,
8339                                         inf_data->any_syscall_count,
8340                                         VEC_length (int,
8341                                                     inf_data->syscalls_counts),
8342                                         VEC_address (int,
8343                                                      inf_data->syscalls_counts));
8344 }
8345
8346 /* Implement the "breakpoint_hit" breakpoint_ops method for syscall
8347    catchpoints.  */
8348
8349 static int
8350 breakpoint_hit_catch_syscall (const struct bp_location *bl,
8351                               struct address_space *aspace, CORE_ADDR bp_addr,
8352                               const struct target_waitstatus *ws)
8353 {
8354   /* We must check if we are catching specific syscalls in this
8355      breakpoint.  If we are, then we must guarantee that the called
8356      syscall is the same syscall we are catching.  */
8357   int syscall_number = 0;
8358   const struct syscall_catchpoint *c
8359     = (const struct syscall_catchpoint *) bl->owner;
8360
8361   if (ws->kind != TARGET_WAITKIND_SYSCALL_ENTRY
8362       && ws->kind != TARGET_WAITKIND_SYSCALL_RETURN)
8363     return 0;
8364
8365   syscall_number = ws->value.syscall_number;
8366
8367   /* Now, checking if the syscall is the same.  */
8368   if (c->syscalls_to_be_caught)
8369     {
8370       int i, iter;
8371
8372       for (i = 0;
8373            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
8374            i++)
8375         if (syscall_number == iter)
8376           return 1;
8377
8378       return 0;
8379     }
8380
8381   return 1;
8382 }
8383
8384 /* Implement the "print_it" breakpoint_ops method for syscall
8385    catchpoints.  */
8386
8387 static enum print_stop_action
8388 print_it_catch_syscall (bpstat bs)
8389 {
8390   struct ui_out *uiout = current_uiout;
8391   struct breakpoint *b = bs->breakpoint_at;
8392   /* These are needed because we want to know in which state a
8393      syscall is.  It can be in the TARGET_WAITKIND_SYSCALL_ENTRY
8394      or TARGET_WAITKIND_SYSCALL_RETURN, and depending on it we
8395      must print "called syscall" or "returned from syscall".  */
8396   ptid_t ptid;
8397   struct target_waitstatus last;
8398   struct syscall s;
8399
8400   get_last_target_status (&ptid, &last);
8401
8402   get_syscall_by_number (last.value.syscall_number, &s);
8403
8404   annotate_catchpoint (b->number);
8405
8406   if (b->disposition == disp_del)
8407     ui_out_text (uiout, "\nTemporary catchpoint ");
8408   else
8409     ui_out_text (uiout, "\nCatchpoint ");
8410   if (ui_out_is_mi_like_p (uiout))
8411     {
8412       ui_out_field_string (uiout, "reason",
8413                            async_reason_lookup (last.kind == TARGET_WAITKIND_SYSCALL_ENTRY
8414                                                 ? EXEC_ASYNC_SYSCALL_ENTRY
8415                                                 : EXEC_ASYNC_SYSCALL_RETURN));
8416       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
8417     }
8418   ui_out_field_int (uiout, "bkptno", b->number);
8419
8420   if (last.kind == TARGET_WAITKIND_SYSCALL_ENTRY)
8421     ui_out_text (uiout, " (call to syscall ");
8422   else
8423     ui_out_text (uiout, " (returned from syscall ");
8424
8425   if (s.name == NULL || ui_out_is_mi_like_p (uiout))
8426     ui_out_field_int (uiout, "syscall-number", last.value.syscall_number);
8427   if (s.name != NULL)
8428     ui_out_field_string (uiout, "syscall-name", s.name);
8429
8430   ui_out_text (uiout, "), ");
8431
8432   return PRINT_SRC_AND_LOC;
8433 }
8434
8435 /* Implement the "print_one" breakpoint_ops method for syscall
8436    catchpoints.  */
8437
8438 static void
8439 print_one_catch_syscall (struct breakpoint *b,
8440                          struct bp_location **last_loc)
8441 {
8442   struct syscall_catchpoint *c = (struct syscall_catchpoint *) b;
8443   struct value_print_options opts;
8444   struct ui_out *uiout = current_uiout;
8445
8446   get_user_print_options (&opts);
8447   /* Field 4, the address, is omitted (which makes the columns not
8448      line up too nicely with the headers, but the effect is relatively
8449      readable).  */
8450   if (opts.addressprint)
8451     ui_out_field_skip (uiout, "addr");
8452   annotate_field (5);
8453
8454   if (c->syscalls_to_be_caught
8455       && VEC_length (int, c->syscalls_to_be_caught) > 1)
8456     ui_out_text (uiout, "syscalls \"");
8457   else
8458     ui_out_text (uiout, "syscall \"");
8459
8460   if (c->syscalls_to_be_caught)
8461     {
8462       int i, iter;
8463       char *text = xstrprintf ("%s", "");
8464
8465       for (i = 0;
8466            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
8467            i++)
8468         {
8469           char *x = text;
8470           struct syscall s;
8471           get_syscall_by_number (iter, &s);
8472
8473           if (s.name != NULL)
8474             text = xstrprintf ("%s%s, ", text, s.name);
8475           else
8476             text = xstrprintf ("%s%d, ", text, iter);
8477
8478           /* We have to xfree the last 'text' (now stored at 'x')
8479              because xstrprintf dynamically allocates new space for it
8480              on every call.  */
8481           xfree (x);
8482         }
8483       /* Remove the last comma.  */
8484       text[strlen (text) - 2] = '\0';
8485       ui_out_field_string (uiout, "what", text);
8486     }
8487   else
8488     ui_out_field_string (uiout, "what", "<any syscall>");
8489   ui_out_text (uiout, "\" ");
8490
8491   if (ui_out_is_mi_like_p (uiout))
8492     ui_out_field_string (uiout, "catch-type", "syscall");
8493 }
8494
8495 /* Implement the "print_mention" breakpoint_ops method for syscall
8496    catchpoints.  */
8497
8498 static void
8499 print_mention_catch_syscall (struct breakpoint *b)
8500 {
8501   struct syscall_catchpoint *c = (struct syscall_catchpoint *) b;
8502
8503   if (c->syscalls_to_be_caught)
8504     {
8505       int i, iter;
8506
8507       if (VEC_length (int, c->syscalls_to_be_caught) > 1)
8508         printf_filtered (_("Catchpoint %d (syscalls"), b->number);
8509       else
8510         printf_filtered (_("Catchpoint %d (syscall"), b->number);
8511
8512       for (i = 0;
8513            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
8514            i++)
8515         {
8516           struct syscall s;
8517           get_syscall_by_number (iter, &s);
8518
8519           if (s.name)
8520             printf_filtered (" '%s' [%d]", s.name, s.number);
8521           else
8522             printf_filtered (" %d", s.number);
8523         }
8524       printf_filtered (")");
8525     }
8526   else
8527     printf_filtered (_("Catchpoint %d (any syscall)"),
8528                      b->number);
8529 }
8530
8531 /* Implement the "print_recreate" breakpoint_ops method for syscall
8532    catchpoints.  */
8533
8534 static void
8535 print_recreate_catch_syscall (struct breakpoint *b, struct ui_file *fp)
8536 {
8537   struct syscall_catchpoint *c = (struct syscall_catchpoint *) b;
8538
8539   fprintf_unfiltered (fp, "catch syscall");
8540
8541   if (c->syscalls_to_be_caught)
8542     {
8543       int i, iter;
8544
8545       for (i = 0;
8546            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
8547            i++)
8548         {
8549           struct syscall s;
8550
8551           get_syscall_by_number (iter, &s);
8552           if (s.name)
8553             fprintf_unfiltered (fp, " %s", s.name);
8554           else
8555             fprintf_unfiltered (fp, " %d", s.number);
8556         }
8557     }
8558   print_recreate_thread (b, fp);
8559 }
8560
8561 /* The breakpoint_ops structure to be used in syscall catchpoints.  */
8562
8563 static struct breakpoint_ops catch_syscall_breakpoint_ops;
8564
8565 /* Returns non-zero if 'b' is a syscall catchpoint.  */
8566
8567 static int
8568 syscall_catchpoint_p (struct breakpoint *b)
8569 {
8570   return (b->ops == &catch_syscall_breakpoint_ops);
8571 }
8572
8573 /* Initialize a new breakpoint of the bp_catchpoint kind.  If TEMPFLAG
8574    is non-zero, then make the breakpoint temporary.  If COND_STRING is
8575    not NULL, then store it in the breakpoint.  OPS, if not NULL, is
8576    the breakpoint_ops structure associated to the catchpoint.  */
8577
8578 void
8579 init_catchpoint (struct breakpoint *b,
8580                  struct gdbarch *gdbarch, int tempflag,
8581                  char *cond_string,
8582                  const struct breakpoint_ops *ops)
8583 {
8584   struct symtab_and_line sal;
8585
8586   init_sal (&sal);
8587   sal.pspace = current_program_space;
8588
8589   init_raw_breakpoint (b, gdbarch, sal, bp_catchpoint, ops);
8590
8591   b->cond_string = (cond_string == NULL) ? NULL : xstrdup (cond_string);
8592   b->disposition = tempflag ? disp_del : disp_donttouch;
8593 }
8594
8595 void
8596 install_breakpoint (int internal, struct breakpoint *b, int update_gll)
8597 {
8598   add_to_breakpoint_chain (b);
8599   set_breakpoint_number (internal, b);
8600   if (is_tracepoint (b))
8601     set_tracepoint_count (breakpoint_count);
8602   if (!internal)
8603     mention (b);
8604   observer_notify_breakpoint_created (b);
8605
8606   if (update_gll)
8607     update_global_location_list (1);
8608 }
8609
8610 static void
8611 create_fork_vfork_event_catchpoint (struct gdbarch *gdbarch,
8612                                     int tempflag, char *cond_string,
8613                                     const struct breakpoint_ops *ops)
8614 {
8615   struct fork_catchpoint *c = XNEW (struct fork_catchpoint);
8616
8617   init_catchpoint (&c->base, gdbarch, tempflag, cond_string, ops);
8618
8619   c->forked_inferior_pid = null_ptid;
8620
8621   install_breakpoint (0, &c->base, 1);
8622 }
8623
8624 /* Exec catchpoints.  */
8625
8626 /* An instance of this type is used to represent an exec catchpoint.
8627    It includes a "struct breakpoint" as a kind of base class; users
8628    downcast to "struct breakpoint *" when needed.  A breakpoint is
8629    really of this type iff its ops pointer points to
8630    CATCH_EXEC_BREAKPOINT_OPS.  */
8631
8632 struct exec_catchpoint
8633 {
8634   /* The base class.  */
8635   struct breakpoint base;
8636
8637   /* Filename of a program whose exec triggered this catchpoint.
8638      This field is only valid immediately after this catchpoint has
8639      triggered.  */
8640   char *exec_pathname;
8641 };
8642
8643 /* Implement the "dtor" breakpoint_ops method for exec
8644    catchpoints.  */
8645
8646 static void
8647 dtor_catch_exec (struct breakpoint *b)
8648 {
8649   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
8650
8651   xfree (c->exec_pathname);
8652
8653   base_breakpoint_ops.dtor (b);
8654 }
8655
8656 static int
8657 insert_catch_exec (struct bp_location *bl)
8658 {
8659   return target_insert_exec_catchpoint (ptid_get_pid (inferior_ptid));
8660 }
8661
8662 static int
8663 remove_catch_exec (struct bp_location *bl)
8664 {
8665   return target_remove_exec_catchpoint (ptid_get_pid (inferior_ptid));
8666 }
8667
8668 static int
8669 breakpoint_hit_catch_exec (const struct bp_location *bl,
8670                            struct address_space *aspace, CORE_ADDR bp_addr,
8671                            const struct target_waitstatus *ws)
8672 {
8673   struct exec_catchpoint *c = (struct exec_catchpoint *) bl->owner;
8674
8675   if (ws->kind != TARGET_WAITKIND_EXECD)
8676     return 0;
8677
8678   c->exec_pathname = xstrdup (ws->value.execd_pathname);
8679   return 1;
8680 }
8681
8682 static enum print_stop_action
8683 print_it_catch_exec (bpstat bs)
8684 {
8685   struct ui_out *uiout = current_uiout;
8686   struct breakpoint *b = bs->breakpoint_at;
8687   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
8688
8689   annotate_catchpoint (b->number);
8690   if (b->disposition == disp_del)
8691     ui_out_text (uiout, "\nTemporary catchpoint ");
8692   else
8693     ui_out_text (uiout, "\nCatchpoint ");
8694   if (ui_out_is_mi_like_p (uiout))
8695     {
8696       ui_out_field_string (uiout, "reason",
8697                            async_reason_lookup (EXEC_ASYNC_EXEC));
8698       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
8699     }
8700   ui_out_field_int (uiout, "bkptno", b->number);
8701   ui_out_text (uiout, " (exec'd ");
8702   ui_out_field_string (uiout, "new-exec", c->exec_pathname);
8703   ui_out_text (uiout, "), ");
8704
8705   return PRINT_SRC_AND_LOC;
8706 }
8707
8708 static void
8709 print_one_catch_exec (struct breakpoint *b, struct bp_location **last_loc)
8710 {
8711   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
8712   struct value_print_options opts;
8713   struct ui_out *uiout = current_uiout;
8714
8715   get_user_print_options (&opts);
8716
8717   /* Field 4, the address, is omitted (which makes the columns
8718      not line up too nicely with the headers, but the effect
8719      is relatively readable).  */
8720   if (opts.addressprint)
8721     ui_out_field_skip (uiout, "addr");
8722   annotate_field (5);
8723   ui_out_text (uiout, "exec");
8724   if (c->exec_pathname != NULL)
8725     {
8726       ui_out_text (uiout, ", program \"");
8727       ui_out_field_string (uiout, "what", c->exec_pathname);
8728       ui_out_text (uiout, "\" ");
8729     }
8730
8731   if (ui_out_is_mi_like_p (uiout))
8732     ui_out_field_string (uiout, "catch-type", "exec");
8733 }
8734
8735 static void
8736 print_mention_catch_exec (struct breakpoint *b)
8737 {
8738   printf_filtered (_("Catchpoint %d (exec)"), b->number);
8739 }
8740
8741 /* Implement the "print_recreate" breakpoint_ops method for exec
8742    catchpoints.  */
8743
8744 static void
8745 print_recreate_catch_exec (struct breakpoint *b, struct ui_file *fp)
8746 {
8747   fprintf_unfiltered (fp, "catch exec");
8748   print_recreate_thread (b, fp);
8749 }
8750
8751 static struct breakpoint_ops catch_exec_breakpoint_ops;
8752
8753 static void
8754 create_syscall_event_catchpoint (int tempflag, VEC(int) *filter,
8755                                  const struct breakpoint_ops *ops)
8756 {
8757   struct syscall_catchpoint *c;
8758   struct gdbarch *gdbarch = get_current_arch ();
8759
8760   c = XNEW (struct syscall_catchpoint);
8761   init_catchpoint (&c->base, gdbarch, tempflag, NULL, ops);
8762   c->syscalls_to_be_caught = filter;
8763
8764   install_breakpoint (0, &c->base, 1);
8765 }
8766
8767 static int
8768 hw_breakpoint_used_count (void)
8769 {
8770   int i = 0;
8771   struct breakpoint *b;
8772   struct bp_location *bl;
8773
8774   ALL_BREAKPOINTS (b)
8775   {
8776     if (b->type == bp_hardware_breakpoint && breakpoint_enabled (b))
8777       for (bl = b->loc; bl; bl = bl->next)
8778         {
8779           /* Special types of hardware breakpoints may use more than
8780              one register.  */
8781           i += b->ops->resources_needed (bl);
8782         }
8783   }
8784
8785   return i;
8786 }
8787
8788 /* Returns the resources B would use if it were a hardware
8789    watchpoint.  */
8790
8791 static int
8792 hw_watchpoint_use_count (struct breakpoint *b)
8793 {
8794   int i = 0;
8795   struct bp_location *bl;
8796
8797   if (!breakpoint_enabled (b))
8798     return 0;
8799
8800   for (bl = b->loc; bl; bl = bl->next)
8801     {
8802       /* Special types of hardware watchpoints may use more than
8803          one register.  */
8804       i += b->ops->resources_needed (bl);
8805     }
8806
8807   return i;
8808 }
8809
8810 /* Returns the sum the used resources of all hardware watchpoints of
8811    type TYPE in the breakpoints list.  Also returns in OTHER_TYPE_USED
8812    the sum of the used resources of all hardware watchpoints of other
8813    types _not_ TYPE.  */
8814
8815 static int
8816 hw_watchpoint_used_count_others (struct breakpoint *except,
8817                                  enum bptype type, int *other_type_used)
8818 {
8819   int i = 0;
8820   struct breakpoint *b;
8821
8822   *other_type_used = 0;
8823   ALL_BREAKPOINTS (b)
8824     {
8825       if (b == except)
8826         continue;
8827       if (!breakpoint_enabled (b))
8828         continue;
8829
8830       if (b->type == type)
8831         i += hw_watchpoint_use_count (b);
8832       else if (is_hardware_watchpoint (b))
8833         *other_type_used = 1;
8834     }
8835
8836   return i;
8837 }
8838
8839 void
8840 disable_watchpoints_before_interactive_call_start (void)
8841 {
8842   struct breakpoint *b;
8843
8844   ALL_BREAKPOINTS (b)
8845   {
8846     if (is_watchpoint (b) && breakpoint_enabled (b))
8847       {
8848         b->enable_state = bp_call_disabled;
8849         update_global_location_list (0);
8850       }
8851   }
8852 }
8853
8854 void
8855 enable_watchpoints_after_interactive_call_stop (void)
8856 {
8857   struct breakpoint *b;
8858
8859   ALL_BREAKPOINTS (b)
8860   {
8861     if (is_watchpoint (b) && b->enable_state == bp_call_disabled)
8862       {
8863         b->enable_state = bp_enabled;
8864         update_global_location_list (1);
8865       }
8866   }
8867 }
8868
8869 void
8870 disable_breakpoints_before_startup (void)
8871 {
8872   current_program_space->executing_startup = 1;
8873   update_global_location_list (0);
8874 }
8875
8876 void
8877 enable_breakpoints_after_startup (void)
8878 {
8879   current_program_space->executing_startup = 0;
8880   breakpoint_re_set ();
8881 }
8882
8883
8884 /* Set a breakpoint that will evaporate an end of command
8885    at address specified by SAL.
8886    Restrict it to frame FRAME if FRAME is nonzero.  */
8887
8888 struct breakpoint *
8889 set_momentary_breakpoint (struct gdbarch *gdbarch, struct symtab_and_line sal,
8890                           struct frame_id frame_id, enum bptype type)
8891 {
8892   struct breakpoint *b;
8893
8894   /* If FRAME_ID is valid, it should be a real frame, not an inlined or
8895      tail-called one.  */
8896   gdb_assert (!frame_id_artificial_p (frame_id));
8897
8898   b = set_raw_breakpoint (gdbarch, sal, type, &momentary_breakpoint_ops);
8899   b->enable_state = bp_enabled;
8900   b->disposition = disp_donttouch;
8901   b->frame_id = frame_id;
8902
8903   /* If we're debugging a multi-threaded program, then we want
8904      momentary breakpoints to be active in only a single thread of
8905      control.  */
8906   if (in_thread_list (inferior_ptid))
8907     b->thread = pid_to_thread_id (inferior_ptid);
8908
8909   update_global_location_list_nothrow (1);
8910
8911   return b;
8912 }
8913
8914 /* Make a momentary breakpoint based on the master breakpoint ORIG.
8915    The new breakpoint will have type TYPE, and use OPS as it
8916    breakpoint_ops.  */
8917
8918 static struct breakpoint *
8919 momentary_breakpoint_from_master (struct breakpoint *orig,
8920                                   enum bptype type,
8921                                   const struct breakpoint_ops *ops)
8922 {
8923   struct breakpoint *copy;
8924
8925   copy = set_raw_breakpoint_without_location (orig->gdbarch, type, ops);
8926   copy->loc = allocate_bp_location (copy);
8927   set_breakpoint_location_function (copy->loc, 1);
8928
8929   copy->loc->gdbarch = orig->loc->gdbarch;
8930   copy->loc->requested_address = orig->loc->requested_address;
8931   copy->loc->address = orig->loc->address;
8932   copy->loc->section = orig->loc->section;
8933   copy->loc->pspace = orig->loc->pspace;
8934   copy->loc->probe = orig->loc->probe;
8935   copy->loc->line_number = orig->loc->line_number;
8936   copy->loc->symtab = orig->loc->symtab;
8937   copy->frame_id = orig->frame_id;
8938   copy->thread = orig->thread;
8939   copy->pspace = orig->pspace;
8940
8941   copy->enable_state = bp_enabled;
8942   copy->disposition = disp_donttouch;
8943   copy->number = internal_breakpoint_number--;
8944
8945   update_global_location_list_nothrow (0);
8946   return copy;
8947 }
8948
8949 /* Make a deep copy of momentary breakpoint ORIG.  Returns NULL if
8950    ORIG is NULL.  */
8951
8952 struct breakpoint *
8953 clone_momentary_breakpoint (struct breakpoint *orig)
8954 {
8955   /* If there's nothing to clone, then return nothing.  */
8956   if (orig == NULL)
8957     return NULL;
8958
8959   return momentary_breakpoint_from_master (orig, orig->type, orig->ops);
8960 }
8961
8962 struct breakpoint *
8963 set_momentary_breakpoint_at_pc (struct gdbarch *gdbarch, CORE_ADDR pc,
8964                                 enum bptype type)
8965 {
8966   struct symtab_and_line sal;
8967
8968   sal = find_pc_line (pc, 0);
8969   sal.pc = pc;
8970   sal.section = find_pc_overlay (pc);
8971   sal.explicit_pc = 1;
8972
8973   return set_momentary_breakpoint (gdbarch, sal, null_frame_id, type);
8974 }
8975 \f
8976
8977 /* Tell the user we have just set a breakpoint B.  */
8978
8979 static void
8980 mention (struct breakpoint *b)
8981 {
8982   b->ops->print_mention (b);
8983   if (ui_out_is_mi_like_p (current_uiout))
8984     return;
8985   printf_filtered ("\n");
8986 }
8987 \f
8988
8989 static struct bp_location *
8990 add_location_to_breakpoint (struct breakpoint *b,
8991                             const struct symtab_and_line *sal)
8992 {
8993   struct bp_location *loc, **tmp;
8994   CORE_ADDR adjusted_address;
8995   struct gdbarch *loc_gdbarch = get_sal_arch (*sal);
8996
8997   if (loc_gdbarch == NULL)
8998     loc_gdbarch = b->gdbarch;
8999
9000   /* Adjust the breakpoint's address prior to allocating a location.
9001      Once we call allocate_bp_location(), that mostly uninitialized
9002      location will be placed on the location chain.  Adjustment of the
9003      breakpoint may cause target_read_memory() to be called and we do
9004      not want its scan of the location chain to find a breakpoint and
9005      location that's only been partially initialized.  */
9006   adjusted_address = adjust_breakpoint_address (loc_gdbarch,
9007                                                 sal->pc, b->type);
9008
9009   /* Sort the locations by their ADDRESS.  */
9010   loc = allocate_bp_location (b);
9011   for (tmp = &(b->loc); *tmp != NULL && (*tmp)->address <= adjusted_address;
9012        tmp = &((*tmp)->next))
9013     ;
9014   loc->next = *tmp;
9015   *tmp = loc;
9016
9017   loc->requested_address = sal->pc;
9018   loc->address = adjusted_address;
9019   loc->pspace = sal->pspace;
9020   loc->probe = sal->probe;
9021   gdb_assert (loc->pspace != NULL);
9022   loc->section = sal->section;
9023   loc->gdbarch = loc_gdbarch;
9024   loc->line_number = sal->line;
9025   loc->symtab = sal->symtab;
9026
9027   set_breakpoint_location_function (loc,
9028                                     sal->explicit_pc || sal->explicit_line);
9029   return loc;
9030 }
9031 \f
9032
9033 /* Return 1 if LOC is pointing to a permanent breakpoint, 
9034    return 0 otherwise.  */
9035
9036 static int
9037 bp_loc_is_permanent (struct bp_location *loc)
9038 {
9039   int len;
9040   CORE_ADDR addr;
9041   const gdb_byte *bpoint;
9042   gdb_byte *target_mem;
9043   struct cleanup *cleanup;
9044   int retval = 0;
9045
9046   gdb_assert (loc != NULL);
9047
9048   addr = loc->address;
9049   bpoint = gdbarch_breakpoint_from_pc (loc->gdbarch, &addr, &len);
9050
9051   /* Software breakpoints unsupported?  */
9052   if (bpoint == NULL)
9053     return 0;
9054
9055   target_mem = alloca (len);
9056
9057   /* Enable the automatic memory restoration from breakpoints while
9058      we read the memory.  Otherwise we could say about our temporary
9059      breakpoints they are permanent.  */
9060   cleanup = save_current_space_and_thread ();
9061
9062   switch_to_program_space_and_thread (loc->pspace);
9063   make_show_memory_breakpoints_cleanup (0);
9064
9065   if (target_read_memory (loc->address, target_mem, len) == 0
9066       && memcmp (target_mem, bpoint, len) == 0)
9067     retval = 1;
9068
9069   do_cleanups (cleanup);
9070
9071   return retval;
9072 }
9073
9074 /* Build a command list for the dprintf corresponding to the current
9075    settings of the dprintf style options.  */
9076
9077 static void
9078 update_dprintf_command_list (struct breakpoint *b)
9079 {
9080   char *dprintf_args = b->extra_string;
9081   char *printf_line = NULL;
9082
9083   if (!dprintf_args)
9084     return;
9085
9086   dprintf_args = skip_spaces (dprintf_args);
9087
9088   /* Allow a comma, as it may have terminated a location, but don't
9089      insist on it.  */
9090   if (*dprintf_args == ',')
9091     ++dprintf_args;
9092   dprintf_args = skip_spaces (dprintf_args);
9093
9094   if (*dprintf_args != '"')
9095     error (_("Bad format string, missing '\"'."));
9096
9097   if (strcmp (dprintf_style, dprintf_style_gdb) == 0)
9098     printf_line = xstrprintf ("printf %s", dprintf_args);
9099   else if (strcmp (dprintf_style, dprintf_style_call) == 0)
9100     {
9101       if (!dprintf_function)
9102         error (_("No function supplied for dprintf call"));
9103
9104       if (dprintf_channel && strlen (dprintf_channel) > 0)
9105         printf_line = xstrprintf ("call (void) %s (%s,%s)",
9106                                   dprintf_function,
9107                                   dprintf_channel,
9108                                   dprintf_args);
9109       else
9110         printf_line = xstrprintf ("call (void) %s (%s)",
9111                                   dprintf_function,
9112                                   dprintf_args);
9113     }
9114   else if (strcmp (dprintf_style, dprintf_style_agent) == 0)
9115     {
9116       if (target_can_run_breakpoint_commands ())
9117         printf_line = xstrprintf ("agent-printf %s", dprintf_args);
9118       else
9119         {
9120           warning (_("Target cannot run dprintf commands, falling back to GDB printf"));
9121           printf_line = xstrprintf ("printf %s", dprintf_args);
9122         }
9123     }
9124   else
9125     internal_error (__FILE__, __LINE__,
9126                     _("Invalid dprintf style."));
9127
9128   gdb_assert (printf_line != NULL);
9129   /* Manufacture a printf sequence.  */
9130   {
9131     struct command_line *printf_cmd_line
9132       = xmalloc (sizeof (struct command_line));
9133
9134     printf_cmd_line = xmalloc (sizeof (struct command_line));
9135     printf_cmd_line->control_type = simple_control;
9136     printf_cmd_line->body_count = 0;
9137     printf_cmd_line->body_list = NULL;
9138     printf_cmd_line->next = NULL;
9139     printf_cmd_line->line = printf_line;
9140
9141     breakpoint_set_commands (b, printf_cmd_line);
9142   }
9143 }
9144
9145 /* Update all dprintf commands, making their command lists reflect
9146    current style settings.  */
9147
9148 static void
9149 update_dprintf_commands (char *args, int from_tty,
9150                          struct cmd_list_element *c)
9151 {
9152   struct breakpoint *b;
9153
9154   ALL_BREAKPOINTS (b)
9155     {
9156       if (b->type == bp_dprintf)
9157         update_dprintf_command_list (b);
9158     }
9159 }
9160
9161 /* Create a breakpoint with SAL as location.  Use ADDR_STRING
9162    as textual description of the location, and COND_STRING
9163    as condition expression.  */
9164
9165 static void
9166 init_breakpoint_sal (struct breakpoint *b, struct gdbarch *gdbarch,
9167                      struct symtabs_and_lines sals, char *addr_string,
9168                      char *filter, char *cond_string,
9169                      char *extra_string,
9170                      enum bptype type, enum bpdisp disposition,
9171                      int thread, int task, int ignore_count,
9172                      const struct breakpoint_ops *ops, int from_tty,
9173                      int enabled, int internal, unsigned flags,
9174                      int display_canonical)
9175 {
9176   int i;
9177
9178   if (type == bp_hardware_breakpoint)
9179     {
9180       int target_resources_ok;
9181
9182       i = hw_breakpoint_used_count ();
9183       target_resources_ok =
9184         target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
9185                                             i + 1, 0);
9186       if (target_resources_ok == 0)
9187         error (_("No hardware breakpoint support in the target."));
9188       else if (target_resources_ok < 0)
9189         error (_("Hardware breakpoints used exceeds limit."));
9190     }
9191
9192   gdb_assert (sals.nelts > 0);
9193
9194   for (i = 0; i < sals.nelts; ++i)
9195     {
9196       struct symtab_and_line sal = sals.sals[i];
9197       struct bp_location *loc;
9198
9199       if (from_tty)
9200         {
9201           struct gdbarch *loc_gdbarch = get_sal_arch (sal);
9202           if (!loc_gdbarch)
9203             loc_gdbarch = gdbarch;
9204
9205           describe_other_breakpoints (loc_gdbarch,
9206                                       sal.pspace, sal.pc, sal.section, thread);
9207         }
9208
9209       if (i == 0)
9210         {
9211           init_raw_breakpoint (b, gdbarch, sal, type, ops);
9212           b->thread = thread;
9213           b->task = task;
9214
9215           b->cond_string = cond_string;
9216           b->extra_string = extra_string;
9217           b->ignore_count = ignore_count;
9218           b->enable_state = enabled ? bp_enabled : bp_disabled;
9219           b->disposition = disposition;
9220
9221           if ((flags & CREATE_BREAKPOINT_FLAGS_INSERTED) != 0)
9222             b->loc->inserted = 1;
9223
9224           if (type == bp_static_tracepoint)
9225             {
9226               struct tracepoint *t = (struct tracepoint *) b;
9227               struct static_tracepoint_marker marker;
9228
9229               if (strace_marker_p (b))
9230                 {
9231                   /* We already know the marker exists, otherwise, we
9232                      wouldn't see a sal for it.  */
9233                   char *p = &addr_string[3];
9234                   char *endp;
9235                   char *marker_str;
9236
9237                   p = skip_spaces (p);
9238
9239                   endp = skip_to_space (p);
9240
9241                   marker_str = savestring (p, endp - p);
9242                   t->static_trace_marker_id = marker_str;
9243
9244                   printf_filtered (_("Probed static tracepoint "
9245                                      "marker \"%s\"\n"),
9246                                    t->static_trace_marker_id);
9247                 }
9248               else if (target_static_tracepoint_marker_at (sal.pc, &marker))
9249                 {
9250                   t->static_trace_marker_id = xstrdup (marker.str_id);
9251                   release_static_tracepoint_marker (&marker);
9252
9253                   printf_filtered (_("Probed static tracepoint "
9254                                      "marker \"%s\"\n"),
9255                                    t->static_trace_marker_id);
9256                 }
9257               else
9258                 warning (_("Couldn't determine the static "
9259                            "tracepoint marker to probe"));
9260             }
9261
9262           loc = b->loc;
9263         }
9264       else
9265         {
9266           loc = add_location_to_breakpoint (b, &sal);
9267           if ((flags & CREATE_BREAKPOINT_FLAGS_INSERTED) != 0)
9268             loc->inserted = 1;
9269         }
9270
9271       if (bp_loc_is_permanent (loc))
9272         make_breakpoint_permanent (b);
9273
9274       if (b->cond_string)
9275         {
9276           const char *arg = b->cond_string;
9277
9278           loc->cond = parse_exp_1 (&arg, loc->address,
9279                                    block_for_pc (loc->address), 0);
9280           if (*arg)
9281               error (_("Garbage '%s' follows condition"), arg);
9282         }
9283
9284       /* Dynamic printf requires and uses additional arguments on the
9285          command line, otherwise it's an error.  */
9286       if (type == bp_dprintf)
9287         {
9288           if (b->extra_string)
9289             update_dprintf_command_list (b);
9290           else
9291             error (_("Format string required"));
9292         }
9293       else if (b->extra_string)
9294         error (_("Garbage '%s' at end of command"), b->extra_string);
9295     }
9296
9297   b->display_canonical = display_canonical;
9298   if (addr_string)
9299     b->addr_string = addr_string;
9300   else
9301     /* addr_string has to be used or breakpoint_re_set will delete
9302        me.  */
9303     b->addr_string
9304       = xstrprintf ("*%s", paddress (b->loc->gdbarch, b->loc->address));
9305   b->filter = filter;
9306 }
9307
9308 static void
9309 create_breakpoint_sal (struct gdbarch *gdbarch,
9310                        struct symtabs_and_lines sals, char *addr_string,
9311                        char *filter, char *cond_string,
9312                        char *extra_string,
9313                        enum bptype type, enum bpdisp disposition,
9314                        int thread, int task, int ignore_count,
9315                        const struct breakpoint_ops *ops, int from_tty,
9316                        int enabled, int internal, unsigned flags,
9317                        int display_canonical)
9318 {
9319   struct breakpoint *b;
9320   struct cleanup *old_chain;
9321
9322   if (is_tracepoint_type (type))
9323     {
9324       struct tracepoint *t;
9325
9326       t = XCNEW (struct tracepoint);
9327       b = &t->base;
9328     }
9329   else
9330     b = XNEW (struct breakpoint);
9331
9332   old_chain = make_cleanup (xfree, b);
9333
9334   init_breakpoint_sal (b, gdbarch,
9335                        sals, addr_string,
9336                        filter, cond_string, extra_string,
9337                        type, disposition,
9338                        thread, task, ignore_count,
9339                        ops, from_tty,
9340                        enabled, internal, flags,
9341                        display_canonical);
9342   discard_cleanups (old_chain);
9343
9344   install_breakpoint (internal, b, 0);
9345 }
9346
9347 /* Add SALS.nelts breakpoints to the breakpoint table.  For each
9348    SALS.sal[i] breakpoint, include the corresponding ADDR_STRING[i]
9349    value.  COND_STRING, if not NULL, specified the condition to be
9350    used for all breakpoints.  Essentially the only case where
9351    SALS.nelts is not 1 is when we set a breakpoint on an overloaded
9352    function.  In that case, it's still not possible to specify
9353    separate conditions for different overloaded functions, so
9354    we take just a single condition string.
9355    
9356    NOTE: If the function succeeds, the caller is expected to cleanup
9357    the arrays ADDR_STRING, COND_STRING, and SALS (but not the
9358    array contents).  If the function fails (error() is called), the
9359    caller is expected to cleanups both the ADDR_STRING, COND_STRING,
9360    COND and SALS arrays and each of those arrays contents.  */
9361
9362 static void
9363 create_breakpoints_sal (struct gdbarch *gdbarch,
9364                         struct linespec_result *canonical,
9365                         char *cond_string, char *extra_string,
9366                         enum bptype type, enum bpdisp disposition,
9367                         int thread, int task, int ignore_count,
9368                         const struct breakpoint_ops *ops, int from_tty,
9369                         int enabled, int internal, unsigned flags)
9370 {
9371   int i;
9372   struct linespec_sals *lsal;
9373
9374   if (canonical->pre_expanded)
9375     gdb_assert (VEC_length (linespec_sals, canonical->sals) == 1);
9376
9377   for (i = 0; VEC_iterate (linespec_sals, canonical->sals, i, lsal); ++i)
9378     {
9379       /* Note that 'addr_string' can be NULL in the case of a plain
9380          'break', without arguments.  */
9381       char *addr_string = (canonical->addr_string
9382                            ? xstrdup (canonical->addr_string)
9383                            : NULL);
9384       char *filter_string = lsal->canonical ? xstrdup (lsal->canonical) : NULL;
9385       struct cleanup *inner = make_cleanup (xfree, addr_string);
9386
9387       make_cleanup (xfree, filter_string);
9388       create_breakpoint_sal (gdbarch, lsal->sals,
9389                              addr_string,
9390                              filter_string,
9391                              cond_string, extra_string,
9392                              type, disposition,
9393                              thread, task, ignore_count, ops,
9394                              from_tty, enabled, internal, flags,
9395                              canonical->special_display);
9396       discard_cleanups (inner);
9397     }
9398 }
9399
9400 /* Parse ADDRESS which is assumed to be a SAL specification possibly
9401    followed by conditionals.  On return, SALS contains an array of SAL
9402    addresses found.  ADDR_STRING contains a vector of (canonical)
9403    address strings.  ADDRESS points to the end of the SAL.
9404
9405    The array and the line spec strings are allocated on the heap, it is
9406    the caller's responsibility to free them.  */
9407
9408 static void
9409 parse_breakpoint_sals (char **address,
9410                        struct linespec_result *canonical)
9411 {
9412   /* If no arg given, or if first arg is 'if ', use the default
9413      breakpoint.  */
9414   if ((*address) == NULL
9415       || (strncmp ((*address), "if", 2) == 0 && isspace ((*address)[2])))
9416     {
9417       /* The last displayed codepoint, if it's valid, is our default breakpoint
9418          address.  */
9419       if (last_displayed_sal_is_valid ())
9420         {
9421           struct linespec_sals lsal;
9422           struct symtab_and_line sal;
9423           CORE_ADDR pc;
9424
9425           init_sal (&sal);              /* Initialize to zeroes.  */
9426           lsal.sals.sals = (struct symtab_and_line *)
9427             xmalloc (sizeof (struct symtab_and_line));
9428
9429           /* Set sal's pspace, pc, symtab, and line to the values
9430              corresponding to the last call to print_frame_info.
9431              Be sure to reinitialize LINE with NOTCURRENT == 0
9432              as the breakpoint line number is inappropriate otherwise.
9433              find_pc_line would adjust PC, re-set it back.  */
9434           get_last_displayed_sal (&sal);
9435           pc = sal.pc;
9436           sal = find_pc_line (pc, 0);
9437
9438           /* "break" without arguments is equivalent to "break *PC"
9439              where PC is the last displayed codepoint's address.  So
9440              make sure to set sal.explicit_pc to prevent GDB from
9441              trying to expand the list of sals to include all other
9442              instances with the same symtab and line.  */
9443           sal.pc = pc;
9444           sal.explicit_pc = 1;
9445
9446           lsal.sals.sals[0] = sal;
9447           lsal.sals.nelts = 1;
9448           lsal.canonical = NULL;
9449
9450           VEC_safe_push (linespec_sals, canonical->sals, &lsal);
9451         }
9452       else
9453         error (_("No default breakpoint address now."));
9454     }
9455   else
9456     {
9457       struct symtab_and_line cursal = get_current_source_symtab_and_line ();
9458
9459       /* Force almost all breakpoints to be in terms of the
9460          current_source_symtab (which is decode_line_1's default).
9461          This should produce the results we want almost all of the
9462          time while leaving default_breakpoint_* alone.
9463
9464          ObjC: However, don't match an Objective-C method name which
9465          may have a '+' or '-' succeeded by a '['.  */
9466       if (last_displayed_sal_is_valid ()
9467           && (!cursal.symtab
9468               || ((strchr ("+-", (*address)[0]) != NULL)
9469                   && ((*address)[1] != '['))))
9470         decode_line_full (address, DECODE_LINE_FUNFIRSTLINE,
9471                           get_last_displayed_symtab (),
9472                           get_last_displayed_line (),
9473                           canonical, NULL, NULL);
9474       else
9475         decode_line_full (address, DECODE_LINE_FUNFIRSTLINE,
9476                           cursal.symtab, cursal.line, canonical, NULL, NULL);
9477     }
9478 }
9479
9480
9481 /* Convert each SAL into a real PC.  Verify that the PC can be
9482    inserted as a breakpoint.  If it can't throw an error.  */
9483
9484 static void
9485 breakpoint_sals_to_pc (struct symtabs_and_lines *sals)
9486 {    
9487   int i;
9488
9489   for (i = 0; i < sals->nelts; i++)
9490     resolve_sal_pc (&sals->sals[i]);
9491 }
9492
9493 /* Fast tracepoints may have restrictions on valid locations.  For
9494    instance, a fast tracepoint using a jump instead of a trap will
9495    likely have to overwrite more bytes than a trap would, and so can
9496    only be placed where the instruction is longer than the jump, or a
9497    multi-instruction sequence does not have a jump into the middle of
9498    it, etc.  */
9499
9500 static void
9501 check_fast_tracepoint_sals (struct gdbarch *gdbarch,
9502                             struct symtabs_and_lines *sals)
9503 {
9504   int i, rslt;
9505   struct symtab_and_line *sal;
9506   char *msg;
9507   struct cleanup *old_chain;
9508
9509   for (i = 0; i < sals->nelts; i++)
9510     {
9511       struct gdbarch *sarch;
9512
9513       sal = &sals->sals[i];
9514
9515       sarch = get_sal_arch (*sal);
9516       /* We fall back to GDBARCH if there is no architecture
9517          associated with SAL.  */
9518       if (sarch == NULL)
9519         sarch = gdbarch;
9520       rslt = gdbarch_fast_tracepoint_valid_at (sarch, sal->pc,
9521                                                NULL, &msg);
9522       old_chain = make_cleanup (xfree, msg);
9523
9524       if (!rslt)
9525         error (_("May not have a fast tracepoint at 0x%s%s"),
9526                paddress (sarch, sal->pc), (msg ? msg : ""));
9527
9528       do_cleanups (old_chain);
9529     }
9530 }
9531
9532 /* Issue an invalid thread ID error.  */
9533
9534 static void ATTRIBUTE_NORETURN
9535 invalid_thread_id_error (int id)
9536 {
9537   error (_("Unknown thread %d."), id);
9538 }
9539
9540 /* Given TOK, a string specification of condition and thread, as
9541    accepted by the 'break' command, extract the condition
9542    string and thread number and set *COND_STRING and *THREAD.
9543    PC identifies the context at which the condition should be parsed.
9544    If no condition is found, *COND_STRING is set to NULL.
9545    If no thread is found, *THREAD is set to -1.  */
9546
9547 static void
9548 find_condition_and_thread (const char *tok, CORE_ADDR pc,
9549                            char **cond_string, int *thread, int *task,
9550                            char **rest)
9551 {
9552   *cond_string = NULL;
9553   *thread = -1;
9554   *task = 0;
9555   *rest = NULL;
9556
9557   while (tok && *tok)
9558     {
9559       const char *end_tok;
9560       int toklen;
9561       const char *cond_start = NULL;
9562       const char *cond_end = NULL;
9563
9564       tok = skip_spaces_const (tok);
9565
9566       if ((*tok == '"' || *tok == ',') && rest)
9567         {
9568           *rest = savestring (tok, strlen (tok));
9569           return;
9570         }
9571
9572       end_tok = skip_to_space_const (tok);
9573
9574       toklen = end_tok - tok;
9575
9576       if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
9577         {
9578           struct expression *expr;
9579
9580           tok = cond_start = end_tok + 1;
9581           expr = parse_exp_1 (&tok, pc, block_for_pc (pc), 0);
9582           xfree (expr);
9583           cond_end = tok;
9584           *cond_string = savestring (cond_start, cond_end - cond_start);
9585         }
9586       else if (toklen >= 1 && strncmp (tok, "thread", toklen) == 0)
9587         {
9588           char *tmptok;
9589
9590           tok = end_tok + 1;
9591           *thread = strtol (tok, &tmptok, 0);
9592           if (tok == tmptok)
9593             error (_("Junk after thread keyword."));
9594           if (!valid_thread_id (*thread))
9595             invalid_thread_id_error (*thread);
9596           tok = tmptok;
9597         }
9598       else if (toklen >= 1 && strncmp (tok, "task", toklen) == 0)
9599         {
9600           char *tmptok;
9601
9602           tok = end_tok + 1;
9603           *task = strtol (tok, &tmptok, 0);
9604           if (tok == tmptok)
9605             error (_("Junk after task keyword."));
9606           if (!valid_task_id (*task))
9607             error (_("Unknown task %d."), *task);
9608           tok = tmptok;
9609         }
9610       else if (rest)
9611         {
9612           *rest = savestring (tok, strlen (tok));
9613           return;
9614         }
9615       else
9616         error (_("Junk at end of arguments."));
9617     }
9618 }
9619
9620 /* Decode a static tracepoint marker spec.  */
9621
9622 static struct symtabs_and_lines
9623 decode_static_tracepoint_spec (char **arg_p)
9624 {
9625   VEC(static_tracepoint_marker_p) *markers = NULL;
9626   struct symtabs_and_lines sals;
9627   struct cleanup *old_chain;
9628   char *p = &(*arg_p)[3];
9629   char *endp;
9630   char *marker_str;
9631   int i;
9632
9633   p = skip_spaces (p);
9634
9635   endp = skip_to_space (p);
9636
9637   marker_str = savestring (p, endp - p);
9638   old_chain = make_cleanup (xfree, marker_str);
9639
9640   markers = target_static_tracepoint_markers_by_strid (marker_str);
9641   if (VEC_empty(static_tracepoint_marker_p, markers))
9642     error (_("No known static tracepoint marker named %s"), marker_str);
9643
9644   sals.nelts = VEC_length(static_tracepoint_marker_p, markers);
9645   sals.sals = xmalloc (sizeof *sals.sals * sals.nelts);
9646
9647   for (i = 0; i < sals.nelts; i++)
9648     {
9649       struct static_tracepoint_marker *marker;
9650
9651       marker = VEC_index (static_tracepoint_marker_p, markers, i);
9652
9653       init_sal (&sals.sals[i]);
9654
9655       sals.sals[i] = find_pc_line (marker->address, 0);
9656       sals.sals[i].pc = marker->address;
9657
9658       release_static_tracepoint_marker (marker);
9659     }
9660
9661   do_cleanups (old_chain);
9662
9663   *arg_p = endp;
9664   return sals;
9665 }
9666
9667 /* Set a breakpoint.  This function is shared between CLI and MI
9668    functions for setting a breakpoint.  This function has two major
9669    modes of operations, selected by the PARSE_ARG parameter.  If
9670    non-zero, the function will parse ARG, extracting location,
9671    condition, thread and extra string.  Otherwise, ARG is just the
9672    breakpoint's location, with condition, thread, and extra string
9673    specified by the COND_STRING, THREAD and EXTRA_STRING parameters.
9674    If INTERNAL is non-zero, the breakpoint number will be allocated
9675    from the internal breakpoint count.  Returns true if any breakpoint
9676    was created; false otherwise.  */
9677
9678 int
9679 create_breakpoint (struct gdbarch *gdbarch,
9680                    char *arg, char *cond_string,
9681                    int thread, char *extra_string,
9682                    int parse_arg,
9683                    int tempflag, enum bptype type_wanted,
9684                    int ignore_count,
9685                    enum auto_boolean pending_break_support,
9686                    const struct breakpoint_ops *ops,
9687                    int from_tty, int enabled, int internal,
9688                    unsigned flags)
9689 {
9690   volatile struct gdb_exception e;
9691   char *copy_arg = NULL;
9692   char *addr_start = arg;
9693   struct linespec_result canonical;
9694   struct cleanup *old_chain;
9695   struct cleanup *bkpt_chain = NULL;
9696   int pending = 0;
9697   int task = 0;
9698   int prev_bkpt_count = breakpoint_count;
9699
9700   gdb_assert (ops != NULL);
9701
9702   init_linespec_result (&canonical);
9703
9704   TRY_CATCH (e, RETURN_MASK_ALL)
9705     {
9706       ops->create_sals_from_address (&arg, &canonical, type_wanted,
9707                                      addr_start, &copy_arg);
9708     }
9709
9710   /* If caller is interested in rc value from parse, set value.  */
9711   switch (e.reason)
9712     {
9713     case GDB_NO_ERROR:
9714       if (VEC_empty (linespec_sals, canonical.sals))
9715         return 0;
9716       break;
9717     case RETURN_ERROR:
9718       switch (e.error)
9719         {
9720         case NOT_FOUND_ERROR:
9721
9722           /* If pending breakpoint support is turned off, throw
9723              error.  */
9724
9725           if (pending_break_support == AUTO_BOOLEAN_FALSE)
9726             throw_exception (e);
9727
9728           exception_print (gdb_stderr, e);
9729
9730           /* If pending breakpoint support is auto query and the user
9731              selects no, then simply return the error code.  */
9732           if (pending_break_support == AUTO_BOOLEAN_AUTO
9733               && !nquery (_("Make %s pending on future shared library load? "),
9734                           bptype_string (type_wanted)))
9735             return 0;
9736
9737           /* At this point, either the user was queried about setting
9738              a pending breakpoint and selected yes, or pending
9739              breakpoint behavior is on and thus a pending breakpoint
9740              is defaulted on behalf of the user.  */
9741           {
9742             struct linespec_sals lsal;
9743
9744             copy_arg = xstrdup (addr_start);
9745             lsal.canonical = xstrdup (copy_arg);
9746             lsal.sals.nelts = 1;
9747             lsal.sals.sals = XNEW (struct symtab_and_line);
9748             init_sal (&lsal.sals.sals[0]);
9749             pending = 1;
9750             VEC_safe_push (linespec_sals, canonical.sals, &lsal);
9751           }
9752           break;
9753         default:
9754           throw_exception (e);
9755         }
9756       break;
9757     default:
9758       throw_exception (e);
9759     }
9760
9761   /* Create a chain of things that always need to be cleaned up.  */
9762   old_chain = make_cleanup_destroy_linespec_result (&canonical);
9763
9764   /* ----------------------------- SNIP -----------------------------
9765      Anything added to the cleanup chain beyond this point is assumed
9766      to be part of a breakpoint.  If the breakpoint create succeeds
9767      then the memory is not reclaimed.  */
9768   bkpt_chain = make_cleanup (null_cleanup, 0);
9769
9770   /* Resolve all line numbers to PC's and verify that the addresses
9771      are ok for the target.  */
9772   if (!pending)
9773     {
9774       int ix;
9775       struct linespec_sals *iter;
9776
9777       for (ix = 0; VEC_iterate (linespec_sals, canonical.sals, ix, iter); ++ix)
9778         breakpoint_sals_to_pc (&iter->sals);
9779     }
9780
9781   /* Fast tracepoints may have additional restrictions on location.  */
9782   if (!pending && type_wanted == bp_fast_tracepoint)
9783     {
9784       int ix;
9785       struct linespec_sals *iter;
9786
9787       for (ix = 0; VEC_iterate (linespec_sals, canonical.sals, ix, iter); ++ix)
9788         check_fast_tracepoint_sals (gdbarch, &iter->sals);
9789     }
9790
9791   /* Verify that condition can be parsed, before setting any
9792      breakpoints.  Allocate a separate condition expression for each
9793      breakpoint.  */
9794   if (!pending)
9795     {
9796       if (parse_arg)
9797         {
9798           char *rest;
9799           struct linespec_sals *lsal;
9800
9801           lsal = VEC_index (linespec_sals, canonical.sals, 0);
9802
9803           /* Here we only parse 'arg' to separate condition
9804              from thread number, so parsing in context of first
9805              sal is OK.  When setting the breakpoint we'll
9806              re-parse it in context of each sal.  */
9807
9808           find_condition_and_thread (arg, lsal->sals.sals[0].pc, &cond_string,
9809                                      &thread, &task, &rest);
9810           if (cond_string)
9811             make_cleanup (xfree, cond_string);
9812           if (rest)
9813             make_cleanup (xfree, rest);
9814           if (rest)
9815             extra_string = rest;
9816         }
9817       else
9818         {
9819           if (*arg != '\0')
9820             error (_("Garbage '%s' at end of location"), arg);
9821
9822           /* Create a private copy of condition string.  */
9823           if (cond_string)
9824             {
9825               cond_string = xstrdup (cond_string);
9826               make_cleanup (xfree, cond_string);
9827             }
9828           /* Create a private copy of any extra string.  */
9829           if (extra_string)
9830             {
9831               extra_string = xstrdup (extra_string);
9832               make_cleanup (xfree, extra_string);
9833             }
9834         }
9835
9836       ops->create_breakpoints_sal (gdbarch, &canonical,
9837                                    cond_string, extra_string, type_wanted,
9838                                    tempflag ? disp_del : disp_donttouch,
9839                                    thread, task, ignore_count, ops,
9840                                    from_tty, enabled, internal, flags);
9841     }
9842   else
9843     {
9844       struct breakpoint *b;
9845
9846       make_cleanup (xfree, copy_arg);
9847
9848       if (is_tracepoint_type (type_wanted))
9849         {
9850           struct tracepoint *t;
9851
9852           t = XCNEW (struct tracepoint);
9853           b = &t->base;
9854         }
9855       else
9856         b = XNEW (struct breakpoint);
9857
9858       init_raw_breakpoint_without_location (b, gdbarch, type_wanted, ops);
9859
9860       b->addr_string = copy_arg;
9861       if (parse_arg)
9862         b->cond_string = NULL;
9863       else
9864         {
9865           /* Create a private copy of condition string.  */
9866           if (cond_string)
9867             {
9868               cond_string = xstrdup (cond_string);
9869               make_cleanup (xfree, cond_string);
9870             }
9871           b->cond_string = cond_string;
9872         }
9873       b->extra_string = NULL;
9874       b->ignore_count = ignore_count;
9875       b->disposition = tempflag ? disp_del : disp_donttouch;
9876       b->condition_not_parsed = 1;
9877       b->enable_state = enabled ? bp_enabled : bp_disabled;
9878       if ((type_wanted != bp_breakpoint
9879            && type_wanted != bp_hardware_breakpoint) || thread != -1)
9880         b->pspace = current_program_space;
9881
9882       install_breakpoint (internal, b, 0);
9883     }
9884   
9885   if (VEC_length (linespec_sals, canonical.sals) > 1)
9886     {
9887       warning (_("Multiple breakpoints were set.\nUse the "
9888                  "\"delete\" command to delete unwanted breakpoints."));
9889       prev_breakpoint_count = prev_bkpt_count;
9890     }
9891
9892   /* That's it.  Discard the cleanups for data inserted into the
9893      breakpoint.  */
9894   discard_cleanups (bkpt_chain);
9895   /* But cleanup everything else.  */
9896   do_cleanups (old_chain);
9897
9898   /* error call may happen here - have BKPT_CHAIN already discarded.  */
9899   update_global_location_list (1);
9900
9901   return 1;
9902 }
9903
9904 /* Set a breakpoint.
9905    ARG is a string describing breakpoint address,
9906    condition, and thread.
9907    FLAG specifies if a breakpoint is hardware on,
9908    and if breakpoint is temporary, using BP_HARDWARE_FLAG
9909    and BP_TEMPFLAG.  */
9910
9911 static void
9912 break_command_1 (char *arg, int flag, int from_tty)
9913 {
9914   int tempflag = flag & BP_TEMPFLAG;
9915   enum bptype type_wanted = (flag & BP_HARDWAREFLAG
9916                              ? bp_hardware_breakpoint
9917                              : bp_breakpoint);
9918   struct breakpoint_ops *ops;
9919   const char *arg_cp = arg;
9920
9921   /* Matching breakpoints on probes.  */
9922   if (arg && probe_linespec_to_ops (&arg_cp) != NULL)
9923     ops = &bkpt_probe_breakpoint_ops;
9924   else
9925     ops = &bkpt_breakpoint_ops;
9926
9927   create_breakpoint (get_current_arch (),
9928                      arg,
9929                      NULL, 0, NULL, 1 /* parse arg */,
9930                      tempflag, type_wanted,
9931                      0 /* Ignore count */,
9932                      pending_break_support,
9933                      ops,
9934                      from_tty,
9935                      1 /* enabled */,
9936                      0 /* internal */,
9937                      0);
9938 }
9939
9940 /* Helper function for break_command_1 and disassemble_command.  */
9941
9942 void
9943 resolve_sal_pc (struct symtab_and_line *sal)
9944 {
9945   CORE_ADDR pc;
9946
9947   if (sal->pc == 0 && sal->symtab != NULL)
9948     {
9949       if (!find_line_pc (sal->symtab, sal->line, &pc))
9950         error (_("No line %d in file \"%s\"."),
9951                sal->line, symtab_to_filename_for_display (sal->symtab));
9952       sal->pc = pc;
9953
9954       /* If this SAL corresponds to a breakpoint inserted using a line
9955          number, then skip the function prologue if necessary.  */
9956       if (sal->explicit_line)
9957         skip_prologue_sal (sal);
9958     }
9959
9960   if (sal->section == 0 && sal->symtab != NULL)
9961     {
9962       struct blockvector *bv;
9963       struct block *b;
9964       struct symbol *sym;
9965
9966       bv = blockvector_for_pc_sect (sal->pc, 0, &b, sal->symtab);
9967       if (bv != NULL)
9968         {
9969           sym = block_linkage_function (b);
9970           if (sym != NULL)
9971             {
9972               fixup_symbol_section (sym, sal->symtab->objfile);
9973               sal->section = SYMBOL_OBJ_SECTION (sal->symtab->objfile, sym);
9974             }
9975           else
9976             {
9977               /* It really is worthwhile to have the section, so we'll
9978                  just have to look harder. This case can be executed
9979                  if we have line numbers but no functions (as can
9980                  happen in assembly source).  */
9981
9982               struct bound_minimal_symbol msym;
9983               struct cleanup *old_chain = save_current_space_and_thread ();
9984
9985               switch_to_program_space_and_thread (sal->pspace);
9986
9987               msym = lookup_minimal_symbol_by_pc (sal->pc);
9988               if (msym.minsym)
9989                 sal->section = SYMBOL_OBJ_SECTION (msym.objfile, msym.minsym);
9990
9991               do_cleanups (old_chain);
9992             }
9993         }
9994     }
9995 }
9996
9997 void
9998 break_command (char *arg, int from_tty)
9999 {
10000   break_command_1 (arg, 0, from_tty);
10001 }
10002
10003 void
10004 tbreak_command (char *arg, int from_tty)
10005 {
10006   break_command_1 (arg, BP_TEMPFLAG, from_tty);
10007 }
10008
10009 static void
10010 hbreak_command (char *arg, int from_tty)
10011 {
10012   break_command_1 (arg, BP_HARDWAREFLAG, from_tty);
10013 }
10014
10015 static void
10016 thbreak_command (char *arg, int from_tty)
10017 {
10018   break_command_1 (arg, (BP_TEMPFLAG | BP_HARDWAREFLAG), from_tty);
10019 }
10020
10021 static void
10022 stop_command (char *arg, int from_tty)
10023 {
10024   printf_filtered (_("Specify the type of breakpoint to set.\n\
10025 Usage: stop in <function | address>\n\
10026        stop at <line>\n"));
10027 }
10028
10029 static void
10030 stopin_command (char *arg, int from_tty)
10031 {
10032   int badInput = 0;
10033
10034   if (arg == (char *) NULL)
10035     badInput = 1;
10036   else if (*arg != '*')
10037     {
10038       char *argptr = arg;
10039       int hasColon = 0;
10040
10041       /* Look for a ':'.  If this is a line number specification, then
10042          say it is bad, otherwise, it should be an address or
10043          function/method name.  */
10044       while (*argptr && !hasColon)
10045         {
10046           hasColon = (*argptr == ':');
10047           argptr++;
10048         }
10049
10050       if (hasColon)
10051         badInput = (*argptr != ':');    /* Not a class::method */
10052       else
10053         badInput = isdigit (*arg);      /* a simple line number */
10054     }
10055
10056   if (badInput)
10057     printf_filtered (_("Usage: stop in <function | address>\n"));
10058   else
10059     break_command_1 (arg, 0, from_tty);
10060 }
10061
10062 static void
10063 stopat_command (char *arg, int from_tty)
10064 {
10065   int badInput = 0;
10066
10067   if (arg == (char *) NULL || *arg == '*')      /* no line number */
10068     badInput = 1;
10069   else
10070     {
10071       char *argptr = arg;
10072       int hasColon = 0;
10073
10074       /* Look for a ':'.  If there is a '::' then get out, otherwise
10075          it is probably a line number.  */
10076       while (*argptr && !hasColon)
10077         {
10078           hasColon = (*argptr == ':');
10079           argptr++;
10080         }
10081
10082       if (hasColon)
10083         badInput = (*argptr == ':');    /* we have class::method */
10084       else
10085         badInput = !isdigit (*arg);     /* not a line number */
10086     }
10087
10088   if (badInput)
10089     printf_filtered (_("Usage: stop at <line>\n"));
10090   else
10091     break_command_1 (arg, 0, from_tty);
10092 }
10093
10094 /* The dynamic printf command is mostly like a regular breakpoint, but
10095    with a prewired command list consisting of a single output command,
10096    built from extra arguments supplied on the dprintf command
10097    line.  */
10098
10099 static void
10100 dprintf_command (char *arg, int from_tty)
10101 {
10102   create_breakpoint (get_current_arch (),
10103                      arg,
10104                      NULL, 0, NULL, 1 /* parse arg */,
10105                      0, bp_dprintf,
10106                      0 /* Ignore count */,
10107                      pending_break_support,
10108                      &dprintf_breakpoint_ops,
10109                      from_tty,
10110                      1 /* enabled */,
10111                      0 /* internal */,
10112                      0);
10113 }
10114
10115 static void
10116 agent_printf_command (char *arg, int from_tty)
10117 {
10118   error (_("May only run agent-printf on the target"));
10119 }
10120
10121 /* Implement the "breakpoint_hit" breakpoint_ops method for
10122    ranged breakpoints.  */
10123
10124 static int
10125 breakpoint_hit_ranged_breakpoint (const struct bp_location *bl,
10126                                   struct address_space *aspace,
10127                                   CORE_ADDR bp_addr,
10128                                   const struct target_waitstatus *ws)
10129 {
10130   if (ws->kind != TARGET_WAITKIND_STOPPED
10131       || ws->value.sig != GDB_SIGNAL_TRAP)
10132     return 0;
10133
10134   return breakpoint_address_match_range (bl->pspace->aspace, bl->address,
10135                                          bl->length, aspace, bp_addr);
10136 }
10137
10138 /* Implement the "resources_needed" breakpoint_ops method for
10139    ranged breakpoints.  */
10140
10141 static int
10142 resources_needed_ranged_breakpoint (const struct bp_location *bl)
10143 {
10144   return target_ranged_break_num_registers ();
10145 }
10146
10147 /* Implement the "print_it" breakpoint_ops method for
10148    ranged breakpoints.  */
10149
10150 static enum print_stop_action
10151 print_it_ranged_breakpoint (bpstat bs)
10152 {
10153   struct breakpoint *b = bs->breakpoint_at;
10154   struct bp_location *bl = b->loc;
10155   struct ui_out *uiout = current_uiout;
10156
10157   gdb_assert (b->type == bp_hardware_breakpoint);
10158
10159   /* Ranged breakpoints have only one location.  */
10160   gdb_assert (bl && bl->next == NULL);
10161
10162   annotate_breakpoint (b->number);
10163   if (b->disposition == disp_del)
10164     ui_out_text (uiout, "\nTemporary ranged breakpoint ");
10165   else
10166     ui_out_text (uiout, "\nRanged breakpoint ");
10167   if (ui_out_is_mi_like_p (uiout))
10168     {
10169       ui_out_field_string (uiout, "reason",
10170                       async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
10171       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
10172     }
10173   ui_out_field_int (uiout, "bkptno", b->number);
10174   ui_out_text (uiout, ", ");
10175
10176   return PRINT_SRC_AND_LOC;
10177 }
10178
10179 /* Implement the "print_one" breakpoint_ops method for
10180    ranged breakpoints.  */
10181
10182 static void
10183 print_one_ranged_breakpoint (struct breakpoint *b,
10184                              struct bp_location **last_loc)
10185 {
10186   struct bp_location *bl = b->loc;
10187   struct value_print_options opts;
10188   struct ui_out *uiout = current_uiout;
10189
10190   /* Ranged breakpoints have only one location.  */
10191   gdb_assert (bl && bl->next == NULL);
10192
10193   get_user_print_options (&opts);
10194
10195   if (opts.addressprint)
10196     /* We don't print the address range here, it will be printed later
10197        by print_one_detail_ranged_breakpoint.  */
10198     ui_out_field_skip (uiout, "addr");
10199   annotate_field (5);
10200   print_breakpoint_location (b, bl);
10201   *last_loc = bl;
10202 }
10203
10204 /* Implement the "print_one_detail" breakpoint_ops method for
10205    ranged breakpoints.  */
10206
10207 static void
10208 print_one_detail_ranged_breakpoint (const struct breakpoint *b,
10209                                     struct ui_out *uiout)
10210 {
10211   CORE_ADDR address_start, address_end;
10212   struct bp_location *bl = b->loc;
10213   struct ui_file *stb = mem_fileopen ();
10214   struct cleanup *cleanup = make_cleanup_ui_file_delete (stb);
10215
10216   gdb_assert (bl);
10217
10218   address_start = bl->address;
10219   address_end = address_start + bl->length - 1;
10220
10221   ui_out_text (uiout, "\taddress range: ");
10222   fprintf_unfiltered (stb, "[%s, %s]",
10223                       print_core_address (bl->gdbarch, address_start),
10224                       print_core_address (bl->gdbarch, address_end));
10225   ui_out_field_stream (uiout, "addr", stb);
10226   ui_out_text (uiout, "\n");
10227
10228   do_cleanups (cleanup);
10229 }
10230
10231 /* Implement the "print_mention" breakpoint_ops method for
10232    ranged breakpoints.  */
10233
10234 static void
10235 print_mention_ranged_breakpoint (struct breakpoint *b)
10236 {
10237   struct bp_location *bl = b->loc;
10238   struct ui_out *uiout = current_uiout;
10239
10240   gdb_assert (bl);
10241   gdb_assert (b->type == bp_hardware_breakpoint);
10242
10243   if (ui_out_is_mi_like_p (uiout))
10244     return;
10245
10246   printf_filtered (_("Hardware assisted ranged breakpoint %d from %s to %s."),
10247                    b->number, paddress (bl->gdbarch, bl->address),
10248                    paddress (bl->gdbarch, bl->address + bl->length - 1));
10249 }
10250
10251 /* Implement the "print_recreate" breakpoint_ops method for
10252    ranged breakpoints.  */
10253
10254 static void
10255 print_recreate_ranged_breakpoint (struct breakpoint *b, struct ui_file *fp)
10256 {
10257   fprintf_unfiltered (fp, "break-range %s, %s", b->addr_string,
10258                       b->addr_string_range_end);
10259   print_recreate_thread (b, fp);
10260 }
10261
10262 /* The breakpoint_ops structure to be used in ranged breakpoints.  */
10263
10264 static struct breakpoint_ops ranged_breakpoint_ops;
10265
10266 /* Find the address where the end of the breakpoint range should be
10267    placed, given the SAL of the end of the range.  This is so that if
10268    the user provides a line number, the end of the range is set to the
10269    last instruction of the given line.  */
10270
10271 static CORE_ADDR
10272 find_breakpoint_range_end (struct symtab_and_line sal)
10273 {
10274   CORE_ADDR end;
10275
10276   /* If the user provided a PC value, use it.  Otherwise,
10277      find the address of the end of the given location.  */
10278   if (sal.explicit_pc)
10279     end = sal.pc;
10280   else
10281     {
10282       int ret;
10283       CORE_ADDR start;
10284
10285       ret = find_line_pc_range (sal, &start, &end);
10286       if (!ret)
10287         error (_("Could not find location of the end of the range."));
10288
10289       /* find_line_pc_range returns the start of the next line.  */
10290       end--;
10291     }
10292
10293   return end;
10294 }
10295
10296 /* Implement the "break-range" CLI command.  */
10297
10298 static void
10299 break_range_command (char *arg, int from_tty)
10300 {
10301   char *arg_start, *addr_string_start, *addr_string_end;
10302   struct linespec_result canonical_start, canonical_end;
10303   int bp_count, can_use_bp, length;
10304   CORE_ADDR end;
10305   struct breakpoint *b;
10306   struct symtab_and_line sal_start, sal_end;
10307   struct cleanup *cleanup_bkpt;
10308   struct linespec_sals *lsal_start, *lsal_end;
10309
10310   /* We don't support software ranged breakpoints.  */
10311   if (target_ranged_break_num_registers () < 0)
10312     error (_("This target does not support hardware ranged breakpoints."));
10313
10314   bp_count = hw_breakpoint_used_count ();
10315   bp_count += target_ranged_break_num_registers ();
10316   can_use_bp = target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
10317                                                    bp_count, 0);
10318   if (can_use_bp < 0)
10319     error (_("Hardware breakpoints used exceeds limit."));
10320
10321   arg = skip_spaces (arg);
10322   if (arg == NULL || arg[0] == '\0')
10323     error(_("No address range specified."));
10324
10325   init_linespec_result (&canonical_start);
10326
10327   arg_start = arg;
10328   parse_breakpoint_sals (&arg, &canonical_start);
10329
10330   cleanup_bkpt = make_cleanup_destroy_linespec_result (&canonical_start);
10331
10332   if (arg[0] != ',')
10333     error (_("Too few arguments."));
10334   else if (VEC_empty (linespec_sals, canonical_start.sals))
10335     error (_("Could not find location of the beginning of the range."));
10336
10337   lsal_start = VEC_index (linespec_sals, canonical_start.sals, 0);
10338
10339   if (VEC_length (linespec_sals, canonical_start.sals) > 1
10340       || lsal_start->sals.nelts != 1)
10341     error (_("Cannot create a ranged breakpoint with multiple locations."));
10342
10343   sal_start = lsal_start->sals.sals[0];
10344   addr_string_start = savestring (arg_start, arg - arg_start);
10345   make_cleanup (xfree, addr_string_start);
10346
10347   arg++;        /* Skip the comma.  */
10348   arg = skip_spaces (arg);
10349
10350   /* Parse the end location.  */
10351
10352   init_linespec_result (&canonical_end);
10353   arg_start = arg;
10354
10355   /* We call decode_line_full directly here instead of using
10356      parse_breakpoint_sals because we need to specify the start location's
10357      symtab and line as the default symtab and line for the end of the
10358      range.  This makes it possible to have ranges like "foo.c:27, +14",
10359      where +14 means 14 lines from the start location.  */
10360   decode_line_full (&arg, DECODE_LINE_FUNFIRSTLINE,
10361                     sal_start.symtab, sal_start.line,
10362                     &canonical_end, NULL, NULL);
10363
10364   make_cleanup_destroy_linespec_result (&canonical_end);
10365
10366   if (VEC_empty (linespec_sals, canonical_end.sals))
10367     error (_("Could not find location of the end of the range."));
10368
10369   lsal_end = VEC_index (linespec_sals, canonical_end.sals, 0);
10370   if (VEC_length (linespec_sals, canonical_end.sals) > 1
10371       || lsal_end->sals.nelts != 1)
10372     error (_("Cannot create a ranged breakpoint with multiple locations."));
10373
10374   sal_end = lsal_end->sals.sals[0];
10375   addr_string_end = savestring (arg_start, arg - arg_start);
10376   make_cleanup (xfree, addr_string_end);
10377
10378   end = find_breakpoint_range_end (sal_end);
10379   if (sal_start.pc > end)
10380     error (_("Invalid address range, end precedes start."));
10381
10382   length = end - sal_start.pc + 1;
10383   if (length < 0)
10384     /* Length overflowed.  */
10385     error (_("Address range too large."));
10386   else if (length == 1)
10387     {
10388       /* This range is simple enough to be handled by
10389          the `hbreak' command.  */
10390       hbreak_command (addr_string_start, 1);
10391
10392       do_cleanups (cleanup_bkpt);
10393
10394       return;
10395     }
10396
10397   /* Now set up the breakpoint.  */
10398   b = set_raw_breakpoint (get_current_arch (), sal_start,
10399                           bp_hardware_breakpoint, &ranged_breakpoint_ops);
10400   set_breakpoint_count (breakpoint_count + 1);
10401   b->number = breakpoint_count;
10402   b->disposition = disp_donttouch;
10403   b->addr_string = xstrdup (addr_string_start);
10404   b->addr_string_range_end = xstrdup (addr_string_end);
10405   b->loc->length = length;
10406
10407   do_cleanups (cleanup_bkpt);
10408
10409   mention (b);
10410   observer_notify_breakpoint_created (b);
10411   update_global_location_list (1);
10412 }
10413
10414 /*  Return non-zero if EXP is verified as constant.  Returned zero
10415     means EXP is variable.  Also the constant detection may fail for
10416     some constant expressions and in such case still falsely return
10417     zero.  */
10418
10419 static int
10420 watchpoint_exp_is_const (const struct expression *exp)
10421 {
10422   int i = exp->nelts;
10423
10424   while (i > 0)
10425     {
10426       int oplenp, argsp;
10427
10428       /* We are only interested in the descriptor of each element.  */
10429       operator_length (exp, i, &oplenp, &argsp);
10430       i -= oplenp;
10431
10432       switch (exp->elts[i].opcode)
10433         {
10434         case BINOP_ADD:
10435         case BINOP_SUB:
10436         case BINOP_MUL:
10437         case BINOP_DIV:
10438         case BINOP_REM:
10439         case BINOP_MOD:
10440         case BINOP_LSH:
10441         case BINOP_RSH:
10442         case BINOP_LOGICAL_AND:
10443         case BINOP_LOGICAL_OR:
10444         case BINOP_BITWISE_AND:
10445         case BINOP_BITWISE_IOR:
10446         case BINOP_BITWISE_XOR:
10447         case BINOP_EQUAL:
10448         case BINOP_NOTEQUAL:
10449         case BINOP_LESS:
10450         case BINOP_GTR:
10451         case BINOP_LEQ:
10452         case BINOP_GEQ:
10453         case BINOP_REPEAT:
10454         case BINOP_COMMA:
10455         case BINOP_EXP:
10456         case BINOP_MIN:
10457         case BINOP_MAX:
10458         case BINOP_INTDIV:
10459         case BINOP_CONCAT:
10460         case BINOP_IN:
10461         case BINOP_RANGE:
10462         case TERNOP_COND:
10463         case TERNOP_SLICE:
10464
10465         case OP_LONG:
10466         case OP_DOUBLE:
10467         case OP_DECFLOAT:
10468         case OP_LAST:
10469         case OP_COMPLEX:
10470         case OP_STRING:
10471         case OP_ARRAY:
10472         case OP_TYPE:
10473         case OP_TYPEOF:
10474         case OP_DECLTYPE:
10475         case OP_TYPEID:
10476         case OP_NAME:
10477         case OP_OBJC_NSSTRING:
10478
10479         case UNOP_NEG:
10480         case UNOP_LOGICAL_NOT:
10481         case UNOP_COMPLEMENT:
10482         case UNOP_ADDR:
10483         case UNOP_HIGH:
10484         case UNOP_CAST:
10485
10486         case UNOP_CAST_TYPE:
10487         case UNOP_REINTERPRET_CAST:
10488         case UNOP_DYNAMIC_CAST:
10489           /* Unary, binary and ternary operators: We have to check
10490              their operands.  If they are constant, then so is the
10491              result of that operation.  For instance, if A and B are
10492              determined to be constants, then so is "A + B".
10493
10494              UNOP_IND is one exception to the rule above, because the
10495              value of *ADDR is not necessarily a constant, even when
10496              ADDR is.  */
10497           break;
10498
10499         case OP_VAR_VALUE:
10500           /* Check whether the associated symbol is a constant.
10501
10502              We use SYMBOL_CLASS rather than TYPE_CONST because it's
10503              possible that a buggy compiler could mark a variable as
10504              constant even when it is not, and TYPE_CONST would return
10505              true in this case, while SYMBOL_CLASS wouldn't.
10506
10507              We also have to check for function symbols because they
10508              are always constant.  */
10509           {
10510             struct symbol *s = exp->elts[i + 2].symbol;
10511
10512             if (SYMBOL_CLASS (s) != LOC_BLOCK
10513                 && SYMBOL_CLASS (s) != LOC_CONST
10514                 && SYMBOL_CLASS (s) != LOC_CONST_BYTES)
10515               return 0;
10516             break;
10517           }
10518
10519         /* The default action is to return 0 because we are using
10520            the optimistic approach here: If we don't know something,
10521            then it is not a constant.  */
10522         default:
10523           return 0;
10524         }
10525     }
10526
10527   return 1;
10528 }
10529
10530 /* Implement the "dtor" breakpoint_ops method for watchpoints.  */
10531
10532 static void
10533 dtor_watchpoint (struct breakpoint *self)
10534 {
10535   struct watchpoint *w = (struct watchpoint *) self;
10536
10537   xfree (w->cond_exp);
10538   xfree (w->exp);
10539   xfree (w->exp_string);
10540   xfree (w->exp_string_reparse);
10541   value_free (w->val);
10542
10543   base_breakpoint_ops.dtor (self);
10544 }
10545
10546 /* Implement the "re_set" breakpoint_ops method for watchpoints.  */
10547
10548 static void
10549 re_set_watchpoint (struct breakpoint *b)
10550 {
10551   struct watchpoint *w = (struct watchpoint *) b;
10552
10553   /* Watchpoint can be either on expression using entirely global
10554      variables, or it can be on local variables.
10555
10556      Watchpoints of the first kind are never auto-deleted, and even
10557      persist across program restarts.  Since they can use variables
10558      from shared libraries, we need to reparse expression as libraries
10559      are loaded and unloaded.
10560
10561      Watchpoints on local variables can also change meaning as result
10562      of solib event.  For example, if a watchpoint uses both a local
10563      and a global variables in expression, it's a local watchpoint,
10564      but unloading of a shared library will make the expression
10565      invalid.  This is not a very common use case, but we still
10566      re-evaluate expression, to avoid surprises to the user.
10567
10568      Note that for local watchpoints, we re-evaluate it only if
10569      watchpoints frame id is still valid.  If it's not, it means the
10570      watchpoint is out of scope and will be deleted soon.  In fact,
10571      I'm not sure we'll ever be called in this case.
10572
10573      If a local watchpoint's frame id is still valid, then
10574      w->exp_valid_block is likewise valid, and we can safely use it.
10575
10576      Don't do anything about disabled watchpoints, since they will be
10577      reevaluated again when enabled.  */
10578   update_watchpoint (w, 1 /* reparse */);
10579 }
10580
10581 /* Implement the "insert" breakpoint_ops method for hardware watchpoints.  */
10582
10583 static int
10584 insert_watchpoint (struct bp_location *bl)
10585 {
10586   struct watchpoint *w = (struct watchpoint *) bl->owner;
10587   int length = w->exact ? 1 : bl->length;
10588
10589   return target_insert_watchpoint (bl->address, length, bl->watchpoint_type,
10590                                    w->cond_exp);
10591 }
10592
10593 /* Implement the "remove" breakpoint_ops method for hardware watchpoints.  */
10594
10595 static int
10596 remove_watchpoint (struct bp_location *bl)
10597 {
10598   struct watchpoint *w = (struct watchpoint *) bl->owner;
10599   int length = w->exact ? 1 : bl->length;
10600
10601   return target_remove_watchpoint (bl->address, length, bl->watchpoint_type,
10602                                    w->cond_exp);
10603 }
10604
10605 static int
10606 breakpoint_hit_watchpoint (const struct bp_location *bl,
10607                            struct address_space *aspace, CORE_ADDR bp_addr,
10608                            const struct target_waitstatus *ws)
10609 {
10610   struct breakpoint *b = bl->owner;
10611   struct watchpoint *w = (struct watchpoint *) b;
10612
10613   /* Continuable hardware watchpoints are treated as non-existent if the
10614      reason we stopped wasn't a hardware watchpoint (we didn't stop on
10615      some data address).  Otherwise gdb won't stop on a break instruction
10616      in the code (not from a breakpoint) when a hardware watchpoint has
10617      been defined.  Also skip watchpoints which we know did not trigger
10618      (did not match the data address).  */
10619   if (is_hardware_watchpoint (b)
10620       && w->watchpoint_triggered == watch_triggered_no)
10621     return 0;
10622
10623   return 1;
10624 }
10625
10626 static void
10627 check_status_watchpoint (bpstat bs)
10628 {
10629   gdb_assert (is_watchpoint (bs->breakpoint_at));
10630
10631   bpstat_check_watchpoint (bs);
10632 }
10633
10634 /* Implement the "resources_needed" breakpoint_ops method for
10635    hardware watchpoints.  */
10636
10637 static int
10638 resources_needed_watchpoint (const struct bp_location *bl)
10639 {
10640   struct watchpoint *w = (struct watchpoint *) bl->owner;
10641   int length = w->exact? 1 : bl->length;
10642
10643   return target_region_ok_for_hw_watchpoint (bl->address, length);
10644 }
10645
10646 /* Implement the "works_in_software_mode" breakpoint_ops method for
10647    hardware watchpoints.  */
10648
10649 static int
10650 works_in_software_mode_watchpoint (const struct breakpoint *b)
10651 {
10652   /* Read and access watchpoints only work with hardware support.  */
10653   return b->type == bp_watchpoint || b->type == bp_hardware_watchpoint;
10654 }
10655
10656 static enum print_stop_action
10657 print_it_watchpoint (bpstat bs)
10658 {
10659   struct cleanup *old_chain;
10660   struct breakpoint *b;
10661   struct ui_file *stb;
10662   enum print_stop_action result;
10663   struct watchpoint *w;
10664   struct ui_out *uiout = current_uiout;
10665
10666   gdb_assert (bs->bp_location_at != NULL);
10667
10668   b = bs->breakpoint_at;
10669   w = (struct watchpoint *) b;
10670
10671   stb = mem_fileopen ();
10672   old_chain = make_cleanup_ui_file_delete (stb);
10673
10674   switch (b->type)
10675     {
10676     case bp_watchpoint:
10677     case bp_hardware_watchpoint:
10678       annotate_watchpoint (b->number);
10679       if (ui_out_is_mi_like_p (uiout))
10680         ui_out_field_string
10681           (uiout, "reason",
10682            async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
10683       mention (b);
10684       make_cleanup_ui_out_tuple_begin_end (uiout, "value");
10685       ui_out_text (uiout, "\nOld value = ");
10686       watchpoint_value_print (bs->old_val, stb);
10687       ui_out_field_stream (uiout, "old", stb);
10688       ui_out_text (uiout, "\nNew value = ");
10689       watchpoint_value_print (w->val, stb);
10690       ui_out_field_stream (uiout, "new", stb);
10691       ui_out_text (uiout, "\n");
10692       /* More than one watchpoint may have been triggered.  */
10693       result = PRINT_UNKNOWN;
10694       break;
10695
10696     case bp_read_watchpoint:
10697       if (ui_out_is_mi_like_p (uiout))
10698         ui_out_field_string
10699           (uiout, "reason",
10700            async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
10701       mention (b);
10702       make_cleanup_ui_out_tuple_begin_end (uiout, "value");
10703       ui_out_text (uiout, "\nValue = ");
10704       watchpoint_value_print (w->val, stb);
10705       ui_out_field_stream (uiout, "value", stb);
10706       ui_out_text (uiout, "\n");
10707       result = PRINT_UNKNOWN;
10708       break;
10709
10710     case bp_access_watchpoint:
10711       if (bs->old_val != NULL)
10712         {
10713           annotate_watchpoint (b->number);
10714           if (ui_out_is_mi_like_p (uiout))
10715             ui_out_field_string
10716               (uiout, "reason",
10717                async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10718           mention (b);
10719           make_cleanup_ui_out_tuple_begin_end (uiout, "value");
10720           ui_out_text (uiout, "\nOld value = ");
10721           watchpoint_value_print (bs->old_val, stb);
10722           ui_out_field_stream (uiout, "old", stb);
10723           ui_out_text (uiout, "\nNew value = ");
10724         }
10725       else
10726         {
10727           mention (b);
10728           if (ui_out_is_mi_like_p (uiout))
10729             ui_out_field_string
10730               (uiout, "reason",
10731                async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10732           make_cleanup_ui_out_tuple_begin_end (uiout, "value");
10733           ui_out_text (uiout, "\nValue = ");
10734         }
10735       watchpoint_value_print (w->val, stb);
10736       ui_out_field_stream (uiout, "new", stb);
10737       ui_out_text (uiout, "\n");
10738       result = PRINT_UNKNOWN;
10739       break;
10740     default:
10741       result = PRINT_UNKNOWN;
10742     }
10743
10744   do_cleanups (old_chain);
10745   return result;
10746 }
10747
10748 /* Implement the "print_mention" breakpoint_ops method for hardware
10749    watchpoints.  */
10750
10751 static void
10752 print_mention_watchpoint (struct breakpoint *b)
10753 {
10754   struct cleanup *ui_out_chain;
10755   struct watchpoint *w = (struct watchpoint *) b;
10756   struct ui_out *uiout = current_uiout;
10757
10758   switch (b->type)
10759     {
10760     case bp_watchpoint:
10761       ui_out_text (uiout, "Watchpoint ");
10762       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "wpt");
10763       break;
10764     case bp_hardware_watchpoint:
10765       ui_out_text (uiout, "Hardware watchpoint ");
10766       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "wpt");
10767       break;
10768     case bp_read_watchpoint:
10769       ui_out_text (uiout, "Hardware read watchpoint ");
10770       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-rwpt");
10771       break;
10772     case bp_access_watchpoint:
10773       ui_out_text (uiout, "Hardware access (read/write) watchpoint ");
10774       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-awpt");
10775       break;
10776     default:
10777       internal_error (__FILE__, __LINE__,
10778                       _("Invalid hardware watchpoint type."));
10779     }
10780
10781   ui_out_field_int (uiout, "number", b->number);
10782   ui_out_text (uiout, ": ");
10783   ui_out_field_string (uiout, "exp", w->exp_string);
10784   do_cleanups (ui_out_chain);
10785 }
10786
10787 /* Implement the "print_recreate" breakpoint_ops method for
10788    watchpoints.  */
10789
10790 static void
10791 print_recreate_watchpoint (struct breakpoint *b, struct ui_file *fp)
10792 {
10793   struct watchpoint *w = (struct watchpoint *) b;
10794
10795   switch (b->type)
10796     {
10797     case bp_watchpoint:
10798     case bp_hardware_watchpoint:
10799       fprintf_unfiltered (fp, "watch");
10800       break;
10801     case bp_read_watchpoint:
10802       fprintf_unfiltered (fp, "rwatch");
10803       break;
10804     case bp_access_watchpoint:
10805       fprintf_unfiltered (fp, "awatch");
10806       break;
10807     default:
10808       internal_error (__FILE__, __LINE__,
10809                       _("Invalid watchpoint type."));
10810     }
10811
10812   fprintf_unfiltered (fp, " %s", w->exp_string);
10813   print_recreate_thread (b, fp);
10814 }
10815
10816 /* Implement the "explains_signal" breakpoint_ops method for
10817    watchpoints.  */
10818
10819 static int
10820 explains_signal_watchpoint (struct breakpoint *b, enum gdb_signal sig)
10821 {
10822   /* A software watchpoint cannot cause a signal other than
10823      GDB_SIGNAL_TRAP.  */
10824   if (b->type == bp_watchpoint && sig != GDB_SIGNAL_TRAP)
10825     return 0;
10826
10827   return 1;
10828 }
10829
10830 /* The breakpoint_ops structure to be used in hardware watchpoints.  */
10831
10832 static struct breakpoint_ops watchpoint_breakpoint_ops;
10833
10834 /* Implement the "insert" breakpoint_ops method for
10835    masked hardware watchpoints.  */
10836
10837 static int
10838 insert_masked_watchpoint (struct bp_location *bl)
10839 {
10840   struct watchpoint *w = (struct watchpoint *) bl->owner;
10841
10842   return target_insert_mask_watchpoint (bl->address, w->hw_wp_mask,
10843                                         bl->watchpoint_type);
10844 }
10845
10846 /* Implement the "remove" breakpoint_ops method for
10847    masked hardware watchpoints.  */
10848
10849 static int
10850 remove_masked_watchpoint (struct bp_location *bl)
10851 {
10852   struct watchpoint *w = (struct watchpoint *) bl->owner;
10853
10854   return target_remove_mask_watchpoint (bl->address, w->hw_wp_mask,
10855                                         bl->watchpoint_type);
10856 }
10857
10858 /* Implement the "resources_needed" breakpoint_ops method for
10859    masked hardware watchpoints.  */
10860
10861 static int
10862 resources_needed_masked_watchpoint (const struct bp_location *bl)
10863 {
10864   struct watchpoint *w = (struct watchpoint *) bl->owner;
10865
10866   return target_masked_watch_num_registers (bl->address, w->hw_wp_mask);
10867 }
10868
10869 /* Implement the "works_in_software_mode" breakpoint_ops method for
10870    masked hardware watchpoints.  */
10871
10872 static int
10873 works_in_software_mode_masked_watchpoint (const struct breakpoint *b)
10874 {
10875   return 0;
10876 }
10877
10878 /* Implement the "print_it" breakpoint_ops method for
10879    masked hardware watchpoints.  */
10880
10881 static enum print_stop_action
10882 print_it_masked_watchpoint (bpstat bs)
10883 {
10884   struct breakpoint *b = bs->breakpoint_at;
10885   struct ui_out *uiout = current_uiout;
10886
10887   /* Masked watchpoints have only one location.  */
10888   gdb_assert (b->loc && b->loc->next == NULL);
10889
10890   switch (b->type)
10891     {
10892     case bp_hardware_watchpoint:
10893       annotate_watchpoint (b->number);
10894       if (ui_out_is_mi_like_p (uiout))
10895         ui_out_field_string
10896           (uiout, "reason",
10897            async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
10898       break;
10899
10900     case bp_read_watchpoint:
10901       if (ui_out_is_mi_like_p (uiout))
10902         ui_out_field_string
10903           (uiout, "reason",
10904            async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
10905       break;
10906
10907     case bp_access_watchpoint:
10908       if (ui_out_is_mi_like_p (uiout))
10909         ui_out_field_string
10910           (uiout, "reason",
10911            async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10912       break;
10913     default:
10914       internal_error (__FILE__, __LINE__,
10915                       _("Invalid hardware watchpoint type."));
10916     }
10917
10918   mention (b);
10919   ui_out_text (uiout, _("\n\
10920 Check the underlying instruction at PC for the memory\n\
10921 address and value which triggered this watchpoint.\n"));
10922   ui_out_text (uiout, "\n");
10923
10924   /* More than one watchpoint may have been triggered.  */
10925   return PRINT_UNKNOWN;
10926 }
10927
10928 /* Implement the "print_one_detail" breakpoint_ops method for
10929    masked hardware watchpoints.  */
10930
10931 static void
10932 print_one_detail_masked_watchpoint (const struct breakpoint *b,
10933                                     struct ui_out *uiout)
10934 {
10935   struct watchpoint *w = (struct watchpoint *) b;
10936
10937   /* Masked watchpoints have only one location.  */
10938   gdb_assert (b->loc && b->loc->next == NULL);
10939
10940   ui_out_text (uiout, "\tmask ");
10941   ui_out_field_core_addr (uiout, "mask", b->loc->gdbarch, w->hw_wp_mask);
10942   ui_out_text (uiout, "\n");
10943 }
10944
10945 /* Implement the "print_mention" breakpoint_ops method for
10946    masked hardware watchpoints.  */
10947
10948 static void
10949 print_mention_masked_watchpoint (struct breakpoint *b)
10950 {
10951   struct watchpoint *w = (struct watchpoint *) b;
10952   struct ui_out *uiout = current_uiout;
10953   struct cleanup *ui_out_chain;
10954
10955   switch (b->type)
10956     {
10957     case bp_hardware_watchpoint:
10958       ui_out_text (uiout, "Masked hardware watchpoint ");
10959       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "wpt");
10960       break;
10961     case bp_read_watchpoint:
10962       ui_out_text (uiout, "Masked hardware read watchpoint ");
10963       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-rwpt");
10964       break;
10965     case bp_access_watchpoint:
10966       ui_out_text (uiout, "Masked hardware access (read/write) watchpoint ");
10967       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-awpt");
10968       break;
10969     default:
10970       internal_error (__FILE__, __LINE__,
10971                       _("Invalid hardware watchpoint type."));
10972     }
10973
10974   ui_out_field_int (uiout, "number", b->number);
10975   ui_out_text (uiout, ": ");
10976   ui_out_field_string (uiout, "exp", w->exp_string);
10977   do_cleanups (ui_out_chain);
10978 }
10979
10980 /* Implement the "print_recreate" breakpoint_ops method for
10981    masked hardware watchpoints.  */
10982
10983 static void
10984 print_recreate_masked_watchpoint (struct breakpoint *b, struct ui_file *fp)
10985 {
10986   struct watchpoint *w = (struct watchpoint *) b;
10987   char tmp[40];
10988
10989   switch (b->type)
10990     {
10991     case bp_hardware_watchpoint:
10992       fprintf_unfiltered (fp, "watch");
10993       break;
10994     case bp_read_watchpoint:
10995       fprintf_unfiltered (fp, "rwatch");
10996       break;
10997     case bp_access_watchpoint:
10998       fprintf_unfiltered (fp, "awatch");
10999       break;
11000     default:
11001       internal_error (__FILE__, __LINE__,
11002                       _("Invalid hardware watchpoint type."));
11003     }
11004
11005   sprintf_vma (tmp, w->hw_wp_mask);
11006   fprintf_unfiltered (fp, " %s mask 0x%s", w->exp_string, tmp);
11007   print_recreate_thread (b, fp);
11008 }
11009
11010 /* The breakpoint_ops structure to be used in masked hardware watchpoints.  */
11011
11012 static struct breakpoint_ops masked_watchpoint_breakpoint_ops;
11013
11014 /* Tell whether the given watchpoint is a masked hardware watchpoint.  */
11015
11016 static int
11017 is_masked_watchpoint (const struct breakpoint *b)
11018 {
11019   return b->ops == &masked_watchpoint_breakpoint_ops;
11020 }
11021
11022 /* accessflag:  hw_write:  watch write, 
11023                 hw_read:   watch read, 
11024                 hw_access: watch access (read or write) */
11025 static void
11026 watch_command_1 (const char *arg, int accessflag, int from_tty,
11027                  int just_location, int internal)
11028 {
11029   volatile struct gdb_exception e;
11030   struct breakpoint *b, *scope_breakpoint = NULL;
11031   struct expression *exp;
11032   const struct block *exp_valid_block = NULL, *cond_exp_valid_block = NULL;
11033   struct value *val, *mark, *result;
11034   struct frame_info *frame;
11035   const char *exp_start = NULL;
11036   const char *exp_end = NULL;
11037   const char *tok, *end_tok;
11038   int toklen = -1;
11039   const char *cond_start = NULL;
11040   const char *cond_end = NULL;
11041   enum bptype bp_type;
11042   int thread = -1;
11043   int pc = 0;
11044   /* Flag to indicate whether we are going to use masks for
11045      the hardware watchpoint.  */
11046   int use_mask = 0;
11047   CORE_ADDR mask = 0;
11048   struct watchpoint *w;
11049   char *expression;
11050   struct cleanup *back_to;
11051
11052   /* Make sure that we actually have parameters to parse.  */
11053   if (arg != NULL && arg[0] != '\0')
11054     {
11055       const char *value_start;
11056
11057       exp_end = arg + strlen (arg);
11058
11059       /* Look for "parameter value" pairs at the end
11060          of the arguments string.  */
11061       for (tok = exp_end - 1; tok > arg; tok--)
11062         {
11063           /* Skip whitespace at the end of the argument list.  */
11064           while (tok > arg && (*tok == ' ' || *tok == '\t'))
11065             tok--;
11066
11067           /* Find the beginning of the last token.
11068              This is the value of the parameter.  */
11069           while (tok > arg && (*tok != ' ' && *tok != '\t'))
11070             tok--;
11071           value_start = tok + 1;
11072
11073           /* Skip whitespace.  */
11074           while (tok > arg && (*tok == ' ' || *tok == '\t'))
11075             tok--;
11076
11077           end_tok = tok;
11078
11079           /* Find the beginning of the second to last token.
11080              This is the parameter itself.  */
11081           while (tok > arg && (*tok != ' ' && *tok != '\t'))
11082             tok--;
11083           tok++;
11084           toklen = end_tok - tok + 1;
11085
11086           if (toklen == 6 && !strncmp (tok, "thread", 6))
11087             {
11088               /* At this point we've found a "thread" token, which means
11089                  the user is trying to set a watchpoint that triggers
11090                  only in a specific thread.  */
11091               char *endp;
11092
11093               if (thread != -1)
11094                 error(_("You can specify only one thread."));
11095
11096               /* Extract the thread ID from the next token.  */
11097               thread = strtol (value_start, &endp, 0);
11098
11099               /* Check if the user provided a valid numeric value for the
11100                  thread ID.  */
11101               if (*endp != ' ' && *endp != '\t' && *endp != '\0')
11102                 error (_("Invalid thread ID specification %s."), value_start);
11103
11104               /* Check if the thread actually exists.  */
11105               if (!valid_thread_id (thread))
11106                 invalid_thread_id_error (thread);
11107             }
11108           else if (toklen == 4 && !strncmp (tok, "mask", 4))
11109             {
11110               /* We've found a "mask" token, which means the user wants to
11111                  create a hardware watchpoint that is going to have the mask
11112                  facility.  */
11113               struct value *mask_value, *mark;
11114
11115               if (use_mask)
11116                 error(_("You can specify only one mask."));
11117
11118               use_mask = just_location = 1;
11119
11120               mark = value_mark ();
11121               mask_value = parse_to_comma_and_eval (&value_start);
11122               mask = value_as_address (mask_value);
11123               value_free_to_mark (mark);
11124             }
11125           else
11126             /* We didn't recognize what we found.  We should stop here.  */
11127             break;
11128
11129           /* Truncate the string and get rid of the "parameter value" pair before
11130              the arguments string is parsed by the parse_exp_1 function.  */
11131           exp_end = tok;
11132         }
11133     }
11134   else
11135     exp_end = arg;
11136
11137   /* Parse the rest of the arguments.  From here on out, everything
11138      is in terms of a newly allocated string instead of the original
11139      ARG.  */
11140   innermost_block = NULL;
11141   expression = savestring (arg, exp_end - arg);
11142   back_to = make_cleanup (xfree, expression);
11143   exp_start = arg = expression;
11144   exp = parse_exp_1 (&arg, 0, 0, 0);
11145   exp_end = arg;
11146   /* Remove trailing whitespace from the expression before saving it.
11147      This makes the eventual display of the expression string a bit
11148      prettier.  */
11149   while (exp_end > exp_start && (exp_end[-1] == ' ' || exp_end[-1] == '\t'))
11150     --exp_end;
11151
11152   /* Checking if the expression is not constant.  */
11153   if (watchpoint_exp_is_const (exp))
11154     {
11155       int len;
11156
11157       len = exp_end - exp_start;
11158       while (len > 0 && isspace (exp_start[len - 1]))
11159         len--;
11160       error (_("Cannot watch constant value `%.*s'."), len, exp_start);
11161     }
11162
11163   exp_valid_block = innermost_block;
11164   mark = value_mark ();
11165   fetch_subexp_value (exp, &pc, &val, &result, NULL, just_location);
11166
11167   if (just_location)
11168     {
11169       int ret;
11170
11171       exp_valid_block = NULL;
11172       val = value_addr (result);
11173       release_value (val);
11174       value_free_to_mark (mark);
11175
11176       if (use_mask)
11177         {
11178           ret = target_masked_watch_num_registers (value_as_address (val),
11179                                                    mask);
11180           if (ret == -1)
11181             error (_("This target does not support masked watchpoints."));
11182           else if (ret == -2)
11183             error (_("Invalid mask or memory region."));
11184         }
11185     }
11186   else if (val != NULL)
11187     release_value (val);
11188
11189   tok = skip_spaces_const (arg);
11190   end_tok = skip_to_space_const (tok);
11191
11192   toklen = end_tok - tok;
11193   if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
11194     {
11195       struct expression *cond;
11196
11197       innermost_block = NULL;
11198       tok = cond_start = end_tok + 1;
11199       cond = parse_exp_1 (&tok, 0, 0, 0);
11200
11201       /* The watchpoint expression may not be local, but the condition
11202          may still be.  E.g.: `watch global if local > 0'.  */
11203       cond_exp_valid_block = innermost_block;
11204
11205       xfree (cond);
11206       cond_end = tok;
11207     }
11208   if (*tok)
11209     error (_("Junk at end of command."));
11210
11211   frame = block_innermost_frame (exp_valid_block);
11212
11213   /* If the expression is "local", then set up a "watchpoint scope"
11214      breakpoint at the point where we've left the scope of the watchpoint
11215      expression.  Create the scope breakpoint before the watchpoint, so
11216      that we will encounter it first in bpstat_stop_status.  */
11217   if (exp_valid_block && frame)
11218     {
11219       if (frame_id_p (frame_unwind_caller_id (frame)))
11220         {
11221           scope_breakpoint
11222             = create_internal_breakpoint (frame_unwind_caller_arch (frame),
11223                                           frame_unwind_caller_pc (frame),
11224                                           bp_watchpoint_scope,
11225                                           &momentary_breakpoint_ops);
11226
11227           scope_breakpoint->enable_state = bp_enabled;
11228
11229           /* Automatically delete the breakpoint when it hits.  */
11230           scope_breakpoint->disposition = disp_del;
11231
11232           /* Only break in the proper frame (help with recursion).  */
11233           scope_breakpoint->frame_id = frame_unwind_caller_id (frame);
11234
11235           /* Set the address at which we will stop.  */
11236           scope_breakpoint->loc->gdbarch
11237             = frame_unwind_caller_arch (frame);
11238           scope_breakpoint->loc->requested_address
11239             = frame_unwind_caller_pc (frame);
11240           scope_breakpoint->loc->address
11241             = adjust_breakpoint_address (scope_breakpoint->loc->gdbarch,
11242                                          scope_breakpoint->loc->requested_address,
11243                                          scope_breakpoint->type);
11244         }
11245     }
11246
11247   /* Now set up the breakpoint.  We create all watchpoints as hardware
11248      watchpoints here even if hardware watchpoints are turned off, a call
11249      to update_watchpoint later in this function will cause the type to
11250      drop back to bp_watchpoint (software watchpoint) if required.  */
11251
11252   if (accessflag == hw_read)
11253     bp_type = bp_read_watchpoint;
11254   else if (accessflag == hw_access)
11255     bp_type = bp_access_watchpoint;
11256   else
11257     bp_type = bp_hardware_watchpoint;
11258
11259   w = XCNEW (struct watchpoint);
11260   b = &w->base;
11261   if (use_mask)
11262     init_raw_breakpoint_without_location (b, NULL, bp_type,
11263                                           &masked_watchpoint_breakpoint_ops);
11264   else
11265     init_raw_breakpoint_without_location (b, NULL, bp_type,
11266                                           &watchpoint_breakpoint_ops);
11267   b->thread = thread;
11268   b->disposition = disp_donttouch;
11269   b->pspace = current_program_space;
11270   w->exp = exp;
11271   w->exp_valid_block = exp_valid_block;
11272   w->cond_exp_valid_block = cond_exp_valid_block;
11273   if (just_location)
11274     {
11275       struct type *t = value_type (val);
11276       CORE_ADDR addr = value_as_address (val);
11277       char *name;
11278
11279       t = check_typedef (TYPE_TARGET_TYPE (check_typedef (t)));
11280       name = type_to_string (t);
11281
11282       w->exp_string_reparse = xstrprintf ("* (%s *) %s", name,
11283                                           core_addr_to_string (addr));
11284       xfree (name);
11285
11286       w->exp_string = xstrprintf ("-location %.*s",
11287                                   (int) (exp_end - exp_start), exp_start);
11288
11289       /* The above expression is in C.  */
11290       b->language = language_c;
11291     }
11292   else
11293     w->exp_string = savestring (exp_start, exp_end - exp_start);
11294
11295   if (use_mask)
11296     {
11297       w->hw_wp_mask = mask;
11298     }
11299   else
11300     {
11301       w->val = val;
11302       w->val_valid = 1;
11303     }
11304
11305   if (cond_start)
11306     b->cond_string = savestring (cond_start, cond_end - cond_start);
11307   else
11308     b->cond_string = 0;
11309
11310   if (frame)
11311     {
11312       w->watchpoint_frame = get_frame_id (frame);
11313       w->watchpoint_thread = inferior_ptid;
11314     }
11315   else
11316     {
11317       w->watchpoint_frame = null_frame_id;
11318       w->watchpoint_thread = null_ptid;
11319     }
11320
11321   if (scope_breakpoint != NULL)
11322     {
11323       /* The scope breakpoint is related to the watchpoint.  We will
11324          need to act on them together.  */
11325       b->related_breakpoint = scope_breakpoint;
11326       scope_breakpoint->related_breakpoint = b;
11327     }
11328
11329   if (!just_location)
11330     value_free_to_mark (mark);
11331
11332   TRY_CATCH (e, RETURN_MASK_ALL)
11333     {
11334       /* Finally update the new watchpoint.  This creates the locations
11335          that should be inserted.  */
11336       update_watchpoint (w, 1);
11337     }
11338   if (e.reason < 0)
11339     {
11340       delete_breakpoint (b);
11341       throw_exception (e);
11342     }
11343
11344   install_breakpoint (internal, b, 1);
11345   do_cleanups (back_to);
11346 }
11347
11348 /* Return count of debug registers needed to watch the given expression.
11349    If the watchpoint cannot be handled in hardware return zero.  */
11350
11351 static int
11352 can_use_hardware_watchpoint (struct value *v)
11353 {
11354   int found_memory_cnt = 0;
11355   struct value *head = v;
11356
11357   /* Did the user specifically forbid us to use hardware watchpoints? */
11358   if (!can_use_hw_watchpoints)
11359     return 0;
11360
11361   /* Make sure that the value of the expression depends only upon
11362      memory contents, and values computed from them within GDB.  If we
11363      find any register references or function calls, we can't use a
11364      hardware watchpoint.
11365
11366      The idea here is that evaluating an expression generates a series
11367      of values, one holding the value of every subexpression.  (The
11368      expression a*b+c has five subexpressions: a, b, a*b, c, and
11369      a*b+c.)  GDB's values hold almost enough information to establish
11370      the criteria given above --- they identify memory lvalues,
11371      register lvalues, computed values, etcetera.  So we can evaluate
11372      the expression, and then scan the chain of values that leaves
11373      behind to decide whether we can detect any possible change to the
11374      expression's final value using only hardware watchpoints.
11375
11376      However, I don't think that the values returned by inferior
11377      function calls are special in any way.  So this function may not
11378      notice that an expression involving an inferior function call
11379      can't be watched with hardware watchpoints.  FIXME.  */
11380   for (; v; v = value_next (v))
11381     {
11382       if (VALUE_LVAL (v) == lval_memory)
11383         {
11384           if (v != head && value_lazy (v))
11385             /* A lazy memory lvalue in the chain is one that GDB never
11386                needed to fetch; we either just used its address (e.g.,
11387                `a' in `a.b') or we never needed it at all (e.g., `a'
11388                in `a,b').  This doesn't apply to HEAD; if that is
11389                lazy then it was not readable, but watch it anyway.  */
11390             ;
11391           else
11392             {
11393               /* Ahh, memory we actually used!  Check if we can cover
11394                  it with hardware watchpoints.  */
11395               struct type *vtype = check_typedef (value_type (v));
11396
11397               /* We only watch structs and arrays if user asked for it
11398                  explicitly, never if they just happen to appear in a
11399                  middle of some value chain.  */
11400               if (v == head
11401                   || (TYPE_CODE (vtype) != TYPE_CODE_STRUCT
11402                       && TYPE_CODE (vtype) != TYPE_CODE_ARRAY))
11403                 {
11404                   CORE_ADDR vaddr = value_address (v);
11405                   int len;
11406                   int num_regs;
11407
11408                   len = (target_exact_watchpoints
11409                          && is_scalar_type_recursive (vtype))?
11410                     1 : TYPE_LENGTH (value_type (v));
11411
11412                   num_regs = target_region_ok_for_hw_watchpoint (vaddr, len);
11413                   if (!num_regs)
11414                     return 0;
11415                   else
11416                     found_memory_cnt += num_regs;
11417                 }
11418             }
11419         }
11420       else if (VALUE_LVAL (v) != not_lval
11421                && deprecated_value_modifiable (v) == 0)
11422         return 0;       /* These are values from the history (e.g., $1).  */
11423       else if (VALUE_LVAL (v) == lval_register)
11424         return 0;       /* Cannot watch a register with a HW watchpoint.  */
11425     }
11426
11427   /* The expression itself looks suitable for using a hardware
11428      watchpoint, but give the target machine a chance to reject it.  */
11429   return found_memory_cnt;
11430 }
11431
11432 void
11433 watch_command_wrapper (char *arg, int from_tty, int internal)
11434 {
11435   watch_command_1 (arg, hw_write, from_tty, 0, internal);
11436 }
11437
11438 /* A helper function that looks for the "-location" argument and then
11439    calls watch_command_1.  */
11440
11441 static void
11442 watch_maybe_just_location (char *arg, int accessflag, int from_tty)
11443 {
11444   int just_location = 0;
11445
11446   if (arg
11447       && (check_for_argument (&arg, "-location", sizeof ("-location") - 1)
11448           || check_for_argument (&arg, "-l", sizeof ("-l") - 1)))
11449     {
11450       arg = skip_spaces (arg);
11451       just_location = 1;
11452     }
11453
11454   watch_command_1 (arg, accessflag, from_tty, just_location, 0);
11455 }
11456
11457 static void
11458 watch_command (char *arg, int from_tty)
11459 {
11460   watch_maybe_just_location (arg, hw_write, from_tty);
11461 }
11462
11463 void
11464 rwatch_command_wrapper (char *arg, int from_tty, int internal)
11465 {
11466   watch_command_1 (arg, hw_read, from_tty, 0, internal);
11467 }
11468
11469 static void
11470 rwatch_command (char *arg, int from_tty)
11471 {
11472   watch_maybe_just_location (arg, hw_read, from_tty);
11473 }
11474
11475 void
11476 awatch_command_wrapper (char *arg, int from_tty, int internal)
11477 {
11478   watch_command_1 (arg, hw_access, from_tty, 0, internal);
11479 }
11480
11481 static void
11482 awatch_command (char *arg, int from_tty)
11483 {
11484   watch_maybe_just_location (arg, hw_access, from_tty);
11485 }
11486 \f
11487
11488 /* Helper routines for the until_command routine in infcmd.c.  Here
11489    because it uses the mechanisms of breakpoints.  */
11490
11491 struct until_break_command_continuation_args
11492 {
11493   struct breakpoint *breakpoint;
11494   struct breakpoint *breakpoint2;
11495   int thread_num;
11496 };
11497
11498 /* This function is called by fetch_inferior_event via the
11499    cmd_continuation pointer, to complete the until command.  It takes
11500    care of cleaning up the temporary breakpoints set up by the until
11501    command.  */
11502 static void
11503 until_break_command_continuation (void *arg, int err)
11504 {
11505   struct until_break_command_continuation_args *a = arg;
11506
11507   delete_breakpoint (a->breakpoint);
11508   if (a->breakpoint2)
11509     delete_breakpoint (a->breakpoint2);
11510   delete_longjmp_breakpoint (a->thread_num);
11511 }
11512
11513 void
11514 until_break_command (char *arg, int from_tty, int anywhere)
11515 {
11516   struct symtabs_and_lines sals;
11517   struct symtab_and_line sal;
11518   struct frame_info *frame;
11519   struct gdbarch *frame_gdbarch;
11520   struct frame_id stack_frame_id;
11521   struct frame_id caller_frame_id;
11522   struct breakpoint *breakpoint;
11523   struct breakpoint *breakpoint2 = NULL;
11524   struct cleanup *old_chain;
11525   int thread;
11526   struct thread_info *tp;
11527
11528   clear_proceed_status ();
11529
11530   /* Set a breakpoint where the user wants it and at return from
11531      this function.  */
11532
11533   if (last_displayed_sal_is_valid ())
11534     sals = decode_line_1 (&arg, DECODE_LINE_FUNFIRSTLINE,
11535                           get_last_displayed_symtab (),
11536                           get_last_displayed_line ());
11537   else
11538     sals = decode_line_1 (&arg, DECODE_LINE_FUNFIRSTLINE,
11539                           (struct symtab *) NULL, 0);
11540
11541   if (sals.nelts != 1)
11542     error (_("Couldn't get information on specified line."));
11543
11544   sal = sals.sals[0];
11545   xfree (sals.sals);    /* malloc'd, so freed.  */
11546
11547   if (*arg)
11548     error (_("Junk at end of arguments."));
11549
11550   resolve_sal_pc (&sal);
11551
11552   tp = inferior_thread ();
11553   thread = tp->num;
11554
11555   old_chain = make_cleanup (null_cleanup, NULL);
11556
11557   /* Note linespec handling above invalidates the frame chain.
11558      Installing a breakpoint also invalidates the frame chain (as it
11559      may need to switch threads), so do any frame handling before
11560      that.  */
11561
11562   frame = get_selected_frame (NULL);
11563   frame_gdbarch = get_frame_arch (frame);
11564   stack_frame_id = get_stack_frame_id (frame);
11565   caller_frame_id = frame_unwind_caller_id (frame);
11566
11567   /* Keep within the current frame, or in frames called by the current
11568      one.  */
11569
11570   if (frame_id_p (caller_frame_id))
11571     {
11572       struct symtab_and_line sal2;
11573
11574       sal2 = find_pc_line (frame_unwind_caller_pc (frame), 0);
11575       sal2.pc = frame_unwind_caller_pc (frame);
11576       breakpoint2 = set_momentary_breakpoint (frame_unwind_caller_arch (frame),
11577                                               sal2,
11578                                               caller_frame_id,
11579                                               bp_until);
11580       make_cleanup_delete_breakpoint (breakpoint2);
11581
11582       set_longjmp_breakpoint (tp, caller_frame_id);
11583       make_cleanup (delete_longjmp_breakpoint_cleanup, &thread);
11584     }
11585
11586   /* set_momentary_breakpoint could invalidate FRAME.  */
11587   frame = NULL;
11588
11589   if (anywhere)
11590     /* If the user told us to continue until a specified location,
11591        we don't specify a frame at which we need to stop.  */
11592     breakpoint = set_momentary_breakpoint (frame_gdbarch, sal,
11593                                            null_frame_id, bp_until);
11594   else
11595     /* Otherwise, specify the selected frame, because we want to stop
11596        only at the very same frame.  */
11597     breakpoint = set_momentary_breakpoint (frame_gdbarch, sal,
11598                                            stack_frame_id, bp_until);
11599   make_cleanup_delete_breakpoint (breakpoint);
11600
11601   proceed (-1, GDB_SIGNAL_DEFAULT, 0);
11602
11603   /* If we are running asynchronously, and proceed call above has
11604      actually managed to start the target, arrange for breakpoints to
11605      be deleted when the target stops.  Otherwise, we're already
11606      stopped and delete breakpoints via cleanup chain.  */
11607
11608   if (target_can_async_p () && is_running (inferior_ptid))
11609     {
11610       struct until_break_command_continuation_args *args;
11611       args = xmalloc (sizeof (*args));
11612
11613       args->breakpoint = breakpoint;
11614       args->breakpoint2 = breakpoint2;
11615       args->thread_num = thread;
11616
11617       discard_cleanups (old_chain);
11618       add_continuation (inferior_thread (),
11619                         until_break_command_continuation, args,
11620                         xfree);
11621     }
11622   else
11623     do_cleanups (old_chain);
11624 }
11625
11626 /* This function attempts to parse an optional "if <cond>" clause
11627    from the arg string.  If one is not found, it returns NULL.
11628
11629    Else, it returns a pointer to the condition string.  (It does not
11630    attempt to evaluate the string against a particular block.)  And,
11631    it updates arg to point to the first character following the parsed
11632    if clause in the arg string.  */
11633
11634 char *
11635 ep_parse_optional_if_clause (char **arg)
11636 {
11637   char *cond_string;
11638
11639   if (((*arg)[0] != 'i') || ((*arg)[1] != 'f') || !isspace ((*arg)[2]))
11640     return NULL;
11641
11642   /* Skip the "if" keyword.  */
11643   (*arg) += 2;
11644
11645   /* Skip any extra leading whitespace, and record the start of the
11646      condition string.  */
11647   *arg = skip_spaces (*arg);
11648   cond_string = *arg;
11649
11650   /* Assume that the condition occupies the remainder of the arg
11651      string.  */
11652   (*arg) += strlen (cond_string);
11653
11654   return cond_string;
11655 }
11656
11657 /* Commands to deal with catching events, such as signals, exceptions,
11658    process start/exit, etc.  */
11659
11660 typedef enum
11661 {
11662   catch_fork_temporary, catch_vfork_temporary,
11663   catch_fork_permanent, catch_vfork_permanent
11664 }
11665 catch_fork_kind;
11666
11667 static void
11668 catch_fork_command_1 (char *arg, int from_tty, 
11669                       struct cmd_list_element *command)
11670 {
11671   struct gdbarch *gdbarch = get_current_arch ();
11672   char *cond_string = NULL;
11673   catch_fork_kind fork_kind;
11674   int tempflag;
11675
11676   fork_kind = (catch_fork_kind) (uintptr_t) get_cmd_context (command);
11677   tempflag = (fork_kind == catch_fork_temporary
11678               || fork_kind == catch_vfork_temporary);
11679
11680   if (!arg)
11681     arg = "";
11682   arg = skip_spaces (arg);
11683
11684   /* The allowed syntax is:
11685      catch [v]fork
11686      catch [v]fork if <cond>
11687
11688      First, check if there's an if clause.  */
11689   cond_string = ep_parse_optional_if_clause (&arg);
11690
11691   if ((*arg != '\0') && !isspace (*arg))
11692     error (_("Junk at end of arguments."));
11693
11694   /* If this target supports it, create a fork or vfork catchpoint
11695      and enable reporting of such events.  */
11696   switch (fork_kind)
11697     {
11698     case catch_fork_temporary:
11699     case catch_fork_permanent:
11700       create_fork_vfork_event_catchpoint (gdbarch, tempflag, cond_string,
11701                                           &catch_fork_breakpoint_ops);
11702       break;
11703     case catch_vfork_temporary:
11704     case catch_vfork_permanent:
11705       create_fork_vfork_event_catchpoint (gdbarch, tempflag, cond_string,
11706                                           &catch_vfork_breakpoint_ops);
11707       break;
11708     default:
11709       error (_("unsupported or unknown fork kind; cannot catch it"));
11710       break;
11711     }
11712 }
11713
11714 static void
11715 catch_exec_command_1 (char *arg, int from_tty, 
11716                       struct cmd_list_element *command)
11717 {
11718   struct exec_catchpoint *c;
11719   struct gdbarch *gdbarch = get_current_arch ();
11720   int tempflag;
11721   char *cond_string = NULL;
11722
11723   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
11724
11725   if (!arg)
11726     arg = "";
11727   arg = skip_spaces (arg);
11728
11729   /* The allowed syntax is:
11730      catch exec
11731      catch exec if <cond>
11732
11733      First, check if there's an if clause.  */
11734   cond_string = ep_parse_optional_if_clause (&arg);
11735
11736   if ((*arg != '\0') && !isspace (*arg))
11737     error (_("Junk at end of arguments."));
11738
11739   c = XNEW (struct exec_catchpoint);
11740   init_catchpoint (&c->base, gdbarch, tempflag, cond_string,
11741                    &catch_exec_breakpoint_ops);
11742   c->exec_pathname = NULL;
11743
11744   install_breakpoint (0, &c->base, 1);
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 enabled,
11755                                int from_tty)
11756 {
11757   if (from_tty)
11758     {
11759       struct gdbarch *loc_gdbarch = get_sal_arch (sal);
11760       if (!loc_gdbarch)
11761         loc_gdbarch = gdbarch;
11762
11763       describe_other_breakpoints (loc_gdbarch,
11764                                   sal.pspace, sal.pc, sal.section, -1);
11765       /* FIXME: brobecker/2006-12-28: Actually, re-implement a special
11766          version for exception catchpoints, because two catchpoints
11767          used for different exception names will use the same address.
11768          In this case, a "breakpoint ... also set at..." warning is
11769          unproductive.  Besides, the warning phrasing is also a bit
11770          inappropriate, we should use the word catchpoint, and tell
11771          the user what type of catchpoint it is.  The above is good
11772          enough for now, though.  */
11773     }
11774
11775   init_raw_breakpoint (b, gdbarch, sal, bp_breakpoint, ops);
11776
11777   b->enable_state = enabled ? bp_enabled : bp_disabled;
11778   b->disposition = tempflag ? disp_del : disp_donttouch;
11779   b->addr_string = addr_string;
11780   b->language = language_ada;
11781 }
11782
11783 /* Splits the argument using space as delimiter.  Returns an xmalloc'd
11784    filter list, or NULL if no filtering is required.  */
11785 static VEC(int) *
11786 catch_syscall_split_args (char *arg)
11787 {
11788   VEC(int) *result = NULL;
11789   struct cleanup *cleanup = make_cleanup (VEC_cleanup (int), &result);
11790
11791   while (*arg != '\0')
11792     {
11793       int i, syscall_number;
11794       char *endptr;
11795       char cur_name[128];
11796       struct syscall s;
11797
11798       /* Skip whitespace.  */
11799       arg = skip_spaces (arg);
11800
11801       for (i = 0; i < 127 && arg[i] && !isspace (arg[i]); ++i)
11802         cur_name[i] = arg[i];
11803       cur_name[i] = '\0';
11804       arg += i;
11805
11806       /* Check if the user provided a syscall name or a number.  */
11807       syscall_number = (int) strtol (cur_name, &endptr, 0);
11808       if (*endptr == '\0')
11809         get_syscall_by_number (syscall_number, &s);
11810       else
11811         {
11812           /* We have a name.  Let's check if it's valid and convert it
11813              to a number.  */
11814           get_syscall_by_name (cur_name, &s);
11815
11816           if (s.number == UNKNOWN_SYSCALL)
11817             /* Here we have to issue an error instead of a warning,
11818                because GDB cannot do anything useful if there's no
11819                syscall number to be caught.  */
11820             error (_("Unknown syscall name '%s'."), cur_name);
11821         }
11822
11823       /* Ok, it's valid.  */
11824       VEC_safe_push (int, result, s.number);
11825     }
11826
11827   discard_cleanups (cleanup);
11828   return result;
11829 }
11830
11831 /* Implement the "catch syscall" command.  */
11832
11833 static void
11834 catch_syscall_command_1 (char *arg, int from_tty, 
11835                          struct cmd_list_element *command)
11836 {
11837   int tempflag;
11838   VEC(int) *filter;
11839   struct syscall s;
11840   struct gdbarch *gdbarch = get_current_arch ();
11841
11842   /* Checking if the feature if supported.  */
11843   if (gdbarch_get_syscall_number_p (gdbarch) == 0)
11844     error (_("The feature 'catch syscall' is not supported on \
11845 this architecture yet."));
11846
11847   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
11848
11849   arg = skip_spaces (arg);
11850
11851   /* We need to do this first "dummy" translation in order
11852      to get the syscall XML file loaded or, most important,
11853      to display a warning to the user if there's no XML file
11854      for his/her architecture.  */
11855   get_syscall_by_number (0, &s);
11856
11857   /* The allowed syntax is:
11858      catch syscall
11859      catch syscall <name | number> [<name | number> ... <name | number>]
11860
11861      Let's check if there's a syscall name.  */
11862
11863   if (arg != NULL)
11864     filter = catch_syscall_split_args (arg);
11865   else
11866     filter = NULL;
11867
11868   create_syscall_event_catchpoint (tempflag, filter,
11869                                    &catch_syscall_breakpoint_ops);
11870 }
11871
11872 static void
11873 catch_command (char *arg, int from_tty)
11874 {
11875   error (_("Catch requires an event name."));
11876 }
11877 \f
11878
11879 static void
11880 tcatch_command (char *arg, int from_tty)
11881 {
11882   error (_("Catch requires an event name."));
11883 }
11884
11885 /* A qsort comparison function that sorts breakpoints in order.  */
11886
11887 static int
11888 compare_breakpoints (const void *a, const void *b)
11889 {
11890   const breakpoint_p *ba = a;
11891   uintptr_t ua = (uintptr_t) *ba;
11892   const breakpoint_p *bb = b;
11893   uintptr_t ub = (uintptr_t) *bb;
11894
11895   if ((*ba)->number < (*bb)->number)
11896     return -1;
11897   else if ((*ba)->number > (*bb)->number)
11898     return 1;
11899
11900   /* Now sort by address, in case we see, e..g, two breakpoints with
11901      the number 0.  */
11902   if (ua < ub)
11903     return -1;
11904   return ua > ub ? 1 : 0;
11905 }
11906
11907 /* Delete breakpoints by address or line.  */
11908
11909 static void
11910 clear_command (char *arg, int from_tty)
11911 {
11912   struct breakpoint *b, *prev;
11913   VEC(breakpoint_p) *found = 0;
11914   int ix;
11915   int default_match;
11916   struct symtabs_and_lines sals;
11917   struct symtab_and_line sal;
11918   int i;
11919   struct cleanup *cleanups = make_cleanup (null_cleanup, NULL);
11920
11921   if (arg)
11922     {
11923       sals = decode_line_with_current_source (arg,
11924                                               (DECODE_LINE_FUNFIRSTLINE
11925                                                | DECODE_LINE_LIST_MODE));
11926       make_cleanup (xfree, sals.sals);
11927       default_match = 0;
11928     }
11929   else
11930     {
11931       sals.sals = (struct symtab_and_line *)
11932         xmalloc (sizeof (struct symtab_and_line));
11933       make_cleanup (xfree, sals.sals);
11934       init_sal (&sal);          /* Initialize to zeroes.  */
11935
11936       /* Set sal's line, symtab, pc, and pspace to the values
11937          corresponding to the last call to print_frame_info.  If the
11938          codepoint is not valid, this will set all the fields to 0.  */
11939       get_last_displayed_sal (&sal);
11940       if (sal.symtab == 0)
11941         error (_("No source file specified."));
11942
11943       sals.sals[0] = sal;
11944       sals.nelts = 1;
11945
11946       default_match = 1;
11947     }
11948
11949   /* We don't call resolve_sal_pc here.  That's not as bad as it
11950      seems, because all existing breakpoints typically have both
11951      file/line and pc set.  So, if clear is given file/line, we can
11952      match this to existing breakpoint without obtaining pc at all.
11953
11954      We only support clearing given the address explicitly 
11955      present in breakpoint table.  Say, we've set breakpoint 
11956      at file:line.  There were several PC values for that file:line,
11957      due to optimization, all in one block.
11958
11959      We've picked one PC value.  If "clear" is issued with another
11960      PC corresponding to the same file:line, the breakpoint won't
11961      be cleared.  We probably can still clear the breakpoint, but 
11962      since the other PC value is never presented to user, user
11963      can only find it by guessing, and it does not seem important
11964      to support that.  */
11965
11966   /* For each line spec given, delete bps which correspond to it.  Do
11967      it in two passes, solely to preserve the current behavior that
11968      from_tty is forced true if we delete more than one
11969      breakpoint.  */
11970
11971   found = NULL;
11972   make_cleanup (VEC_cleanup (breakpoint_p), &found);
11973   for (i = 0; i < sals.nelts; i++)
11974     {
11975       const char *sal_fullname;
11976
11977       /* If exact pc given, clear bpts at that pc.
11978          If line given (pc == 0), clear all bpts on specified line.
11979          If defaulting, clear all bpts on default line
11980          or at default pc.
11981
11982          defaulting    sal.pc != 0    tests to do
11983
11984          0              1             pc
11985          1              1             pc _and_ line
11986          0              0             line
11987          1              0             <can't happen> */
11988
11989       sal = sals.sals[i];
11990       sal_fullname = (sal.symtab == NULL
11991                       ? NULL : symtab_to_fullname (sal.symtab));
11992
11993       /* Find all matching breakpoints and add them to 'found'.  */
11994       ALL_BREAKPOINTS (b)
11995         {
11996           int match = 0;
11997           /* Are we going to delete b?  */
11998           if (b->type != bp_none && !is_watchpoint (b))
11999             {
12000               struct bp_location *loc = b->loc;
12001               for (; loc; loc = loc->next)
12002                 {
12003                   /* If the user specified file:line, don't allow a PC
12004                      match.  This matches historical gdb behavior.  */
12005                   int pc_match = (!sal.explicit_line
12006                                   && sal.pc
12007                                   && (loc->pspace == sal.pspace)
12008                                   && (loc->address == sal.pc)
12009                                   && (!section_is_overlay (loc->section)
12010                                       || loc->section == sal.section));
12011                   int line_match = 0;
12012
12013                   if ((default_match || sal.explicit_line)
12014                       && loc->symtab != NULL
12015                       && sal_fullname != NULL
12016                       && sal.pspace == loc->pspace
12017                       && loc->line_number == sal.line
12018                       && filename_cmp (symtab_to_fullname (loc->symtab),
12019                                        sal_fullname) == 0)
12020                     line_match = 1;
12021
12022                   if (pc_match || line_match)
12023                     {
12024                       match = 1;
12025                       break;
12026                     }
12027                 }
12028             }
12029
12030           if (match)
12031             VEC_safe_push(breakpoint_p, found, b);
12032         }
12033     }
12034
12035   /* Now go thru the 'found' chain and delete them.  */
12036   if (VEC_empty(breakpoint_p, found))
12037     {
12038       if (arg)
12039         error (_("No breakpoint at %s."), arg);
12040       else
12041         error (_("No breakpoint at this line."));
12042     }
12043
12044   /* Remove duplicates from the vec.  */
12045   qsort (VEC_address (breakpoint_p, found),
12046          VEC_length (breakpoint_p, found),
12047          sizeof (breakpoint_p),
12048          compare_breakpoints);
12049   prev = VEC_index (breakpoint_p, found, 0);
12050   for (ix = 1; VEC_iterate (breakpoint_p, found, ix, b); ++ix)
12051     {
12052       if (b == prev)
12053         {
12054           VEC_ordered_remove (breakpoint_p, found, ix);
12055           --ix;
12056         }
12057     }
12058
12059   if (VEC_length(breakpoint_p, found) > 1)
12060     from_tty = 1;       /* Always report if deleted more than one.  */
12061   if (from_tty)
12062     {
12063       if (VEC_length(breakpoint_p, found) == 1)
12064         printf_unfiltered (_("Deleted breakpoint "));
12065       else
12066         printf_unfiltered (_("Deleted breakpoints "));
12067     }
12068
12069   for (ix = 0; VEC_iterate(breakpoint_p, found, ix, b); ix++)
12070     {
12071       if (from_tty)
12072         printf_unfiltered ("%d ", b->number);
12073       delete_breakpoint (b);
12074     }
12075   if (from_tty)
12076     putchar_unfiltered ('\n');
12077
12078   do_cleanups (cleanups);
12079 }
12080 \f
12081 /* Delete breakpoint in BS if they are `delete' breakpoints and
12082    all breakpoints that are marked for deletion, whether hit or not.
12083    This is called after any breakpoint is hit, or after errors.  */
12084
12085 void
12086 breakpoint_auto_delete (bpstat bs)
12087 {
12088   struct breakpoint *b, *b_tmp;
12089
12090   for (; bs; bs = bs->next)
12091     if (bs->breakpoint_at
12092         && bs->breakpoint_at->disposition == disp_del
12093         && bs->stop)
12094       delete_breakpoint (bs->breakpoint_at);
12095
12096   ALL_BREAKPOINTS_SAFE (b, b_tmp)
12097   {
12098     if (b->disposition == disp_del_at_next_stop)
12099       delete_breakpoint (b);
12100   }
12101 }
12102
12103 /* A comparison function for bp_location AP and BP being interfaced to
12104    qsort.  Sort elements primarily by their ADDRESS (no matter what
12105    does breakpoint_address_is_meaningful say for its OWNER),
12106    secondarily by ordering first bp_permanent OWNERed elements and
12107    terciarily just ensuring the array is sorted stable way despite
12108    qsort being an unstable algorithm.  */
12109
12110 static int
12111 bp_location_compare (const void *ap, const void *bp)
12112 {
12113   struct bp_location *a = *(void **) ap;
12114   struct bp_location *b = *(void **) bp;
12115   /* A and B come from existing breakpoints having non-NULL OWNER.  */
12116   int a_perm = a->owner->enable_state == bp_permanent;
12117   int b_perm = b->owner->enable_state == bp_permanent;
12118
12119   if (a->address != b->address)
12120     return (a->address > b->address) - (a->address < b->address);
12121
12122   /* Sort locations at the same address by their pspace number, keeping
12123      locations of the same inferior (in a multi-inferior environment)
12124      grouped.  */
12125
12126   if (a->pspace->num != b->pspace->num)
12127     return ((a->pspace->num > b->pspace->num)
12128             - (a->pspace->num < b->pspace->num));
12129
12130   /* Sort permanent breakpoints first.  */
12131   if (a_perm != b_perm)
12132     return (a_perm < b_perm) - (a_perm > b_perm);
12133
12134   /* Make the internal GDB representation stable across GDB runs
12135      where A and B memory inside GDB can differ.  Breakpoint locations of
12136      the same type at the same address can be sorted in arbitrary order.  */
12137
12138   if (a->owner->number != b->owner->number)
12139     return ((a->owner->number > b->owner->number)
12140             - (a->owner->number < b->owner->number));
12141
12142   return (a > b) - (a < b);
12143 }
12144
12145 /* Set bp_location_placed_address_before_address_max and
12146    bp_location_shadow_len_after_address_max according to the current
12147    content of the bp_location array.  */
12148
12149 static void
12150 bp_location_target_extensions_update (void)
12151 {
12152   struct bp_location *bl, **blp_tmp;
12153
12154   bp_location_placed_address_before_address_max = 0;
12155   bp_location_shadow_len_after_address_max = 0;
12156
12157   ALL_BP_LOCATIONS (bl, blp_tmp)
12158     {
12159       CORE_ADDR start, end, addr;
12160
12161       if (!bp_location_has_shadow (bl))
12162         continue;
12163
12164       start = bl->target_info.placed_address;
12165       end = start + bl->target_info.shadow_len;
12166
12167       gdb_assert (bl->address >= start);
12168       addr = bl->address - start;
12169       if (addr > bp_location_placed_address_before_address_max)
12170         bp_location_placed_address_before_address_max = addr;
12171
12172       /* Zero SHADOW_LEN would not pass bp_location_has_shadow.  */
12173
12174       gdb_assert (bl->address < end);
12175       addr = end - bl->address;
12176       if (addr > bp_location_shadow_len_after_address_max)
12177         bp_location_shadow_len_after_address_max = addr;
12178     }
12179 }
12180
12181 /* Download tracepoint locations if they haven't been.  */
12182
12183 static void
12184 download_tracepoint_locations (void)
12185 {
12186   struct breakpoint *b;
12187   struct cleanup *old_chain;
12188
12189   if (!target_can_download_tracepoint ())
12190     return;
12191
12192   old_chain = save_current_space_and_thread ();
12193
12194   ALL_TRACEPOINTS (b)
12195     {
12196       struct bp_location *bl;
12197       struct tracepoint *t;
12198       int bp_location_downloaded = 0;
12199
12200       if ((b->type == bp_fast_tracepoint
12201            ? !may_insert_fast_tracepoints
12202            : !may_insert_tracepoints))
12203         continue;
12204
12205       for (bl = b->loc; bl; bl = bl->next)
12206         {
12207           /* In tracepoint, locations are _never_ duplicated, so
12208              should_be_inserted is equivalent to
12209              unduplicated_should_be_inserted.  */
12210           if (!should_be_inserted (bl) || bl->inserted)
12211             continue;
12212
12213           switch_to_program_space_and_thread (bl->pspace);
12214
12215           target_download_tracepoint (bl);
12216
12217           bl->inserted = 1;
12218           bp_location_downloaded = 1;
12219         }
12220       t = (struct tracepoint *) b;
12221       t->number_on_target = b->number;
12222       if (bp_location_downloaded)
12223         observer_notify_breakpoint_modified (b);
12224     }
12225
12226   do_cleanups (old_chain);
12227 }
12228
12229 /* Swap the insertion/duplication state between two locations.  */
12230
12231 static void
12232 swap_insertion (struct bp_location *left, struct bp_location *right)
12233 {
12234   const int left_inserted = left->inserted;
12235   const int left_duplicate = left->duplicate;
12236   const int left_needs_update = left->needs_update;
12237   const struct bp_target_info left_target_info = left->target_info;
12238
12239   /* Locations of tracepoints can never be duplicated.  */
12240   if (is_tracepoint (left->owner))
12241     gdb_assert (!left->duplicate);
12242   if (is_tracepoint (right->owner))
12243     gdb_assert (!right->duplicate);
12244
12245   left->inserted = right->inserted;
12246   left->duplicate = right->duplicate;
12247   left->needs_update = right->needs_update;
12248   left->target_info = right->target_info;
12249   right->inserted = left_inserted;
12250   right->duplicate = left_duplicate;
12251   right->needs_update = left_needs_update;
12252   right->target_info = left_target_info;
12253 }
12254
12255 /* Force the re-insertion of the locations at ADDRESS.  This is called
12256    once a new/deleted/modified duplicate location is found and we are evaluating
12257    conditions on the target's side.  Such conditions need to be updated on
12258    the target.  */
12259
12260 static void
12261 force_breakpoint_reinsertion (struct bp_location *bl)
12262 {
12263   struct bp_location **locp = NULL, **loc2p;
12264   struct bp_location *loc;
12265   CORE_ADDR address = 0;
12266   int pspace_num;
12267
12268   address = bl->address;
12269   pspace_num = bl->pspace->num;
12270
12271   /* This is only meaningful if the target is
12272      evaluating conditions and if the user has
12273      opted for condition evaluation on the target's
12274      side.  */
12275   if (gdb_evaluates_breakpoint_condition_p ()
12276       || !target_supports_evaluation_of_breakpoint_conditions ())
12277     return;
12278
12279   /* Flag all breakpoint locations with this address and
12280      the same program space as the location
12281      as "its condition has changed".  We need to
12282      update the conditions on the target's side.  */
12283   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, address)
12284     {
12285       loc = *loc2p;
12286
12287       if (!is_breakpoint (loc->owner)
12288           || pspace_num != loc->pspace->num)
12289         continue;
12290
12291       /* Flag the location appropriately.  We use a different state to
12292          let everyone know that we already updated the set of locations
12293          with addr bl->address and program space bl->pspace.  This is so
12294          we don't have to keep calling these functions just to mark locations
12295          that have already been marked.  */
12296       loc->condition_changed = condition_updated;
12297
12298       /* Free the agent expression bytecode as well.  We will compute
12299          it later on.  */
12300       if (loc->cond_bytecode)
12301         {
12302           free_agent_expr (loc->cond_bytecode);
12303           loc->cond_bytecode = NULL;
12304         }
12305     }
12306 }
12307
12308 /* If SHOULD_INSERT is false, do not insert any breakpoint locations
12309    into the inferior, only remove already-inserted locations that no
12310    longer should be inserted.  Functions that delete a breakpoint or
12311    breakpoints should pass false, so that deleting a breakpoint
12312    doesn't have the side effect of inserting the locations of other
12313    breakpoints that are marked not-inserted, but should_be_inserted
12314    returns true on them.
12315
12316    This behaviour is useful is situations close to tear-down -- e.g.,
12317    after an exec, while the target still has execution, but breakpoint
12318    shadows of the previous executable image should *NOT* be restored
12319    to the new image; or before detaching, where the target still has
12320    execution and wants to delete breakpoints from GDB's lists, and all
12321    breakpoints had already been removed from the inferior.  */
12322
12323 static void
12324 update_global_location_list (int should_insert)
12325 {
12326   struct breakpoint *b;
12327   struct bp_location **locp, *loc;
12328   struct cleanup *cleanups;
12329   /* Last breakpoint location address that was marked for update.  */
12330   CORE_ADDR last_addr = 0;
12331   /* Last breakpoint location program space that was marked for update.  */
12332   int last_pspace_num = -1;
12333
12334   /* Used in the duplicates detection below.  When iterating over all
12335      bp_locations, points to the first bp_location of a given address.
12336      Breakpoints and watchpoints of different types are never
12337      duplicates of each other.  Keep one pointer for each type of
12338      breakpoint/watchpoint, so we only need to loop over all locations
12339      once.  */
12340   struct bp_location *bp_loc_first;  /* breakpoint */
12341   struct bp_location *wp_loc_first;  /* hardware watchpoint */
12342   struct bp_location *awp_loc_first; /* access watchpoint */
12343   struct bp_location *rwp_loc_first; /* read watchpoint */
12344
12345   /* Saved former bp_location array which we compare against the newly
12346      built bp_location from the current state of ALL_BREAKPOINTS.  */
12347   struct bp_location **old_location, **old_locp;
12348   unsigned old_location_count;
12349
12350   old_location = bp_location;
12351   old_location_count = bp_location_count;
12352   bp_location = NULL;
12353   bp_location_count = 0;
12354   cleanups = make_cleanup (xfree, old_location);
12355
12356   ALL_BREAKPOINTS (b)
12357     for (loc = b->loc; loc; loc = loc->next)
12358       bp_location_count++;
12359
12360   bp_location = xmalloc (sizeof (*bp_location) * bp_location_count);
12361   locp = bp_location;
12362   ALL_BREAKPOINTS (b)
12363     for (loc = b->loc; loc; loc = loc->next)
12364       *locp++ = loc;
12365   qsort (bp_location, bp_location_count, sizeof (*bp_location),
12366          bp_location_compare);
12367
12368   bp_location_target_extensions_update ();
12369
12370   /* Identify bp_location instances that are no longer present in the
12371      new list, and therefore should be freed.  Note that it's not
12372      necessary that those locations should be removed from inferior --
12373      if there's another location at the same address (previously
12374      marked as duplicate), we don't need to remove/insert the
12375      location.
12376      
12377      LOCP is kept in sync with OLD_LOCP, each pointing to the current
12378      and former bp_location array state respectively.  */
12379
12380   locp = bp_location;
12381   for (old_locp = old_location; old_locp < old_location + old_location_count;
12382        old_locp++)
12383     {
12384       struct bp_location *old_loc = *old_locp;
12385       struct bp_location **loc2p;
12386
12387       /* Tells if 'old_loc' is found among the new locations.  If
12388          not, we have to free it.  */
12389       int found_object = 0;
12390       /* Tells if the location should remain inserted in the target.  */
12391       int keep_in_target = 0;
12392       int removed = 0;
12393
12394       /* Skip LOCP entries which will definitely never be needed.
12395          Stop either at or being the one matching OLD_LOC.  */
12396       while (locp < bp_location + bp_location_count
12397              && (*locp)->address < old_loc->address)
12398         locp++;
12399
12400       for (loc2p = locp;
12401            (loc2p < bp_location + bp_location_count
12402             && (*loc2p)->address == old_loc->address);
12403            loc2p++)
12404         {
12405           /* Check if this is a new/duplicated location or a duplicated
12406              location that had its condition modified.  If so, we want to send
12407              its condition to the target if evaluation of conditions is taking
12408              place there.  */
12409           if ((*loc2p)->condition_changed == condition_modified
12410               && (last_addr != old_loc->address
12411                   || last_pspace_num != old_loc->pspace->num))
12412             {
12413               force_breakpoint_reinsertion (*loc2p);
12414               last_pspace_num = old_loc->pspace->num;
12415             }
12416
12417           if (*loc2p == old_loc)
12418             found_object = 1;
12419         }
12420
12421       /* We have already handled this address, update it so that we don't
12422          have to go through updates again.  */
12423       last_addr = old_loc->address;
12424
12425       /* Target-side condition evaluation: Handle deleted locations.  */
12426       if (!found_object)
12427         force_breakpoint_reinsertion (old_loc);
12428
12429       /* If this location is no longer present, and inserted, look if
12430          there's maybe a new location at the same address.  If so,
12431          mark that one inserted, and don't remove this one.  This is
12432          needed so that we don't have a time window where a breakpoint
12433          at certain location is not inserted.  */
12434
12435       if (old_loc->inserted)
12436         {
12437           /* If the location is inserted now, we might have to remove
12438              it.  */
12439
12440           if (found_object && should_be_inserted (old_loc))
12441             {
12442               /* The location is still present in the location list,
12443                  and still should be inserted.  Don't do anything.  */
12444               keep_in_target = 1;
12445             }
12446           else
12447             {
12448               /* This location still exists, but it won't be kept in the
12449                  target since it may have been disabled.  We proceed to
12450                  remove its target-side condition.  */
12451
12452               /* The location is either no longer present, or got
12453                  disabled.  See if there's another location at the
12454                  same address, in which case we don't need to remove
12455                  this one from the target.  */
12456
12457               /* OLD_LOC comes from existing struct breakpoint.  */
12458               if (breakpoint_address_is_meaningful (old_loc->owner))
12459                 {
12460                   for (loc2p = locp;
12461                        (loc2p < bp_location + bp_location_count
12462                         && (*loc2p)->address == old_loc->address);
12463                        loc2p++)
12464                     {
12465                       struct bp_location *loc2 = *loc2p;
12466
12467                       if (breakpoint_locations_match (loc2, old_loc))
12468                         {
12469                           /* Read watchpoint locations are switched to
12470                              access watchpoints, if the former are not
12471                              supported, but the latter are.  */
12472                           if (is_hardware_watchpoint (old_loc->owner))
12473                             {
12474                               gdb_assert (is_hardware_watchpoint (loc2->owner));
12475                               loc2->watchpoint_type = old_loc->watchpoint_type;
12476                             }
12477
12478                           /* loc2 is a duplicated location. We need to check
12479                              if it should be inserted in case it will be
12480                              unduplicated.  */
12481                           if (loc2 != old_loc
12482                               && unduplicated_should_be_inserted (loc2))
12483                             {
12484                               swap_insertion (old_loc, loc2);
12485                               keep_in_target = 1;
12486                               break;
12487                             }
12488                         }
12489                     }
12490                 }
12491             }
12492
12493           if (!keep_in_target)
12494             {
12495               if (remove_breakpoint (old_loc, mark_uninserted))
12496                 {
12497                   /* This is just about all we can do.  We could keep
12498                      this location on the global list, and try to
12499                      remove it next time, but there's no particular
12500                      reason why we will succeed next time.
12501                      
12502                      Note that at this point, old_loc->owner is still
12503                      valid, as delete_breakpoint frees the breakpoint
12504                      only after calling us.  */
12505                   printf_filtered (_("warning: Error removing "
12506                                      "breakpoint %d\n"), 
12507                                    old_loc->owner->number);
12508                 }
12509               removed = 1;
12510             }
12511         }
12512
12513       if (!found_object)
12514         {
12515           if (removed && non_stop
12516               && breakpoint_address_is_meaningful (old_loc->owner)
12517               && !is_hardware_watchpoint (old_loc->owner))
12518             {
12519               /* This location was removed from the target.  In
12520                  non-stop mode, a race condition is possible where
12521                  we've removed a breakpoint, but stop events for that
12522                  breakpoint are already queued and will arrive later.
12523                  We apply an heuristic to be able to distinguish such
12524                  SIGTRAPs from other random SIGTRAPs: we keep this
12525                  breakpoint location for a bit, and will retire it
12526                  after we see some number of events.  The theory here
12527                  is that reporting of events should, "on the average",
12528                  be fair, so after a while we'll see events from all
12529                  threads that have anything of interest, and no longer
12530                  need to keep this breakpoint location around.  We
12531                  don't hold locations forever so to reduce chances of
12532                  mistaking a non-breakpoint SIGTRAP for a breakpoint
12533                  SIGTRAP.
12534
12535                  The heuristic failing can be disastrous on
12536                  decr_pc_after_break targets.
12537
12538                  On decr_pc_after_break targets, like e.g., x86-linux,
12539                  if we fail to recognize a late breakpoint SIGTRAP,
12540                  because events_till_retirement has reached 0 too
12541                  soon, we'll fail to do the PC adjustment, and report
12542                  a random SIGTRAP to the user.  When the user resumes
12543                  the inferior, it will most likely immediately crash
12544                  with SIGILL/SIGBUS/SIGSEGV, or worse, get silently
12545                  corrupted, because of being resumed e.g., in the
12546                  middle of a multi-byte instruction, or skipped a
12547                  one-byte instruction.  This was actually seen happen
12548                  on native x86-linux, and should be less rare on
12549                  targets that do not support new thread events, like
12550                  remote, due to the heuristic depending on
12551                  thread_count.
12552
12553                  Mistaking a random SIGTRAP for a breakpoint trap
12554                  causes similar symptoms (PC adjustment applied when
12555                  it shouldn't), but then again, playing with SIGTRAPs
12556                  behind the debugger's back is asking for trouble.
12557
12558                  Since hardware watchpoint traps are always
12559                  distinguishable from other traps, so we don't need to
12560                  apply keep hardware watchpoint moribund locations
12561                  around.  We simply always ignore hardware watchpoint
12562                  traps we can no longer explain.  */
12563
12564               old_loc->events_till_retirement = 3 * (thread_count () + 1);
12565               old_loc->owner = NULL;
12566
12567               VEC_safe_push (bp_location_p, moribund_locations, old_loc);
12568             }
12569           else
12570             {
12571               old_loc->owner = NULL;
12572               decref_bp_location (&old_loc);
12573             }
12574         }
12575     }
12576
12577   /* Rescan breakpoints at the same address and section, marking the
12578      first one as "first" and any others as "duplicates".  This is so
12579      that the bpt instruction is only inserted once.  If we have a
12580      permanent breakpoint at the same place as BPT, make that one the
12581      official one, and the rest as duplicates.  Permanent breakpoints
12582      are sorted first for the same address.
12583
12584      Do the same for hardware watchpoints, but also considering the
12585      watchpoint's type (regular/access/read) and length.  */
12586
12587   bp_loc_first = NULL;
12588   wp_loc_first = NULL;
12589   awp_loc_first = NULL;
12590   rwp_loc_first = NULL;
12591   ALL_BP_LOCATIONS (loc, locp)
12592     {
12593       /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always
12594          non-NULL.  */
12595       struct bp_location **loc_first_p;
12596       b = loc->owner;
12597
12598       if (!unduplicated_should_be_inserted (loc)
12599           || !breakpoint_address_is_meaningful (b)
12600           /* Don't detect duplicate for tracepoint locations because they are
12601            never duplicated.  See the comments in field `duplicate' of
12602            `struct bp_location'.  */
12603           || is_tracepoint (b))
12604         {
12605           /* Clear the condition modification flag.  */
12606           loc->condition_changed = condition_unchanged;
12607           continue;
12608         }
12609
12610       /* Permanent breakpoint should always be inserted.  */
12611       if (b->enable_state == bp_permanent && ! loc->inserted)
12612         internal_error (__FILE__, __LINE__,
12613                         _("allegedly permanent breakpoint is not "
12614                         "actually inserted"));
12615
12616       if (b->type == bp_hardware_watchpoint)
12617         loc_first_p = &wp_loc_first;
12618       else if (b->type == bp_read_watchpoint)
12619         loc_first_p = &rwp_loc_first;
12620       else if (b->type == bp_access_watchpoint)
12621         loc_first_p = &awp_loc_first;
12622       else
12623         loc_first_p = &bp_loc_first;
12624
12625       if (*loc_first_p == NULL
12626           || (overlay_debugging && loc->section != (*loc_first_p)->section)
12627           || !breakpoint_locations_match (loc, *loc_first_p))
12628         {
12629           *loc_first_p = loc;
12630           loc->duplicate = 0;
12631
12632           if (is_breakpoint (loc->owner) && loc->condition_changed)
12633             {
12634               loc->needs_update = 1;
12635               /* Clear the condition modification flag.  */
12636               loc->condition_changed = condition_unchanged;
12637             }
12638           continue;
12639         }
12640
12641
12642       /* This and the above ensure the invariant that the first location
12643          is not duplicated, and is the inserted one.
12644          All following are marked as duplicated, and are not inserted.  */
12645       if (loc->inserted)
12646         swap_insertion (loc, *loc_first_p);
12647       loc->duplicate = 1;
12648
12649       /* Clear the condition modification flag.  */
12650       loc->condition_changed = condition_unchanged;
12651
12652       if ((*loc_first_p)->owner->enable_state == bp_permanent && loc->inserted
12653           && b->enable_state != bp_permanent)
12654         internal_error (__FILE__, __LINE__,
12655                         _("another breakpoint was inserted on top of "
12656                         "a permanent breakpoint"));
12657     }
12658
12659   if (breakpoints_always_inserted_mode ()
12660       && (have_live_inferiors ()
12661           || (gdbarch_has_global_breakpoints (target_gdbarch ()))))
12662     {
12663       if (should_insert)
12664         insert_breakpoint_locations ();
12665       else
12666         {
12667           /* Though should_insert is false, we may need to update conditions
12668              on the target's side if it is evaluating such conditions.  We
12669              only update conditions for locations that are marked
12670              "needs_update".  */
12671           update_inserted_breakpoint_locations ();
12672         }
12673     }
12674
12675   if (should_insert)
12676     download_tracepoint_locations ();
12677
12678   do_cleanups (cleanups);
12679 }
12680
12681 void
12682 breakpoint_retire_moribund (void)
12683 {
12684   struct bp_location *loc;
12685   int ix;
12686
12687   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
12688     if (--(loc->events_till_retirement) == 0)
12689       {
12690         decref_bp_location (&loc);
12691         VEC_unordered_remove (bp_location_p, moribund_locations, ix);
12692         --ix;
12693       }
12694 }
12695
12696 static void
12697 update_global_location_list_nothrow (int inserting)
12698 {
12699   volatile struct gdb_exception e;
12700
12701   TRY_CATCH (e, RETURN_MASK_ERROR)
12702     update_global_location_list (inserting);
12703 }
12704
12705 /* Clear BKP from a BPS.  */
12706
12707 static void
12708 bpstat_remove_bp_location (bpstat bps, struct breakpoint *bpt)
12709 {
12710   bpstat bs;
12711
12712   for (bs = bps; bs; bs = bs->next)
12713     if (bs->breakpoint_at == bpt)
12714       {
12715         bs->breakpoint_at = NULL;
12716         bs->old_val = NULL;
12717         /* bs->commands will be freed later.  */
12718       }
12719 }
12720
12721 /* Callback for iterate_over_threads.  */
12722 static int
12723 bpstat_remove_breakpoint_callback (struct thread_info *th, void *data)
12724 {
12725   struct breakpoint *bpt = data;
12726
12727   bpstat_remove_bp_location (th->control.stop_bpstat, bpt);
12728   return 0;
12729 }
12730
12731 /* Helper for breakpoint and tracepoint breakpoint_ops->mention
12732    callbacks.  */
12733
12734 static void
12735 say_where (struct breakpoint *b)
12736 {
12737   struct value_print_options opts;
12738
12739   get_user_print_options (&opts);
12740
12741   /* i18n: cagney/2005-02-11: Below needs to be merged into a
12742      single string.  */
12743   if (b->loc == NULL)
12744     {
12745       printf_filtered (_(" (%s) pending."), b->addr_string);
12746     }
12747   else
12748     {
12749       if (opts.addressprint || b->loc->symtab == NULL)
12750         {
12751           printf_filtered (" at ");
12752           fputs_filtered (paddress (b->loc->gdbarch, b->loc->address),
12753                           gdb_stdout);
12754         }
12755       if (b->loc->symtab != NULL)
12756         {
12757           /* If there is a single location, we can print the location
12758              more nicely.  */
12759           if (b->loc->next == NULL)
12760             printf_filtered (": file %s, line %d.",
12761                              symtab_to_filename_for_display (b->loc->symtab),
12762                              b->loc->line_number);
12763           else
12764             /* This is not ideal, but each location may have a
12765                different file name, and this at least reflects the
12766                real situation somewhat.  */
12767             printf_filtered (": %s.", b->addr_string);
12768         }
12769
12770       if (b->loc->next)
12771         {
12772           struct bp_location *loc = b->loc;
12773           int n = 0;
12774           for (; loc; loc = loc->next)
12775             ++n;
12776           printf_filtered (" (%d locations)", n);
12777         }
12778     }
12779 }
12780
12781 /* Default bp_location_ops methods.  */
12782
12783 static void
12784 bp_location_dtor (struct bp_location *self)
12785 {
12786   xfree (self->cond);
12787   if (self->cond_bytecode)
12788     free_agent_expr (self->cond_bytecode);
12789   xfree (self->function_name);
12790
12791   VEC_free (agent_expr_p, self->target_info.conditions);
12792   VEC_free (agent_expr_p, self->target_info.tcommands);
12793 }
12794
12795 static const struct bp_location_ops bp_location_ops =
12796 {
12797   bp_location_dtor
12798 };
12799
12800 /* Default breakpoint_ops methods all breakpoint_ops ultimately
12801    inherit from.  */
12802
12803 static void
12804 base_breakpoint_dtor (struct breakpoint *self)
12805 {
12806   decref_counted_command_line (&self->commands);
12807   xfree (self->cond_string);
12808   xfree (self->extra_string);
12809   xfree (self->addr_string);
12810   xfree (self->filter);
12811   xfree (self->addr_string_range_end);
12812 }
12813
12814 static struct bp_location *
12815 base_breakpoint_allocate_location (struct breakpoint *self)
12816 {
12817   struct bp_location *loc;
12818
12819   loc = XNEW (struct bp_location);
12820   init_bp_location (loc, &bp_location_ops, self);
12821   return loc;
12822 }
12823
12824 static void
12825 base_breakpoint_re_set (struct breakpoint *b)
12826 {
12827   /* Nothing to re-set. */
12828 }
12829
12830 #define internal_error_pure_virtual_called() \
12831   gdb_assert_not_reached ("pure virtual function called")
12832
12833 static int
12834 base_breakpoint_insert_location (struct bp_location *bl)
12835 {
12836   internal_error_pure_virtual_called ();
12837 }
12838
12839 static int
12840 base_breakpoint_remove_location (struct bp_location *bl)
12841 {
12842   internal_error_pure_virtual_called ();
12843 }
12844
12845 static int
12846 base_breakpoint_breakpoint_hit (const struct bp_location *bl,
12847                                 struct address_space *aspace,
12848                                 CORE_ADDR bp_addr,
12849                                 const struct target_waitstatus *ws)
12850 {
12851   internal_error_pure_virtual_called ();
12852 }
12853
12854 static void
12855 base_breakpoint_check_status (bpstat bs)
12856 {
12857   /* Always stop.   */
12858 }
12859
12860 /* A "works_in_software_mode" breakpoint_ops method that just internal
12861    errors.  */
12862
12863 static int
12864 base_breakpoint_works_in_software_mode (const struct breakpoint *b)
12865 {
12866   internal_error_pure_virtual_called ();
12867 }
12868
12869 /* A "resources_needed" breakpoint_ops method that just internal
12870    errors.  */
12871
12872 static int
12873 base_breakpoint_resources_needed (const struct bp_location *bl)
12874 {
12875   internal_error_pure_virtual_called ();
12876 }
12877
12878 static enum print_stop_action
12879 base_breakpoint_print_it (bpstat bs)
12880 {
12881   internal_error_pure_virtual_called ();
12882 }
12883
12884 static void
12885 base_breakpoint_print_one_detail (const struct breakpoint *self,
12886                                   struct ui_out *uiout)
12887 {
12888   /* nothing */
12889 }
12890
12891 static void
12892 base_breakpoint_print_mention (struct breakpoint *b)
12893 {
12894   internal_error_pure_virtual_called ();
12895 }
12896
12897 static void
12898 base_breakpoint_print_recreate (struct breakpoint *b, struct ui_file *fp)
12899 {
12900   internal_error_pure_virtual_called ();
12901 }
12902
12903 static void
12904 base_breakpoint_create_sals_from_address (char **arg,
12905                                           struct linespec_result *canonical,
12906                                           enum bptype type_wanted,
12907                                           char *addr_start,
12908                                           char **copy_arg)
12909 {
12910   internal_error_pure_virtual_called ();
12911 }
12912
12913 static void
12914 base_breakpoint_create_breakpoints_sal (struct gdbarch *gdbarch,
12915                                         struct linespec_result *c,
12916                                         char *cond_string,
12917                                         char *extra_string,
12918                                         enum bptype type_wanted,
12919                                         enum bpdisp disposition,
12920                                         int thread,
12921                                         int task, int ignore_count,
12922                                         const struct breakpoint_ops *o,
12923                                         int from_tty, int enabled,
12924                                         int internal, unsigned flags)
12925 {
12926   internal_error_pure_virtual_called ();
12927 }
12928
12929 static void
12930 base_breakpoint_decode_linespec (struct breakpoint *b, char **s,
12931                                  struct symtabs_and_lines *sals)
12932 {
12933   internal_error_pure_virtual_called ();
12934 }
12935
12936 /* The default 'explains_signal' method.  */
12937
12938 static int
12939 base_breakpoint_explains_signal (struct breakpoint *b, enum gdb_signal sig)
12940 {
12941   return 1;
12942 }
12943
12944 /* The default "after_condition_true" method.  */
12945
12946 static void
12947 base_breakpoint_after_condition_true (struct bpstats *bs)
12948 {
12949   /* Nothing to do.   */
12950 }
12951
12952 struct breakpoint_ops base_breakpoint_ops =
12953 {
12954   base_breakpoint_dtor,
12955   base_breakpoint_allocate_location,
12956   base_breakpoint_re_set,
12957   base_breakpoint_insert_location,
12958   base_breakpoint_remove_location,
12959   base_breakpoint_breakpoint_hit,
12960   base_breakpoint_check_status,
12961   base_breakpoint_resources_needed,
12962   base_breakpoint_works_in_software_mode,
12963   base_breakpoint_print_it,
12964   NULL,
12965   base_breakpoint_print_one_detail,
12966   base_breakpoint_print_mention,
12967   base_breakpoint_print_recreate,
12968   base_breakpoint_create_sals_from_address,
12969   base_breakpoint_create_breakpoints_sal,
12970   base_breakpoint_decode_linespec,
12971   base_breakpoint_explains_signal,
12972   base_breakpoint_after_condition_true,
12973 };
12974
12975 /* Default breakpoint_ops methods.  */
12976
12977 static void
12978 bkpt_re_set (struct breakpoint *b)
12979 {
12980   /* FIXME: is this still reachable?  */
12981   if (b->addr_string == NULL)
12982     {
12983       /* Anything without a string can't be re-set.  */
12984       delete_breakpoint (b);
12985       return;
12986     }
12987
12988   breakpoint_re_set_default (b);
12989 }
12990
12991 static int
12992 bkpt_insert_location (struct bp_location *bl)
12993 {
12994   if (bl->loc_type == bp_loc_hardware_breakpoint)
12995     return target_insert_hw_breakpoint (bl->gdbarch,
12996                                         &bl->target_info);
12997   else
12998     return target_insert_breakpoint (bl->gdbarch,
12999                                      &bl->target_info);
13000 }
13001
13002 static int
13003 bkpt_remove_location (struct bp_location *bl)
13004 {
13005   if (bl->loc_type == bp_loc_hardware_breakpoint)
13006     return target_remove_hw_breakpoint (bl->gdbarch, &bl->target_info);
13007   else
13008     return target_remove_breakpoint (bl->gdbarch, &bl->target_info);
13009 }
13010
13011 static int
13012 bkpt_breakpoint_hit (const struct bp_location *bl,
13013                      struct address_space *aspace, CORE_ADDR bp_addr,
13014                      const struct target_waitstatus *ws)
13015 {
13016   if (ws->kind != TARGET_WAITKIND_STOPPED
13017       || ws->value.sig != GDB_SIGNAL_TRAP)
13018     return 0;
13019
13020   if (!breakpoint_address_match (bl->pspace->aspace, bl->address,
13021                                  aspace, bp_addr))
13022     return 0;
13023
13024   if (overlay_debugging         /* unmapped overlay section */
13025       && section_is_overlay (bl->section)
13026       && !section_is_mapped (bl->section))
13027     return 0;
13028
13029   return 1;
13030 }
13031
13032 static int
13033 bkpt_resources_needed (const struct bp_location *bl)
13034 {
13035   gdb_assert (bl->owner->type == bp_hardware_breakpoint);
13036
13037   return 1;
13038 }
13039
13040 static enum print_stop_action
13041 bkpt_print_it (bpstat bs)
13042 {
13043   struct breakpoint *b;
13044   const struct bp_location *bl;
13045   int bp_temp;
13046   struct ui_out *uiout = current_uiout;
13047
13048   gdb_assert (bs->bp_location_at != NULL);
13049
13050   bl = bs->bp_location_at;
13051   b = bs->breakpoint_at;
13052
13053   bp_temp = b->disposition == disp_del;
13054   if (bl->address != bl->requested_address)
13055     breakpoint_adjustment_warning (bl->requested_address,
13056                                    bl->address,
13057                                    b->number, 1);
13058   annotate_breakpoint (b->number);
13059   if (bp_temp)
13060     ui_out_text (uiout, "\nTemporary breakpoint ");
13061   else
13062     ui_out_text (uiout, "\nBreakpoint ");
13063   if (ui_out_is_mi_like_p (uiout))
13064     {
13065       ui_out_field_string (uiout, "reason",
13066                            async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
13067       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
13068     }
13069   ui_out_field_int (uiout, "bkptno", b->number);
13070   ui_out_text (uiout, ", ");
13071
13072   return PRINT_SRC_AND_LOC;
13073 }
13074
13075 static void
13076 bkpt_print_mention (struct breakpoint *b)
13077 {
13078   if (ui_out_is_mi_like_p (current_uiout))
13079     return;
13080
13081   switch (b->type)
13082     {
13083     case bp_breakpoint:
13084     case bp_gnu_ifunc_resolver:
13085       if (b->disposition == disp_del)
13086         printf_filtered (_("Temporary breakpoint"));
13087       else
13088         printf_filtered (_("Breakpoint"));
13089       printf_filtered (_(" %d"), b->number);
13090       if (b->type == bp_gnu_ifunc_resolver)
13091         printf_filtered (_(" at gnu-indirect-function resolver"));
13092       break;
13093     case bp_hardware_breakpoint:
13094       printf_filtered (_("Hardware assisted breakpoint %d"), b->number);
13095       break;
13096     case bp_dprintf:
13097       printf_filtered (_("Dprintf %d"), b->number);
13098       break;
13099     }
13100
13101   say_where (b);
13102 }
13103
13104 static void
13105 bkpt_print_recreate (struct breakpoint *tp, struct ui_file *fp)
13106 {
13107   if (tp->type == bp_breakpoint && tp->disposition == disp_del)
13108     fprintf_unfiltered (fp, "tbreak");
13109   else if (tp->type == bp_breakpoint)
13110     fprintf_unfiltered (fp, "break");
13111   else if (tp->type == bp_hardware_breakpoint
13112            && tp->disposition == disp_del)
13113     fprintf_unfiltered (fp, "thbreak");
13114   else if (tp->type == bp_hardware_breakpoint)
13115     fprintf_unfiltered (fp, "hbreak");
13116   else
13117     internal_error (__FILE__, __LINE__,
13118                     _("unhandled breakpoint type %d"), (int) tp->type);
13119
13120   fprintf_unfiltered (fp, " %s", tp->addr_string);
13121   print_recreate_thread (tp, fp);
13122 }
13123
13124 static void
13125 bkpt_create_sals_from_address (char **arg,
13126                                struct linespec_result *canonical,
13127                                enum bptype type_wanted,
13128                                char *addr_start, char **copy_arg)
13129 {
13130   create_sals_from_address_default (arg, canonical, type_wanted,
13131                                     addr_start, copy_arg);
13132 }
13133
13134 static void
13135 bkpt_create_breakpoints_sal (struct gdbarch *gdbarch,
13136                              struct linespec_result *canonical,
13137                              char *cond_string,
13138                              char *extra_string,
13139                              enum bptype type_wanted,
13140                              enum bpdisp disposition,
13141                              int thread,
13142                              int task, int ignore_count,
13143                              const struct breakpoint_ops *ops,
13144                              int from_tty, int enabled,
13145                              int internal, unsigned flags)
13146 {
13147   create_breakpoints_sal_default (gdbarch, canonical,
13148                                   cond_string, extra_string,
13149                                   type_wanted,
13150                                   disposition, thread, task,
13151                                   ignore_count, ops, from_tty,
13152                                   enabled, internal, flags);
13153 }
13154
13155 static void
13156 bkpt_decode_linespec (struct breakpoint *b, char **s,
13157                       struct symtabs_and_lines *sals)
13158 {
13159   decode_linespec_default (b, s, sals);
13160 }
13161
13162 /* Virtual table for internal breakpoints.  */
13163
13164 static void
13165 internal_bkpt_re_set (struct breakpoint *b)
13166 {
13167   switch (b->type)
13168     {
13169       /* Delete overlay event and longjmp master breakpoints; they
13170          will be reset later by breakpoint_re_set.  */
13171     case bp_overlay_event:
13172     case bp_longjmp_master:
13173     case bp_std_terminate_master:
13174     case bp_exception_master:
13175       delete_breakpoint (b);
13176       break;
13177
13178       /* This breakpoint is special, it's set up when the inferior
13179          starts and we really don't want to touch it.  */
13180     case bp_shlib_event:
13181
13182       /* Like bp_shlib_event, this breakpoint type is special.  Once
13183          it is set up, we do not want to touch it.  */
13184     case bp_thread_event:
13185       break;
13186     }
13187 }
13188
13189 static void
13190 internal_bkpt_check_status (bpstat bs)
13191 {
13192   if (bs->breakpoint_at->type == bp_shlib_event)
13193     {
13194       /* If requested, stop when the dynamic linker notifies GDB of
13195          events.  This allows the user to get control and place
13196          breakpoints in initializer routines for dynamically loaded
13197          objects (among other things).  */
13198       bs->stop = stop_on_solib_events;
13199       bs->print = stop_on_solib_events;
13200     }
13201   else
13202     bs->stop = 0;
13203 }
13204
13205 static enum print_stop_action
13206 internal_bkpt_print_it (bpstat bs)
13207 {
13208   struct breakpoint *b;
13209
13210   b = bs->breakpoint_at;
13211
13212   switch (b->type)
13213     {
13214     case bp_shlib_event:
13215       /* Did we stop because the user set the stop_on_solib_events
13216          variable?  (If so, we report this as a generic, "Stopped due
13217          to shlib event" message.) */
13218       print_solib_event (0);
13219       break;
13220
13221     case bp_thread_event:
13222       /* Not sure how we will get here.
13223          GDB should not stop for these breakpoints.  */
13224       printf_filtered (_("Thread Event Breakpoint: gdb should not stop!\n"));
13225       break;
13226
13227     case bp_overlay_event:
13228       /* By analogy with the thread event, GDB should not stop for these.  */
13229       printf_filtered (_("Overlay Event Breakpoint: gdb should not stop!\n"));
13230       break;
13231
13232     case bp_longjmp_master:
13233       /* These should never be enabled.  */
13234       printf_filtered (_("Longjmp Master Breakpoint: gdb should not stop!\n"));
13235       break;
13236
13237     case bp_std_terminate_master:
13238       /* These should never be enabled.  */
13239       printf_filtered (_("std::terminate Master Breakpoint: "
13240                          "gdb should not stop!\n"));
13241       break;
13242
13243     case bp_exception_master:
13244       /* These should never be enabled.  */
13245       printf_filtered (_("Exception Master Breakpoint: "
13246                          "gdb should not stop!\n"));
13247       break;
13248     }
13249
13250   return PRINT_NOTHING;
13251 }
13252
13253 static void
13254 internal_bkpt_print_mention (struct breakpoint *b)
13255 {
13256   /* Nothing to mention.  These breakpoints are internal.  */
13257 }
13258
13259 /* Virtual table for momentary breakpoints  */
13260
13261 static void
13262 momentary_bkpt_re_set (struct breakpoint *b)
13263 {
13264   /* Keep temporary breakpoints, which can be encountered when we step
13265      over a dlopen call and solib_add is resetting the breakpoints.
13266      Otherwise these should have been blown away via the cleanup chain
13267      or by breakpoint_init_inferior when we rerun the executable.  */
13268 }
13269
13270 static void
13271 momentary_bkpt_check_status (bpstat bs)
13272 {
13273   /* Nothing.  The point of these breakpoints is causing a stop.  */
13274 }
13275
13276 static enum print_stop_action
13277 momentary_bkpt_print_it (bpstat bs)
13278 {
13279   struct ui_out *uiout = current_uiout;
13280
13281   if (ui_out_is_mi_like_p (uiout))
13282     {
13283       struct breakpoint *b = bs->breakpoint_at;
13284
13285       switch (b->type)
13286         {
13287         case bp_finish:
13288           ui_out_field_string
13289             (uiout, "reason",
13290              async_reason_lookup (EXEC_ASYNC_FUNCTION_FINISHED));
13291           break;
13292
13293         case bp_until:
13294           ui_out_field_string
13295             (uiout, "reason",
13296              async_reason_lookup (EXEC_ASYNC_LOCATION_REACHED));
13297           break;
13298         }
13299     }
13300
13301   return PRINT_UNKNOWN;
13302 }
13303
13304 static void
13305 momentary_bkpt_print_mention (struct breakpoint *b)
13306 {
13307   /* Nothing to mention.  These breakpoints are internal.  */
13308 }
13309
13310 /* Ensure INITIATING_FRAME is cleared when no such breakpoint exists.
13311
13312    It gets cleared already on the removal of the first one of such placed
13313    breakpoints.  This is OK as they get all removed altogether.  */
13314
13315 static void
13316 longjmp_bkpt_dtor (struct breakpoint *self)
13317 {
13318   struct thread_info *tp = find_thread_id (self->thread);
13319
13320   if (tp)
13321     tp->initiating_frame = null_frame_id;
13322
13323   momentary_breakpoint_ops.dtor (self);
13324 }
13325
13326 /* Specific methods for probe breakpoints.  */
13327
13328 static int
13329 bkpt_probe_insert_location (struct bp_location *bl)
13330 {
13331   int v = bkpt_insert_location (bl);
13332
13333   if (v == 0)
13334     {
13335       /* The insertion was successful, now let's set the probe's semaphore
13336          if needed.  */
13337       bl->probe->pops->set_semaphore (bl->probe, bl->gdbarch);
13338     }
13339
13340   return v;
13341 }
13342
13343 static int
13344 bkpt_probe_remove_location (struct bp_location *bl)
13345 {
13346   /* Let's clear the semaphore before removing the location.  */
13347   bl->probe->pops->clear_semaphore (bl->probe, bl->gdbarch);
13348
13349   return bkpt_remove_location (bl);
13350 }
13351
13352 static void
13353 bkpt_probe_create_sals_from_address (char **arg,
13354                                      struct linespec_result *canonical,
13355                                      enum bptype type_wanted,
13356                                      char *addr_start, char **copy_arg)
13357 {
13358   struct linespec_sals lsal;
13359
13360   lsal.sals = parse_probes (arg, canonical);
13361
13362   *copy_arg = xstrdup (canonical->addr_string);
13363   lsal.canonical = xstrdup (*copy_arg);
13364
13365   VEC_safe_push (linespec_sals, canonical->sals, &lsal);
13366 }
13367
13368 static void
13369 bkpt_probe_decode_linespec (struct breakpoint *b, char **s,
13370                             struct symtabs_and_lines *sals)
13371 {
13372   *sals = parse_probes (s, NULL);
13373   if (!sals->sals)
13374     error (_("probe not found"));
13375 }
13376
13377 /* The breakpoint_ops structure to be used in tracepoints.  */
13378
13379 static void
13380 tracepoint_re_set (struct breakpoint *b)
13381 {
13382   breakpoint_re_set_default (b);
13383 }
13384
13385 static int
13386 tracepoint_breakpoint_hit (const struct bp_location *bl,
13387                            struct address_space *aspace, CORE_ADDR bp_addr,
13388                            const struct target_waitstatus *ws)
13389 {
13390   /* By definition, the inferior does not report stops at
13391      tracepoints.  */
13392   return 0;
13393 }
13394
13395 static void
13396 tracepoint_print_one_detail (const struct breakpoint *self,
13397                              struct ui_out *uiout)
13398 {
13399   struct tracepoint *tp = (struct tracepoint *) self;
13400   if (tp->static_trace_marker_id)
13401     {
13402       gdb_assert (self->type == bp_static_tracepoint);
13403
13404       ui_out_text (uiout, "\tmarker id is ");
13405       ui_out_field_string (uiout, "static-tracepoint-marker-string-id",
13406                            tp->static_trace_marker_id);
13407       ui_out_text (uiout, "\n");
13408     }
13409 }
13410
13411 static void
13412 tracepoint_print_mention (struct breakpoint *b)
13413 {
13414   if (ui_out_is_mi_like_p (current_uiout))
13415     return;
13416
13417   switch (b->type)
13418     {
13419     case bp_tracepoint:
13420       printf_filtered (_("Tracepoint"));
13421       printf_filtered (_(" %d"), b->number);
13422       break;
13423     case bp_fast_tracepoint:
13424       printf_filtered (_("Fast tracepoint"));
13425       printf_filtered (_(" %d"), b->number);
13426       break;
13427     case bp_static_tracepoint:
13428       printf_filtered (_("Static tracepoint"));
13429       printf_filtered (_(" %d"), b->number);
13430       break;
13431     default:
13432       internal_error (__FILE__, __LINE__,
13433                       _("unhandled tracepoint type %d"), (int) b->type);
13434     }
13435
13436   say_where (b);
13437 }
13438
13439 static void
13440 tracepoint_print_recreate (struct breakpoint *self, struct ui_file *fp)
13441 {
13442   struct tracepoint *tp = (struct tracepoint *) self;
13443
13444   if (self->type == bp_fast_tracepoint)
13445     fprintf_unfiltered (fp, "ftrace");
13446   if (self->type == bp_static_tracepoint)
13447     fprintf_unfiltered (fp, "strace");
13448   else if (self->type == bp_tracepoint)
13449     fprintf_unfiltered (fp, "trace");
13450   else
13451     internal_error (__FILE__, __LINE__,
13452                     _("unhandled tracepoint type %d"), (int) self->type);
13453
13454   fprintf_unfiltered (fp, " %s", self->addr_string);
13455   print_recreate_thread (self, fp);
13456
13457   if (tp->pass_count)
13458     fprintf_unfiltered (fp, "  passcount %d\n", tp->pass_count);
13459 }
13460
13461 static void
13462 tracepoint_create_sals_from_address (char **arg,
13463                                      struct linespec_result *canonical,
13464                                      enum bptype type_wanted,
13465                                      char *addr_start, char **copy_arg)
13466 {
13467   create_sals_from_address_default (arg, canonical, type_wanted,
13468                                     addr_start, copy_arg);
13469 }
13470
13471 static void
13472 tracepoint_create_breakpoints_sal (struct gdbarch *gdbarch,
13473                                    struct linespec_result *canonical,
13474                                    char *cond_string,
13475                                    char *extra_string,
13476                                    enum bptype type_wanted,
13477                                    enum bpdisp disposition,
13478                                    int thread,
13479                                    int task, int ignore_count,
13480                                    const struct breakpoint_ops *ops,
13481                                    int from_tty, int enabled,
13482                                    int internal, unsigned flags)
13483 {
13484   create_breakpoints_sal_default (gdbarch, canonical,
13485                                   cond_string, extra_string,
13486                                   type_wanted,
13487                                   disposition, thread, task,
13488                                   ignore_count, ops, from_tty,
13489                                   enabled, internal, flags);
13490 }
13491
13492 static void
13493 tracepoint_decode_linespec (struct breakpoint *b, char **s,
13494                             struct symtabs_and_lines *sals)
13495 {
13496   decode_linespec_default (b, s, sals);
13497 }
13498
13499 struct breakpoint_ops tracepoint_breakpoint_ops;
13500
13501 /* The breakpoint_ops structure to be use on tracepoints placed in a
13502    static probe.  */
13503
13504 static void
13505 tracepoint_probe_create_sals_from_address (char **arg,
13506                                            struct linespec_result *canonical,
13507                                            enum bptype type_wanted,
13508                                            char *addr_start, char **copy_arg)
13509 {
13510   /* We use the same method for breakpoint on probes.  */
13511   bkpt_probe_create_sals_from_address (arg, canonical, type_wanted,
13512                                        addr_start, copy_arg);
13513 }
13514
13515 static void
13516 tracepoint_probe_decode_linespec (struct breakpoint *b, char **s,
13517                                   struct symtabs_and_lines *sals)
13518 {
13519   /* We use the same method for breakpoint on probes.  */
13520   bkpt_probe_decode_linespec (b, s, sals);
13521 }
13522
13523 static struct breakpoint_ops tracepoint_probe_breakpoint_ops;
13524
13525 /* Dprintf breakpoint_ops methods.  */
13526
13527 static void
13528 dprintf_re_set (struct breakpoint *b)
13529 {
13530   breakpoint_re_set_default (b);
13531
13532   /* This breakpoint could have been pending, and be resolved now, and
13533      if so, we should now have the extra string.  If we don't, the
13534      dprintf was malformed when created, but we couldn't tell because
13535      we can't extract the extra string until the location is
13536      resolved.  */
13537   if (b->loc != NULL && b->extra_string == NULL)
13538     error (_("Format string required"));
13539
13540   /* 1 - connect to target 1, that can run breakpoint commands.
13541      2 - create a dprintf, which resolves fine.
13542      3 - disconnect from target 1
13543      4 - connect to target 2, that can NOT run breakpoint commands.
13544
13545      After steps #3/#4, you'll want the dprintf command list to
13546      be updated, because target 1 and 2 may well return different
13547      answers for target_can_run_breakpoint_commands().
13548      Given absence of finer grained resetting, we get to do
13549      it all the time.  */
13550   if (b->extra_string != NULL)
13551     update_dprintf_command_list (b);
13552 }
13553
13554 /* Implement the "print_recreate" breakpoint_ops method for dprintf.  */
13555
13556 static void
13557 dprintf_print_recreate (struct breakpoint *tp, struct ui_file *fp)
13558 {
13559   fprintf_unfiltered (fp, "dprintf %s%s", tp->addr_string,
13560                       tp->extra_string);
13561   print_recreate_thread (tp, fp);
13562 }
13563
13564 /* Implement the "after_condition_true" breakpoint_ops method for
13565    dprintf.
13566
13567    dprintf's are implemented with regular commands in their command
13568    list, but we run the commands here instead of before presenting the
13569    stop to the user, as dprintf's don't actually cause a stop.  This
13570    also makes it so that the commands of multiple dprintfs at the same
13571    address are all handled.  */
13572
13573 static void
13574 dprintf_after_condition_true (struct bpstats *bs)
13575 {
13576   struct cleanup *old_chain;
13577   struct bpstats tmp_bs = { NULL };
13578   struct bpstats *tmp_bs_p = &tmp_bs;
13579
13580   /* dprintf's never cause a stop.  This wasn't set in the
13581      check_status hook instead because that would make the dprintf's
13582      condition not be evaluated.  */
13583   bs->stop = 0;
13584
13585   /* Run the command list here.  Take ownership of it instead of
13586      copying.  We never want these commands to run later in
13587      bpstat_do_actions, if a breakpoint that causes a stop happens to
13588      be set at same address as this dprintf, or even if running the
13589      commands here throws.  */
13590   tmp_bs.commands = bs->commands;
13591   bs->commands = NULL;
13592   old_chain = make_cleanup_decref_counted_command_line (&tmp_bs.commands);
13593
13594   bpstat_do_actions_1 (&tmp_bs_p);
13595
13596   /* 'tmp_bs.commands' will usually be NULL by now, but
13597      bpstat_do_actions_1 may return early without processing the whole
13598      list.  */
13599   do_cleanups (old_chain);
13600 }
13601
13602 /* The breakpoint_ops structure to be used on static tracepoints with
13603    markers (`-m').  */
13604
13605 static void
13606 strace_marker_create_sals_from_address (char **arg,
13607                                         struct linespec_result *canonical,
13608                                         enum bptype type_wanted,
13609                                         char *addr_start, char **copy_arg)
13610 {
13611   struct linespec_sals lsal;
13612
13613   lsal.sals = decode_static_tracepoint_spec (arg);
13614
13615   *copy_arg = savestring (addr_start, *arg - addr_start);
13616
13617   canonical->addr_string = xstrdup (*copy_arg);
13618   lsal.canonical = xstrdup (*copy_arg);
13619   VEC_safe_push (linespec_sals, canonical->sals, &lsal);
13620 }
13621
13622 static void
13623 strace_marker_create_breakpoints_sal (struct gdbarch *gdbarch,
13624                                       struct linespec_result *canonical,
13625                                       char *cond_string,
13626                                       char *extra_string,
13627                                       enum bptype type_wanted,
13628                                       enum bpdisp disposition,
13629                                       int thread,
13630                                       int task, int ignore_count,
13631                                       const struct breakpoint_ops *ops,
13632                                       int from_tty, int enabled,
13633                                       int internal, unsigned flags)
13634 {
13635   int i;
13636   struct linespec_sals *lsal = VEC_index (linespec_sals,
13637                                           canonical->sals, 0);
13638
13639   /* If the user is creating a static tracepoint by marker id
13640      (strace -m MARKER_ID), then store the sals index, so that
13641      breakpoint_re_set can try to match up which of the newly
13642      found markers corresponds to this one, and, don't try to
13643      expand multiple locations for each sal, given than SALS
13644      already should contain all sals for MARKER_ID.  */
13645
13646   for (i = 0; i < lsal->sals.nelts; ++i)
13647     {
13648       struct symtabs_and_lines expanded;
13649       struct tracepoint *tp;
13650       struct cleanup *old_chain;
13651       char *addr_string;
13652
13653       expanded.nelts = 1;
13654       expanded.sals = &lsal->sals.sals[i];
13655
13656       addr_string = xstrdup (canonical->addr_string);
13657       old_chain = make_cleanup (xfree, addr_string);
13658
13659       tp = XCNEW (struct tracepoint);
13660       init_breakpoint_sal (&tp->base, gdbarch, expanded,
13661                            addr_string, NULL,
13662                            cond_string, extra_string,
13663                            type_wanted, disposition,
13664                            thread, task, ignore_count, ops,
13665                            from_tty, enabled, internal, flags,
13666                            canonical->special_display);
13667       /* Given that its possible to have multiple markers with
13668          the same string id, if the user is creating a static
13669          tracepoint by marker id ("strace -m MARKER_ID"), then
13670          store the sals index, so that breakpoint_re_set can
13671          try to match up which of the newly found markers
13672          corresponds to this one  */
13673       tp->static_trace_marker_id_idx = i;
13674
13675       install_breakpoint (internal, &tp->base, 0);
13676
13677       discard_cleanups (old_chain);
13678     }
13679 }
13680
13681 static void
13682 strace_marker_decode_linespec (struct breakpoint *b, char **s,
13683                                struct symtabs_and_lines *sals)
13684 {
13685   struct tracepoint *tp = (struct tracepoint *) b;
13686
13687   *sals = decode_static_tracepoint_spec (s);
13688   if (sals->nelts > tp->static_trace_marker_id_idx)
13689     {
13690       sals->sals[0] = sals->sals[tp->static_trace_marker_id_idx];
13691       sals->nelts = 1;
13692     }
13693   else
13694     error (_("marker %s not found"), tp->static_trace_marker_id);
13695 }
13696
13697 static struct breakpoint_ops strace_marker_breakpoint_ops;
13698
13699 static int
13700 strace_marker_p (struct breakpoint *b)
13701 {
13702   return b->ops == &strace_marker_breakpoint_ops;
13703 }
13704
13705 /* Delete a breakpoint and clean up all traces of it in the data
13706    structures.  */
13707
13708 void
13709 delete_breakpoint (struct breakpoint *bpt)
13710 {
13711   struct breakpoint *b;
13712
13713   gdb_assert (bpt != NULL);
13714
13715   /* Has this bp already been deleted?  This can happen because
13716      multiple lists can hold pointers to bp's.  bpstat lists are
13717      especial culprits.
13718
13719      One example of this happening is a watchpoint's scope bp.  When
13720      the scope bp triggers, we notice that the watchpoint is out of
13721      scope, and delete it.  We also delete its scope bp.  But the
13722      scope bp is marked "auto-deleting", and is already on a bpstat.
13723      That bpstat is then checked for auto-deleting bp's, which are
13724      deleted.
13725
13726      A real solution to this problem might involve reference counts in
13727      bp's, and/or giving them pointers back to their referencing
13728      bpstat's, and teaching delete_breakpoint to only free a bp's
13729      storage when no more references were extent.  A cheaper bandaid
13730      was chosen.  */
13731   if (bpt->type == bp_none)
13732     return;
13733
13734   /* At least avoid this stale reference until the reference counting
13735      of breakpoints gets resolved.  */
13736   if (bpt->related_breakpoint != bpt)
13737     {
13738       struct breakpoint *related;
13739       struct watchpoint *w;
13740
13741       if (bpt->type == bp_watchpoint_scope)
13742         w = (struct watchpoint *) bpt->related_breakpoint;
13743       else if (bpt->related_breakpoint->type == bp_watchpoint_scope)
13744         w = (struct watchpoint *) bpt;
13745       else
13746         w = NULL;
13747       if (w != NULL)
13748         watchpoint_del_at_next_stop (w);
13749
13750       /* Unlink bpt from the bpt->related_breakpoint ring.  */
13751       for (related = bpt; related->related_breakpoint != bpt;
13752            related = related->related_breakpoint);
13753       related->related_breakpoint = bpt->related_breakpoint;
13754       bpt->related_breakpoint = bpt;
13755     }
13756
13757   /* watch_command_1 creates a watchpoint but only sets its number if
13758      update_watchpoint succeeds in creating its bp_locations.  If there's
13759      a problem in that process, we'll be asked to delete the half-created
13760      watchpoint.  In that case, don't announce the deletion.  */
13761   if (bpt->number)
13762     observer_notify_breakpoint_deleted (bpt);
13763
13764   if (breakpoint_chain == bpt)
13765     breakpoint_chain = bpt->next;
13766
13767   ALL_BREAKPOINTS (b)
13768     if (b->next == bpt)
13769     {
13770       b->next = bpt->next;
13771       break;
13772     }
13773
13774   /* Be sure no bpstat's are pointing at the breakpoint after it's
13775      been freed.  */
13776   /* FIXME, how can we find all bpstat's?  We just check stop_bpstat
13777      in all threads for now.  Note that we cannot just remove bpstats
13778      pointing at bpt from the stop_bpstat list entirely, as breakpoint
13779      commands are associated with the bpstat; if we remove it here,
13780      then the later call to bpstat_do_actions (&stop_bpstat); in
13781      event-top.c won't do anything, and temporary breakpoints with
13782      commands won't work.  */
13783
13784   iterate_over_threads (bpstat_remove_breakpoint_callback, bpt);
13785
13786   /* Now that breakpoint is removed from breakpoint list, update the
13787      global location list.  This will remove locations that used to
13788      belong to this breakpoint.  Do this before freeing the breakpoint
13789      itself, since remove_breakpoint looks at location's owner.  It
13790      might be better design to have location completely
13791      self-contained, but it's not the case now.  */
13792   update_global_location_list (0);
13793
13794   bpt->ops->dtor (bpt);
13795   /* On the chance that someone will soon try again to delete this
13796      same bp, we mark it as deleted before freeing its storage.  */
13797   bpt->type = bp_none;
13798   xfree (bpt);
13799 }
13800
13801 static void
13802 do_delete_breakpoint_cleanup (void *b)
13803 {
13804   delete_breakpoint (b);
13805 }
13806
13807 struct cleanup *
13808 make_cleanup_delete_breakpoint (struct breakpoint *b)
13809 {
13810   return make_cleanup (do_delete_breakpoint_cleanup, b);
13811 }
13812
13813 /* Iterator function to call a user-provided callback function once
13814    for each of B and its related breakpoints.  */
13815
13816 static void
13817 iterate_over_related_breakpoints (struct breakpoint *b,
13818                                   void (*function) (struct breakpoint *,
13819                                                     void *),
13820                                   void *data)
13821 {
13822   struct breakpoint *related;
13823
13824   related = b;
13825   do
13826     {
13827       struct breakpoint *next;
13828
13829       /* FUNCTION may delete RELATED.  */
13830       next = related->related_breakpoint;
13831
13832       if (next == related)
13833         {
13834           /* RELATED is the last ring entry.  */
13835           function (related, data);
13836
13837           /* FUNCTION may have deleted it, so we'd never reach back to
13838              B.  There's nothing left to do anyway, so just break
13839              out.  */
13840           break;
13841         }
13842       else
13843         function (related, data);
13844
13845       related = next;
13846     }
13847   while (related != b);
13848 }
13849
13850 static void
13851 do_delete_breakpoint (struct breakpoint *b, void *ignore)
13852 {
13853   delete_breakpoint (b);
13854 }
13855
13856 /* A callback for map_breakpoint_numbers that calls
13857    delete_breakpoint.  */
13858
13859 static void
13860 do_map_delete_breakpoint (struct breakpoint *b, void *ignore)
13861 {
13862   iterate_over_related_breakpoints (b, do_delete_breakpoint, NULL);
13863 }
13864
13865 void
13866 delete_command (char *arg, int from_tty)
13867 {
13868   struct breakpoint *b, *b_tmp;
13869
13870   dont_repeat ();
13871
13872   if (arg == 0)
13873     {
13874       int breaks_to_delete = 0;
13875
13876       /* Delete all breakpoints if no argument.  Do not delete
13877          internal breakpoints, these have to be deleted with an
13878          explicit breakpoint number argument.  */
13879       ALL_BREAKPOINTS (b)
13880         if (user_breakpoint_p (b))
13881           {
13882             breaks_to_delete = 1;
13883             break;
13884           }
13885
13886       /* Ask user only if there are some breakpoints to delete.  */
13887       if (!from_tty
13888           || (breaks_to_delete && query (_("Delete all breakpoints? "))))
13889         {
13890           ALL_BREAKPOINTS_SAFE (b, b_tmp)
13891             if (user_breakpoint_p (b))
13892               delete_breakpoint (b);
13893         }
13894     }
13895   else
13896     map_breakpoint_numbers (arg, do_map_delete_breakpoint, NULL);
13897 }
13898
13899 static int
13900 all_locations_are_pending (struct bp_location *loc)
13901 {
13902   for (; loc; loc = loc->next)
13903     if (!loc->shlib_disabled
13904         && !loc->pspace->executing_startup)
13905       return 0;
13906   return 1;
13907 }
13908
13909 /* Subroutine of update_breakpoint_locations to simplify it.
13910    Return non-zero if multiple fns in list LOC have the same name.
13911    Null names are ignored.  */
13912
13913 static int
13914 ambiguous_names_p (struct bp_location *loc)
13915 {
13916   struct bp_location *l;
13917   htab_t htab = htab_create_alloc (13, htab_hash_string,
13918                                    (int (*) (const void *, 
13919                                              const void *)) streq,
13920                                    NULL, xcalloc, xfree);
13921
13922   for (l = loc; l != NULL; l = l->next)
13923     {
13924       const char **slot;
13925       const char *name = l->function_name;
13926
13927       /* Allow for some names to be NULL, ignore them.  */
13928       if (name == NULL)
13929         continue;
13930
13931       slot = (const char **) htab_find_slot (htab, (const void *) name,
13932                                              INSERT);
13933       /* NOTE: We can assume slot != NULL here because xcalloc never
13934          returns NULL.  */
13935       if (*slot != NULL)
13936         {
13937           htab_delete (htab);
13938           return 1;
13939         }
13940       *slot = name;
13941     }
13942
13943   htab_delete (htab);
13944   return 0;
13945 }
13946
13947 /* When symbols change, it probably means the sources changed as well,
13948    and it might mean the static tracepoint markers are no longer at
13949    the same address or line numbers they used to be at last we
13950    checked.  Losing your static tracepoints whenever you rebuild is
13951    undesirable.  This function tries to resync/rematch gdb static
13952    tracepoints with the markers on the target, for static tracepoints
13953    that have not been set by marker id.  Static tracepoint that have
13954    been set by marker id are reset by marker id in breakpoint_re_set.
13955    The heuristic is:
13956
13957    1) For a tracepoint set at a specific address, look for a marker at
13958    the old PC.  If one is found there, assume to be the same marker.
13959    If the name / string id of the marker found is different from the
13960    previous known name, assume that means the user renamed the marker
13961    in the sources, and output a warning.
13962
13963    2) For a tracepoint set at a given line number, look for a marker
13964    at the new address of the old line number.  If one is found there,
13965    assume to be the same marker.  If the name / string id of the
13966    marker found is different from the previous known name, assume that
13967    means the user renamed the marker in the sources, and output a
13968    warning.
13969
13970    3) If a marker is no longer found at the same address or line, it
13971    may mean the marker no longer exists.  But it may also just mean
13972    the code changed a bit.  Maybe the user added a few lines of code
13973    that made the marker move up or down (in line number terms).  Ask
13974    the target for info about the marker with the string id as we knew
13975    it.  If found, update line number and address in the matching
13976    static tracepoint.  This will get confused if there's more than one
13977    marker with the same ID (possible in UST, although unadvised
13978    precisely because it confuses tools).  */
13979
13980 static struct symtab_and_line
13981 update_static_tracepoint (struct breakpoint *b, struct symtab_and_line sal)
13982 {
13983   struct tracepoint *tp = (struct tracepoint *) b;
13984   struct static_tracepoint_marker marker;
13985   CORE_ADDR pc;
13986
13987   pc = sal.pc;
13988   if (sal.line)
13989     find_line_pc (sal.symtab, sal.line, &pc);
13990
13991   if (target_static_tracepoint_marker_at (pc, &marker))
13992     {
13993       if (strcmp (tp->static_trace_marker_id, marker.str_id) != 0)
13994         warning (_("static tracepoint %d changed probed marker from %s to %s"),
13995                  b->number,
13996                  tp->static_trace_marker_id, marker.str_id);
13997
13998       xfree (tp->static_trace_marker_id);
13999       tp->static_trace_marker_id = xstrdup (marker.str_id);
14000       release_static_tracepoint_marker (&marker);
14001
14002       return sal;
14003     }
14004
14005   /* Old marker wasn't found on target at lineno.  Try looking it up
14006      by string ID.  */
14007   if (!sal.explicit_pc
14008       && sal.line != 0
14009       && sal.symtab != NULL
14010       && tp->static_trace_marker_id != NULL)
14011     {
14012       VEC(static_tracepoint_marker_p) *markers;
14013
14014       markers
14015         = target_static_tracepoint_markers_by_strid (tp->static_trace_marker_id);
14016
14017       if (!VEC_empty(static_tracepoint_marker_p, markers))
14018         {
14019           struct symtab_and_line sal2;
14020           struct symbol *sym;
14021           struct static_tracepoint_marker *tpmarker;
14022           struct ui_out *uiout = current_uiout;
14023
14024           tpmarker = VEC_index (static_tracepoint_marker_p, markers, 0);
14025
14026           xfree (tp->static_trace_marker_id);
14027           tp->static_trace_marker_id = xstrdup (tpmarker->str_id);
14028
14029           warning (_("marker for static tracepoint %d (%s) not "
14030                      "found at previous line number"),
14031                    b->number, tp->static_trace_marker_id);
14032
14033           init_sal (&sal2);
14034
14035           sal2.pc = tpmarker->address;
14036
14037           sal2 = find_pc_line (tpmarker->address, 0);
14038           sym = find_pc_sect_function (tpmarker->address, NULL);
14039           ui_out_text (uiout, "Now in ");
14040           if (sym)
14041             {
14042               ui_out_field_string (uiout, "func",
14043                                    SYMBOL_PRINT_NAME (sym));
14044               ui_out_text (uiout, " at ");
14045             }
14046           ui_out_field_string (uiout, "file",
14047                                symtab_to_filename_for_display (sal2.symtab));
14048           ui_out_text (uiout, ":");
14049
14050           if (ui_out_is_mi_like_p (uiout))
14051             {
14052               const char *fullname = symtab_to_fullname (sal2.symtab);
14053
14054               ui_out_field_string (uiout, "fullname", fullname);
14055             }
14056
14057           ui_out_field_int (uiout, "line", sal2.line);
14058           ui_out_text (uiout, "\n");
14059
14060           b->loc->line_number = sal2.line;
14061           b->loc->symtab = sym != NULL ? sal2.symtab : NULL;
14062
14063           xfree (b->addr_string);
14064           b->addr_string = xstrprintf ("%s:%d",
14065                                    symtab_to_filename_for_display (sal2.symtab),
14066                                        b->loc->line_number);
14067
14068           /* Might be nice to check if function changed, and warn if
14069              so.  */
14070
14071           release_static_tracepoint_marker (tpmarker);
14072         }
14073     }
14074   return sal;
14075 }
14076
14077 /* Returns 1 iff locations A and B are sufficiently same that
14078    we don't need to report breakpoint as changed.  */
14079
14080 static int
14081 locations_are_equal (struct bp_location *a, struct bp_location *b)
14082 {
14083   while (a && b)
14084     {
14085       if (a->address != b->address)
14086         return 0;
14087
14088       if (a->shlib_disabled != b->shlib_disabled)
14089         return 0;
14090
14091       if (a->enabled != b->enabled)
14092         return 0;
14093
14094       a = a->next;
14095       b = b->next;
14096     }
14097
14098   if ((a == NULL) != (b == NULL))
14099     return 0;
14100
14101   return 1;
14102 }
14103
14104 /* Create new breakpoint locations for B (a hardware or software breakpoint)
14105    based on SALS and SALS_END.  If SALS_END.NELTS is not zero, then B is
14106    a ranged breakpoint.  */
14107
14108 void
14109 update_breakpoint_locations (struct breakpoint *b,
14110                              struct symtabs_and_lines sals,
14111                              struct symtabs_and_lines sals_end)
14112 {
14113   int i;
14114   struct bp_location *existing_locations = b->loc;
14115
14116   if (sals_end.nelts != 0 && (sals.nelts != 1 || sals_end.nelts != 1))
14117     {
14118       /* Ranged breakpoints have only one start location and one end
14119          location.  */
14120       b->enable_state = bp_disabled;
14121       update_global_location_list (1);
14122       printf_unfiltered (_("Could not reset ranged breakpoint %d: "
14123                            "multiple locations found\n"),
14124                          b->number);
14125       return;
14126     }
14127
14128   /* If there's no new locations, and all existing locations are
14129      pending, don't do anything.  This optimizes the common case where
14130      all locations are in the same shared library, that was unloaded.
14131      We'd like to retain the location, so that when the library is
14132      loaded again, we don't loose the enabled/disabled status of the
14133      individual locations.  */
14134   if (all_locations_are_pending (existing_locations) && sals.nelts == 0)
14135     return;
14136
14137   b->loc = NULL;
14138
14139   for (i = 0; i < sals.nelts; ++i)
14140     {
14141       struct bp_location *new_loc;
14142
14143       switch_to_program_space_and_thread (sals.sals[i].pspace);
14144
14145       new_loc = add_location_to_breakpoint (b, &(sals.sals[i]));
14146
14147       /* Reparse conditions, they might contain references to the
14148          old symtab.  */
14149       if (b->cond_string != NULL)
14150         {
14151           const char *s;
14152           volatile struct gdb_exception e;
14153
14154           s = b->cond_string;
14155           TRY_CATCH (e, RETURN_MASK_ERROR)
14156             {
14157               new_loc->cond = parse_exp_1 (&s, sals.sals[i].pc,
14158                                            block_for_pc (sals.sals[i].pc), 
14159                                            0);
14160             }
14161           if (e.reason < 0)
14162             {
14163               warning (_("failed to reevaluate condition "
14164                          "for breakpoint %d: %s"), 
14165                        b->number, e.message);
14166               new_loc->enabled = 0;
14167             }
14168         }
14169
14170       if (sals_end.nelts)
14171         {
14172           CORE_ADDR end = find_breakpoint_range_end (sals_end.sals[0]);
14173
14174           new_loc->length = end - sals.sals[0].pc + 1;
14175         }
14176     }
14177
14178   /* Update locations of permanent breakpoints.  */
14179   if (b->enable_state == bp_permanent)
14180     make_breakpoint_permanent (b);
14181
14182   /* If possible, carry over 'disable' status from existing
14183      breakpoints.  */
14184   {
14185     struct bp_location *e = existing_locations;
14186     /* If there are multiple breakpoints with the same function name,
14187        e.g. for inline functions, comparing function names won't work.
14188        Instead compare pc addresses; this is just a heuristic as things
14189        may have moved, but in practice it gives the correct answer
14190        often enough until a better solution is found.  */
14191     int have_ambiguous_names = ambiguous_names_p (b->loc);
14192
14193     for (; e; e = e->next)
14194       {
14195         if (!e->enabled && e->function_name)
14196           {
14197             struct bp_location *l = b->loc;
14198             if (have_ambiguous_names)
14199               {
14200                 for (; l; l = l->next)
14201                   if (breakpoint_locations_match (e, l))
14202                     {
14203                       l->enabled = 0;
14204                       break;
14205                     }
14206               }
14207             else
14208               {
14209                 for (; l; l = l->next)
14210                   if (l->function_name
14211                       && strcmp (e->function_name, l->function_name) == 0)
14212                     {
14213                       l->enabled = 0;
14214                       break;
14215                     }
14216               }
14217           }
14218       }
14219   }
14220
14221   if (!locations_are_equal (existing_locations, b->loc))
14222     observer_notify_breakpoint_modified (b);
14223
14224   update_global_location_list (1);
14225 }
14226
14227 /* Find the SaL locations corresponding to the given ADDR_STRING.
14228    On return, FOUND will be 1 if any SaL was found, zero otherwise.  */
14229
14230 static struct symtabs_and_lines
14231 addr_string_to_sals (struct breakpoint *b, char *addr_string, int *found)
14232 {
14233   char *s;
14234   struct symtabs_and_lines sals = {0};
14235   volatile struct gdb_exception e;
14236
14237   gdb_assert (b->ops != NULL);
14238   s = addr_string;
14239
14240   TRY_CATCH (e, RETURN_MASK_ERROR)
14241     {
14242       b->ops->decode_linespec (b, &s, &sals);
14243     }
14244   if (e.reason < 0)
14245     {
14246       int not_found_and_ok = 0;
14247       /* For pending breakpoints, it's expected that parsing will
14248          fail until the right shared library is loaded.  User has
14249          already told to create pending breakpoints and don't need
14250          extra messages.  If breakpoint is in bp_shlib_disabled
14251          state, then user already saw the message about that
14252          breakpoint being disabled, and don't want to see more
14253          errors.  */
14254       if (e.error == NOT_FOUND_ERROR
14255           && (b->condition_not_parsed 
14256               || (b->loc && b->loc->shlib_disabled)
14257               || (b->loc && b->loc->pspace->executing_startup)
14258               || b->enable_state == bp_disabled))
14259         not_found_and_ok = 1;
14260
14261       if (!not_found_and_ok)
14262         {
14263           /* We surely don't want to warn about the same breakpoint
14264              10 times.  One solution, implemented here, is disable
14265              the breakpoint on error.  Another solution would be to
14266              have separate 'warning emitted' flag.  Since this
14267              happens only when a binary has changed, I don't know
14268              which approach is better.  */
14269           b->enable_state = bp_disabled;
14270           throw_exception (e);
14271         }
14272     }
14273
14274   if (e.reason == 0 || e.error != NOT_FOUND_ERROR)
14275     {
14276       int i;
14277
14278       for (i = 0; i < sals.nelts; ++i)
14279         resolve_sal_pc (&sals.sals[i]);
14280       if (b->condition_not_parsed && s && s[0])
14281         {
14282           char *cond_string, *extra_string;
14283           int thread, task;
14284
14285           find_condition_and_thread (s, sals.sals[0].pc,
14286                                      &cond_string, &thread, &task,
14287                                      &extra_string);
14288           if (cond_string)
14289             b->cond_string = cond_string;
14290           b->thread = thread;
14291           b->task = task;
14292           if (extra_string)
14293             b->extra_string = extra_string;
14294           b->condition_not_parsed = 0;
14295         }
14296
14297       if (b->type == bp_static_tracepoint && !strace_marker_p (b))
14298         sals.sals[0] = update_static_tracepoint (b, sals.sals[0]);
14299
14300       *found = 1;
14301     }
14302   else
14303     *found = 0;
14304
14305   return sals;
14306 }
14307
14308 /* The default re_set method, for typical hardware or software
14309    breakpoints.  Reevaluate the breakpoint and recreate its
14310    locations.  */
14311
14312 static void
14313 breakpoint_re_set_default (struct breakpoint *b)
14314 {
14315   int found;
14316   struct symtabs_and_lines sals, sals_end;
14317   struct symtabs_and_lines expanded = {0};
14318   struct symtabs_and_lines expanded_end = {0};
14319
14320   sals = addr_string_to_sals (b, b->addr_string, &found);
14321   if (found)
14322     {
14323       make_cleanup (xfree, sals.sals);
14324       expanded = sals;
14325     }
14326
14327   if (b->addr_string_range_end)
14328     {
14329       sals_end = addr_string_to_sals (b, b->addr_string_range_end, &found);
14330       if (found)
14331         {
14332           make_cleanup (xfree, sals_end.sals);
14333           expanded_end = sals_end;
14334         }
14335     }
14336
14337   update_breakpoint_locations (b, expanded, expanded_end);
14338 }
14339
14340 /* Default method for creating SALs from an address string.  It basically
14341    calls parse_breakpoint_sals.  Return 1 for success, zero for failure.  */
14342
14343 static void
14344 create_sals_from_address_default (char **arg,
14345                                   struct linespec_result *canonical,
14346                                   enum bptype type_wanted,
14347                                   char *addr_start, char **copy_arg)
14348 {
14349   parse_breakpoint_sals (arg, canonical);
14350 }
14351
14352 /* Call create_breakpoints_sal for the given arguments.  This is the default
14353    function for the `create_breakpoints_sal' method of
14354    breakpoint_ops.  */
14355
14356 static void
14357 create_breakpoints_sal_default (struct gdbarch *gdbarch,
14358                                 struct linespec_result *canonical,
14359                                 char *cond_string,
14360                                 char *extra_string,
14361                                 enum bptype type_wanted,
14362                                 enum bpdisp disposition,
14363                                 int thread,
14364                                 int task, int ignore_count,
14365                                 const struct breakpoint_ops *ops,
14366                                 int from_tty, int enabled,
14367                                 int internal, unsigned flags)
14368 {
14369   create_breakpoints_sal (gdbarch, canonical, cond_string,
14370                           extra_string,
14371                           type_wanted, disposition,
14372                           thread, task, ignore_count, ops, from_tty,
14373                           enabled, internal, flags);
14374 }
14375
14376 /* Decode the line represented by S by calling decode_line_full.  This is the
14377    default function for the `decode_linespec' method of breakpoint_ops.  */
14378
14379 static void
14380 decode_linespec_default (struct breakpoint *b, char **s,
14381                          struct symtabs_and_lines *sals)
14382 {
14383   struct linespec_result canonical;
14384
14385   init_linespec_result (&canonical);
14386   decode_line_full (s, DECODE_LINE_FUNFIRSTLINE,
14387                     (struct symtab *) NULL, 0,
14388                     &canonical, multiple_symbols_all,
14389                     b->filter);
14390
14391   /* We should get 0 or 1 resulting SALs.  */
14392   gdb_assert (VEC_length (linespec_sals, canonical.sals) < 2);
14393
14394   if (VEC_length (linespec_sals, canonical.sals) > 0)
14395     {
14396       struct linespec_sals *lsal;
14397
14398       lsal = VEC_index (linespec_sals, canonical.sals, 0);
14399       *sals = lsal->sals;
14400       /* Arrange it so the destructor does not free the
14401          contents.  */
14402       lsal->sals.sals = NULL;
14403     }
14404
14405   destroy_linespec_result (&canonical);
14406 }
14407
14408 /* Prepare the global context for a re-set of breakpoint B.  */
14409
14410 static struct cleanup *
14411 prepare_re_set_context (struct breakpoint *b)
14412 {
14413   struct cleanup *cleanups;
14414
14415   input_radix = b->input_radix;
14416   cleanups = save_current_space_and_thread ();
14417   if (b->pspace != NULL)
14418     switch_to_program_space_and_thread (b->pspace);
14419   set_language (b->language);
14420
14421   return cleanups;
14422 }
14423
14424 /* Reset a breakpoint given it's struct breakpoint * BINT.
14425    The value we return ends up being the return value from catch_errors.
14426    Unused in this case.  */
14427
14428 static int
14429 breakpoint_re_set_one (void *bint)
14430 {
14431   /* Get past catch_errs.  */
14432   struct breakpoint *b = (struct breakpoint *) bint;
14433   struct cleanup *cleanups;
14434
14435   cleanups = prepare_re_set_context (b);
14436   b->ops->re_set (b);
14437   do_cleanups (cleanups);
14438   return 0;
14439 }
14440
14441 /* Re-set all breakpoints after symbols have been re-loaded.  */
14442 void
14443 breakpoint_re_set (void)
14444 {
14445   struct breakpoint *b, *b_tmp;
14446   enum language save_language;
14447   int save_input_radix;
14448   struct cleanup *old_chain;
14449
14450   save_language = current_language->la_language;
14451   save_input_radix = input_radix;
14452   old_chain = save_current_program_space ();
14453
14454   ALL_BREAKPOINTS_SAFE (b, b_tmp)
14455   {
14456     /* Format possible error msg.  */
14457     char *message = xstrprintf ("Error in re-setting breakpoint %d: ",
14458                                 b->number);
14459     struct cleanup *cleanups = make_cleanup (xfree, message);
14460     catch_errors (breakpoint_re_set_one, b, message, RETURN_MASK_ALL);
14461     do_cleanups (cleanups);
14462   }
14463   set_language (save_language);
14464   input_radix = save_input_radix;
14465
14466   jit_breakpoint_re_set ();
14467
14468   do_cleanups (old_chain);
14469
14470   create_overlay_event_breakpoint ();
14471   create_longjmp_master_breakpoint ();
14472   create_std_terminate_master_breakpoint ();
14473   create_exception_master_breakpoint ();
14474 }
14475 \f
14476 /* Reset the thread number of this breakpoint:
14477
14478    - If the breakpoint is for all threads, leave it as-is.
14479    - Else, reset it to the current thread for inferior_ptid.  */
14480 void
14481 breakpoint_re_set_thread (struct breakpoint *b)
14482 {
14483   if (b->thread != -1)
14484     {
14485       if (in_thread_list (inferior_ptid))
14486         b->thread = pid_to_thread_id (inferior_ptid);
14487
14488       /* We're being called after following a fork.  The new fork is
14489          selected as current, and unless this was a vfork will have a
14490          different program space from the original thread.  Reset that
14491          as well.  */
14492       b->loc->pspace = current_program_space;
14493     }
14494 }
14495
14496 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
14497    If from_tty is nonzero, it prints a message to that effect,
14498    which ends with a period (no newline).  */
14499
14500 void
14501 set_ignore_count (int bptnum, int count, int from_tty)
14502 {
14503   struct breakpoint *b;
14504
14505   if (count < 0)
14506     count = 0;
14507
14508   ALL_BREAKPOINTS (b)
14509     if (b->number == bptnum)
14510     {
14511       if (is_tracepoint (b))
14512         {
14513           if (from_tty && count != 0)
14514             printf_filtered (_("Ignore count ignored for tracepoint %d."),
14515                              bptnum);
14516           return;
14517         }
14518       
14519       b->ignore_count = count;
14520       if (from_tty)
14521         {
14522           if (count == 0)
14523             printf_filtered (_("Will stop next time "
14524                                "breakpoint %d is reached."),
14525                              bptnum);
14526           else if (count == 1)
14527             printf_filtered (_("Will ignore next crossing of breakpoint %d."),
14528                              bptnum);
14529           else
14530             printf_filtered (_("Will ignore next %d "
14531                                "crossings of breakpoint %d."),
14532                              count, bptnum);
14533         }
14534       observer_notify_breakpoint_modified (b);
14535       return;
14536     }
14537
14538   error (_("No breakpoint number %d."), bptnum);
14539 }
14540
14541 /* Command to set ignore-count of breakpoint N to COUNT.  */
14542
14543 static void
14544 ignore_command (char *args, int from_tty)
14545 {
14546   char *p = args;
14547   int num;
14548
14549   if (p == 0)
14550     error_no_arg (_("a breakpoint number"));
14551
14552   num = get_number (&p);
14553   if (num == 0)
14554     error (_("bad breakpoint number: '%s'"), args);
14555   if (*p == 0)
14556     error (_("Second argument (specified ignore-count) is missing."));
14557
14558   set_ignore_count (num,
14559                     longest_to_int (value_as_long (parse_and_eval (p))),
14560                     from_tty);
14561   if (from_tty)
14562     printf_filtered ("\n");
14563 }
14564 \f
14565 /* Call FUNCTION on each of the breakpoints
14566    whose numbers are given in ARGS.  */
14567
14568 static void
14569 map_breakpoint_numbers (char *args, void (*function) (struct breakpoint *,
14570                                                       void *),
14571                         void *data)
14572 {
14573   int num;
14574   struct breakpoint *b, *tmp;
14575   int match;
14576   struct get_number_or_range_state state;
14577
14578   if (args == 0)
14579     error_no_arg (_("one or more breakpoint numbers"));
14580
14581   init_number_or_range (&state, args);
14582
14583   while (!state.finished)
14584     {
14585       char *p = state.string;
14586
14587       match = 0;
14588
14589       num = get_number_or_range (&state);
14590       if (num == 0)
14591         {
14592           warning (_("bad breakpoint number at or near '%s'"), p);
14593         }
14594       else
14595         {
14596           ALL_BREAKPOINTS_SAFE (b, tmp)
14597             if (b->number == num)
14598               {
14599                 match = 1;
14600                 function (b, data);
14601                 break;
14602               }
14603           if (match == 0)
14604             printf_unfiltered (_("No breakpoint number %d.\n"), num);
14605         }
14606     }
14607 }
14608
14609 static struct bp_location *
14610 find_location_by_number (char *number)
14611 {
14612   char *dot = strchr (number, '.');
14613   char *p1;
14614   int bp_num;
14615   int loc_num;
14616   struct breakpoint *b;
14617   struct bp_location *loc;  
14618
14619   *dot = '\0';
14620
14621   p1 = number;
14622   bp_num = get_number (&p1);
14623   if (bp_num == 0)
14624     error (_("Bad breakpoint number '%s'"), number);
14625
14626   ALL_BREAKPOINTS (b)
14627     if (b->number == bp_num)
14628       {
14629         break;
14630       }
14631
14632   if (!b || b->number != bp_num)
14633     error (_("Bad breakpoint number '%s'"), number);
14634   
14635   p1 = dot+1;
14636   loc_num = get_number (&p1);
14637   if (loc_num == 0)
14638     error (_("Bad breakpoint location number '%s'"), number);
14639
14640   --loc_num;
14641   loc = b->loc;
14642   for (;loc_num && loc; --loc_num, loc = loc->next)
14643     ;
14644   if (!loc)
14645     error (_("Bad breakpoint location number '%s'"), dot+1);
14646     
14647   return loc;  
14648 }
14649
14650
14651 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
14652    If from_tty is nonzero, it prints a message to that effect,
14653    which ends with a period (no newline).  */
14654
14655 void
14656 disable_breakpoint (struct breakpoint *bpt)
14657 {
14658   /* Never disable a watchpoint scope breakpoint; we want to
14659      hit them when we leave scope so we can delete both the
14660      watchpoint and its scope breakpoint at that time.  */
14661   if (bpt->type == bp_watchpoint_scope)
14662     return;
14663
14664   /* You can't disable permanent breakpoints.  */
14665   if (bpt->enable_state == bp_permanent)
14666     return;
14667
14668   bpt->enable_state = bp_disabled;
14669
14670   /* Mark breakpoint locations modified.  */
14671   mark_breakpoint_modified (bpt);
14672
14673   if (target_supports_enable_disable_tracepoint ()
14674       && current_trace_status ()->running && is_tracepoint (bpt))
14675     {
14676       struct bp_location *location;
14677      
14678       for (location = bpt->loc; location; location = location->next)
14679         target_disable_tracepoint (location);
14680     }
14681
14682   update_global_location_list (0);
14683
14684   observer_notify_breakpoint_modified (bpt);
14685 }
14686
14687 /* A callback for iterate_over_related_breakpoints.  */
14688
14689 static void
14690 do_disable_breakpoint (struct breakpoint *b, void *ignore)
14691 {
14692   disable_breakpoint (b);
14693 }
14694
14695 /* A callback for map_breakpoint_numbers that calls
14696    disable_breakpoint.  */
14697
14698 static void
14699 do_map_disable_breakpoint (struct breakpoint *b, void *ignore)
14700 {
14701   iterate_over_related_breakpoints (b, do_disable_breakpoint, NULL);
14702 }
14703
14704 static void
14705 disable_command (char *args, int from_tty)
14706 {
14707   if (args == 0)
14708     {
14709       struct breakpoint *bpt;
14710
14711       ALL_BREAKPOINTS (bpt)
14712         if (user_breakpoint_p (bpt))
14713           disable_breakpoint (bpt);
14714     }
14715   else
14716     {
14717       char *num = extract_arg (&args);
14718
14719       while (num)
14720         {
14721           if (strchr (num, '.'))
14722             {
14723               struct bp_location *loc = find_location_by_number (num);
14724
14725               if (loc)
14726                 {
14727                   if (loc->enabled)
14728                     {
14729                       loc->enabled = 0;
14730                       mark_breakpoint_location_modified (loc);
14731                     }
14732                   if (target_supports_enable_disable_tracepoint ()
14733                       && current_trace_status ()->running && loc->owner
14734                       && is_tracepoint (loc->owner))
14735                     target_disable_tracepoint (loc);
14736                 }
14737               update_global_location_list (0);
14738             }
14739           else
14740             map_breakpoint_numbers (num, do_map_disable_breakpoint, NULL);
14741           num = extract_arg (&args);
14742         }
14743     }
14744 }
14745
14746 static void
14747 enable_breakpoint_disp (struct breakpoint *bpt, enum bpdisp disposition,
14748                         int count)
14749 {
14750   int target_resources_ok;
14751
14752   if (bpt->type == bp_hardware_breakpoint)
14753     {
14754       int i;
14755       i = hw_breakpoint_used_count ();
14756       target_resources_ok = 
14757         target_can_use_hardware_watchpoint (bp_hardware_breakpoint, 
14758                                             i + 1, 0);
14759       if (target_resources_ok == 0)
14760         error (_("No hardware breakpoint support in the target."));
14761       else if (target_resources_ok < 0)
14762         error (_("Hardware breakpoints used exceeds limit."));
14763     }
14764
14765   if (is_watchpoint (bpt))
14766     {
14767       /* Initialize it just to avoid a GCC false warning.  */
14768       enum enable_state orig_enable_state = 0;
14769       volatile struct gdb_exception e;
14770
14771       TRY_CATCH (e, RETURN_MASK_ALL)
14772         {
14773           struct watchpoint *w = (struct watchpoint *) bpt;
14774
14775           orig_enable_state = bpt->enable_state;
14776           bpt->enable_state = bp_enabled;
14777           update_watchpoint (w, 1 /* reparse */);
14778         }
14779       if (e.reason < 0)
14780         {
14781           bpt->enable_state = orig_enable_state;
14782           exception_fprintf (gdb_stderr, e, _("Cannot enable watchpoint %d: "),
14783                              bpt->number);
14784           return;
14785         }
14786     }
14787
14788   if (bpt->enable_state != bp_permanent)
14789     bpt->enable_state = bp_enabled;
14790
14791   bpt->enable_state = bp_enabled;
14792
14793   /* Mark breakpoint locations modified.  */
14794   mark_breakpoint_modified (bpt);
14795
14796   if (target_supports_enable_disable_tracepoint ()
14797       && current_trace_status ()->running && is_tracepoint (bpt))
14798     {
14799       struct bp_location *location;
14800
14801       for (location = bpt->loc; location; location = location->next)
14802         target_enable_tracepoint (location);
14803     }
14804
14805   bpt->disposition = disposition;
14806   bpt->enable_count = count;
14807   update_global_location_list (1);
14808
14809   observer_notify_breakpoint_modified (bpt);
14810 }
14811
14812
14813 void
14814 enable_breakpoint (struct breakpoint *bpt)
14815 {
14816   enable_breakpoint_disp (bpt, bpt->disposition, 0);
14817 }
14818
14819 static void
14820 do_enable_breakpoint (struct breakpoint *bpt, void *arg)
14821 {
14822   enable_breakpoint (bpt);
14823 }
14824
14825 /* A callback for map_breakpoint_numbers that calls
14826    enable_breakpoint.  */
14827
14828 static void
14829 do_map_enable_breakpoint (struct breakpoint *b, void *ignore)
14830 {
14831   iterate_over_related_breakpoints (b, do_enable_breakpoint, NULL);
14832 }
14833
14834 /* The enable command enables the specified breakpoints (or all defined
14835    breakpoints) so they once again become (or continue to be) effective
14836    in stopping the inferior.  */
14837
14838 static void
14839 enable_command (char *args, int from_tty)
14840 {
14841   if (args == 0)
14842     {
14843       struct breakpoint *bpt;
14844
14845       ALL_BREAKPOINTS (bpt)
14846         if (user_breakpoint_p (bpt))
14847           enable_breakpoint (bpt);
14848     }
14849   else
14850     {
14851       char *num = extract_arg (&args);
14852
14853       while (num)
14854         {
14855           if (strchr (num, '.'))
14856             {
14857               struct bp_location *loc = find_location_by_number (num);
14858
14859               if (loc)
14860                 {
14861                   if (!loc->enabled)
14862                     {
14863                       loc->enabled = 1;
14864                       mark_breakpoint_location_modified (loc);
14865                     }
14866                   if (target_supports_enable_disable_tracepoint ()
14867                       && current_trace_status ()->running && loc->owner
14868                       && is_tracepoint (loc->owner))
14869                     target_enable_tracepoint (loc);
14870                 }
14871               update_global_location_list (1);
14872             }
14873           else
14874             map_breakpoint_numbers (num, do_map_enable_breakpoint, NULL);
14875           num = extract_arg (&args);
14876         }
14877     }
14878 }
14879
14880 /* This struct packages up disposition data for application to multiple
14881    breakpoints.  */
14882
14883 struct disp_data
14884 {
14885   enum bpdisp disp;
14886   int count;
14887 };
14888
14889 static void
14890 do_enable_breakpoint_disp (struct breakpoint *bpt, void *arg)
14891 {
14892   struct disp_data disp_data = *(struct disp_data *) arg;
14893
14894   enable_breakpoint_disp (bpt, disp_data.disp, disp_data.count);
14895 }
14896
14897 static void
14898 do_map_enable_once_breakpoint (struct breakpoint *bpt, void *ignore)
14899 {
14900   struct disp_data disp = { disp_disable, 1 };
14901
14902   iterate_over_related_breakpoints (bpt, do_enable_breakpoint_disp, &disp);
14903 }
14904
14905 static void
14906 enable_once_command (char *args, int from_tty)
14907 {
14908   map_breakpoint_numbers (args, do_map_enable_once_breakpoint, NULL);
14909 }
14910
14911 static void
14912 do_map_enable_count_breakpoint (struct breakpoint *bpt, void *countptr)
14913 {
14914   struct disp_data disp = { disp_disable, *(int *) countptr };
14915
14916   iterate_over_related_breakpoints (bpt, do_enable_breakpoint_disp, &disp);
14917 }
14918
14919 static void
14920 enable_count_command (char *args, int from_tty)
14921 {
14922   int count = get_number (&args);
14923
14924   map_breakpoint_numbers (args, do_map_enable_count_breakpoint, &count);
14925 }
14926
14927 static void
14928 do_map_enable_delete_breakpoint (struct breakpoint *bpt, void *ignore)
14929 {
14930   struct disp_data disp = { disp_del, 1 };
14931
14932   iterate_over_related_breakpoints (bpt, do_enable_breakpoint_disp, &disp);
14933 }
14934
14935 static void
14936 enable_delete_command (char *args, int from_tty)
14937 {
14938   map_breakpoint_numbers (args, do_map_enable_delete_breakpoint, NULL);
14939 }
14940 \f
14941 static void
14942 set_breakpoint_cmd (char *args, int from_tty)
14943 {
14944 }
14945
14946 static void
14947 show_breakpoint_cmd (char *args, int from_tty)
14948 {
14949 }
14950
14951 /* Invalidate last known value of any hardware watchpoint if
14952    the memory which that value represents has been written to by
14953    GDB itself.  */
14954
14955 static void
14956 invalidate_bp_value_on_memory_change (struct inferior *inferior,
14957                                       CORE_ADDR addr, ssize_t len,
14958                                       const bfd_byte *data)
14959 {
14960   struct breakpoint *bp;
14961
14962   ALL_BREAKPOINTS (bp)
14963     if (bp->enable_state == bp_enabled
14964         && bp->type == bp_hardware_watchpoint)
14965       {
14966         struct watchpoint *wp = (struct watchpoint *) bp;
14967
14968         if (wp->val_valid && wp->val)
14969           {
14970             struct bp_location *loc;
14971
14972             for (loc = bp->loc; loc != NULL; loc = loc->next)
14973               if (loc->loc_type == bp_loc_hardware_watchpoint
14974                   && loc->address + loc->length > addr
14975                   && addr + len > loc->address)
14976                 {
14977                   value_free (wp->val);
14978                   wp->val = NULL;
14979                   wp->val_valid = 0;
14980                 }
14981           }
14982       }
14983 }
14984
14985 /* Create and insert a raw software breakpoint at PC.  Return an
14986    identifier, which should be used to remove the breakpoint later.
14987    In general, places which call this should be using something on the
14988    breakpoint chain instead; this function should be eliminated
14989    someday.  */
14990
14991 void *
14992 deprecated_insert_raw_breakpoint (struct gdbarch *gdbarch,
14993                                   struct address_space *aspace, CORE_ADDR pc)
14994 {
14995   struct bp_target_info *bp_tgt;
14996
14997   bp_tgt = XCNEW (struct bp_target_info);
14998
14999   bp_tgt->placed_address_space = aspace;
15000   bp_tgt->placed_address = pc;
15001
15002   if (target_insert_breakpoint (gdbarch, bp_tgt) != 0)
15003     {
15004       /* Could not insert the breakpoint.  */
15005       xfree (bp_tgt);
15006       return NULL;
15007     }
15008
15009   return bp_tgt;
15010 }
15011
15012 /* Remove a breakpoint BP inserted by
15013    deprecated_insert_raw_breakpoint.  */
15014
15015 int
15016 deprecated_remove_raw_breakpoint (struct gdbarch *gdbarch, void *bp)
15017 {
15018   struct bp_target_info *bp_tgt = bp;
15019   int ret;
15020
15021   ret = target_remove_breakpoint (gdbarch, bp_tgt);
15022   xfree (bp_tgt);
15023
15024   return ret;
15025 }
15026
15027 /* One (or perhaps two) breakpoints used for software single
15028    stepping.  */
15029
15030 static void *single_step_breakpoints[2];
15031 static struct gdbarch *single_step_gdbarch[2];
15032
15033 /* Create and insert a breakpoint for software single step.  */
15034
15035 void
15036 insert_single_step_breakpoint (struct gdbarch *gdbarch,
15037                                struct address_space *aspace, 
15038                                CORE_ADDR next_pc)
15039 {
15040   void **bpt_p;
15041
15042   if (single_step_breakpoints[0] == NULL)
15043     {
15044       bpt_p = &single_step_breakpoints[0];
15045       single_step_gdbarch[0] = gdbarch;
15046     }
15047   else
15048     {
15049       gdb_assert (single_step_breakpoints[1] == NULL);
15050       bpt_p = &single_step_breakpoints[1];
15051       single_step_gdbarch[1] = gdbarch;
15052     }
15053
15054   /* NOTE drow/2006-04-11: A future improvement to this function would
15055      be to only create the breakpoints once, and actually put them on
15056      the breakpoint chain.  That would let us use set_raw_breakpoint.
15057      We could adjust the addresses each time they were needed.  Doing
15058      this requires corresponding changes elsewhere where single step
15059      breakpoints are handled, however.  So, for now, we use this.  */
15060
15061   *bpt_p = deprecated_insert_raw_breakpoint (gdbarch, aspace, next_pc);
15062   if (*bpt_p == NULL)
15063     error (_("Could not insert single-step breakpoint at %s"),
15064              paddress (gdbarch, next_pc));
15065 }
15066
15067 /* Check if the breakpoints used for software single stepping
15068    were inserted or not.  */
15069
15070 int
15071 single_step_breakpoints_inserted (void)
15072 {
15073   return (single_step_breakpoints[0] != NULL
15074           || single_step_breakpoints[1] != NULL);
15075 }
15076
15077 /* Remove and delete any breakpoints used for software single step.  */
15078
15079 void
15080 remove_single_step_breakpoints (void)
15081 {
15082   gdb_assert (single_step_breakpoints[0] != NULL);
15083
15084   /* See insert_single_step_breakpoint for more about this deprecated
15085      call.  */
15086   deprecated_remove_raw_breakpoint (single_step_gdbarch[0],
15087                                     single_step_breakpoints[0]);
15088   single_step_gdbarch[0] = NULL;
15089   single_step_breakpoints[0] = NULL;
15090
15091   if (single_step_breakpoints[1] != NULL)
15092     {
15093       deprecated_remove_raw_breakpoint (single_step_gdbarch[1],
15094                                         single_step_breakpoints[1]);
15095       single_step_gdbarch[1] = NULL;
15096       single_step_breakpoints[1] = NULL;
15097     }
15098 }
15099
15100 /* Delete software single step breakpoints without removing them from
15101    the inferior.  This is intended to be used if the inferior's address
15102    space where they were inserted is already gone, e.g. after exit or
15103    exec.  */
15104
15105 void
15106 cancel_single_step_breakpoints (void)
15107 {
15108   int i;
15109
15110   for (i = 0; i < 2; i++)
15111     if (single_step_breakpoints[i])
15112       {
15113         xfree (single_step_breakpoints[i]);
15114         single_step_breakpoints[i] = NULL;
15115         single_step_gdbarch[i] = NULL;
15116       }
15117 }
15118
15119 /* Detach software single-step breakpoints from INFERIOR_PTID without
15120    removing them.  */
15121
15122 static void
15123 detach_single_step_breakpoints (void)
15124 {
15125   int i;
15126
15127   for (i = 0; i < 2; i++)
15128     if (single_step_breakpoints[i])
15129       target_remove_breakpoint (single_step_gdbarch[i],
15130                                 single_step_breakpoints[i]);
15131 }
15132
15133 /* Check whether a software single-step breakpoint is inserted at
15134    PC.  */
15135
15136 static int
15137 single_step_breakpoint_inserted_here_p (struct address_space *aspace, 
15138                                         CORE_ADDR pc)
15139 {
15140   int i;
15141
15142   for (i = 0; i < 2; i++)
15143     {
15144       struct bp_target_info *bp_tgt = single_step_breakpoints[i];
15145       if (bp_tgt
15146           && breakpoint_address_match (bp_tgt->placed_address_space,
15147                                        bp_tgt->placed_address,
15148                                        aspace, pc))
15149         return 1;
15150     }
15151
15152   return 0;
15153 }
15154
15155 /* Returns 0 if 'bp' is NOT a syscall catchpoint,
15156    non-zero otherwise.  */
15157 static int
15158 is_syscall_catchpoint_enabled (struct breakpoint *bp)
15159 {
15160   if (syscall_catchpoint_p (bp)
15161       && bp->enable_state != bp_disabled
15162       && bp->enable_state != bp_call_disabled)
15163     return 1;
15164   else
15165     return 0;
15166 }
15167
15168 int
15169 catch_syscall_enabled (void)
15170 {
15171   struct catch_syscall_inferior_data *inf_data
15172     = get_catch_syscall_inferior_data (current_inferior ());
15173
15174   return inf_data->total_syscalls_count != 0;
15175 }
15176
15177 int
15178 catching_syscall_number (int syscall_number)
15179 {
15180   struct breakpoint *bp;
15181
15182   ALL_BREAKPOINTS (bp)
15183     if (is_syscall_catchpoint_enabled (bp))
15184       {
15185         struct syscall_catchpoint *c = (struct syscall_catchpoint *) bp;
15186
15187         if (c->syscalls_to_be_caught)
15188           {
15189             int i, iter;
15190             for (i = 0;
15191                  VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
15192                  i++)
15193               if (syscall_number == iter)
15194                 return 1;
15195           }
15196         else
15197           return 1;
15198       }
15199
15200   return 0;
15201 }
15202
15203 /* Complete syscall names.  Used by "catch syscall".  */
15204 static VEC (char_ptr) *
15205 catch_syscall_completer (struct cmd_list_element *cmd,
15206                          const char *text, const char *word)
15207 {
15208   const char **list = get_syscall_names ();
15209   VEC (char_ptr) *retlist
15210     = (list == NULL) ? NULL : complete_on_enum (list, word, word);
15211
15212   xfree (list);
15213   return retlist;
15214 }
15215
15216 /* Tracepoint-specific operations.  */
15217
15218 /* Set tracepoint count to NUM.  */
15219 static void
15220 set_tracepoint_count (int num)
15221 {
15222   tracepoint_count = num;
15223   set_internalvar_integer (lookup_internalvar ("tpnum"), num);
15224 }
15225
15226 static void
15227 trace_command (char *arg, int from_tty)
15228 {
15229   struct breakpoint_ops *ops;
15230   const char *arg_cp = arg;
15231
15232   if (arg && probe_linespec_to_ops (&arg_cp))
15233     ops = &tracepoint_probe_breakpoint_ops;
15234   else
15235     ops = &tracepoint_breakpoint_ops;
15236
15237   create_breakpoint (get_current_arch (),
15238                      arg,
15239                      NULL, 0, NULL, 1 /* parse arg */,
15240                      0 /* tempflag */,
15241                      bp_tracepoint /* type_wanted */,
15242                      0 /* Ignore count */,
15243                      pending_break_support,
15244                      ops,
15245                      from_tty,
15246                      1 /* enabled */,
15247                      0 /* internal */, 0);
15248 }
15249
15250 static void
15251 ftrace_command (char *arg, int from_tty)
15252 {
15253   create_breakpoint (get_current_arch (),
15254                      arg,
15255                      NULL, 0, NULL, 1 /* parse arg */,
15256                      0 /* tempflag */,
15257                      bp_fast_tracepoint /* type_wanted */,
15258                      0 /* Ignore count */,
15259                      pending_break_support,
15260                      &tracepoint_breakpoint_ops,
15261                      from_tty,
15262                      1 /* enabled */,
15263                      0 /* internal */, 0);
15264 }
15265
15266 /* strace command implementation.  Creates a static tracepoint.  */
15267
15268 static void
15269 strace_command (char *arg, int from_tty)
15270 {
15271   struct breakpoint_ops *ops;
15272
15273   /* Decide if we are dealing with a static tracepoint marker (`-m'),
15274      or with a normal static tracepoint.  */
15275   if (arg && strncmp (arg, "-m", 2) == 0 && isspace (arg[2]))
15276     ops = &strace_marker_breakpoint_ops;
15277   else
15278     ops = &tracepoint_breakpoint_ops;
15279
15280   create_breakpoint (get_current_arch (),
15281                      arg,
15282                      NULL, 0, NULL, 1 /* parse arg */,
15283                      0 /* tempflag */,
15284                      bp_static_tracepoint /* type_wanted */,
15285                      0 /* Ignore count */,
15286                      pending_break_support,
15287                      ops,
15288                      from_tty,
15289                      1 /* enabled */,
15290                      0 /* internal */, 0);
15291 }
15292
15293 /* Set up a fake reader function that gets command lines from a linked
15294    list that was acquired during tracepoint uploading.  */
15295
15296 static struct uploaded_tp *this_utp;
15297 static int next_cmd;
15298
15299 static char *
15300 read_uploaded_action (void)
15301 {
15302   char *rslt;
15303
15304   VEC_iterate (char_ptr, this_utp->cmd_strings, next_cmd, rslt);
15305
15306   next_cmd++;
15307
15308   return rslt;
15309 }
15310
15311 /* Given information about a tracepoint as recorded on a target (which
15312    can be either a live system or a trace file), attempt to create an
15313    equivalent GDB tracepoint.  This is not a reliable process, since
15314    the target does not necessarily have all the information used when
15315    the tracepoint was originally defined.  */
15316   
15317 struct tracepoint *
15318 create_tracepoint_from_upload (struct uploaded_tp *utp)
15319 {
15320   char *addr_str, small_buf[100];
15321   struct tracepoint *tp;
15322
15323   if (utp->at_string)
15324     addr_str = utp->at_string;
15325   else
15326     {
15327       /* In the absence of a source location, fall back to raw
15328          address.  Since there is no way to confirm that the address
15329          means the same thing as when the trace was started, warn the
15330          user.  */
15331       warning (_("Uploaded tracepoint %d has no "
15332                  "source location, using raw address"),
15333                utp->number);
15334       xsnprintf (small_buf, sizeof (small_buf), "*%s", hex_string (utp->addr));
15335       addr_str = small_buf;
15336     }
15337
15338   /* There's not much we can do with a sequence of bytecodes.  */
15339   if (utp->cond && !utp->cond_string)
15340     warning (_("Uploaded tracepoint %d condition "
15341                "has no source form, ignoring it"),
15342              utp->number);
15343
15344   if (!create_breakpoint (get_current_arch (),
15345                           addr_str,
15346                           utp->cond_string, -1, NULL,
15347                           0 /* parse cond/thread */,
15348                           0 /* tempflag */,
15349                           utp->type /* type_wanted */,
15350                           0 /* Ignore count */,
15351                           pending_break_support,
15352                           &tracepoint_breakpoint_ops,
15353                           0 /* from_tty */,
15354                           utp->enabled /* enabled */,
15355                           0 /* internal */,
15356                           CREATE_BREAKPOINT_FLAGS_INSERTED))
15357     return NULL;
15358
15359   /* Get the tracepoint we just created.  */
15360   tp = get_tracepoint (tracepoint_count);
15361   gdb_assert (tp != NULL);
15362
15363   if (utp->pass > 0)
15364     {
15365       xsnprintf (small_buf, sizeof (small_buf), "%d %d", utp->pass,
15366                  tp->base.number);
15367
15368       trace_pass_command (small_buf, 0);
15369     }
15370
15371   /* If we have uploaded versions of the original commands, set up a
15372      special-purpose "reader" function and call the usual command line
15373      reader, then pass the result to the breakpoint command-setting
15374      function.  */
15375   if (!VEC_empty (char_ptr, utp->cmd_strings))
15376     {
15377       struct command_line *cmd_list;
15378
15379       this_utp = utp;
15380       next_cmd = 0;
15381
15382       cmd_list = read_command_lines_1 (read_uploaded_action, 1, NULL, NULL);
15383
15384       breakpoint_set_commands (&tp->base, cmd_list);
15385     }
15386   else if (!VEC_empty (char_ptr, utp->actions)
15387            || !VEC_empty (char_ptr, utp->step_actions))
15388     warning (_("Uploaded tracepoint %d actions "
15389                "have no source form, ignoring them"),
15390              utp->number);
15391
15392   /* Copy any status information that might be available.  */
15393   tp->base.hit_count = utp->hit_count;
15394   tp->traceframe_usage = utp->traceframe_usage;
15395
15396   return tp;
15397 }
15398   
15399 /* Print information on tracepoint number TPNUM_EXP, or all if
15400    omitted.  */
15401
15402 static void
15403 tracepoints_info (char *args, int from_tty)
15404 {
15405   struct ui_out *uiout = current_uiout;
15406   int num_printed;
15407
15408   num_printed = breakpoint_1 (args, 0, is_tracepoint);
15409
15410   if (num_printed == 0)
15411     {
15412       if (args == NULL || *args == '\0')
15413         ui_out_message (uiout, 0, "No tracepoints.\n");
15414       else
15415         ui_out_message (uiout, 0, "No tracepoint matching '%s'.\n", args);
15416     }
15417
15418   default_collect_info ();
15419 }
15420
15421 /* The 'enable trace' command enables tracepoints.
15422    Not supported by all targets.  */
15423 static void
15424 enable_trace_command (char *args, int from_tty)
15425 {
15426   enable_command (args, from_tty);
15427 }
15428
15429 /* The 'disable trace' command disables tracepoints.
15430    Not supported by all targets.  */
15431 static void
15432 disable_trace_command (char *args, int from_tty)
15433 {
15434   disable_command (args, from_tty);
15435 }
15436
15437 /* Remove a tracepoint (or all if no argument).  */
15438 static void
15439 delete_trace_command (char *arg, int from_tty)
15440 {
15441   struct breakpoint *b, *b_tmp;
15442
15443   dont_repeat ();
15444
15445   if (arg == 0)
15446     {
15447       int breaks_to_delete = 0;
15448
15449       /* Delete all breakpoints if no argument.
15450          Do not delete internal or call-dummy breakpoints, these
15451          have to be deleted with an explicit breakpoint number 
15452          argument.  */
15453       ALL_TRACEPOINTS (b)
15454         if (is_tracepoint (b) && user_breakpoint_p (b))
15455           {
15456             breaks_to_delete = 1;
15457             break;
15458           }
15459
15460       /* Ask user only if there are some breakpoints to delete.  */
15461       if (!from_tty
15462           || (breaks_to_delete && query (_("Delete all tracepoints? "))))
15463         {
15464           ALL_BREAKPOINTS_SAFE (b, b_tmp)
15465             if (is_tracepoint (b) && user_breakpoint_p (b))
15466               delete_breakpoint (b);
15467         }
15468     }
15469   else
15470     map_breakpoint_numbers (arg, do_map_delete_breakpoint, NULL);
15471 }
15472
15473 /* Helper function for trace_pass_command.  */
15474
15475 static void
15476 trace_pass_set_count (struct tracepoint *tp, int count, int from_tty)
15477 {
15478   tp->pass_count = count;
15479   observer_notify_breakpoint_modified (&tp->base);
15480   if (from_tty)
15481     printf_filtered (_("Setting tracepoint %d's passcount to %d\n"),
15482                      tp->base.number, count);
15483 }
15484
15485 /* Set passcount for tracepoint.
15486
15487    First command argument is passcount, second is tracepoint number.
15488    If tracepoint number omitted, apply to most recently defined.
15489    Also accepts special argument "all".  */
15490
15491 static void
15492 trace_pass_command (char *args, int from_tty)
15493 {
15494   struct tracepoint *t1;
15495   unsigned int count;
15496
15497   if (args == 0 || *args == 0)
15498     error (_("passcount command requires an "
15499              "argument (count + optional TP num)"));
15500
15501   count = strtoul (args, &args, 10);    /* Count comes first, then TP num.  */
15502
15503   args = skip_spaces (args);
15504   if (*args && strncasecmp (args, "all", 3) == 0)
15505     {
15506       struct breakpoint *b;
15507
15508       args += 3;                        /* Skip special argument "all".  */
15509       if (*args)
15510         error (_("Junk at end of arguments."));
15511
15512       ALL_TRACEPOINTS (b)
15513       {
15514         t1 = (struct tracepoint *) b;
15515         trace_pass_set_count (t1, count, from_tty);
15516       }
15517     }
15518   else if (*args == '\0')
15519     {
15520       t1 = get_tracepoint_by_number (&args, NULL, 1);
15521       if (t1)
15522         trace_pass_set_count (t1, count, from_tty);
15523     }
15524   else
15525     {
15526       struct get_number_or_range_state state;
15527
15528       init_number_or_range (&state, args);
15529       while (!state.finished)
15530         {
15531           t1 = get_tracepoint_by_number (&args, &state, 1);
15532           if (t1)
15533             trace_pass_set_count (t1, count, from_tty);
15534         }
15535     }
15536 }
15537
15538 struct tracepoint *
15539 get_tracepoint (int num)
15540 {
15541   struct breakpoint *t;
15542
15543   ALL_TRACEPOINTS (t)
15544     if (t->number == num)
15545       return (struct tracepoint *) t;
15546
15547   return NULL;
15548 }
15549
15550 /* Find the tracepoint with the given target-side number (which may be
15551    different from the tracepoint number after disconnecting and
15552    reconnecting).  */
15553
15554 struct tracepoint *
15555 get_tracepoint_by_number_on_target (int num)
15556 {
15557   struct breakpoint *b;
15558
15559   ALL_TRACEPOINTS (b)
15560     {
15561       struct tracepoint *t = (struct tracepoint *) b;
15562
15563       if (t->number_on_target == num)
15564         return t;
15565     }
15566
15567   return NULL;
15568 }
15569
15570 /* Utility: parse a tracepoint number and look it up in the list.
15571    If STATE is not NULL, use, get_number_or_range_state and ignore ARG.
15572    If OPTIONAL_P is true, then if the argument is missing, the most
15573    recent tracepoint (tracepoint_count) is returned.  */
15574 struct tracepoint *
15575 get_tracepoint_by_number (char **arg,
15576                           struct get_number_or_range_state *state,
15577                           int optional_p)
15578 {
15579   struct breakpoint *t;
15580   int tpnum;
15581   char *instring = arg == NULL ? NULL : *arg;
15582
15583   if (state)
15584     {
15585       gdb_assert (!state->finished);
15586       tpnum = get_number_or_range (state);
15587     }
15588   else if (arg == NULL || *arg == NULL || ! **arg)
15589     {
15590       if (optional_p)
15591         tpnum = tracepoint_count;
15592       else
15593         error_no_arg (_("tracepoint number"));
15594     }
15595   else
15596     tpnum = get_number (arg);
15597
15598   if (tpnum <= 0)
15599     {
15600       if (instring && *instring)
15601         printf_filtered (_("bad tracepoint number at or near '%s'\n"), 
15602                          instring);
15603       else
15604         printf_filtered (_("Tracepoint argument missing "
15605                            "and no previous tracepoint\n"));
15606       return NULL;
15607     }
15608
15609   ALL_TRACEPOINTS (t)
15610     if (t->number == tpnum)
15611     {
15612       return (struct tracepoint *) t;
15613     }
15614
15615   printf_unfiltered ("No tracepoint number %d.\n", tpnum);
15616   return NULL;
15617 }
15618
15619 void
15620 print_recreate_thread (struct breakpoint *b, struct ui_file *fp)
15621 {
15622   if (b->thread != -1)
15623     fprintf_unfiltered (fp, " thread %d", b->thread);
15624
15625   if (b->task != 0)
15626     fprintf_unfiltered (fp, " task %d", b->task);
15627
15628   fprintf_unfiltered (fp, "\n");
15629 }
15630
15631 /* Save information on user settable breakpoints (watchpoints, etc) to
15632    a new script file named FILENAME.  If FILTER is non-NULL, call it
15633    on each breakpoint and only include the ones for which it returns
15634    non-zero.  */
15635
15636 static void
15637 save_breakpoints (char *filename, int from_tty,
15638                   int (*filter) (const struct breakpoint *))
15639 {
15640   struct breakpoint *tp;
15641   int any = 0;
15642   struct cleanup *cleanup;
15643   struct ui_file *fp;
15644   int extra_trace_bits = 0;
15645
15646   if (filename == 0 || *filename == 0)
15647     error (_("Argument required (file name in which to save)"));
15648
15649   /* See if we have anything to save.  */
15650   ALL_BREAKPOINTS (tp)
15651   {
15652     /* Skip internal and momentary breakpoints.  */
15653     if (!user_breakpoint_p (tp))
15654       continue;
15655
15656     /* If we have a filter, only save the breakpoints it accepts.  */
15657     if (filter && !filter (tp))
15658       continue;
15659
15660     any = 1;
15661
15662     if (is_tracepoint (tp))
15663       {
15664         extra_trace_bits = 1;
15665
15666         /* We can stop searching.  */
15667         break;
15668       }
15669   }
15670
15671   if (!any)
15672     {
15673       warning (_("Nothing to save."));
15674       return;
15675     }
15676
15677   filename = tilde_expand (filename);
15678   cleanup = make_cleanup (xfree, filename);
15679   fp = gdb_fopen (filename, "w");
15680   if (!fp)
15681     error (_("Unable to open file '%s' for saving (%s)"),
15682            filename, safe_strerror (errno));
15683   make_cleanup_ui_file_delete (fp);
15684
15685   if (extra_trace_bits)
15686     save_trace_state_variables (fp);
15687
15688   ALL_BREAKPOINTS (tp)
15689   {
15690     /* Skip internal and momentary breakpoints.  */
15691     if (!user_breakpoint_p (tp))
15692       continue;
15693
15694     /* If we have a filter, only save the breakpoints it accepts.  */
15695     if (filter && !filter (tp))
15696       continue;
15697
15698     tp->ops->print_recreate (tp, fp);
15699
15700     /* Note, we can't rely on tp->number for anything, as we can't
15701        assume the recreated breakpoint numbers will match.  Use $bpnum
15702        instead.  */
15703
15704     if (tp->cond_string)
15705       fprintf_unfiltered (fp, "  condition $bpnum %s\n", tp->cond_string);
15706
15707     if (tp->ignore_count)
15708       fprintf_unfiltered (fp, "  ignore $bpnum %d\n", tp->ignore_count);
15709
15710     if (tp->type != bp_dprintf && tp->commands)
15711       {
15712         volatile struct gdb_exception ex;       
15713
15714         fprintf_unfiltered (fp, "  commands\n");
15715         
15716         ui_out_redirect (current_uiout, fp);
15717         TRY_CATCH (ex, RETURN_MASK_ALL)
15718           {
15719             print_command_lines (current_uiout, tp->commands->commands, 2);
15720           }
15721         ui_out_redirect (current_uiout, NULL);
15722
15723         if (ex.reason < 0)
15724           throw_exception (ex);
15725
15726         fprintf_unfiltered (fp, "  end\n");
15727       }
15728
15729     if (tp->enable_state == bp_disabled)
15730       fprintf_unfiltered (fp, "disable\n");
15731
15732     /* If this is a multi-location breakpoint, check if the locations
15733        should be individually disabled.  Watchpoint locations are
15734        special, and not user visible.  */
15735     if (!is_watchpoint (tp) && tp->loc && tp->loc->next)
15736       {
15737         struct bp_location *loc;
15738         int n = 1;
15739
15740         for (loc = tp->loc; loc != NULL; loc = loc->next, n++)
15741           if (!loc->enabled)
15742             fprintf_unfiltered (fp, "disable $bpnum.%d\n", n);
15743       }
15744   }
15745
15746   if (extra_trace_bits && *default_collect)
15747     fprintf_unfiltered (fp, "set default-collect %s\n", default_collect);
15748
15749   if (from_tty)
15750     printf_filtered (_("Saved to file '%s'.\n"), filename);
15751   do_cleanups (cleanup);
15752 }
15753
15754 /* The `save breakpoints' command.  */
15755
15756 static void
15757 save_breakpoints_command (char *args, int from_tty)
15758 {
15759   save_breakpoints (args, from_tty, NULL);
15760 }
15761
15762 /* The `save tracepoints' command.  */
15763
15764 static void
15765 save_tracepoints_command (char *args, int from_tty)
15766 {
15767   save_breakpoints (args, from_tty, is_tracepoint);
15768 }
15769
15770 /* Create a vector of all tracepoints.  */
15771
15772 VEC(breakpoint_p) *
15773 all_tracepoints (void)
15774 {
15775   VEC(breakpoint_p) *tp_vec = 0;
15776   struct breakpoint *tp;
15777
15778   ALL_TRACEPOINTS (tp)
15779   {
15780     VEC_safe_push (breakpoint_p, tp_vec, tp);
15781   }
15782
15783   return tp_vec;
15784 }
15785
15786 \f
15787 /* This help string is used for the break, hbreak, tbreak and thbreak
15788    commands.  It is defined as a macro to prevent duplication.
15789    COMMAND should be a string constant containing the name of the
15790    command.  */
15791 #define BREAK_ARGS_HELP(command) \
15792 command" [PROBE_MODIFIER] [LOCATION] [thread THREADNUM] [if CONDITION]\n\
15793 PROBE_MODIFIER shall be present if the command is to be placed in a\n\
15794 probe point.  Accepted values are `-probe' (for a generic, automatically\n\
15795 guessed probe type) or `-probe-stap' (for a SystemTap probe).\n\
15796 LOCATION may be a line number, function name, or \"*\" and an address.\n\
15797 If a line number is specified, break at start of code for that line.\n\
15798 If a function is specified, break at start of code for that function.\n\
15799 If an address is specified, break at that exact address.\n\
15800 With no LOCATION, uses current execution address of the selected\n\
15801 stack frame.  This is useful for breaking on return to a stack frame.\n\
15802 \n\
15803 THREADNUM is the number from \"info threads\".\n\
15804 CONDITION is a boolean expression.\n\
15805 \n\
15806 Multiple breakpoints at one place are permitted, and useful if their\n\
15807 conditions are different.\n\
15808 \n\
15809 Do \"help breakpoints\" for info on other commands dealing with breakpoints."
15810
15811 /* List of subcommands for "catch".  */
15812 static struct cmd_list_element *catch_cmdlist;
15813
15814 /* List of subcommands for "tcatch".  */
15815 static struct cmd_list_element *tcatch_cmdlist;
15816
15817 void
15818 add_catch_command (char *name, char *docstring,
15819                    void (*sfunc) (char *args, int from_tty,
15820                                   struct cmd_list_element *command),
15821                    completer_ftype *completer,
15822                    void *user_data_catch,
15823                    void *user_data_tcatch)
15824 {
15825   struct cmd_list_element *command;
15826
15827   command = add_cmd (name, class_breakpoint, NULL, docstring,
15828                      &catch_cmdlist);
15829   set_cmd_sfunc (command, sfunc);
15830   set_cmd_context (command, user_data_catch);
15831   set_cmd_completer (command, completer);
15832
15833   command = add_cmd (name, class_breakpoint, NULL, docstring,
15834                      &tcatch_cmdlist);
15835   set_cmd_sfunc (command, sfunc);
15836   set_cmd_context (command, user_data_tcatch);
15837   set_cmd_completer (command, completer);
15838 }
15839
15840 static void
15841 clear_syscall_counts (struct inferior *inf)
15842 {
15843   struct catch_syscall_inferior_data *inf_data
15844     = get_catch_syscall_inferior_data (inf);
15845
15846   inf_data->total_syscalls_count = 0;
15847   inf_data->any_syscall_count = 0;
15848   VEC_free (int, inf_data->syscalls_counts);
15849 }
15850
15851 static void
15852 save_command (char *arg, int from_tty)
15853 {
15854   printf_unfiltered (_("\"save\" must be followed by "
15855                        "the name of a save subcommand.\n"));
15856   help_list (save_cmdlist, "save ", -1, gdb_stdout);
15857 }
15858
15859 struct breakpoint *
15860 iterate_over_breakpoints (int (*callback) (struct breakpoint *, void *),
15861                           void *data)
15862 {
15863   struct breakpoint *b, *b_tmp;
15864
15865   ALL_BREAKPOINTS_SAFE (b, b_tmp)
15866     {
15867       if ((*callback) (b, data))
15868         return b;
15869     }
15870
15871   return NULL;
15872 }
15873
15874 /* Zero if any of the breakpoint's locations could be a location where
15875    functions have been inlined, nonzero otherwise.  */
15876
15877 static int
15878 is_non_inline_function (struct breakpoint *b)
15879 {
15880   /* The shared library event breakpoint is set on the address of a
15881      non-inline function.  */
15882   if (b->type == bp_shlib_event)
15883     return 1;
15884
15885   return 0;
15886 }
15887
15888 /* Nonzero if the specified PC cannot be a location where functions
15889    have been inlined.  */
15890
15891 int
15892 pc_at_non_inline_function (struct address_space *aspace, CORE_ADDR pc,
15893                            const struct target_waitstatus *ws)
15894 {
15895   struct breakpoint *b;
15896   struct bp_location *bl;
15897
15898   ALL_BREAKPOINTS (b)
15899     {
15900       if (!is_non_inline_function (b))
15901         continue;
15902
15903       for (bl = b->loc; bl != NULL; bl = bl->next)
15904         {
15905           if (!bl->shlib_disabled
15906               && bpstat_check_location (bl, aspace, pc, ws))
15907             return 1;
15908         }
15909     }
15910
15911   return 0;
15912 }
15913
15914 /* Remove any references to OBJFILE which is going to be freed.  */
15915
15916 void
15917 breakpoint_free_objfile (struct objfile *objfile)
15918 {
15919   struct bp_location **locp, *loc;
15920
15921   ALL_BP_LOCATIONS (loc, locp)
15922     if (loc->symtab != NULL && loc->symtab->objfile == objfile)
15923       loc->symtab = NULL;
15924 }
15925
15926 void
15927 initialize_breakpoint_ops (void)
15928 {
15929   static int initialized = 0;
15930
15931   struct breakpoint_ops *ops;
15932
15933   if (initialized)
15934     return;
15935   initialized = 1;
15936
15937   /* The breakpoint_ops structure to be inherit by all kinds of
15938      breakpoints (real breakpoints, i.e., user "break" breakpoints,
15939      internal and momentary breakpoints, etc.).  */
15940   ops = &bkpt_base_breakpoint_ops;
15941   *ops = base_breakpoint_ops;
15942   ops->re_set = bkpt_re_set;
15943   ops->insert_location = bkpt_insert_location;
15944   ops->remove_location = bkpt_remove_location;
15945   ops->breakpoint_hit = bkpt_breakpoint_hit;
15946   ops->create_sals_from_address = bkpt_create_sals_from_address;
15947   ops->create_breakpoints_sal = bkpt_create_breakpoints_sal;
15948   ops->decode_linespec = bkpt_decode_linespec;
15949
15950   /* The breakpoint_ops structure to be used in regular breakpoints.  */
15951   ops = &bkpt_breakpoint_ops;
15952   *ops = bkpt_base_breakpoint_ops;
15953   ops->re_set = bkpt_re_set;
15954   ops->resources_needed = bkpt_resources_needed;
15955   ops->print_it = bkpt_print_it;
15956   ops->print_mention = bkpt_print_mention;
15957   ops->print_recreate = bkpt_print_recreate;
15958
15959   /* Ranged breakpoints.  */
15960   ops = &ranged_breakpoint_ops;
15961   *ops = bkpt_breakpoint_ops;
15962   ops->breakpoint_hit = breakpoint_hit_ranged_breakpoint;
15963   ops->resources_needed = resources_needed_ranged_breakpoint;
15964   ops->print_it = print_it_ranged_breakpoint;
15965   ops->print_one = print_one_ranged_breakpoint;
15966   ops->print_one_detail = print_one_detail_ranged_breakpoint;
15967   ops->print_mention = print_mention_ranged_breakpoint;
15968   ops->print_recreate = print_recreate_ranged_breakpoint;
15969
15970   /* Internal breakpoints.  */
15971   ops = &internal_breakpoint_ops;
15972   *ops = bkpt_base_breakpoint_ops;
15973   ops->re_set = internal_bkpt_re_set;
15974   ops->check_status = internal_bkpt_check_status;
15975   ops->print_it = internal_bkpt_print_it;
15976   ops->print_mention = internal_bkpt_print_mention;
15977
15978   /* Momentary breakpoints.  */
15979   ops = &momentary_breakpoint_ops;
15980   *ops = bkpt_base_breakpoint_ops;
15981   ops->re_set = momentary_bkpt_re_set;
15982   ops->check_status = momentary_bkpt_check_status;
15983   ops->print_it = momentary_bkpt_print_it;
15984   ops->print_mention = momentary_bkpt_print_mention;
15985
15986   /* Momentary breakpoints for bp_longjmp and bp_exception.  */
15987   ops = &longjmp_breakpoint_ops;
15988   *ops = momentary_breakpoint_ops;
15989   ops->dtor = longjmp_bkpt_dtor;
15990
15991   /* Probe breakpoints.  */
15992   ops = &bkpt_probe_breakpoint_ops;
15993   *ops = bkpt_breakpoint_ops;
15994   ops->insert_location = bkpt_probe_insert_location;
15995   ops->remove_location = bkpt_probe_remove_location;
15996   ops->create_sals_from_address = bkpt_probe_create_sals_from_address;
15997   ops->decode_linespec = bkpt_probe_decode_linespec;
15998
15999   /* Watchpoints.  */
16000   ops = &watchpoint_breakpoint_ops;
16001   *ops = base_breakpoint_ops;
16002   ops->dtor = dtor_watchpoint;
16003   ops->re_set = re_set_watchpoint;
16004   ops->insert_location = insert_watchpoint;
16005   ops->remove_location = remove_watchpoint;
16006   ops->breakpoint_hit = breakpoint_hit_watchpoint;
16007   ops->check_status = check_status_watchpoint;
16008   ops->resources_needed = resources_needed_watchpoint;
16009   ops->works_in_software_mode = works_in_software_mode_watchpoint;
16010   ops->print_it = print_it_watchpoint;
16011   ops->print_mention = print_mention_watchpoint;
16012   ops->print_recreate = print_recreate_watchpoint;
16013   ops->explains_signal = explains_signal_watchpoint;
16014
16015   /* Masked watchpoints.  */
16016   ops = &masked_watchpoint_breakpoint_ops;
16017   *ops = watchpoint_breakpoint_ops;
16018   ops->insert_location = insert_masked_watchpoint;
16019   ops->remove_location = remove_masked_watchpoint;
16020   ops->resources_needed = resources_needed_masked_watchpoint;
16021   ops->works_in_software_mode = works_in_software_mode_masked_watchpoint;
16022   ops->print_it = print_it_masked_watchpoint;
16023   ops->print_one_detail = print_one_detail_masked_watchpoint;
16024   ops->print_mention = print_mention_masked_watchpoint;
16025   ops->print_recreate = print_recreate_masked_watchpoint;
16026
16027   /* Tracepoints.  */
16028   ops = &tracepoint_breakpoint_ops;
16029   *ops = base_breakpoint_ops;
16030   ops->re_set = tracepoint_re_set;
16031   ops->breakpoint_hit = tracepoint_breakpoint_hit;
16032   ops->print_one_detail = tracepoint_print_one_detail;
16033   ops->print_mention = tracepoint_print_mention;
16034   ops->print_recreate = tracepoint_print_recreate;
16035   ops->create_sals_from_address = tracepoint_create_sals_from_address;
16036   ops->create_breakpoints_sal = tracepoint_create_breakpoints_sal;
16037   ops->decode_linespec = tracepoint_decode_linespec;
16038
16039   /* Probe tracepoints.  */
16040   ops = &tracepoint_probe_breakpoint_ops;
16041   *ops = tracepoint_breakpoint_ops;
16042   ops->create_sals_from_address = tracepoint_probe_create_sals_from_address;
16043   ops->decode_linespec = tracepoint_probe_decode_linespec;
16044
16045   /* Static tracepoints with marker (`-m').  */
16046   ops = &strace_marker_breakpoint_ops;
16047   *ops = tracepoint_breakpoint_ops;
16048   ops->create_sals_from_address = strace_marker_create_sals_from_address;
16049   ops->create_breakpoints_sal = strace_marker_create_breakpoints_sal;
16050   ops->decode_linespec = strace_marker_decode_linespec;
16051
16052   /* Fork catchpoints.  */
16053   ops = &catch_fork_breakpoint_ops;
16054   *ops = base_breakpoint_ops;
16055   ops->insert_location = insert_catch_fork;
16056   ops->remove_location = remove_catch_fork;
16057   ops->breakpoint_hit = breakpoint_hit_catch_fork;
16058   ops->print_it = print_it_catch_fork;
16059   ops->print_one = print_one_catch_fork;
16060   ops->print_mention = print_mention_catch_fork;
16061   ops->print_recreate = print_recreate_catch_fork;
16062
16063   /* Vfork catchpoints.  */
16064   ops = &catch_vfork_breakpoint_ops;
16065   *ops = base_breakpoint_ops;
16066   ops->insert_location = insert_catch_vfork;
16067   ops->remove_location = remove_catch_vfork;
16068   ops->breakpoint_hit = breakpoint_hit_catch_vfork;
16069   ops->print_it = print_it_catch_vfork;
16070   ops->print_one = print_one_catch_vfork;
16071   ops->print_mention = print_mention_catch_vfork;
16072   ops->print_recreate = print_recreate_catch_vfork;
16073
16074   /* Exec catchpoints.  */
16075   ops = &catch_exec_breakpoint_ops;
16076   *ops = base_breakpoint_ops;
16077   ops->dtor = dtor_catch_exec;
16078   ops->insert_location = insert_catch_exec;
16079   ops->remove_location = remove_catch_exec;
16080   ops->breakpoint_hit = breakpoint_hit_catch_exec;
16081   ops->print_it = print_it_catch_exec;
16082   ops->print_one = print_one_catch_exec;
16083   ops->print_mention = print_mention_catch_exec;
16084   ops->print_recreate = print_recreate_catch_exec;
16085
16086   /* Syscall catchpoints.  */
16087   ops = &catch_syscall_breakpoint_ops;
16088   *ops = base_breakpoint_ops;
16089   ops->dtor = dtor_catch_syscall;
16090   ops->insert_location = insert_catch_syscall;
16091   ops->remove_location = remove_catch_syscall;
16092   ops->breakpoint_hit = breakpoint_hit_catch_syscall;
16093   ops->print_it = print_it_catch_syscall;
16094   ops->print_one = print_one_catch_syscall;
16095   ops->print_mention = print_mention_catch_syscall;
16096   ops->print_recreate = print_recreate_catch_syscall;
16097
16098   /* Solib-related catchpoints.  */
16099   ops = &catch_solib_breakpoint_ops;
16100   *ops = base_breakpoint_ops;
16101   ops->dtor = dtor_catch_solib;
16102   ops->insert_location = insert_catch_solib;
16103   ops->remove_location = remove_catch_solib;
16104   ops->breakpoint_hit = breakpoint_hit_catch_solib;
16105   ops->check_status = check_status_catch_solib;
16106   ops->print_it = print_it_catch_solib;
16107   ops->print_one = print_one_catch_solib;
16108   ops->print_mention = print_mention_catch_solib;
16109   ops->print_recreate = print_recreate_catch_solib;
16110
16111   ops = &dprintf_breakpoint_ops;
16112   *ops = bkpt_base_breakpoint_ops;
16113   ops->re_set = dprintf_re_set;
16114   ops->resources_needed = bkpt_resources_needed;
16115   ops->print_it = bkpt_print_it;
16116   ops->print_mention = bkpt_print_mention;
16117   ops->print_recreate = dprintf_print_recreate;
16118   ops->after_condition_true = dprintf_after_condition_true;
16119 }
16120
16121 /* Chain containing all defined "enable breakpoint" subcommands.  */
16122
16123 static struct cmd_list_element *enablebreaklist = NULL;
16124
16125 void
16126 _initialize_breakpoint (void)
16127 {
16128   struct cmd_list_element *c;
16129
16130   initialize_breakpoint_ops ();
16131
16132   observer_attach_solib_unloaded (disable_breakpoints_in_unloaded_shlib);
16133   observer_attach_free_objfile (disable_breakpoints_in_freed_objfile);
16134   observer_attach_inferior_exit (clear_syscall_counts);
16135   observer_attach_memory_changed (invalidate_bp_value_on_memory_change);
16136
16137   breakpoint_objfile_key
16138     = register_objfile_data_with_cleanup (NULL, free_breakpoint_probes);
16139
16140   catch_syscall_inferior_data
16141     = register_inferior_data_with_cleanup (NULL,
16142                                            catch_syscall_inferior_data_cleanup);
16143
16144   breakpoint_chain = 0;
16145   /* Don't bother to call set_breakpoint_count.  $bpnum isn't useful
16146      before a breakpoint is set.  */
16147   breakpoint_count = 0;
16148
16149   tracepoint_count = 0;
16150
16151   add_com ("ignore", class_breakpoint, ignore_command, _("\
16152 Set ignore-count of breakpoint number N to COUNT.\n\
16153 Usage is `ignore N COUNT'."));
16154   if (xdb_commands)
16155     add_com_alias ("bc", "ignore", class_breakpoint, 1);
16156
16157   add_com ("commands", class_breakpoint, commands_command, _("\
16158 Set commands to be executed when a breakpoint is hit.\n\
16159 Give breakpoint number as argument after \"commands\".\n\
16160 With no argument, the targeted breakpoint is the last one set.\n\
16161 The commands themselves follow starting on the next line.\n\
16162 Type a line containing \"end\" to indicate the end of them.\n\
16163 Give \"silent\" as the first line to make the breakpoint silent;\n\
16164 then no output is printed when it is hit, except what the commands print."));
16165
16166   c = add_com ("condition", class_breakpoint, condition_command, _("\
16167 Specify breakpoint number N to break only if COND is true.\n\
16168 Usage is `condition N COND', where N is an integer and COND is an\n\
16169 expression to be evaluated whenever breakpoint N is reached."));
16170   set_cmd_completer (c, condition_completer);
16171
16172   c = add_com ("tbreak", class_breakpoint, tbreak_command, _("\
16173 Set a temporary breakpoint.\n\
16174 Like \"break\" except the breakpoint is only temporary,\n\
16175 so it will be deleted when hit.  Equivalent to \"break\" followed\n\
16176 by using \"enable delete\" on the breakpoint number.\n\
16177 \n"
16178 BREAK_ARGS_HELP ("tbreak")));
16179   set_cmd_completer (c, location_completer);
16180
16181   c = add_com ("hbreak", class_breakpoint, hbreak_command, _("\
16182 Set a hardware assisted breakpoint.\n\
16183 Like \"break\" except the breakpoint requires hardware support,\n\
16184 some target hardware may not have this support.\n\
16185 \n"
16186 BREAK_ARGS_HELP ("hbreak")));
16187   set_cmd_completer (c, location_completer);
16188
16189   c = add_com ("thbreak", class_breakpoint, thbreak_command, _("\
16190 Set a temporary hardware assisted breakpoint.\n\
16191 Like \"hbreak\" except the breakpoint is only temporary,\n\
16192 so it will be deleted when hit.\n\
16193 \n"
16194 BREAK_ARGS_HELP ("thbreak")));
16195   set_cmd_completer (c, location_completer);
16196
16197   add_prefix_cmd ("enable", class_breakpoint, enable_command, _("\
16198 Enable some breakpoints.\n\
16199 Give breakpoint numbers (separated by spaces) as arguments.\n\
16200 With no subcommand, breakpoints are enabled until you command otherwise.\n\
16201 This is used to cancel the effect of the \"disable\" command.\n\
16202 With a subcommand you can enable temporarily."),
16203                   &enablelist, "enable ", 1, &cmdlist);
16204   if (xdb_commands)
16205     add_com ("ab", class_breakpoint, enable_command, _("\
16206 Enable some breakpoints.\n\
16207 Give breakpoint numbers (separated by spaces) as arguments.\n\
16208 With no subcommand, breakpoints are enabled until you command otherwise.\n\
16209 This is used to cancel the effect of the \"disable\" command.\n\
16210 With a subcommand you can enable temporarily."));
16211
16212   add_com_alias ("en", "enable", class_breakpoint, 1);
16213
16214   add_prefix_cmd ("breakpoints", class_breakpoint, enable_command, _("\
16215 Enable some breakpoints.\n\
16216 Give breakpoint numbers (separated by spaces) as arguments.\n\
16217 This is used to cancel the effect of the \"disable\" command.\n\
16218 May be abbreviated to simply \"enable\".\n"),
16219                    &enablebreaklist, "enable breakpoints ", 1, &enablelist);
16220
16221   add_cmd ("once", no_class, enable_once_command, _("\
16222 Enable breakpoints for one hit.  Give breakpoint numbers.\n\
16223 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
16224            &enablebreaklist);
16225
16226   add_cmd ("delete", no_class, enable_delete_command, _("\
16227 Enable breakpoints and delete when hit.  Give breakpoint numbers.\n\
16228 If a breakpoint is hit while enabled in this fashion, it is deleted."),
16229            &enablebreaklist);
16230
16231   add_cmd ("count", no_class, enable_count_command, _("\
16232 Enable breakpoints for COUNT hits.  Give count and then breakpoint numbers.\n\
16233 If a breakpoint is hit while enabled in this fashion,\n\
16234 the count is decremented; when it reaches zero, the breakpoint is disabled."),
16235            &enablebreaklist);
16236
16237   add_cmd ("delete", no_class, enable_delete_command, _("\
16238 Enable breakpoints and delete when hit.  Give breakpoint numbers.\n\
16239 If a breakpoint is hit while enabled in this fashion, it is deleted."),
16240            &enablelist);
16241
16242   add_cmd ("once", no_class, enable_once_command, _("\
16243 Enable breakpoints for one hit.  Give breakpoint numbers.\n\
16244 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
16245            &enablelist);
16246
16247   add_cmd ("count", no_class, enable_count_command, _("\
16248 Enable breakpoints for COUNT hits.  Give count and then breakpoint numbers.\n\
16249 If a breakpoint is hit while enabled in this fashion,\n\
16250 the count is decremented; when it reaches zero, the breakpoint is disabled."),
16251            &enablelist);
16252
16253   add_prefix_cmd ("disable", class_breakpoint, disable_command, _("\
16254 Disable some breakpoints.\n\
16255 Arguments are breakpoint numbers with spaces in between.\n\
16256 To disable all breakpoints, give no argument.\n\
16257 A disabled breakpoint is not forgotten, but has no effect until re-enabled."),
16258                   &disablelist, "disable ", 1, &cmdlist);
16259   add_com_alias ("dis", "disable", class_breakpoint, 1);
16260   add_com_alias ("disa", "disable", class_breakpoint, 1);
16261   if (xdb_commands)
16262     add_com ("sb", class_breakpoint, disable_command, _("\
16263 Disable some breakpoints.\n\
16264 Arguments are breakpoint numbers with spaces in between.\n\
16265 To disable all breakpoints, give no argument.\n\
16266 A disabled breakpoint is not forgotten, but has no effect until re-enabled."));
16267
16268   add_cmd ("breakpoints", class_alias, disable_command, _("\
16269 Disable some breakpoints.\n\
16270 Arguments are breakpoint numbers with spaces in between.\n\
16271 To disable all breakpoints, give no argument.\n\
16272 A disabled breakpoint is not forgotten, but has no effect until re-enabled.\n\
16273 This command may be abbreviated \"disable\"."),
16274            &disablelist);
16275
16276   add_prefix_cmd ("delete", class_breakpoint, delete_command, _("\
16277 Delete some breakpoints or auto-display expressions.\n\
16278 Arguments are breakpoint numbers with spaces in between.\n\
16279 To delete all breakpoints, give no argument.\n\
16280 \n\
16281 Also a prefix command for deletion of other GDB objects.\n\
16282 The \"unset\" command is also an alias for \"delete\"."),
16283                   &deletelist, "delete ", 1, &cmdlist);
16284   add_com_alias ("d", "delete", class_breakpoint, 1);
16285   add_com_alias ("del", "delete", class_breakpoint, 1);
16286   if (xdb_commands)
16287     add_com ("db", class_breakpoint, delete_command, _("\
16288 Delete some breakpoints.\n\
16289 Arguments are breakpoint numbers with spaces in between.\n\
16290 To delete all breakpoints, give no argument.\n"));
16291
16292   add_cmd ("breakpoints", class_alias, delete_command, _("\
16293 Delete some breakpoints or auto-display expressions.\n\
16294 Arguments are breakpoint numbers with spaces in between.\n\
16295 To delete all breakpoints, give no argument.\n\
16296 This command may be abbreviated \"delete\"."),
16297            &deletelist);
16298
16299   add_com ("clear", class_breakpoint, clear_command, _("\
16300 Clear breakpoint at specified line or function.\n\
16301 Argument may be line number, function name, or \"*\" and an address.\n\
16302 If line number is specified, all breakpoints in that line are cleared.\n\
16303 If function is specified, breakpoints at beginning of function are cleared.\n\
16304 If an address is specified, breakpoints at that address are cleared.\n\
16305 \n\
16306 With no argument, clears all breakpoints in the line that the selected frame\n\
16307 is executing in.\n\
16308 \n\
16309 See also the \"delete\" command which clears breakpoints by number."));
16310   add_com_alias ("cl", "clear", class_breakpoint, 1);
16311
16312   c = add_com ("break", class_breakpoint, break_command, _("\
16313 Set breakpoint at specified line or function.\n"
16314 BREAK_ARGS_HELP ("break")));
16315   set_cmd_completer (c, location_completer);
16316
16317   add_com_alias ("b", "break", class_run, 1);
16318   add_com_alias ("br", "break", class_run, 1);
16319   add_com_alias ("bre", "break", class_run, 1);
16320   add_com_alias ("brea", "break", class_run, 1);
16321
16322   if (xdb_commands)
16323    add_com_alias ("ba", "break", class_breakpoint, 1);
16324
16325   if (dbx_commands)
16326     {
16327       add_abbrev_prefix_cmd ("stop", class_breakpoint, stop_command, _("\
16328 Break in function/address or break at a line in the current file."),
16329                              &stoplist, "stop ", 1, &cmdlist);
16330       add_cmd ("in", class_breakpoint, stopin_command,
16331                _("Break in function or address."), &stoplist);
16332       add_cmd ("at", class_breakpoint, stopat_command,
16333                _("Break at a line in the current file."), &stoplist);
16334       add_com ("status", class_info, breakpoints_info, _("\
16335 Status of user-settable breakpoints, or breakpoint number NUMBER.\n\
16336 The \"Type\" column indicates one of:\n\
16337 \tbreakpoint     - normal breakpoint\n\
16338 \twatchpoint     - watchpoint\n\
16339 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
16340 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
16341 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
16342 address and file/line number respectively.\n\
16343 \n\
16344 Convenience variable \"$_\" and default examine address for \"x\"\n\
16345 are set to the address of the last breakpoint listed unless the command\n\
16346 is prefixed with \"server \".\n\n\
16347 Convenience variable \"$bpnum\" contains the number of the last\n\
16348 breakpoint set."));
16349     }
16350
16351   add_info ("breakpoints", breakpoints_info, _("\
16352 Status of specified breakpoints (all user-settable breakpoints if no argument).\n\
16353 The \"Type\" column indicates one of:\n\
16354 \tbreakpoint     - normal breakpoint\n\
16355 \twatchpoint     - watchpoint\n\
16356 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
16357 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
16358 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
16359 address and file/line number respectively.\n\
16360 \n\
16361 Convenience variable \"$_\" and default examine address for \"x\"\n\
16362 are set to the address of the last breakpoint listed unless the command\n\
16363 is prefixed with \"server \".\n\n\
16364 Convenience variable \"$bpnum\" contains the number of the last\n\
16365 breakpoint set."));
16366
16367   add_info_alias ("b", "breakpoints", 1);
16368
16369   if (xdb_commands)
16370     add_com ("lb", class_breakpoint, breakpoints_info, _("\
16371 Status of user-settable breakpoints, or breakpoint number NUMBER.\n\
16372 The \"Type\" column indicates one of:\n\
16373 \tbreakpoint     - normal breakpoint\n\
16374 \twatchpoint     - watchpoint\n\
16375 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
16376 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
16377 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
16378 address and file/line number respectively.\n\
16379 \n\
16380 Convenience variable \"$_\" and default examine address for \"x\"\n\
16381 are set to the address of the last breakpoint listed unless the command\n\
16382 is prefixed with \"server \".\n\n\
16383 Convenience variable \"$bpnum\" contains the number of the last\n\
16384 breakpoint set."));
16385
16386   add_cmd ("breakpoints", class_maintenance, maintenance_info_breakpoints, _("\
16387 Status of all breakpoints, or breakpoint number NUMBER.\n\
16388 The \"Type\" column indicates one of:\n\
16389 \tbreakpoint     - normal breakpoint\n\
16390 \twatchpoint     - watchpoint\n\
16391 \tlongjmp        - internal breakpoint used to step through longjmp()\n\
16392 \tlongjmp resume - internal breakpoint at the target of longjmp()\n\
16393 \tuntil          - internal breakpoint used by the \"until\" command\n\
16394 \tfinish         - internal breakpoint used by the \"finish\" command\n\
16395 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
16396 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
16397 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
16398 address and file/line number respectively.\n\
16399 \n\
16400 Convenience variable \"$_\" and default examine address for \"x\"\n\
16401 are set to the address of the last breakpoint listed unless the command\n\
16402 is prefixed with \"server \".\n\n\
16403 Convenience variable \"$bpnum\" contains the number of the last\n\
16404 breakpoint set."),
16405            &maintenanceinfolist);
16406
16407   add_prefix_cmd ("catch", class_breakpoint, catch_command, _("\
16408 Set catchpoints to catch events."),
16409                   &catch_cmdlist, "catch ",
16410                   0/*allow-unknown*/, &cmdlist);
16411
16412   add_prefix_cmd ("tcatch", class_breakpoint, tcatch_command, _("\
16413 Set temporary catchpoints to catch events."),
16414                   &tcatch_cmdlist, "tcatch ",
16415                   0/*allow-unknown*/, &cmdlist);
16416
16417   add_catch_command ("fork", _("Catch calls to fork."),
16418                      catch_fork_command_1,
16419                      NULL,
16420                      (void *) (uintptr_t) catch_fork_permanent,
16421                      (void *) (uintptr_t) catch_fork_temporary);
16422   add_catch_command ("vfork", _("Catch calls to vfork."),
16423                      catch_fork_command_1,
16424                      NULL,
16425                      (void *) (uintptr_t) catch_vfork_permanent,
16426                      (void *) (uintptr_t) catch_vfork_temporary);
16427   add_catch_command ("exec", _("Catch calls to exec."),
16428                      catch_exec_command_1,
16429                      NULL,
16430                      CATCH_PERMANENT,
16431                      CATCH_TEMPORARY);
16432   add_catch_command ("load", _("Catch loads of shared libraries.\n\
16433 Usage: catch load [REGEX]\n\
16434 If REGEX is given, only stop for libraries matching the regular expression."),
16435                      catch_load_command_1,
16436                      NULL,
16437                      CATCH_PERMANENT,
16438                      CATCH_TEMPORARY);
16439   add_catch_command ("unload", _("Catch unloads of shared libraries.\n\
16440 Usage: catch unload [REGEX]\n\
16441 If REGEX is given, only stop for libraries matching the regular expression."),
16442                      catch_unload_command_1,
16443                      NULL,
16444                      CATCH_PERMANENT,
16445                      CATCH_TEMPORARY);
16446   add_catch_command ("syscall", _("\
16447 Catch system calls by their names and/or numbers.\n\
16448 Arguments say which system calls to catch.  If no arguments\n\
16449 are given, every system call will be caught.\n\
16450 Arguments, if given, should be one or more system call names\n\
16451 (if your system supports that), or system call numbers."),
16452                      catch_syscall_command_1,
16453                      catch_syscall_completer,
16454                      CATCH_PERMANENT,
16455                      CATCH_TEMPORARY);
16456
16457   c = add_com ("watch", class_breakpoint, watch_command, _("\
16458 Set a watchpoint for an expression.\n\
16459 Usage: watch [-l|-location] EXPRESSION\n\
16460 A watchpoint stops execution of your program whenever the value of\n\
16461 an expression changes.\n\
16462 If -l or -location is given, this evaluates EXPRESSION and watches\n\
16463 the memory to which it refers."));
16464   set_cmd_completer (c, expression_completer);
16465
16466   c = add_com ("rwatch", class_breakpoint, rwatch_command, _("\
16467 Set a read watchpoint for an expression.\n\
16468 Usage: rwatch [-l|-location] EXPRESSION\n\
16469 A watchpoint stops execution of your program whenever the value of\n\
16470 an expression is read.\n\
16471 If -l or -location is given, this evaluates EXPRESSION and watches\n\
16472 the memory to which it refers."));
16473   set_cmd_completer (c, expression_completer);
16474
16475   c = add_com ("awatch", class_breakpoint, awatch_command, _("\
16476 Set a watchpoint for an expression.\n\
16477 Usage: awatch [-l|-location] EXPRESSION\n\
16478 A watchpoint stops execution of your program whenever the value of\n\
16479 an expression is either read or written.\n\
16480 If -l or -location is given, this evaluates EXPRESSION and watches\n\
16481 the memory to which it refers."));
16482   set_cmd_completer (c, expression_completer);
16483
16484   add_info ("watchpoints", watchpoints_info, _("\
16485 Status of specified watchpoints (all watchpoints if no argument)."));
16486
16487   /* XXX: cagney/2005-02-23: This should be a boolean, and should
16488      respond to changes - contrary to the description.  */
16489   add_setshow_zinteger_cmd ("can-use-hw-watchpoints", class_support,
16490                             &can_use_hw_watchpoints, _("\
16491 Set debugger's willingness to use watchpoint hardware."), _("\
16492 Show debugger's willingness to use watchpoint hardware."), _("\
16493 If zero, gdb will not use hardware for new watchpoints, even if\n\
16494 such is available.  (However, any hardware watchpoints that were\n\
16495 created before setting this to nonzero, will continue to use watchpoint\n\
16496 hardware.)"),
16497                             NULL,
16498                             show_can_use_hw_watchpoints,
16499                             &setlist, &showlist);
16500
16501   can_use_hw_watchpoints = 1;
16502
16503   /* Tracepoint manipulation commands.  */
16504
16505   c = add_com ("trace", class_breakpoint, trace_command, _("\
16506 Set a tracepoint at specified line or function.\n\
16507 \n"
16508 BREAK_ARGS_HELP ("trace") "\n\
16509 Do \"help tracepoints\" for info on other tracepoint commands."));
16510   set_cmd_completer (c, location_completer);
16511
16512   add_com_alias ("tp", "trace", class_alias, 0);
16513   add_com_alias ("tr", "trace", class_alias, 1);
16514   add_com_alias ("tra", "trace", class_alias, 1);
16515   add_com_alias ("trac", "trace", class_alias, 1);
16516
16517   c = add_com ("ftrace", class_breakpoint, ftrace_command, _("\
16518 Set a fast tracepoint at specified line or function.\n\
16519 \n"
16520 BREAK_ARGS_HELP ("ftrace") "\n\
16521 Do \"help tracepoints\" for info on other tracepoint commands."));
16522   set_cmd_completer (c, location_completer);
16523
16524   c = add_com ("strace", class_breakpoint, strace_command, _("\
16525 Set a static tracepoint at specified line, function or marker.\n\
16526 \n\
16527 strace [LOCATION] [if CONDITION]\n\
16528 LOCATION may be a line number, function name, \"*\" and an address,\n\
16529 or -m MARKER_ID.\n\
16530 If a line number is specified, probe the marker at start of code\n\
16531 for that line.  If a function is specified, probe the marker at start\n\
16532 of code for that function.  If an address is specified, probe the marker\n\
16533 at that exact address.  If a marker id is specified, probe the marker\n\
16534 with that name.  With no LOCATION, uses current execution address of\n\
16535 the selected stack frame.\n\
16536 Static tracepoints accept an extra collect action -- ``collect $_sdata''.\n\
16537 This collects arbitrary user data passed in the probe point call to the\n\
16538 tracing library.  You can inspect it when analyzing the trace buffer,\n\
16539 by printing the $_sdata variable like any other convenience variable.\n\
16540 \n\
16541 CONDITION is a boolean expression.\n\
16542 \n\
16543 Multiple tracepoints at one place are permitted, and useful if their\n\
16544 conditions are different.\n\
16545 \n\
16546 Do \"help breakpoints\" for info on other commands dealing with breakpoints.\n\
16547 Do \"help tracepoints\" for info on other tracepoint commands."));
16548   set_cmd_completer (c, location_completer);
16549
16550   add_info ("tracepoints", tracepoints_info, _("\
16551 Status of specified tracepoints (all tracepoints if no argument).\n\
16552 Convenience variable \"$tpnum\" contains the number of the\n\
16553 last tracepoint set."));
16554
16555   add_info_alias ("tp", "tracepoints", 1);
16556
16557   add_cmd ("tracepoints", class_trace, delete_trace_command, _("\
16558 Delete specified tracepoints.\n\
16559 Arguments are tracepoint numbers, separated by spaces.\n\
16560 No argument means delete all tracepoints."),
16561            &deletelist);
16562   add_alias_cmd ("tr", "tracepoints", class_trace, 1, &deletelist);
16563
16564   c = add_cmd ("tracepoints", class_trace, disable_trace_command, _("\
16565 Disable specified tracepoints.\n\
16566 Arguments are tracepoint numbers, separated by spaces.\n\
16567 No argument means disable all tracepoints."),
16568            &disablelist);
16569   deprecate_cmd (c, "disable");
16570
16571   c = add_cmd ("tracepoints", class_trace, enable_trace_command, _("\
16572 Enable specified tracepoints.\n\
16573 Arguments are tracepoint numbers, separated by spaces.\n\
16574 No argument means enable all tracepoints."),
16575            &enablelist);
16576   deprecate_cmd (c, "enable");
16577
16578   add_com ("passcount", class_trace, trace_pass_command, _("\
16579 Set the passcount for a tracepoint.\n\
16580 The trace will end when the tracepoint has been passed 'count' times.\n\
16581 Usage: passcount COUNT TPNUM, where TPNUM may also be \"all\";\n\
16582 if TPNUM is omitted, passcount refers to the last tracepoint defined."));
16583
16584   add_prefix_cmd ("save", class_breakpoint, save_command,
16585                   _("Save breakpoint definitions as a script."),
16586                   &save_cmdlist, "save ",
16587                   0/*allow-unknown*/, &cmdlist);
16588
16589   c = add_cmd ("breakpoints", class_breakpoint, save_breakpoints_command, _("\
16590 Save current breakpoint definitions as a script.\n\
16591 This includes all types of breakpoints (breakpoints, watchpoints,\n\
16592 catchpoints, tracepoints).  Use the 'source' command in another debug\n\
16593 session to restore them."),
16594                &save_cmdlist);
16595   set_cmd_completer (c, filename_completer);
16596
16597   c = add_cmd ("tracepoints", class_trace, save_tracepoints_command, _("\
16598 Save current tracepoint definitions as a script.\n\
16599 Use the 'source' command in another debug session to restore them."),
16600                &save_cmdlist);
16601   set_cmd_completer (c, filename_completer);
16602
16603   c = add_com_alias ("save-tracepoints", "save tracepoints", class_trace, 0);
16604   deprecate_cmd (c, "save tracepoints");
16605
16606   add_prefix_cmd ("breakpoint", class_maintenance, set_breakpoint_cmd, _("\
16607 Breakpoint specific settings\n\
16608 Configure various breakpoint-specific variables such as\n\
16609 pending breakpoint behavior"),
16610                   &breakpoint_set_cmdlist, "set breakpoint ",
16611                   0/*allow-unknown*/, &setlist);
16612   add_prefix_cmd ("breakpoint", class_maintenance, show_breakpoint_cmd, _("\
16613 Breakpoint specific settings\n\
16614 Configure various breakpoint-specific variables such as\n\
16615 pending breakpoint behavior"),
16616                   &breakpoint_show_cmdlist, "show breakpoint ",
16617                   0/*allow-unknown*/, &showlist);
16618
16619   add_setshow_auto_boolean_cmd ("pending", no_class,
16620                                 &pending_break_support, _("\
16621 Set debugger's behavior regarding pending breakpoints."), _("\
16622 Show debugger's behavior regarding pending breakpoints."), _("\
16623 If on, an unrecognized breakpoint location will cause gdb to create a\n\
16624 pending breakpoint.  If off, an unrecognized breakpoint location results in\n\
16625 an error.  If auto, an unrecognized breakpoint location results in a\n\
16626 user-query to see if a pending breakpoint should be created."),
16627                                 NULL,
16628                                 show_pending_break_support,
16629                                 &breakpoint_set_cmdlist,
16630                                 &breakpoint_show_cmdlist);
16631
16632   pending_break_support = AUTO_BOOLEAN_AUTO;
16633
16634   add_setshow_boolean_cmd ("auto-hw", no_class,
16635                            &automatic_hardware_breakpoints, _("\
16636 Set automatic usage of hardware breakpoints."), _("\
16637 Show automatic usage of hardware breakpoints."), _("\
16638 If set, the debugger will automatically use hardware breakpoints for\n\
16639 breakpoints set with \"break\" but falling in read-only memory.  If not set,\n\
16640 a warning will be emitted for such breakpoints."),
16641                            NULL,
16642                            show_automatic_hardware_breakpoints,
16643                            &breakpoint_set_cmdlist,
16644                            &breakpoint_show_cmdlist);
16645
16646   add_setshow_auto_boolean_cmd ("always-inserted", class_support,
16647                                 &always_inserted_mode, _("\
16648 Set mode for inserting breakpoints."), _("\
16649 Show mode for inserting breakpoints."), _("\
16650 When this mode is off, breakpoints are inserted in inferior when it is\n\
16651 resumed, and removed when execution stops.  When this mode is on,\n\
16652 breakpoints are inserted immediately and removed only when the user\n\
16653 deletes the breakpoint.  When this mode is auto (which is the default),\n\
16654 the behaviour depends on the non-stop setting (see help set non-stop).\n\
16655 In this case, if gdb is controlling the inferior in non-stop mode, gdb\n\
16656 behaves as if always-inserted mode is on; if gdb is controlling the\n\
16657 inferior in all-stop mode, gdb behaves as if always-inserted mode is off."),
16658                                 NULL,
16659                                 &show_always_inserted_mode,
16660                                 &breakpoint_set_cmdlist,
16661                                 &breakpoint_show_cmdlist);
16662
16663   add_setshow_enum_cmd ("condition-evaluation", class_breakpoint,
16664                         condition_evaluation_enums,
16665                         &condition_evaluation_mode_1, _("\
16666 Set mode of breakpoint condition evaluation."), _("\
16667 Show mode of breakpoint condition evaluation."), _("\
16668 When this is set to \"host\", breakpoint conditions will be\n\
16669 evaluated on the host's side by GDB.  When it is set to \"target\",\n\
16670 breakpoint conditions will be downloaded to the target (if the target\n\
16671 supports such feature) and conditions will be evaluated on the target's side.\n\
16672 If this is set to \"auto\" (default), this will be automatically set to\n\
16673 \"target\" if it supports condition evaluation, otherwise it will\n\
16674 be set to \"gdb\""),
16675                            &set_condition_evaluation_mode,
16676                            &show_condition_evaluation_mode,
16677                            &breakpoint_set_cmdlist,
16678                            &breakpoint_show_cmdlist);
16679
16680   add_com ("break-range", class_breakpoint, break_range_command, _("\
16681 Set a breakpoint for an address range.\n\
16682 break-range START-LOCATION, END-LOCATION\n\
16683 where START-LOCATION and END-LOCATION can be one of the following:\n\
16684   LINENUM, for that line in the current file,\n\
16685   FILE:LINENUM, for that line in that file,\n\
16686   +OFFSET, for that number of lines after the current line\n\
16687            or the start of the range\n\
16688   FUNCTION, for the first line in that function,\n\
16689   FILE:FUNCTION, to distinguish among like-named static functions.\n\
16690   *ADDRESS, for the instruction at that address.\n\
16691 \n\
16692 The breakpoint will stop execution of the inferior whenever it executes\n\
16693 an instruction at any address within the [START-LOCATION, END-LOCATION]\n\
16694 range (including START-LOCATION and END-LOCATION)."));
16695
16696   c = add_com ("dprintf", class_breakpoint, dprintf_command, _("\
16697 Set a dynamic printf at specified line or function.\n\
16698 dprintf location,format string,arg1,arg2,...\n\
16699 location may be a line number, function name, or \"*\" and an address.\n\
16700 If a line number is specified, break at start of code for that line.\n\
16701 If a function is specified, break at start of code for that function."));
16702   set_cmd_completer (c, location_completer);
16703
16704   add_setshow_enum_cmd ("dprintf-style", class_support,
16705                         dprintf_style_enums, &dprintf_style, _("\
16706 Set the style of usage for dynamic printf."), _("\
16707 Show the style of usage for dynamic printf."), _("\
16708 This setting chooses how GDB will do a dynamic printf.\n\
16709 If the value is \"gdb\", then the printing is done by GDB to its own\n\
16710 console, as with the \"printf\" command.\n\
16711 If the value is \"call\", the print is done by calling a function in your\n\
16712 program; by default printf(), but you can choose a different function or\n\
16713 output stream by setting dprintf-function and dprintf-channel."),
16714                         update_dprintf_commands, NULL,
16715                         &setlist, &showlist);
16716
16717   dprintf_function = xstrdup ("printf");
16718   add_setshow_string_cmd ("dprintf-function", class_support,
16719                           &dprintf_function, _("\
16720 Set the function to use for dynamic printf"), _("\
16721 Show the function to use for dynamic printf"), NULL,
16722                           update_dprintf_commands, NULL,
16723                           &setlist, &showlist);
16724
16725   dprintf_channel = xstrdup ("");
16726   add_setshow_string_cmd ("dprintf-channel", class_support,
16727                           &dprintf_channel, _("\
16728 Set the channel to use for dynamic printf"), _("\
16729 Show the channel to use for dynamic printf"), NULL,
16730                           update_dprintf_commands, NULL,
16731                           &setlist, &showlist);
16732
16733   add_setshow_boolean_cmd ("disconnected-dprintf", no_class,
16734                            &disconnected_dprintf, _("\
16735 Set whether dprintf continues after GDB disconnects."), _("\
16736 Show whether dprintf continues after GDB disconnects."), _("\
16737 Use this to let dprintf commands continue to hit and produce output\n\
16738 even if GDB disconnects or detaches from the target."),
16739                            NULL,
16740                            NULL,
16741                            &setlist, &showlist);
16742
16743   add_com ("agent-printf", class_vars, agent_printf_command, _("\
16744 agent-printf \"printf format string\", arg1, arg2, arg3, ..., argn\n\
16745 (target agent only) This is useful for formatted output in user-defined commands."));
16746
16747   automatic_hardware_breakpoints = 1;
16748
16749   observer_attach_about_to_proceed (breakpoint_about_to_proceed);
16750   observer_attach_thread_exit (remove_threaded_breakpoints);
16751 }